MDL-55927 auth_radius: Move to third party plugin.
[moodle.git] / lib / moodlelib.php
blobc25acd3a3903d6c1f621cba8a0df2faf1c8944aa
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
25 * @package core
26 * @subpackage lib
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
36 /**
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
41 /**
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
46 /**
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
51 /**
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
56 /**
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
61 /**
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
66 /**
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 // Parameter constants - every call to optional_param(), required_param()
72 // or clean_param() should have a specified type of parameter.
74 /**
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
77 define('PARAM_ALPHA', 'alpha');
79 /**
80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
83 define('PARAM_ALPHAEXT', 'alphaext');
85 /**
86 * PARAM_ALPHANUM - expected numbers and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
90 /**
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
95 /**
96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
98 define('PARAM_AUTH', 'auth');
101 * PARAM_BASE64 - Base 64 encoded format
103 define('PARAM_BASE64', 'base64');
106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
108 define('PARAM_BOOL', 'bool');
111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112 * checked against the list of capabilities in the database.
114 define('PARAM_CAPABILITY', 'capability');
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
119 * the input (required/optional_param or formslib) and then sanitse the HTML
120 * using format_text on output. This is for the rare cases when you want to
121 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
123 define('PARAM_CLEANHTML', 'cleanhtml');
126 * PARAM_EMAIL - an email address following the RFC
128 define('PARAM_EMAIL', 'email');
131 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
133 define('PARAM_FILE', 'file');
136 * PARAM_FLOAT - a real/floating point number.
138 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139 * It does not work for languages that use , as a decimal separator.
140 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
146 define('PARAM_FLOAT', 'float');
149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
151 define('PARAM_HOST', 'host');
154 * PARAM_INT - integers only, use when expecting only numbers.
156 define('PARAM_INT', 'int');
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
161 define('PARAM_LANG', 'lang');
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
167 define('PARAM_LOCALURL', 'localurl');
170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
172 define('PARAM_NOTAGS', 'notags');
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
178 define('PARAM_PATH', 'path');
181 * PARAM_PEM - Privacy Enhanced Mail format
183 define('PARAM_PEM', 'pem');
186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
188 define('PARAM_PERMISSION', 'permission');
191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
193 define('PARAM_RAW', 'raw');
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
198 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
203 define('PARAM_SAFEDIR', 'safedir');
206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
208 define('PARAM_SAFEPATH', 'safepath');
211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
213 define('PARAM_SEQUENCE', 'sequence');
216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
218 define('PARAM_TAG', 'tag');
221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
223 define('PARAM_TAGLIST', 'taglist');
226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
228 define('PARAM_TEXT', 'text');
231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
233 define('PARAM_THEME', 'theme');
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * http://localhost.localdomain/ is ok.
239 define('PARAM_URL', 'url');
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243 * accounts, do NOT use when syncing with external systems!!
245 define('PARAM_USERNAME', 'username');
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
250 define('PARAM_STRINGID', 'stringid');
252 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
256 * @deprecated since 2.0
258 define('PARAM_CLEAN', 'clean');
261 * PARAM_INTEGER - deprecated alias for PARAM_INT
262 * @deprecated since 2.0
264 define('PARAM_INTEGER', 'int');
267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268 * @deprecated since 2.0
270 define('PARAM_NUMBER', 'float');
273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274 * NOTE: originally alias for PARAM_APLHA
275 * @deprecated since 2.0
277 define('PARAM_ACTION', 'alphanumext');
280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
282 * @deprecated since 2.0
284 define('PARAM_FORMAT', 'alphanumext');
287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288 * @deprecated since 2.0
290 define('PARAM_MULTILANG', 'text');
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295 * America/Port-au-Prince)
297 define('PARAM_TIMEZONE', 'timezone');
300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
302 define('PARAM_CLEANFILE', 'file');
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
310 define('PARAM_COMPONENT', 'component');
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
317 define('PARAM_AREA', 'area');
320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
324 define('PARAM_PLUGIN', 'plugin');
327 // Web Services.
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
332 define('VALUE_REQUIRED', 1);
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
337 define('VALUE_OPTIONAL', 2);
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
342 define('VALUE_DEFAULT', 0);
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
347 define('NULL_NOT_ALLOWED', false);
350 * NULL_ALLOWED - the parameter can be set to null in the database
352 define('NULL_ALLOWED', true);
354 // Page types.
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
374 // Tag constants.
376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
421 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
423 /** Type of module */
424 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425 /** True if module supports intro editor */
426 define('FEATURE_MOD_INTRO', 'mod_intro');
427 /** True if module has default completion */
428 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
430 define('FEATURE_COMMENT', 'comment');
432 define('FEATURE_RATE', 'rate');
433 /** True if module supports backup/restore of moodle2 format */
434 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
436 /** True if module can show description on course main page */
437 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
439 /** True if module uses the question bank */
440 define('FEATURE_USES_QUESTIONS', 'usesquestions');
442 /** Unspecified module archetype */
443 define('MOD_ARCHETYPE_OTHER', 0);
444 /** Resource-like type module */
445 define('MOD_ARCHETYPE_RESOURCE', 1);
446 /** Assignment module archetype */
447 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
448 /** System (not user-addable) module archetype */
449 define('MOD_ARCHETYPE_SYSTEM', 3);
452 * Return this from modname_get_types callback to use default display in activity chooser.
453 * Deprecated, will be removed in 3.5, TODO MDL-53697.
454 * @deprecated since Moodle 3.1
456 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
459 * Security token used for allowing access
460 * from external application such as web services.
461 * Scripts do not use any session, performance is relatively
462 * low because we need to load access info in each request.
463 * Scripts are executed in parallel.
465 define('EXTERNAL_TOKEN_PERMANENT', 0);
468 * Security token used for allowing access
469 * of embedded applications, the code is executed in the
470 * active user session. Token is invalidated after user logs out.
471 * Scripts are executed serially - normal session locking is used.
473 define('EXTERNAL_TOKEN_EMBEDDED', 1);
476 * The home page should be the site home
478 define('HOMEPAGE_SITE', 0);
480 * The home page should be the users my page
482 define('HOMEPAGE_MY', 1);
484 * The home page can be chosen by the user
486 define('HOMEPAGE_USER', 2);
489 * Hub directory url (should be moodle.org)
491 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
495 * Moodle.org url (should be moodle.org)
497 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
500 * Moodle mobile app service name
502 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
505 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
507 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
510 * Course display settings: display all sections on one page.
512 define('COURSE_DISPLAY_SINGLEPAGE', 0);
514 * Course display settings: split pages into a page per section.
516 define('COURSE_DISPLAY_MULTIPAGE', 1);
519 * Authentication constant: String used in password field when password is not stored.
521 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
523 // PARAMETER HANDLING.
526 * Returns a particular value for the named variable, taken from
527 * POST or GET. If the parameter doesn't exist then an error is
528 * thrown because we require this variable.
530 * This function should be used to initialise all required values
531 * in a script that are based on parameters. Usually it will be
532 * used like this:
533 * $id = required_param('id', PARAM_INT);
535 * Please note the $type parameter is now required and the value can not be array.
537 * @param string $parname the name of the page parameter we want
538 * @param string $type expected type of parameter
539 * @return mixed
540 * @throws coding_exception
542 function required_param($parname, $type) {
543 if (func_num_args() != 2 or empty($parname) or empty($type)) {
544 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
546 // POST has precedence.
547 if (isset($_POST[$parname])) {
548 $param = $_POST[$parname];
549 } else if (isset($_GET[$parname])) {
550 $param = $_GET[$parname];
551 } else {
552 print_error('missingparam', '', '', $parname);
555 if (is_array($param)) {
556 debugging('Invalid array parameter detected in required_param(): '.$parname);
557 // TODO: switch to fatal error in Moodle 2.3.
558 return required_param_array($parname, $type);
561 return clean_param($param, $type);
565 * Returns a particular array value for the named variable, taken from
566 * POST or GET. If the parameter doesn't exist then an error is
567 * thrown because we require this variable.
569 * This function should be used to initialise all required values
570 * in a script that are based on parameters. Usually it will be
571 * used like this:
572 * $ids = required_param_array('ids', PARAM_INT);
574 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
576 * @param string $parname the name of the page parameter we want
577 * @param string $type expected type of parameter
578 * @return array
579 * @throws coding_exception
581 function required_param_array($parname, $type) {
582 if (func_num_args() != 2 or empty($parname) or empty($type)) {
583 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
585 // POST has precedence.
586 if (isset($_POST[$parname])) {
587 $param = $_POST[$parname];
588 } else if (isset($_GET[$parname])) {
589 $param = $_GET[$parname];
590 } else {
591 print_error('missingparam', '', '', $parname);
593 if (!is_array($param)) {
594 print_error('missingparam', '', '', $parname);
597 $result = array();
598 foreach ($param as $key => $value) {
599 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
600 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
601 continue;
603 $result[$key] = clean_param($value, $type);
606 return $result;
610 * Returns a particular value for the named variable, taken from
611 * POST or GET, otherwise returning a given default.
613 * This function should be used to initialise all optional values
614 * in a script that are based on parameters. Usually it will be
615 * used like this:
616 * $name = optional_param('name', 'Fred', PARAM_TEXT);
618 * Please note the $type parameter is now required and the value can not be array.
620 * @param string $parname the name of the page parameter we want
621 * @param mixed $default the default value to return if nothing is found
622 * @param string $type expected type of parameter
623 * @return mixed
624 * @throws coding_exception
626 function optional_param($parname, $default, $type) {
627 if (func_num_args() != 3 or empty($parname) or empty($type)) {
628 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
631 // POST has precedence.
632 if (isset($_POST[$parname])) {
633 $param = $_POST[$parname];
634 } else if (isset($_GET[$parname])) {
635 $param = $_GET[$parname];
636 } else {
637 return $default;
640 if (is_array($param)) {
641 debugging('Invalid array parameter detected in required_param(): '.$parname);
642 // TODO: switch to $default in Moodle 2.3.
643 return optional_param_array($parname, $default, $type);
646 return clean_param($param, $type);
650 * Returns a particular array value for the named variable, taken from
651 * POST or GET, otherwise returning a given default.
653 * This function should be used to initialise all optional values
654 * in a script that are based on parameters. Usually it will be
655 * used like this:
656 * $ids = optional_param('id', array(), PARAM_INT);
658 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
660 * @param string $parname the name of the page parameter we want
661 * @param mixed $default the default value to return if nothing is found
662 * @param string $type expected type of parameter
663 * @return array
664 * @throws coding_exception
666 function optional_param_array($parname, $default, $type) {
667 if (func_num_args() != 3 or empty($parname) or empty($type)) {
668 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
671 // POST has precedence.
672 if (isset($_POST[$parname])) {
673 $param = $_POST[$parname];
674 } else if (isset($_GET[$parname])) {
675 $param = $_GET[$parname];
676 } else {
677 return $default;
679 if (!is_array($param)) {
680 debugging('optional_param_array() expects array parameters only: '.$parname);
681 return $default;
684 $result = array();
685 foreach ($param as $key => $value) {
686 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
687 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
688 continue;
690 $result[$key] = clean_param($value, $type);
693 return $result;
697 * Strict validation of parameter values, the values are only converted
698 * to requested PHP type. Internally it is using clean_param, the values
699 * before and after cleaning must be equal - otherwise
700 * an invalid_parameter_exception is thrown.
701 * Objects and classes are not accepted.
703 * @param mixed $param
704 * @param string $type PARAM_ constant
705 * @param bool $allownull are nulls valid value?
706 * @param string $debuginfo optional debug information
707 * @return mixed the $param value converted to PHP type
708 * @throws invalid_parameter_exception if $param is not of given type
710 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
711 if (is_null($param)) {
712 if ($allownull == NULL_ALLOWED) {
713 return null;
714 } else {
715 throw new invalid_parameter_exception($debuginfo);
718 if (is_array($param) or is_object($param)) {
719 throw new invalid_parameter_exception($debuginfo);
722 $cleaned = clean_param($param, $type);
724 if ($type == PARAM_FLOAT) {
725 // Do not detect precision loss here.
726 if (is_float($param) or is_int($param)) {
727 // These always fit.
728 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
729 throw new invalid_parameter_exception($debuginfo);
731 } else if ((string)$param !== (string)$cleaned) {
732 // Conversion to string is usually lossless.
733 throw new invalid_parameter_exception($debuginfo);
736 return $cleaned;
740 * Makes sure array contains only the allowed types, this function does not validate array key names!
742 * <code>
743 * $options = clean_param($options, PARAM_INT);
744 * </code>
746 * @param array $param the variable array we are cleaning
747 * @param string $type expected format of param after cleaning.
748 * @param bool $recursive clean recursive arrays
749 * @return array
750 * @throws coding_exception
752 function clean_param_array(array $param = null, $type, $recursive = false) {
753 // Convert null to empty array.
754 $param = (array)$param;
755 foreach ($param as $key => $value) {
756 if (is_array($value)) {
757 if ($recursive) {
758 $param[$key] = clean_param_array($value, $type, true);
759 } else {
760 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
762 } else {
763 $param[$key] = clean_param($value, $type);
766 return $param;
770 * Used by {@link optional_param()} and {@link required_param()} to
771 * clean the variables and/or cast to specific types, based on
772 * an options field.
773 * <code>
774 * $course->format = clean_param($course->format, PARAM_ALPHA);
775 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
776 * </code>
778 * @param mixed $param the variable we are cleaning
779 * @param string $type expected format of param after cleaning.
780 * @return mixed
781 * @throws coding_exception
783 function clean_param($param, $type) {
784 global $CFG;
786 if (is_array($param)) {
787 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
788 } else if (is_object($param)) {
789 if (method_exists($param, '__toString')) {
790 $param = $param->__toString();
791 } else {
792 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
796 switch ($type) {
797 case PARAM_RAW:
798 // No cleaning at all.
799 $param = fix_utf8($param);
800 return $param;
802 case PARAM_RAW_TRIMMED:
803 // No cleaning, but strip leading and trailing whitespace.
804 $param = fix_utf8($param);
805 return trim($param);
807 case PARAM_CLEAN:
808 // General HTML cleaning, try to use more specific type if possible this is deprecated!
809 // Please use more specific type instead.
810 if (is_numeric($param)) {
811 return $param;
813 $param = fix_utf8($param);
814 // Sweep for scripts, etc.
815 return clean_text($param);
817 case PARAM_CLEANHTML:
818 // Clean html fragment.
819 $param = fix_utf8($param);
820 // Sweep for scripts, etc.
821 $param = clean_text($param, FORMAT_HTML);
822 return trim($param);
824 case PARAM_INT:
825 // Convert to integer.
826 return (int)$param;
828 case PARAM_FLOAT:
829 // Convert to float.
830 return (float)$param;
832 case PARAM_ALPHA:
833 // Remove everything not `a-z`.
834 return preg_replace('/[^a-zA-Z]/i', '', $param);
836 case PARAM_ALPHAEXT:
837 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
838 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
840 case PARAM_ALPHANUM:
841 // Remove everything not `a-zA-Z0-9`.
842 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
844 case PARAM_ALPHANUMEXT:
845 // Remove everything not `a-zA-Z0-9_-`.
846 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
848 case PARAM_SEQUENCE:
849 // Remove everything not `0-9,`.
850 return preg_replace('/[^0-9,]/i', '', $param);
852 case PARAM_BOOL:
853 // Convert to 1 or 0.
854 $tempstr = strtolower($param);
855 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
856 $param = 1;
857 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
858 $param = 0;
859 } else {
860 $param = empty($param) ? 0 : 1;
862 return $param;
864 case PARAM_NOTAGS:
865 // Strip all tags.
866 $param = fix_utf8($param);
867 return strip_tags($param);
869 case PARAM_TEXT:
870 // Leave only tags needed for multilang.
871 $param = fix_utf8($param);
872 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
873 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
874 do {
875 if (strpos($param, '</lang>') !== false) {
876 // Old and future mutilang syntax.
877 $param = strip_tags($param, '<lang>');
878 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
879 break;
881 $open = false;
882 foreach ($matches[0] as $match) {
883 if ($match === '</lang>') {
884 if ($open) {
885 $open = false;
886 continue;
887 } else {
888 break 2;
891 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
892 break 2;
893 } else {
894 $open = true;
897 if ($open) {
898 break;
900 return $param;
902 } else if (strpos($param, '</span>') !== false) {
903 // Current problematic multilang syntax.
904 $param = strip_tags($param, '<span>');
905 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
906 break;
908 $open = false;
909 foreach ($matches[0] as $match) {
910 if ($match === '</span>') {
911 if ($open) {
912 $open = false;
913 continue;
914 } else {
915 break 2;
918 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
919 break 2;
920 } else {
921 $open = true;
924 if ($open) {
925 break;
927 return $param;
929 } while (false);
930 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
931 return strip_tags($param);
933 case PARAM_COMPONENT:
934 // We do not want any guessing here, either the name is correct or not
935 // please note only normalised component names are accepted.
936 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
937 return '';
939 if (strpos($param, '__') !== false) {
940 return '';
942 if (strpos($param, 'mod_') === 0) {
943 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
944 if (substr_count($param, '_') != 1) {
945 return '';
948 return $param;
950 case PARAM_PLUGIN:
951 case PARAM_AREA:
952 // We do not want any guessing here, either the name is correct or not.
953 if (!is_valid_plugin_name($param)) {
954 return '';
956 return $param;
958 case PARAM_SAFEDIR:
959 // Remove everything not a-zA-Z0-9_- .
960 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
962 case PARAM_SAFEPATH:
963 // Remove everything not a-zA-Z0-9/_- .
964 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
966 case PARAM_FILE:
967 // Strip all suspicious characters from filename.
968 $param = fix_utf8($param);
969 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
970 if ($param === '.' || $param === '..') {
971 $param = '';
973 return $param;
975 case PARAM_PATH:
976 // Strip all suspicious characters from file path.
977 $param = fix_utf8($param);
978 $param = str_replace('\\', '/', $param);
980 // Explode the path and clean each element using the PARAM_FILE rules.
981 $breadcrumb = explode('/', $param);
982 foreach ($breadcrumb as $key => $crumb) {
983 if ($crumb === '.' && $key === 0) {
984 // Special condition to allow for relative current path such as ./currentdirfile.txt.
985 } else {
986 $crumb = clean_param($crumb, PARAM_FILE);
988 $breadcrumb[$key] = $crumb;
990 $param = implode('/', $breadcrumb);
992 // Remove multiple current path (./././) and multiple slashes (///).
993 $param = preg_replace('~//+~', '/', $param);
994 $param = preg_replace('~/(\./)+~', '/', $param);
995 return $param;
997 case PARAM_HOST:
998 // Allow FQDN or IPv4 dotted quad.
999 $param = preg_replace('/[^\.\d\w-]/', '', $param );
1000 // Match ipv4 dotted quad.
1001 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1002 // Confirm values are ok.
1003 if ( $match[0] > 255
1004 || $match[1] > 255
1005 || $match[3] > 255
1006 || $match[4] > 255 ) {
1007 // Hmmm, what kind of dotted quad is this?
1008 $param = '';
1010 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1011 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1012 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1014 // All is ok - $param is respected.
1015 } else {
1016 // All is not ok...
1017 $param='';
1019 return $param;
1021 case PARAM_URL: // Allow safe ftp, http, mailto urls.
1022 $param = fix_utf8($param);
1023 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1024 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1025 // All is ok, param is respected.
1026 } else {
1027 // Not really ok.
1028 $param ='';
1030 return $param;
1032 case PARAM_LOCALURL:
1033 // Allow http absolute, root relative and relative URLs within wwwroot.
1034 $param = clean_param($param, PARAM_URL);
1035 if (!empty($param)) {
1037 // Simulate the HTTPS version of the site.
1038 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1040 if ($param === $CFG->wwwroot) {
1041 // Exact match;
1042 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1043 // Exact match;
1044 } else if (preg_match(':^/:', $param)) {
1045 // Root-relative, ok!
1046 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1047 // Absolute, and matches our wwwroot.
1048 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
1049 // Absolute, and matches our httpswwwroot.
1050 } else {
1051 // Relative - let's make sure there are no tricks.
1052 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1053 // Looks ok.
1054 } else {
1055 $param = '';
1059 return $param;
1061 case PARAM_PEM:
1062 $param = trim($param);
1063 // PEM formatted strings may contain letters/numbers and the symbols:
1064 // forward slash: /
1065 // plus sign: +
1066 // equal sign: =
1067 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1068 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1069 list($wholething, $body) = $matches;
1070 unset($wholething, $matches);
1071 $b64 = clean_param($body, PARAM_BASE64);
1072 if (!empty($b64)) {
1073 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1074 } else {
1075 return '';
1078 return '';
1080 case PARAM_BASE64:
1081 if (!empty($param)) {
1082 // PEM formatted strings may contain letters/numbers and the symbols
1083 // forward slash: /
1084 // plus sign: +
1085 // equal sign: =.
1086 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1087 return '';
1089 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1090 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1091 // than (or equal to) 64 characters long.
1092 for ($i=0, $j=count($lines); $i < $j; $i++) {
1093 if ($i + 1 == $j) {
1094 if (64 < strlen($lines[$i])) {
1095 return '';
1097 continue;
1100 if (64 != strlen($lines[$i])) {
1101 return '';
1104 return implode("\n", $lines);
1105 } else {
1106 return '';
1109 case PARAM_TAG:
1110 $param = fix_utf8($param);
1111 // Please note it is not safe to use the tag name directly anywhere,
1112 // it must be processed with s(), urlencode() before embedding anywhere.
1113 // Remove some nasties.
1114 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1115 // Convert many whitespace chars into one.
1116 $param = preg_replace('/\s+/u', ' ', $param);
1117 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1118 return $param;
1120 case PARAM_TAGLIST:
1121 $param = fix_utf8($param);
1122 $tags = explode(',', $param);
1123 $result = array();
1124 foreach ($tags as $tag) {
1125 $res = clean_param($tag, PARAM_TAG);
1126 if ($res !== '') {
1127 $result[] = $res;
1130 if ($result) {
1131 return implode(',', $result);
1132 } else {
1133 return '';
1136 case PARAM_CAPABILITY:
1137 if (get_capability_info($param)) {
1138 return $param;
1139 } else {
1140 return '';
1143 case PARAM_PERMISSION:
1144 $param = (int)$param;
1145 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1146 return $param;
1147 } else {
1148 return CAP_INHERIT;
1151 case PARAM_AUTH:
1152 $param = clean_param($param, PARAM_PLUGIN);
1153 if (empty($param)) {
1154 return '';
1155 } else if (exists_auth_plugin($param)) {
1156 return $param;
1157 } else {
1158 return '';
1161 case PARAM_LANG:
1162 $param = clean_param($param, PARAM_SAFEDIR);
1163 if (get_string_manager()->translation_exists($param)) {
1164 return $param;
1165 } else {
1166 // Specified language is not installed or param malformed.
1167 return '';
1170 case PARAM_THEME:
1171 $param = clean_param($param, PARAM_PLUGIN);
1172 if (empty($param)) {
1173 return '';
1174 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1175 return $param;
1176 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1177 return $param;
1178 } else {
1179 // Specified theme is not installed.
1180 return '';
1183 case PARAM_USERNAME:
1184 $param = fix_utf8($param);
1185 $param = trim($param);
1186 // Convert uppercase to lowercase MDL-16919.
1187 $param = core_text::strtolower($param);
1188 if (empty($CFG->extendedusernamechars)) {
1189 $param = str_replace(" " , "", $param);
1190 // Regular expression, eliminate all chars EXCEPT:
1191 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1192 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1194 return $param;
1196 case PARAM_EMAIL:
1197 $param = fix_utf8($param);
1198 if (validate_email($param)) {
1199 return $param;
1200 } else {
1201 return '';
1204 case PARAM_STRINGID:
1205 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1206 return $param;
1207 } else {
1208 return '';
1211 case PARAM_TIMEZONE:
1212 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1213 $param = fix_utf8($param);
1214 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1215 if (preg_match($timezonepattern, $param)) {
1216 return $param;
1217 } else {
1218 return '';
1221 default:
1222 // Doh! throw error, switched parameters in optional_param or another serious problem.
1223 print_error("unknownparamtype", '', '', $type);
1228 * Whether the PARAM_* type is compatible in RTL.
1230 * Being compatible with RTL means that the data they contain can flow
1231 * from right-to-left or left-to-right without compromising the user experience.
1233 * Take URLs for example, they are not RTL compatible as they should always
1234 * flow from the left to the right. This also applies to numbers, email addresses,
1235 * configuration snippets, base64 strings, etc...
1237 * This function tries to best guess which parameters can contain localised strings.
1239 * @param string $paramtype Constant PARAM_*.
1240 * @return bool
1242 function is_rtl_compatible($paramtype) {
1243 return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1247 * Makes sure the data is using valid utf8, invalid characters are discarded.
1249 * Note: this function is not intended for full objects with methods and private properties.
1251 * @param mixed $value
1252 * @return mixed with proper utf-8 encoding
1254 function fix_utf8($value) {
1255 if (is_null($value) or $value === '') {
1256 return $value;
1258 } else if (is_string($value)) {
1259 if ((string)(int)$value === $value) {
1260 // Shortcut.
1261 return $value;
1263 // No null bytes expected in our data, so let's remove it.
1264 $value = str_replace("\0", '', $value);
1266 // Note: this duplicates min_fix_utf8() intentionally.
1267 static $buggyiconv = null;
1268 if ($buggyiconv === null) {
1269 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1272 if ($buggyiconv) {
1273 if (function_exists('mb_convert_encoding')) {
1274 $subst = mb_substitute_character();
1275 mb_substitute_character('');
1276 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1277 mb_substitute_character($subst);
1279 } else {
1280 // Warn admins on admin/index.php page.
1281 $result = $value;
1284 } else {
1285 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1288 return $result;
1290 } else if (is_array($value)) {
1291 foreach ($value as $k => $v) {
1292 $value[$k] = fix_utf8($v);
1294 return $value;
1296 } else if (is_object($value)) {
1297 // Do not modify original.
1298 $value = clone($value);
1299 foreach ($value as $k => $v) {
1300 $value->$k = fix_utf8($v);
1302 return $value;
1304 } else {
1305 // This is some other type, no utf-8 here.
1306 return $value;
1311 * Return true if given value is integer or string with integer value
1313 * @param mixed $value String or Int
1314 * @return bool true if number, false if not
1316 function is_number($value) {
1317 if (is_int($value)) {
1318 return true;
1319 } else if (is_string($value)) {
1320 return ((string)(int)$value) === $value;
1321 } else {
1322 return false;
1327 * Returns host part from url.
1329 * @param string $url full url
1330 * @return string host, null if not found
1332 function get_host_from_url($url) {
1333 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1334 if ($matches) {
1335 return $matches[1];
1337 return null;
1341 * Tests whether anything was returned by text editor
1343 * This function is useful for testing whether something you got back from
1344 * the HTML editor actually contains anything. Sometimes the HTML editor
1345 * appear to be empty, but actually you get back a <br> tag or something.
1347 * @param string $string a string containing HTML.
1348 * @return boolean does the string contain any actual content - that is text,
1349 * images, objects, etc.
1351 function html_is_blank($string) {
1352 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1356 * Set a key in global configuration
1358 * Set a key/value pair in both this session's {@link $CFG} global variable
1359 * and in the 'config' database table for future sessions.
1361 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1362 * In that case it doesn't affect $CFG.
1364 * A NULL value will delete the entry.
1366 * NOTE: this function is called from lib/db/upgrade.php
1368 * @param string $name the key to set
1369 * @param string $value the value to set (without magic quotes)
1370 * @param string $plugin (optional) the plugin scope, default null
1371 * @return bool true or exception
1373 function set_config($name, $value, $plugin=null) {
1374 global $CFG, $DB;
1376 if (empty($plugin)) {
1377 if (!array_key_exists($name, $CFG->config_php_settings)) {
1378 // So it's defined for this invocation at least.
1379 if (is_null($value)) {
1380 unset($CFG->$name);
1381 } else {
1382 // Settings from db are always strings.
1383 $CFG->$name = (string)$value;
1387 if ($DB->get_field('config', 'name', array('name' => $name))) {
1388 if ($value === null) {
1389 $DB->delete_records('config', array('name' => $name));
1390 } else {
1391 $DB->set_field('config', 'value', $value, array('name' => $name));
1393 } else {
1394 if ($value !== null) {
1395 $config = new stdClass();
1396 $config->name = $name;
1397 $config->value = $value;
1398 $DB->insert_record('config', $config, false);
1401 if ($name === 'siteidentifier') {
1402 cache_helper::update_site_identifier($value);
1404 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1405 } else {
1406 // Plugin scope.
1407 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1408 if ($value===null) {
1409 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1410 } else {
1411 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1413 } else {
1414 if ($value !== null) {
1415 $config = new stdClass();
1416 $config->plugin = $plugin;
1417 $config->name = $name;
1418 $config->value = $value;
1419 $DB->insert_record('config_plugins', $config, false);
1422 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1425 return true;
1429 * Get configuration values from the global config table
1430 * or the config_plugins table.
1432 * If called with one parameter, it will load all the config
1433 * variables for one plugin, and return them as an object.
1435 * If called with 2 parameters it will return a string single
1436 * value or false if the value is not found.
1438 * NOTE: this function is called from lib/db/upgrade.php
1440 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1441 * that we need only fetch it once per request.
1442 * @param string $plugin full component name
1443 * @param string $name default null
1444 * @return mixed hash-like object or single value, return false no config found
1445 * @throws dml_exception
1447 function get_config($plugin, $name = null) {
1448 global $CFG, $DB;
1450 static $siteidentifier = null;
1452 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1453 $forced =& $CFG->config_php_settings;
1454 $iscore = true;
1455 $plugin = 'core';
1456 } else {
1457 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1458 $forced =& $CFG->forced_plugin_settings[$plugin];
1459 } else {
1460 $forced = array();
1462 $iscore = false;
1465 if ($siteidentifier === null) {
1466 try {
1467 // This may fail during installation.
1468 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1469 // install the database.
1470 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1471 } catch (dml_exception $ex) {
1472 // Set siteidentifier to false. We don't want to trip this continually.
1473 $siteidentifier = false;
1474 throw $ex;
1478 if (!empty($name)) {
1479 if (array_key_exists($name, $forced)) {
1480 return (string)$forced[$name];
1481 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1482 return $siteidentifier;
1486 $cache = cache::make('core', 'config');
1487 $result = $cache->get($plugin);
1488 if ($result === false) {
1489 // The user is after a recordset.
1490 if (!$iscore) {
1491 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1492 } else {
1493 // This part is not really used any more, but anyway...
1494 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1496 $cache->set($plugin, $result);
1499 if (!empty($name)) {
1500 if (array_key_exists($name, $result)) {
1501 return $result[$name];
1503 return false;
1506 if ($plugin === 'core') {
1507 $result['siteidentifier'] = $siteidentifier;
1510 foreach ($forced as $key => $value) {
1511 if (is_null($value) or is_array($value) or is_object($value)) {
1512 // We do not want any extra mess here, just real settings that could be saved in db.
1513 unset($result[$key]);
1514 } else {
1515 // Convert to string as if it went through the DB.
1516 $result[$key] = (string)$value;
1520 return (object)$result;
1524 * Removes a key from global configuration.
1526 * NOTE: this function is called from lib/db/upgrade.php
1528 * @param string $name the key to set
1529 * @param string $plugin (optional) the plugin scope
1530 * @return boolean whether the operation succeeded.
1532 function unset_config($name, $plugin=null) {
1533 global $CFG, $DB;
1535 if (empty($plugin)) {
1536 unset($CFG->$name);
1537 $DB->delete_records('config', array('name' => $name));
1538 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1539 } else {
1540 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1541 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1544 return true;
1548 * Remove all the config variables for a given plugin.
1550 * NOTE: this function is called from lib/db/upgrade.php
1552 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1553 * @return boolean whether the operation succeeded.
1555 function unset_all_config_for_plugin($plugin) {
1556 global $DB;
1557 // Delete from the obvious config_plugins first.
1558 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1559 // Next delete any suspect settings from config.
1560 $like = $DB->sql_like('name', '?', true, true, false, '|');
1561 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1562 $DB->delete_records_select('config', $like, $params);
1563 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1564 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1566 return true;
1570 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1572 * All users are verified if they still have the necessary capability.
1574 * @param string $value the value of the config setting.
1575 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1576 * @param bool $includeadmins include administrators.
1577 * @return array of user objects.
1579 function get_users_from_config($value, $capability, $includeadmins = true) {
1580 if (empty($value) or $value === '$@NONE@$') {
1581 return array();
1584 // We have to make sure that users still have the necessary capability,
1585 // it should be faster to fetch them all first and then test if they are present
1586 // instead of validating them one-by-one.
1587 $users = get_users_by_capability(context_system::instance(), $capability);
1588 if ($includeadmins) {
1589 $admins = get_admins();
1590 foreach ($admins as $admin) {
1591 $users[$admin->id] = $admin;
1595 if ($value === '$@ALL@$') {
1596 return $users;
1599 $result = array(); // Result in correct order.
1600 $allowed = explode(',', $value);
1601 foreach ($allowed as $uid) {
1602 if (isset($users[$uid])) {
1603 $user = $users[$uid];
1604 $result[$user->id] = $user;
1608 return $result;
1613 * Invalidates browser caches and cached data in temp.
1615 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1616 * {@link phpunit_util::reset_dataroot()}
1618 * @return void
1620 function purge_all_caches() {
1621 global $CFG, $DB;
1623 reset_text_filters_cache();
1624 js_reset_all_caches();
1625 theme_reset_all_caches();
1626 get_string_manager()->reset_caches();
1627 core_text::reset_caches();
1628 if (class_exists('core_plugin_manager')) {
1629 core_plugin_manager::reset_caches();
1632 // Bump up cacherev field for all courses.
1633 try {
1634 increment_revision_number('course', 'cacherev', '');
1635 } catch (moodle_exception $e) {
1636 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1639 $DB->reset_caches();
1640 cache_helper::purge_all();
1642 // Purge all other caches: rss, simplepie, etc.
1643 clearstatcache();
1644 remove_dir($CFG->cachedir.'', true);
1646 // Make sure cache dir is writable, throws exception if not.
1647 make_cache_directory('');
1649 // This is the only place where we purge local caches, we are only adding files there.
1650 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1651 remove_dir($CFG->localcachedir, true);
1652 set_config('localcachedirpurged', time());
1653 make_localcache_directory('', true);
1654 \core\task\manager::clear_static_caches();
1658 * Get volatile flags
1660 * @param string $type
1661 * @param int $changedsince default null
1662 * @return array records array
1664 function get_cache_flags($type, $changedsince = null) {
1665 global $DB;
1667 $params = array('type' => $type, 'expiry' => time());
1668 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1669 if ($changedsince !== null) {
1670 $params['changedsince'] = $changedsince;
1671 $sqlwhere .= " AND timemodified > :changedsince";
1673 $cf = array();
1674 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1675 foreach ($flags as $flag) {
1676 $cf[$flag->name] = $flag->value;
1679 return $cf;
1683 * Get volatile flags
1685 * @param string $type
1686 * @param string $name
1687 * @param int $changedsince default null
1688 * @return string|false The cache flag value or false
1690 function get_cache_flag($type, $name, $changedsince=null) {
1691 global $DB;
1693 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1695 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1696 if ($changedsince !== null) {
1697 $params['changedsince'] = $changedsince;
1698 $sqlwhere .= " AND timemodified > :changedsince";
1701 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1705 * Set a volatile flag
1707 * @param string $type the "type" namespace for the key
1708 * @param string $name the key to set
1709 * @param string $value the value to set (without magic quotes) - null will remove the flag
1710 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1711 * @return bool Always returns true
1713 function set_cache_flag($type, $name, $value, $expiry = null) {
1714 global $DB;
1716 $timemodified = time();
1717 if ($expiry === null || $expiry < $timemodified) {
1718 $expiry = $timemodified + 24 * 60 * 60;
1719 } else {
1720 $expiry = (int)$expiry;
1723 if ($value === null) {
1724 unset_cache_flag($type, $name);
1725 return true;
1728 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1729 // This is a potential problem in DEBUG_DEVELOPER.
1730 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1731 return true; // No need to update.
1733 $f->value = $value;
1734 $f->expiry = $expiry;
1735 $f->timemodified = $timemodified;
1736 $DB->update_record('cache_flags', $f);
1737 } else {
1738 $f = new stdClass();
1739 $f->flagtype = $type;
1740 $f->name = $name;
1741 $f->value = $value;
1742 $f->expiry = $expiry;
1743 $f->timemodified = $timemodified;
1744 $DB->insert_record('cache_flags', $f);
1746 return true;
1750 * Removes a single volatile flag
1752 * @param string $type the "type" namespace for the key
1753 * @param string $name the key to set
1754 * @return bool
1756 function unset_cache_flag($type, $name) {
1757 global $DB;
1758 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1759 return true;
1763 * Garbage-collect volatile flags
1765 * @return bool Always returns true
1767 function gc_cache_flags() {
1768 global $DB;
1769 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1770 return true;
1773 // USER PREFERENCE API.
1776 * Refresh user preference cache. This is used most often for $USER
1777 * object that is stored in session, but it also helps with performance in cron script.
1779 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1781 * @package core
1782 * @category preference
1783 * @access public
1784 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1785 * @param int $cachelifetime Cache life time on the current page (in seconds)
1786 * @throws coding_exception
1787 * @return null
1789 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1790 global $DB;
1791 // Static cache, we need to check on each page load, not only every 2 minutes.
1792 static $loadedusers = array();
1794 if (!isset($user->id)) {
1795 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1798 if (empty($user->id) or isguestuser($user->id)) {
1799 // No permanent storage for not-logged-in users and guest.
1800 if (!isset($user->preference)) {
1801 $user->preference = array();
1803 return;
1806 $timenow = time();
1808 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1809 // Already loaded at least once on this page. Are we up to date?
1810 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1811 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1812 return;
1814 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1815 // No change since the lastcheck on this page.
1816 $user->preference['_lastloaded'] = $timenow;
1817 return;
1821 // OK, so we have to reload all preferences.
1822 $loadedusers[$user->id] = true;
1823 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1824 $user->preference['_lastloaded'] = $timenow;
1828 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1830 * NOTE: internal function, do not call from other code.
1832 * @package core
1833 * @access private
1834 * @param integer $userid the user whose prefs were changed.
1836 function mark_user_preferences_changed($userid) {
1837 global $CFG;
1839 if (empty($userid) or isguestuser($userid)) {
1840 // No cache flags for guest and not-logged-in users.
1841 return;
1844 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1848 * Sets a preference for the specified user.
1850 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1852 * @package core
1853 * @category preference
1854 * @access public
1855 * @param string $name The key to set as preference for the specified user
1856 * @param string $value The value to set for the $name key in the specified user's
1857 * record, null means delete current value.
1858 * @param stdClass|int|null $user A moodle user object or id, null means current user
1859 * @throws coding_exception
1860 * @return bool Always true or exception
1862 function set_user_preference($name, $value, $user = null) {
1863 global $USER, $DB;
1865 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1866 throw new coding_exception('Invalid preference name in set_user_preference() call');
1869 if (is_null($value)) {
1870 // Null means delete current.
1871 return unset_user_preference($name, $user);
1872 } else if (is_object($value)) {
1873 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1874 } else if (is_array($value)) {
1875 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1877 // Value column maximum length is 1333 characters.
1878 $value = (string)$value;
1879 if (core_text::strlen($value) > 1333) {
1880 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1883 if (is_null($user)) {
1884 $user = $USER;
1885 } else if (isset($user->id)) {
1886 // It is a valid object.
1887 } else if (is_numeric($user)) {
1888 $user = (object)array('id' => (int)$user);
1889 } else {
1890 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1893 check_user_preferences_loaded($user);
1895 if (empty($user->id) or isguestuser($user->id)) {
1896 // No permanent storage for not-logged-in users and guest.
1897 $user->preference[$name] = $value;
1898 return true;
1901 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1902 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1903 // Preference already set to this value.
1904 return true;
1906 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1908 } else {
1909 $preference = new stdClass();
1910 $preference->userid = $user->id;
1911 $preference->name = $name;
1912 $preference->value = $value;
1913 $DB->insert_record('user_preferences', $preference);
1916 // Update value in cache.
1917 $user->preference[$name] = $value;
1919 // Set reload flag for other sessions.
1920 mark_user_preferences_changed($user->id);
1922 return true;
1926 * Sets a whole array of preferences for the current user
1928 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1930 * @package core
1931 * @category preference
1932 * @access public
1933 * @param array $prefarray An array of key/value pairs to be set
1934 * @param stdClass|int|null $user A moodle user object or id, null means current user
1935 * @return bool Always true or exception
1937 function set_user_preferences(array $prefarray, $user = null) {
1938 foreach ($prefarray as $name => $value) {
1939 set_user_preference($name, $value, $user);
1941 return true;
1945 * Unsets a preference completely by deleting it from the database
1947 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1949 * @package core
1950 * @category preference
1951 * @access public
1952 * @param string $name The key to unset as preference for the specified user
1953 * @param stdClass|int|null $user A moodle user object or id, null means current user
1954 * @throws coding_exception
1955 * @return bool Always true or exception
1957 function unset_user_preference($name, $user = null) {
1958 global $USER, $DB;
1960 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1961 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1964 if (is_null($user)) {
1965 $user = $USER;
1966 } else if (isset($user->id)) {
1967 // It is a valid object.
1968 } else if (is_numeric($user)) {
1969 $user = (object)array('id' => (int)$user);
1970 } else {
1971 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1974 check_user_preferences_loaded($user);
1976 if (empty($user->id) or isguestuser($user->id)) {
1977 // No permanent storage for not-logged-in user and guest.
1978 unset($user->preference[$name]);
1979 return true;
1982 // Delete from DB.
1983 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1985 // Delete the preference from cache.
1986 unset($user->preference[$name]);
1988 // Set reload flag for other sessions.
1989 mark_user_preferences_changed($user->id);
1991 return true;
1995 * Used to fetch user preference(s)
1997 * If no arguments are supplied this function will return
1998 * all of the current user preferences as an array.
2000 * If a name is specified then this function
2001 * attempts to return that particular preference value. If
2002 * none is found, then the optional value $default is returned,
2003 * otherwise null.
2005 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2007 * @package core
2008 * @category preference
2009 * @access public
2010 * @param string $name Name of the key to use in finding a preference value
2011 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
2012 * @param stdClass|int|null $user A moodle user object or id, null means current user
2013 * @throws coding_exception
2014 * @return string|mixed|null A string containing the value of a single preference. An
2015 * array with all of the preferences or null
2017 function get_user_preferences($name = null, $default = null, $user = null) {
2018 global $USER;
2020 if (is_null($name)) {
2021 // All prefs.
2022 } else if (is_numeric($name) or $name === '_lastloaded') {
2023 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2026 if (is_null($user)) {
2027 $user = $USER;
2028 } else if (isset($user->id)) {
2029 // Is a valid object.
2030 } else if (is_numeric($user)) {
2031 $user = (object)array('id' => (int)$user);
2032 } else {
2033 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2036 check_user_preferences_loaded($user);
2038 if (empty($name)) {
2039 // All values.
2040 return $user->preference;
2041 } else if (isset($user->preference[$name])) {
2042 // The single string value.
2043 return $user->preference[$name];
2044 } else {
2045 // Default value (null if not specified).
2046 return $default;
2050 // FUNCTIONS FOR HANDLING TIME.
2053 * Given Gregorian date parts in user time produce a GMT timestamp.
2055 * @package core
2056 * @category time
2057 * @param int $year The year part to create timestamp of
2058 * @param int $month The month part to create timestamp of
2059 * @param int $day The day part to create timestamp of
2060 * @param int $hour The hour part to create timestamp of
2061 * @param int $minute The minute part to create timestamp of
2062 * @param int $second The second part to create timestamp of
2063 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2064 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2065 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2066 * applied only if timezone is 99 or string.
2067 * @return int GMT timestamp
2069 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2070 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2071 $date->setDate((int)$year, (int)$month, (int)$day);
2072 $date->setTime((int)$hour, (int)$minute, (int)$second);
2074 $time = $date->getTimestamp();
2076 if ($time === false) {
2077 throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2078 ' This can fail if year is more than 2038 and OS is 32 bit windows');
2081 // Moodle BC DST stuff.
2082 if (!$applydst) {
2083 $time += dst_offset_on($time, $timezone);
2086 return $time;
2091 * Format a date/time (seconds) as weeks, days, hours etc as needed
2093 * Given an amount of time in seconds, returns string
2094 * formatted nicely as weeks, days, hours etc as needed
2096 * @package core
2097 * @category time
2098 * @uses MINSECS
2099 * @uses HOURSECS
2100 * @uses DAYSECS
2101 * @uses YEARSECS
2102 * @param int $totalsecs Time in seconds
2103 * @param stdClass $str Should be a time object
2104 * @return string A nicely formatted date/time string
2106 function format_time($totalsecs, $str = null) {
2108 $totalsecs = abs($totalsecs);
2110 if (!$str) {
2111 // Create the str structure the slow way.
2112 $str = new stdClass();
2113 $str->day = get_string('day');
2114 $str->days = get_string('days');
2115 $str->hour = get_string('hour');
2116 $str->hours = get_string('hours');
2117 $str->min = get_string('min');
2118 $str->mins = get_string('mins');
2119 $str->sec = get_string('sec');
2120 $str->secs = get_string('secs');
2121 $str->year = get_string('year');
2122 $str->years = get_string('years');
2125 $years = floor($totalsecs/YEARSECS);
2126 $remainder = $totalsecs - ($years*YEARSECS);
2127 $days = floor($remainder/DAYSECS);
2128 $remainder = $totalsecs - ($days*DAYSECS);
2129 $hours = floor($remainder/HOURSECS);
2130 $remainder = $remainder - ($hours*HOURSECS);
2131 $mins = floor($remainder/MINSECS);
2132 $secs = $remainder - ($mins*MINSECS);
2134 $ss = ($secs == 1) ? $str->sec : $str->secs;
2135 $sm = ($mins == 1) ? $str->min : $str->mins;
2136 $sh = ($hours == 1) ? $str->hour : $str->hours;
2137 $sd = ($days == 1) ? $str->day : $str->days;
2138 $sy = ($years == 1) ? $str->year : $str->years;
2140 $oyears = '';
2141 $odays = '';
2142 $ohours = '';
2143 $omins = '';
2144 $osecs = '';
2146 if ($years) {
2147 $oyears = $years .' '. $sy;
2149 if ($days) {
2150 $odays = $days .' '. $sd;
2152 if ($hours) {
2153 $ohours = $hours .' '. $sh;
2155 if ($mins) {
2156 $omins = $mins .' '. $sm;
2158 if ($secs) {
2159 $osecs = $secs .' '. $ss;
2162 if ($years) {
2163 return trim($oyears .' '. $odays);
2165 if ($days) {
2166 return trim($odays .' '. $ohours);
2168 if ($hours) {
2169 return trim($ohours .' '. $omins);
2171 if ($mins) {
2172 return trim($omins .' '. $osecs);
2174 if ($secs) {
2175 return $osecs;
2177 return get_string('now');
2181 * Returns a formatted string that represents a date in user time.
2183 * @package core
2184 * @category time
2185 * @param int $date the timestamp in UTC, as obtained from the database.
2186 * @param string $format strftime format. You should probably get this using
2187 * get_string('strftime...', 'langconfig');
2188 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2189 * not 99 then daylight saving will not be added.
2190 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2191 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2192 * If false then the leading zero is maintained.
2193 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2194 * @return string the formatted date/time.
2196 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2197 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2198 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2202 * Returns a formatted date ensuring it is UTF-8.
2204 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2205 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2207 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2208 * @param string $format strftime format.
2209 * @param int|float|string $tz the user timezone
2210 * @return string the formatted date/time.
2211 * @since Moodle 2.3.3
2213 function date_format_string($date, $format, $tz = 99) {
2214 global $CFG;
2216 $localewincharset = null;
2217 // Get the calendar type user is using.
2218 if ($CFG->ostype == 'WINDOWS') {
2219 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2220 $localewincharset = $calendartype->locale_win_charset();
2223 if ($localewincharset) {
2224 $format = core_text::convert($format, 'utf-8', $localewincharset);
2227 date_default_timezone_set(core_date::get_user_timezone($tz));
2228 $datestring = strftime($format, $date);
2229 core_date::set_default_server_timezone();
2231 if ($localewincharset) {
2232 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2235 return $datestring;
2239 * Given a $time timestamp in GMT (seconds since epoch),
2240 * returns an array that represents the Gregorian date in user time
2242 * @package core
2243 * @category time
2244 * @param int $time Timestamp in GMT
2245 * @param float|int|string $timezone user timezone
2246 * @return array An array that represents the date in user time
2248 function usergetdate($time, $timezone=99) {
2249 date_default_timezone_set(core_date::get_user_timezone($timezone));
2250 $result = getdate($time);
2251 core_date::set_default_server_timezone();
2253 return $result;
2257 * Given a GMT timestamp (seconds since epoch), offsets it by
2258 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2260 * NOTE: this function does not include DST properly,
2261 * you should use the PHP date stuff instead!
2263 * @package core
2264 * @category time
2265 * @param int $date Timestamp in GMT
2266 * @param float|int|string $timezone user timezone
2267 * @return int
2269 function usertime($date, $timezone=99) {
2270 $userdate = new DateTime('@' . $date);
2271 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2272 $dst = dst_offset_on($date, $timezone);
2274 return $date - $userdate->getOffset() + $dst;
2278 * Given a time, return the GMT timestamp of the most recent midnight
2279 * for the current user.
2281 * @package core
2282 * @category time
2283 * @param int $date Timestamp in GMT
2284 * @param float|int|string $timezone user timezone
2285 * @return int Returns a GMT timestamp
2287 function usergetmidnight($date, $timezone=99) {
2289 $userdate = usergetdate($date, $timezone);
2291 // Time of midnight of this user's day, in GMT.
2292 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2297 * Returns a string that prints the user's timezone
2299 * @package core
2300 * @category time
2301 * @param float|int|string $timezone user timezone
2302 * @return string
2304 function usertimezone($timezone=99) {
2305 $tz = core_date::get_user_timezone($timezone);
2306 return core_date::get_localised_timezone($tz);
2310 * Returns a float or a string which denotes the user's timezone
2311 * 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)
2312 * means that for this timezone there are also DST rules to be taken into account
2313 * Checks various settings and picks the most dominant of those which have a value
2315 * @package core
2316 * @category time
2317 * @param float|int|string $tz timezone to calculate GMT time offset before
2318 * calculating user timezone, 99 is default user timezone
2319 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2320 * @return float|string
2322 function get_user_timezone($tz = 99) {
2323 global $USER, $CFG;
2325 $timezones = array(
2326 $tz,
2327 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2328 isset($USER->timezone) ? $USER->timezone : 99,
2329 isset($CFG->timezone) ? $CFG->timezone : 99,
2332 $tz = 99;
2334 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2335 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2336 $tz = $next['value'];
2338 return is_numeric($tz) ? (float) $tz : $tz;
2342 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2343 * - Note: Daylight saving only works for string timezones and not for float.
2345 * @package core
2346 * @category time
2347 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2348 * @param int|float|string $strtimezone user timezone
2349 * @return int
2351 function dst_offset_on($time, $strtimezone = null) {
2352 $tz = core_date::get_user_timezone($strtimezone);
2353 $date = new DateTime('@' . $time);
2354 $date->setTimezone(new DateTimeZone($tz));
2355 if ($date->format('I') == '1') {
2356 if ($tz === 'Australia/Lord_Howe') {
2357 return 1800;
2359 return 3600;
2361 return 0;
2365 * Calculates when the day appears in specific month
2367 * @package core
2368 * @category time
2369 * @param int $startday starting day of the month
2370 * @param int $weekday The day when week starts (normally taken from user preferences)
2371 * @param int $month The month whose day is sought
2372 * @param int $year The year of the month whose day is sought
2373 * @return int
2375 function find_day_in_month($startday, $weekday, $month, $year) {
2376 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2378 $daysinmonth = days_in_month($month, $year);
2379 $daysinweek = count($calendartype->get_weekdays());
2381 if ($weekday == -1) {
2382 // Don't care about weekday, so return:
2383 // abs($startday) if $startday != -1
2384 // $daysinmonth otherwise.
2385 return ($startday == -1) ? $daysinmonth : abs($startday);
2388 // From now on we 're looking for a specific weekday.
2389 // Give "end of month" its actual value, since we know it.
2390 if ($startday == -1) {
2391 $startday = -1 * $daysinmonth;
2394 // Starting from day $startday, the sign is the direction.
2395 if ($startday < 1) {
2396 $startday = abs($startday);
2397 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2399 // This is the last such weekday of the month.
2400 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2401 if ($lastinmonth > $daysinmonth) {
2402 $lastinmonth -= $daysinweek;
2405 // Find the first such weekday <= $startday.
2406 while ($lastinmonth > $startday) {
2407 $lastinmonth -= $daysinweek;
2410 return $lastinmonth;
2411 } else {
2412 $indexweekday = dayofweek($startday, $month, $year);
2414 $diff = $weekday - $indexweekday;
2415 if ($diff < 0) {
2416 $diff += $daysinweek;
2419 // This is the first such weekday of the month equal to or after $startday.
2420 $firstfromindex = $startday + $diff;
2422 return $firstfromindex;
2427 * Calculate the number of days in a given month
2429 * @package core
2430 * @category time
2431 * @param int $month The month whose day count is sought
2432 * @param int $year The year of the month whose day count is sought
2433 * @return int
2435 function days_in_month($month, $year) {
2436 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2437 return $calendartype->get_num_days_in_month($year, $month);
2441 * Calculate the position in the week of a specific calendar day
2443 * @package core
2444 * @category time
2445 * @param int $day The day of the date whose position in the week is sought
2446 * @param int $month The month of the date whose position in the week is sought
2447 * @param int $year The year of the date whose position in the week is sought
2448 * @return int
2450 function dayofweek($day, $month, $year) {
2451 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2452 return $calendartype->get_weekday($year, $month, $day);
2455 // USER AUTHENTICATION AND LOGIN.
2458 * Returns full login url.
2460 * @return string login url
2462 function get_login_url() {
2463 global $CFG;
2465 $url = "$CFG->wwwroot/login/index.php";
2467 if (!empty($CFG->loginhttps)) {
2468 $url = str_replace('http:', 'https:', $url);
2471 return $url;
2475 * This function checks that the current user is logged in and has the
2476 * required privileges
2478 * This function checks that the current user is logged in, and optionally
2479 * whether they are allowed to be in a particular course and view a particular
2480 * course module.
2481 * If they are not logged in, then it redirects them to the site login unless
2482 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2483 * case they are automatically logged in as guests.
2484 * If $courseid is given and the user is not enrolled in that course then the
2485 * user is redirected to the course enrolment page.
2486 * If $cm is given and the course module is hidden and the user is not a teacher
2487 * in the course then the user is redirected to the course home page.
2489 * When $cm parameter specified, this function sets page layout to 'module'.
2490 * You need to change it manually later if some other layout needed.
2492 * @package core_access
2493 * @category access
2495 * @param mixed $courseorid id of the course or course object
2496 * @param bool $autologinguest default true
2497 * @param object $cm course module object
2498 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2499 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2500 * in order to keep redirects working properly. MDL-14495
2501 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2502 * @return mixed Void, exit, and die depending on path
2503 * @throws coding_exception
2504 * @throws require_login_exception
2506 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2507 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2509 // Must not redirect when byteserving already started.
2510 if (!empty($_SERVER['HTTP_RANGE'])) {
2511 $preventredirect = true;
2514 if (AJAX_SCRIPT) {
2515 // We cannot redirect for AJAX scripts either.
2516 $preventredirect = true;
2519 // Setup global $COURSE, themes, language and locale.
2520 if (!empty($courseorid)) {
2521 if (is_object($courseorid)) {
2522 $course = $courseorid;
2523 } else if ($courseorid == SITEID) {
2524 $course = clone($SITE);
2525 } else {
2526 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2528 if ($cm) {
2529 if ($cm->course != $course->id) {
2530 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2532 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2533 if (!($cm instanceof cm_info)) {
2534 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2535 // db queries so this is not really a performance concern, however it is obviously
2536 // better if you use get_fast_modinfo to get the cm before calling this.
2537 $modinfo = get_fast_modinfo($course);
2538 $cm = $modinfo->get_cm($cm->id);
2541 } else {
2542 // Do not touch global $COURSE via $PAGE->set_course(),
2543 // the reasons is we need to be able to call require_login() at any time!!
2544 $course = $SITE;
2545 if ($cm) {
2546 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2550 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2551 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2552 // risk leading the user back to the AJAX request URL.
2553 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2554 $setwantsurltome = false;
2557 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2558 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2559 if ($preventredirect) {
2560 throw new require_login_session_timeout_exception();
2561 } else {
2562 if ($setwantsurltome) {
2563 $SESSION->wantsurl = qualified_me();
2565 redirect(get_login_url());
2569 // If the user is not even logged in yet then make sure they are.
2570 if (!isloggedin()) {
2571 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2572 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2573 // Misconfigured site guest, just redirect to login page.
2574 redirect(get_login_url());
2575 exit; // Never reached.
2577 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2578 complete_user_login($guest);
2579 $USER->autologinguest = true;
2580 $SESSION->lang = $lang;
2581 } else {
2582 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2583 if ($preventredirect) {
2584 throw new require_login_exception('You are not logged in');
2587 if ($setwantsurltome) {
2588 $SESSION->wantsurl = qualified_me();
2591 $referer = get_local_referer(false);
2592 if (!empty($referer)) {
2593 $SESSION->fromurl = $referer;
2596 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2597 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2598 foreach($authsequence as $authname) {
2599 $authplugin = get_auth_plugin($authname);
2600 $authplugin->pre_loginpage_hook();
2601 if (isloggedin()) {
2602 break;
2606 // If we're still not logged in then go to the login page
2607 if (!isloggedin()) {
2608 redirect(get_login_url());
2609 exit; // Never reached.
2614 // Loginas as redirection if needed.
2615 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2616 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2617 if ($USER->loginascontext->instanceid != $course->id) {
2618 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2623 // Check whether the user should be changing password (but only if it is REALLY them).
2624 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2625 $userauth = get_auth_plugin($USER->auth);
2626 if ($userauth->can_change_password() and !$preventredirect) {
2627 if ($setwantsurltome) {
2628 $SESSION->wantsurl = qualified_me();
2630 if ($changeurl = $userauth->change_password_url()) {
2631 // Use plugin custom url.
2632 redirect($changeurl);
2633 } else {
2634 // Use moodle internal method.
2635 if (empty($CFG->loginhttps)) {
2636 redirect($CFG->wwwroot .'/login/change_password.php');
2637 } else {
2638 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2639 redirect($wwwroot .'/login/change_password.php');
2642 } else if ($userauth->can_change_password()) {
2643 throw new moodle_exception('forcepasswordchangenotice');
2644 } else {
2645 throw new moodle_exception('nopasswordchangeforced', 'auth');
2649 // Check that the user account is properly set up. If we can't redirect to
2650 // edit their profile, perform just the lax check. It will allow them to
2651 // use filepicker on the profile edit page.
2653 if ($preventredirect) {
2654 $usernotfullysetup = user_not_fully_set_up($USER, false);
2655 } else {
2656 $usernotfullysetup = user_not_fully_set_up($USER, true);
2659 if ($usernotfullysetup) {
2660 if ($preventredirect) {
2661 throw new moodle_exception('usernotfullysetup');
2663 if ($setwantsurltome) {
2664 $SESSION->wantsurl = qualified_me();
2666 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2669 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2670 sesskey();
2672 // Do not bother admins with any formalities.
2673 if (is_siteadmin()) {
2674 // Set the global $COURSE.
2675 if ($cm) {
2676 $PAGE->set_cm($cm, $course);
2677 $PAGE->set_pagelayout('incourse');
2678 } else if (!empty($courseorid)) {
2679 $PAGE->set_course($course);
2681 // Set accesstime or the user will appear offline which messes up messaging.
2682 user_accesstime_log($course->id);
2683 return;
2686 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2687 if (!$USER->policyagreed and !is_siteadmin()) {
2688 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2689 if ($preventredirect) {
2690 throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicy);
2692 if ($setwantsurltome) {
2693 $SESSION->wantsurl = qualified_me();
2695 redirect($CFG->wwwroot .'/user/policy.php');
2696 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2697 if ($preventredirect) {
2698 throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicyguest);
2700 if ($setwantsurltome) {
2701 $SESSION->wantsurl = qualified_me();
2703 redirect($CFG->wwwroot .'/user/policy.php');
2707 // Fetch the system context, the course context, and prefetch its child contexts.
2708 $sysctx = context_system::instance();
2709 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2710 if ($cm) {
2711 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2712 } else {
2713 $cmcontext = null;
2716 // If the site is currently under maintenance, then print a message.
2717 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2718 if ($preventredirect) {
2719 throw new require_login_exception('Maintenance in progress');
2721 $PAGE->set_context(null);
2722 print_maintenance_message();
2725 // Make sure the course itself is not hidden.
2726 if ($course->id == SITEID) {
2727 // Frontpage can not be hidden.
2728 } else {
2729 if (is_role_switched($course->id)) {
2730 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2731 } else {
2732 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2733 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2734 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2735 if ($preventredirect) {
2736 throw new require_login_exception('Course is hidden');
2738 $PAGE->set_context(null);
2739 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2740 // the navigation will mess up when trying to find it.
2741 navigation_node::override_active_url(new moodle_url('/'));
2742 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2747 // Is the user enrolled?
2748 if ($course->id == SITEID) {
2749 // Everybody is enrolled on the frontpage.
2750 } else {
2751 if (\core\session\manager::is_loggedinas()) {
2752 // Make sure the REAL person can access this course first.
2753 $realuser = \core\session\manager::get_realuser();
2754 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2755 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2756 if ($preventredirect) {
2757 throw new require_login_exception('Invalid course login-as access');
2759 $PAGE->set_context(null);
2760 echo $OUTPUT->header();
2761 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2765 $access = false;
2767 if (is_role_switched($course->id)) {
2768 // Ok, user had to be inside this course before the switch.
2769 $access = true;
2771 } else if (is_viewing($coursecontext, $USER)) {
2772 // Ok, no need to mess with enrol.
2773 $access = true;
2775 } else {
2776 if (isset($USER->enrol['enrolled'][$course->id])) {
2777 if ($USER->enrol['enrolled'][$course->id] > time()) {
2778 $access = true;
2779 if (isset($USER->enrol['tempguest'][$course->id])) {
2780 unset($USER->enrol['tempguest'][$course->id]);
2781 remove_temp_course_roles($coursecontext);
2783 } else {
2784 // Expired.
2785 unset($USER->enrol['enrolled'][$course->id]);
2788 if (isset($USER->enrol['tempguest'][$course->id])) {
2789 if ($USER->enrol['tempguest'][$course->id] == 0) {
2790 $access = true;
2791 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2792 $access = true;
2793 } else {
2794 // Expired.
2795 unset($USER->enrol['tempguest'][$course->id]);
2796 remove_temp_course_roles($coursecontext);
2800 if (!$access) {
2801 // Cache not ok.
2802 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2803 if ($until !== false) {
2804 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2805 if ($until == 0) {
2806 $until = ENROL_MAX_TIMESTAMP;
2808 $USER->enrol['enrolled'][$course->id] = $until;
2809 $access = true;
2811 } else {
2812 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2813 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2814 $enrols = enrol_get_plugins(true);
2815 // First ask all enabled enrol instances in course if they want to auto enrol user.
2816 foreach ($instances as $instance) {
2817 if (!isset($enrols[$instance->enrol])) {
2818 continue;
2820 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2821 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2822 if ($until !== false) {
2823 if ($until == 0) {
2824 $until = ENROL_MAX_TIMESTAMP;
2826 $USER->enrol['enrolled'][$course->id] = $until;
2827 $access = true;
2828 break;
2831 // If not enrolled yet try to gain temporary guest access.
2832 if (!$access) {
2833 foreach ($instances as $instance) {
2834 if (!isset($enrols[$instance->enrol])) {
2835 continue;
2837 // Get a duration for the guest access, a timestamp in the future or false.
2838 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2839 if ($until !== false and $until > time()) {
2840 $USER->enrol['tempguest'][$course->id] = $until;
2841 $access = true;
2842 break;
2850 if (!$access) {
2851 if ($preventredirect) {
2852 throw new require_login_exception('Not enrolled');
2854 if ($setwantsurltome) {
2855 $SESSION->wantsurl = qualified_me();
2857 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2861 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2862 if ($cm && !$cm->uservisible) {
2863 if ($preventredirect) {
2864 throw new require_login_exception('Activity is hidden');
2866 if ($course->id != SITEID) {
2867 $url = new moodle_url('/course/view.php', array('id' => $course->id));
2868 } else {
2869 $url = new moodle_url('/');
2871 redirect($url, get_string('activityiscurrentlyhidden'));
2874 // Set the global $COURSE.
2875 if ($cm) {
2876 $PAGE->set_cm($cm, $course);
2877 $PAGE->set_pagelayout('incourse');
2878 } else if (!empty($courseorid)) {
2879 $PAGE->set_course($course);
2882 // Finally access granted, update lastaccess times.
2883 user_accesstime_log($course->id);
2888 * This function just makes sure a user is logged out.
2890 * @package core_access
2891 * @category access
2893 function require_logout() {
2894 global $USER, $DB;
2896 if (!isloggedin()) {
2897 // This should not happen often, no need for hooks or events here.
2898 \core\session\manager::terminate_current();
2899 return;
2902 // Execute hooks before action.
2903 $authplugins = array();
2904 $authsequence = get_enabled_auth_plugins();
2905 foreach ($authsequence as $authname) {
2906 $authplugins[$authname] = get_auth_plugin($authname);
2907 $authplugins[$authname]->prelogout_hook();
2910 // Store info that gets removed during logout.
2911 $sid = session_id();
2912 $event = \core\event\user_loggedout::create(
2913 array(
2914 'userid' => $USER->id,
2915 'objectid' => $USER->id,
2916 'other' => array('sessionid' => $sid),
2919 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2920 $event->add_record_snapshot('sessions', $session);
2923 // Clone of $USER object to be used by auth plugins.
2924 $user = fullclone($USER);
2926 // Delete session record and drop $_SESSION content.
2927 \core\session\manager::terminate_current();
2929 // Trigger event AFTER action.
2930 $event->trigger();
2932 // Hook to execute auth plugins redirection after event trigger.
2933 foreach ($authplugins as $authplugin) {
2934 $authplugin->postlogout_hook($user);
2939 * Weaker version of require_login()
2941 * This is a weaker version of {@link require_login()} which only requires login
2942 * when called from within a course rather than the site page, unless
2943 * the forcelogin option is turned on.
2944 * @see require_login()
2946 * @package core_access
2947 * @category access
2949 * @param mixed $courseorid The course object or id in question
2950 * @param bool $autologinguest Allow autologin guests if that is wanted
2951 * @param object $cm Course activity module if known
2952 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2953 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2954 * in order to keep redirects working properly. MDL-14495
2955 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2956 * @return void
2957 * @throws coding_exception
2959 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2960 global $CFG, $PAGE, $SITE;
2961 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2962 or (!is_object($courseorid) and $courseorid == SITEID));
2963 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2964 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2965 // db queries so this is not really a performance concern, however it is obviously
2966 // better if you use get_fast_modinfo to get the cm before calling this.
2967 if (is_object($courseorid)) {
2968 $course = $courseorid;
2969 } else {
2970 $course = clone($SITE);
2972 $modinfo = get_fast_modinfo($course);
2973 $cm = $modinfo->get_cm($cm->id);
2975 if (!empty($CFG->forcelogin)) {
2976 // Login required for both SITE and courses.
2977 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2979 } else if ($issite && !empty($cm) and !$cm->uservisible) {
2980 // Always login for hidden activities.
2981 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2983 } else if ($issite) {
2984 // Login for SITE not required.
2985 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
2986 if (!empty($courseorid)) {
2987 if (is_object($courseorid)) {
2988 $course = $courseorid;
2989 } else {
2990 $course = clone $SITE;
2992 if ($cm) {
2993 if ($cm->course != $course->id) {
2994 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2996 $PAGE->set_cm($cm, $course);
2997 $PAGE->set_pagelayout('incourse');
2998 } else {
2999 $PAGE->set_course($course);
3001 } else {
3002 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3003 $PAGE->set_course($PAGE->course);
3005 user_accesstime_log(SITEID);
3006 return;
3008 } else {
3009 // Course login always required.
3010 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3015 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3017 * @param string $keyvalue the key value
3018 * @param string $script unique script identifier
3019 * @param int $instance instance id
3020 * @return stdClass the key entry in the user_private_key table
3021 * @since Moodle 3.2
3022 * @throws moodle_exception
3024 function validate_user_key($keyvalue, $script, $instance) {
3025 global $DB;
3027 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3028 print_error('invalidkey');
3031 if (!empty($key->validuntil) and $key->validuntil < time()) {
3032 print_error('expiredkey');
3035 if ($key->iprestriction) {
3036 $remoteaddr = getremoteaddr(null);
3037 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3038 print_error('ipmismatch');
3041 return $key;
3045 * Require key login. Function terminates with error if key not found or incorrect.
3047 * @uses NO_MOODLE_COOKIES
3048 * @uses PARAM_ALPHANUM
3049 * @param string $script unique script identifier
3050 * @param int $instance optional instance id
3051 * @return int Instance ID
3053 function require_user_key_login($script, $instance=null) {
3054 global $DB;
3056 if (!NO_MOODLE_COOKIES) {
3057 print_error('sessioncookiesdisable');
3060 // Extra safety.
3061 \core\session\manager::write_close();
3063 $keyvalue = required_param('key', PARAM_ALPHANUM);
3065 $key = validate_user_key($keyvalue, $script, $instance);
3067 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3068 print_error('invaliduserid');
3071 // Emulate normal session.
3072 enrol_check_plugins($user);
3073 \core\session\manager::set_user($user);
3075 // Note we are not using normal login.
3076 if (!defined('USER_KEY_LOGIN')) {
3077 define('USER_KEY_LOGIN', true);
3080 // Return instance id - it might be empty.
3081 return $key->instance;
3085 * Creates a new private user access key.
3087 * @param string $script unique target identifier
3088 * @param int $userid
3089 * @param int $instance optional instance id
3090 * @param string $iprestriction optional ip restricted access
3091 * @param int $validuntil key valid only until given data
3092 * @return string access key value
3094 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3095 global $DB;
3097 $key = new stdClass();
3098 $key->script = $script;
3099 $key->userid = $userid;
3100 $key->instance = $instance;
3101 $key->iprestriction = $iprestriction;
3102 $key->validuntil = $validuntil;
3103 $key->timecreated = time();
3105 // Something long and unique.
3106 $key->value = md5($userid.'_'.time().random_string(40));
3107 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3108 // Must be unique.
3109 $key->value = md5($userid.'_'.time().random_string(40));
3111 $DB->insert_record('user_private_key', $key);
3112 return $key->value;
3116 * Delete the user's new private user access keys for a particular script.
3118 * @param string $script unique target identifier
3119 * @param int $userid
3120 * @return void
3122 function delete_user_key($script, $userid) {
3123 global $DB;
3124 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3128 * Gets a private user access key (and creates one if one doesn't exist).
3130 * @param string $script unique target identifier
3131 * @param int $userid
3132 * @param int $instance optional instance id
3133 * @param string $iprestriction optional ip restricted access
3134 * @param int $validuntil key valid only until given date
3135 * @return string access key value
3137 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3138 global $DB;
3140 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3141 'instance' => $instance, 'iprestriction' => $iprestriction,
3142 'validuntil' => $validuntil))) {
3143 return $key->value;
3144 } else {
3145 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3151 * Modify the user table by setting the currently logged in user's last login to now.
3153 * @return bool Always returns true
3155 function update_user_login_times() {
3156 global $USER, $DB;
3158 if (isguestuser()) {
3159 // Do not update guest access times/ips for performance.
3160 return true;
3163 $now = time();
3165 $user = new stdClass();
3166 $user->id = $USER->id;
3168 // Make sure all users that logged in have some firstaccess.
3169 if ($USER->firstaccess == 0) {
3170 $USER->firstaccess = $user->firstaccess = $now;
3173 // Store the previous current as lastlogin.
3174 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3176 $USER->currentlogin = $user->currentlogin = $now;
3178 // Function user_accesstime_log() may not update immediately, better do it here.
3179 $USER->lastaccess = $user->lastaccess = $now;
3180 $USER->lastip = $user->lastip = getremoteaddr();
3182 // Note: do not call user_update_user() here because this is part of the login process,
3183 // the login event means that these fields were updated.
3184 $DB->update_record('user', $user);
3185 return true;
3189 * Determines if a user has completed setting up their account.
3191 * The lax mode (with $strict = false) has been introduced for special cases
3192 * only where we want to skip certain checks intentionally. This is valid in
3193 * certain mnet or ajax scenarios when the user cannot / should not be
3194 * redirected to edit their profile. In most cases, you should perform the
3195 * strict check.
3197 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3198 * @param bool $strict Be more strict and assert id and custom profile fields set, too
3199 * @return bool
3201 function user_not_fully_set_up($user, $strict = true) {
3202 global $CFG;
3203 require_once($CFG->dirroot.'/user/profile/lib.php');
3205 if (isguestuser($user)) {
3206 return false;
3209 if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3210 return true;
3213 if ($strict) {
3214 if (empty($user->id)) {
3215 // Strict mode can be used with existing accounts only.
3216 return true;
3218 if (!profile_has_required_custom_fields_set($user->id)) {
3219 return true;
3223 return false;
3227 * Check whether the user has exceeded the bounce threshold
3229 * @param stdClass $user A {@link $USER} object
3230 * @return bool true => User has exceeded bounce threshold
3232 function over_bounce_threshold($user) {
3233 global $CFG, $DB;
3235 if (empty($CFG->handlebounces)) {
3236 return false;
3239 if (empty($user->id)) {
3240 // No real (DB) user, nothing to do here.
3241 return false;
3244 // Set sensible defaults.
3245 if (empty($CFG->minbounces)) {
3246 $CFG->minbounces = 10;
3248 if (empty($CFG->bounceratio)) {
3249 $CFG->bounceratio = .20;
3251 $bouncecount = 0;
3252 $sendcount = 0;
3253 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3254 $bouncecount = $bounce->value;
3256 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3257 $sendcount = $send->value;
3259 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3263 * Used to increment or reset email sent count
3265 * @param stdClass $user object containing an id
3266 * @param bool $reset will reset the count to 0
3267 * @return void
3269 function set_send_count($user, $reset=false) {
3270 global $DB;
3272 if (empty($user->id)) {
3273 // No real (DB) user, nothing to do here.
3274 return;
3277 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3278 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3279 $DB->update_record('user_preferences', $pref);
3280 } else if (!empty($reset)) {
3281 // If it's not there and we're resetting, don't bother. Make a new one.
3282 $pref = new stdClass();
3283 $pref->name = 'email_send_count';
3284 $pref->value = 1;
3285 $pref->userid = $user->id;
3286 $DB->insert_record('user_preferences', $pref, false);
3291 * Increment or reset user's email bounce count
3293 * @param stdClass $user object containing an id
3294 * @param bool $reset will reset the count to 0
3296 function set_bounce_count($user, $reset=false) {
3297 global $DB;
3299 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3300 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3301 $DB->update_record('user_preferences', $pref);
3302 } else if (!empty($reset)) {
3303 // If it's not there and we're resetting, don't bother. Make a new one.
3304 $pref = new stdClass();
3305 $pref->name = 'email_bounce_count';
3306 $pref->value = 1;
3307 $pref->userid = $user->id;
3308 $DB->insert_record('user_preferences', $pref, false);
3313 * Determines if the logged in user is currently moving an activity
3315 * @param int $courseid The id of the course being tested
3316 * @return bool
3318 function ismoving($courseid) {
3319 global $USER;
3321 if (!empty($USER->activitycopy)) {
3322 return ($USER->activitycopycourse == $courseid);
3324 return false;
3328 * Returns a persons full name
3330 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3331 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3332 * specify one.
3334 * @param stdClass $user A {@link $USER} object to get full name of.
3335 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3336 * @return string
3338 function fullname($user, $override=false) {
3339 global $CFG, $SESSION;
3341 if (!isset($user->firstname) and !isset($user->lastname)) {
3342 return '';
3345 // Get all of the name fields.
3346 $allnames = get_all_user_name_fields();
3347 if ($CFG->debugdeveloper) {
3348 foreach ($allnames as $allname) {
3349 if (!property_exists($user, $allname)) {
3350 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3351 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3352 // Message has been sent, no point in sending the message multiple times.
3353 break;
3358 if (!$override) {
3359 if (!empty($CFG->forcefirstname)) {
3360 $user->firstname = $CFG->forcefirstname;
3362 if (!empty($CFG->forcelastname)) {
3363 $user->lastname = $CFG->forcelastname;
3367 if (!empty($SESSION->fullnamedisplay)) {
3368 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3371 $template = null;
3372 // If the fullnamedisplay setting is available, set the template to that.
3373 if (isset($CFG->fullnamedisplay)) {
3374 $template = $CFG->fullnamedisplay;
3376 // If the template is empty, or set to language, return the language string.
3377 if ((empty($template) || $template == 'language') && !$override) {
3378 return get_string('fullnamedisplay', null, $user);
3381 // Check to see if we are displaying according to the alternative full name format.
3382 if ($override) {
3383 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3384 // Default to show just the user names according to the fullnamedisplay string.
3385 return get_string('fullnamedisplay', null, $user);
3386 } else {
3387 // If the override is true, then change the template to use the complete name.
3388 $template = $CFG->alternativefullnameformat;
3392 $requirednames = array();
3393 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3394 foreach ($allnames as $allname) {
3395 if (strpos($template, $allname) !== false) {
3396 $requirednames[] = $allname;
3400 $displayname = $template;
3401 // Switch in the actual data into the template.
3402 foreach ($requirednames as $altname) {
3403 if (isset($user->$altname)) {
3404 // Using empty() on the below if statement causes breakages.
3405 if ((string)$user->$altname == '') {
3406 $displayname = str_replace($altname, 'EMPTY', $displayname);
3407 } else {
3408 $displayname = str_replace($altname, $user->$altname, $displayname);
3410 } else {
3411 $displayname = str_replace($altname, 'EMPTY', $displayname);
3414 // Tidy up any misc. characters (Not perfect, but gets most characters).
3415 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3416 // katakana and parenthesis.
3417 $patterns = array();
3418 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3419 // filled in by a user.
3420 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3421 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3422 // This regular expression is to remove any double spaces in the display name.
3423 $patterns[] = '/\s{2,}/u';
3424 foreach ($patterns as $pattern) {
3425 $displayname = preg_replace($pattern, ' ', $displayname);
3428 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3429 $displayname = trim($displayname);
3430 if (empty($displayname)) {
3431 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3432 // people in general feel is a good setting to fall back on.
3433 $displayname = $user->firstname;
3435 return $displayname;
3439 * A centralised location for the all name fields. Returns an array / sql string snippet.
3441 * @param bool $returnsql True for an sql select field snippet.
3442 * @param string $tableprefix table query prefix to use in front of each field.
3443 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3444 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3445 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3446 * @return array|string All name fields.
3448 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3449 // This array is provided in this order because when called by fullname() (above) if firstname is before
3450 // firstnamephonetic str_replace() will change the wrong placeholder.
3451 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3452 'lastnamephonetic' => 'lastnamephonetic',
3453 'middlename' => 'middlename',
3454 'alternatename' => 'alternatename',
3455 'firstname' => 'firstname',
3456 'lastname' => 'lastname');
3458 // Let's add a prefix to the array of user name fields if provided.
3459 if ($prefix) {
3460 foreach ($alternatenames as $key => $altname) {
3461 $alternatenames[$key] = $prefix . $altname;
3465 // If we want the end result to have firstname and lastname at the front / top of the result.
3466 if ($order) {
3467 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3468 for ($i = 0; $i < 2; $i++) {
3469 // Get the last element.
3470 $lastelement = end($alternatenames);
3471 // Remove it from the array.
3472 unset($alternatenames[$lastelement]);
3473 // Put the element back on the top of the array.
3474 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3478 // Create an sql field snippet if requested.
3479 if ($returnsql) {
3480 if ($tableprefix) {
3481 if ($fieldprefix) {
3482 foreach ($alternatenames as $key => $altname) {
3483 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3485 } else {
3486 foreach ($alternatenames as $key => $altname) {
3487 $alternatenames[$key] = $tableprefix . '.' . $altname;
3491 $alternatenames = implode(',', $alternatenames);
3493 return $alternatenames;
3497 * Reduces lines of duplicated code for getting user name fields.
3499 * See also {@link user_picture::unalias()}
3501 * @param object $addtoobject Object to add user name fields to.
3502 * @param object $secondobject Object that contains user name field information.
3503 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3504 * @param array $additionalfields Additional fields to be matched with data in the second object.
3505 * The key can be set to the user table field name.
3506 * @return object User name fields.
3508 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3509 $fields = get_all_user_name_fields(false, null, $prefix);
3510 if ($additionalfields) {
3511 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3512 // the key is a number and then sets the key to the array value.
3513 foreach ($additionalfields as $key => $value) {
3514 if (is_numeric($key)) {
3515 $additionalfields[$value] = $prefix . $value;
3516 unset($additionalfields[$key]);
3517 } else {
3518 $additionalfields[$key] = $prefix . $value;
3521 $fields = array_merge($fields, $additionalfields);
3523 foreach ($fields as $key => $field) {
3524 // Important that we have all of the user name fields present in the object that we are sending back.
3525 $addtoobject->$key = '';
3526 if (isset($secondobject->$field)) {
3527 $addtoobject->$key = $secondobject->$field;
3530 return $addtoobject;
3534 * Returns an array of values in order of occurance in a provided string.
3535 * The key in the result is the character postion in the string.
3537 * @param array $values Values to be found in the string format
3538 * @param string $stringformat The string which may contain values being searched for.
3539 * @return array An array of values in order according to placement in the string format.
3541 function order_in_string($values, $stringformat) {
3542 $valuearray = array();
3543 foreach ($values as $value) {
3544 $pattern = "/$value\b/";
3545 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3546 if (preg_match($pattern, $stringformat)) {
3547 $replacement = "thing";
3548 // Replace the value with something more unique to ensure we get the right position when using strpos().
3549 $newformat = preg_replace($pattern, $replacement, $stringformat);
3550 $position = strpos($newformat, $replacement);
3551 $valuearray[$position] = $value;
3554 ksort($valuearray);
3555 return $valuearray;
3559 * Checks if current user is shown any extra fields when listing users.
3561 * @param object $context Context
3562 * @param array $already Array of fields that we're going to show anyway
3563 * so don't bother listing them
3564 * @return array Array of field names from user table, not including anything
3565 * listed in $already
3567 function get_extra_user_fields($context, $already = array()) {
3568 global $CFG;
3570 // Only users with permission get the extra fields.
3571 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3572 return array();
3575 // Split showuseridentity on comma.
3576 if (empty($CFG->showuseridentity)) {
3577 // Explode gives wrong result with empty string.
3578 $extra = array();
3579 } else {
3580 $extra = explode(',', $CFG->showuseridentity);
3582 $renumber = false;
3583 foreach ($extra as $key => $field) {
3584 if (in_array($field, $already)) {
3585 unset($extra[$key]);
3586 $renumber = true;
3589 if ($renumber) {
3590 // For consistency, if entries are removed from array, renumber it
3591 // so they are numbered as you would expect.
3592 $extra = array_merge($extra);
3594 return $extra;
3598 * If the current user is to be shown extra user fields when listing or
3599 * selecting users, returns a string suitable for including in an SQL select
3600 * clause to retrieve those fields.
3602 * @param context $context Context
3603 * @param string $alias Alias of user table, e.g. 'u' (default none)
3604 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3605 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3606 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3608 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3609 $fields = get_extra_user_fields($context, $already);
3610 $result = '';
3611 // Add punctuation for alias.
3612 if ($alias !== '') {
3613 $alias .= '.';
3615 foreach ($fields as $field) {
3616 $result .= ', ' . $alias . $field;
3617 if ($prefix) {
3618 $result .= ' AS ' . $prefix . $field;
3621 return $result;
3625 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3626 * @param string $field Field name, e.g. 'phone1'
3627 * @return string Text description taken from language file, e.g. 'Phone number'
3629 function get_user_field_name($field) {
3630 // Some fields have language strings which are not the same as field name.
3631 switch ($field) {
3632 case 'url' : {
3633 return get_string('webpage');
3635 case 'icq' : {
3636 return get_string('icqnumber');
3638 case 'skype' : {
3639 return get_string('skypeid');
3641 case 'aim' : {
3642 return get_string('aimid');
3644 case 'yahoo' : {
3645 return get_string('yahooid');
3647 case 'msn' : {
3648 return get_string('msnid');
3651 // Otherwise just use the same lang string.
3652 return get_string($field);
3656 * Returns whether a given authentication plugin exists.
3658 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3659 * @return boolean Whether the plugin is available.
3661 function exists_auth_plugin($auth) {
3662 global $CFG;
3664 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3665 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3667 return false;
3671 * Checks if a given plugin is in the list of enabled authentication plugins.
3673 * @param string $auth Authentication plugin.
3674 * @return boolean Whether the plugin is enabled.
3676 function is_enabled_auth($auth) {
3677 if (empty($auth)) {
3678 return false;
3681 $enabled = get_enabled_auth_plugins();
3683 return in_array($auth, $enabled);
3687 * Returns an authentication plugin instance.
3689 * @param string $auth name of authentication plugin
3690 * @return auth_plugin_base An instance of the required authentication plugin.
3692 function get_auth_plugin($auth) {
3693 global $CFG;
3695 // Check the plugin exists first.
3696 if (! exists_auth_plugin($auth)) {
3697 print_error('authpluginnotfound', 'debug', '', $auth);
3700 // Return auth plugin instance.
3701 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3702 $class = "auth_plugin_$auth";
3703 return new $class;
3707 * Returns array of active auth plugins.
3709 * @param bool $fix fix $CFG->auth if needed
3710 * @return array
3712 function get_enabled_auth_plugins($fix=false) {
3713 global $CFG;
3715 $default = array('manual', 'nologin');
3717 if (empty($CFG->auth)) {
3718 $auths = array();
3719 } else {
3720 $auths = explode(',', $CFG->auth);
3723 if ($fix) {
3724 $auths = array_unique($auths);
3725 foreach ($auths as $k => $authname) {
3726 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3727 unset($auths[$k]);
3730 $newconfig = implode(',', $auths);
3731 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3732 set_config('auth', $newconfig);
3736 return (array_merge($default, $auths));
3740 * Returns true if an internal authentication method is being used.
3741 * if method not specified then, global default is assumed
3743 * @param string $auth Form of authentication required
3744 * @return bool
3746 function is_internal_auth($auth) {
3747 // Throws error if bad $auth.
3748 $authplugin = get_auth_plugin($auth);
3749 return $authplugin->is_internal();
3753 * Returns true if the user is a 'restored' one.
3755 * Used in the login process to inform the user and allow him/her to reset the password
3757 * @param string $username username to be checked
3758 * @return bool
3760 function is_restored_user($username) {
3761 global $CFG, $DB;
3763 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3767 * Returns an array of user fields
3769 * @return array User field/column names
3771 function get_user_fieldnames() {
3772 global $DB;
3774 $fieldarray = $DB->get_columns('user');
3775 unset($fieldarray['id']);
3776 $fieldarray = array_keys($fieldarray);
3778 return $fieldarray;
3782 * Creates a bare-bones user record
3784 * @todo Outline auth types and provide code example
3786 * @param string $username New user's username to add to record
3787 * @param string $password New user's password to add to record
3788 * @param string $auth Form of authentication required
3789 * @return stdClass A complete user object
3791 function create_user_record($username, $password, $auth = 'manual') {
3792 global $CFG, $DB;
3793 require_once($CFG->dirroot.'/user/profile/lib.php');
3794 require_once($CFG->dirroot.'/user/lib.php');
3796 // Just in case check text case.
3797 $username = trim(core_text::strtolower($username));
3799 $authplugin = get_auth_plugin($auth);
3800 $customfields = $authplugin->get_custom_user_profile_fields();
3801 $newuser = new stdClass();
3802 if ($newinfo = $authplugin->get_userinfo($username)) {
3803 $newinfo = truncate_userinfo($newinfo);
3804 foreach ($newinfo as $key => $value) {
3805 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3806 $newuser->$key = $value;
3811 if (!empty($newuser->email)) {
3812 if (email_is_not_allowed($newuser->email)) {
3813 unset($newuser->email);
3817 if (!isset($newuser->city)) {
3818 $newuser->city = '';
3821 $newuser->auth = $auth;
3822 $newuser->username = $username;
3824 // Fix for MDL-8480
3825 // user CFG lang for user if $newuser->lang is empty
3826 // or $user->lang is not an installed language.
3827 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3828 $newuser->lang = $CFG->lang;
3830 $newuser->confirmed = 1;
3831 $newuser->lastip = getremoteaddr();
3832 $newuser->timecreated = time();
3833 $newuser->timemodified = $newuser->timecreated;
3834 $newuser->mnethostid = $CFG->mnet_localhost_id;
3836 $newuser->id = user_create_user($newuser, false, false);
3838 // Save user profile data.
3839 profile_save_data($newuser);
3841 $user = get_complete_user_data('id', $newuser->id);
3842 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3843 set_user_preference('auth_forcepasswordchange', 1, $user);
3845 // Set the password.
3846 update_internal_user_password($user, $password);
3848 // Trigger event.
3849 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3851 return $user;
3855 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3857 * @param string $username user's username to update the record
3858 * @return stdClass A complete user object
3860 function update_user_record($username) {
3861 global $DB, $CFG;
3862 // Just in case check text case.
3863 $username = trim(core_text::strtolower($username));
3865 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3866 return update_user_record_by_id($oldinfo->id);
3870 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3872 * @param int $id user id
3873 * @return stdClass A complete user object
3875 function update_user_record_by_id($id) {
3876 global $DB, $CFG;
3877 require_once($CFG->dirroot."/user/profile/lib.php");
3878 require_once($CFG->dirroot.'/user/lib.php');
3880 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3881 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3883 $newuser = array();
3884 $userauth = get_auth_plugin($oldinfo->auth);
3886 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3887 $newinfo = truncate_userinfo($newinfo);
3888 $customfields = $userauth->get_custom_user_profile_fields();
3890 foreach ($newinfo as $key => $value) {
3891 $iscustom = in_array($key, $customfields);
3892 if (!$iscustom) {
3893 $key = strtolower($key);
3895 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3896 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3897 // Unknown or must not be changed.
3898 continue;
3900 $confval = $userauth->config->{'field_updatelocal_' . $key};
3901 $lockval = $userauth->config->{'field_lock_' . $key};
3902 if (empty($confval) || empty($lockval)) {
3903 continue;
3905 if ($confval === 'onlogin') {
3906 // MDL-4207 Don't overwrite modified user profile values with
3907 // empty LDAP values when 'unlocked if empty' is set. The purpose
3908 // of the setting 'unlocked if empty' is to allow the user to fill
3909 // in a value for the selected field _if LDAP is giving
3910 // nothing_ for this field. Thus it makes sense to let this value
3911 // stand in until LDAP is giving a value for this field.
3912 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3913 if ($iscustom || (in_array($key, $userauth->userfields) &&
3914 ((string)$oldinfo->$key !== (string)$value))) {
3915 $newuser[$key] = (string)$value;
3920 if ($newuser) {
3921 $newuser['id'] = $oldinfo->id;
3922 $newuser['timemodified'] = time();
3923 user_update_user((object) $newuser, false, false);
3925 // Save user profile data.
3926 profile_save_data((object) $newuser);
3928 // Trigger event.
3929 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
3933 return get_complete_user_data('id', $oldinfo->id);
3937 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
3939 * @param array $info Array of user properties to truncate if needed
3940 * @return array The now truncated information that was passed in
3942 function truncate_userinfo(array $info) {
3943 // Define the limits.
3944 $limit = array(
3945 'username' => 100,
3946 'idnumber' => 255,
3947 'firstname' => 100,
3948 'lastname' => 100,
3949 'email' => 100,
3950 'icq' => 15,
3951 'phone1' => 20,
3952 'phone2' => 20,
3953 'institution' => 255,
3954 'department' => 255,
3955 'address' => 255,
3956 'city' => 120,
3957 'country' => 2,
3958 'url' => 255,
3961 // Apply where needed.
3962 foreach (array_keys($info) as $key) {
3963 if (!empty($limit[$key])) {
3964 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
3968 return $info;
3972 * Marks user deleted in internal user database and notifies the auth plugin.
3973 * Also unenrols user from all roles and does other cleanup.
3975 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3977 * @param stdClass $user full user object before delete
3978 * @return boolean success
3979 * @throws coding_exception if invalid $user parameter detected
3981 function delete_user(stdClass $user) {
3982 global $CFG, $DB;
3983 require_once($CFG->libdir.'/grouplib.php');
3984 require_once($CFG->libdir.'/gradelib.php');
3985 require_once($CFG->dirroot.'/message/lib.php');
3986 require_once($CFG->dirroot.'/user/lib.php');
3988 // Make sure nobody sends bogus record type as parameter.
3989 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
3990 throw new coding_exception('Invalid $user parameter in delete_user() detected');
3993 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
3994 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
3995 debugging('Attempt to delete unknown user account.');
3996 return false;
3999 // There must be always exactly one guest record, originally the guest account was identified by username only,
4000 // now we use $CFG->siteguest for performance reasons.
4001 if ($user->username === 'guest' or isguestuser($user)) {
4002 debugging('Guest user account can not be deleted.');
4003 return false;
4006 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4007 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4008 if ($user->auth === 'manual' and is_siteadmin($user)) {
4009 debugging('Local administrator accounts can not be deleted.');
4010 return false;
4013 // Allow plugins to use this user object before we completely delete it.
4014 if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4015 foreach ($pluginsfunction as $plugintype => $plugins) {
4016 foreach ($plugins as $pluginfunction) {
4017 $pluginfunction($user);
4022 // Keep user record before updating it, as we have to pass this to user_deleted event.
4023 $olduser = clone $user;
4025 // Keep a copy of user context, we need it for event.
4026 $usercontext = context_user::instance($user->id);
4028 // Delete all grades - backup is kept in grade_grades_history table.
4029 grade_user_delete($user->id);
4031 // Move unread messages from this user to read.
4032 message_move_userfrom_unread2read($user->id);
4034 // TODO: remove from cohorts using standard API here.
4036 // Remove user tags.
4037 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4039 // Unconditionally unenrol from all courses.
4040 enrol_user_delete($user);
4042 // Unenrol from all roles in all contexts.
4043 // This might be slow but it is really needed - modules might do some extra cleanup!
4044 role_unassign_all(array('userid' => $user->id));
4046 // Now do a brute force cleanup.
4048 // Remove from all cohorts.
4049 $DB->delete_records('cohort_members', array('userid' => $user->id));
4051 // Remove from all groups.
4052 $DB->delete_records('groups_members', array('userid' => $user->id));
4054 // Brute force unenrol from all courses.
4055 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4057 // Purge user preferences.
4058 $DB->delete_records('user_preferences', array('userid' => $user->id));
4060 // Purge user extra profile info.
4061 $DB->delete_records('user_info_data', array('userid' => $user->id));
4063 // Purge log of previous password hashes.
4064 $DB->delete_records('user_password_history', array('userid' => $user->id));
4066 // Last course access not necessary either.
4067 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4068 // Remove all user tokens.
4069 $DB->delete_records('external_tokens', array('userid' => $user->id));
4071 // Unauthorise the user for all services.
4072 $DB->delete_records('external_services_users', array('userid' => $user->id));
4074 // Remove users private keys.
4075 $DB->delete_records('user_private_key', array('userid' => $user->id));
4077 // Remove users customised pages.
4078 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4080 // Force logout - may fail if file based sessions used, sorry.
4081 \core\session\manager::kill_user_sessions($user->id);
4083 // Generate username from email address, or a fake email.
4084 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4085 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4087 // Workaround for bulk deletes of users with the same email address.
4088 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4089 $delname++;
4092 // Mark internal user record as "deleted".
4093 $updateuser = new stdClass();
4094 $updateuser->id = $user->id;
4095 $updateuser->deleted = 1;
4096 $updateuser->username = $delname; // Remember it just in case.
4097 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4098 $updateuser->idnumber = ''; // Clear this field to free it up.
4099 $updateuser->picture = 0;
4100 $updateuser->timemodified = time();
4102 // Don't trigger update event, as user is being deleted.
4103 user_update_user($updateuser, false, false);
4105 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4106 context_helper::delete_instance(CONTEXT_USER, $user->id);
4108 // Any plugin that needs to cleanup should register this event.
4109 // Trigger event.
4110 $event = \core\event\user_deleted::create(
4111 array(
4112 'objectid' => $user->id,
4113 'relateduserid' => $user->id,
4114 'context' => $usercontext,
4115 'other' => array(
4116 'username' => $user->username,
4117 'email' => $user->email,
4118 'idnumber' => $user->idnumber,
4119 'picture' => $user->picture,
4120 'mnethostid' => $user->mnethostid
4124 $event->add_record_snapshot('user', $olduser);
4125 $event->trigger();
4127 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4128 // should know about this updated property persisted to the user's table.
4129 $user->timemodified = $updateuser->timemodified;
4131 // Notify auth plugin - do not block the delete even when plugin fails.
4132 $authplugin = get_auth_plugin($user->auth);
4133 $authplugin->user_delete($user);
4135 return true;
4139 * Retrieve the guest user object.
4141 * @return stdClass A {@link $USER} object
4143 function guest_user() {
4144 global $CFG, $DB;
4146 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4147 $newuser->confirmed = 1;
4148 $newuser->lang = $CFG->lang;
4149 $newuser->lastip = getremoteaddr();
4152 return $newuser;
4156 * Authenticates a user against the chosen authentication mechanism
4158 * Given a username and password, this function looks them
4159 * up using the currently selected authentication mechanism,
4160 * and if the authentication is successful, it returns a
4161 * valid $user object from the 'user' table.
4163 * Uses auth_ functions from the currently active auth module
4165 * After authenticate_user_login() returns success, you will need to
4166 * log that the user has logged in, and call complete_user_login() to set
4167 * the session up.
4169 * Note: this function works only with non-mnet accounts!
4171 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4172 * @param string $password User's password
4173 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4174 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4175 * @return stdClass|false A {@link $USER} object or false if error
4177 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4178 global $CFG, $DB;
4179 require_once("$CFG->libdir/authlib.php");
4181 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4182 // we have found the user
4184 } else if (!empty($CFG->authloginviaemail)) {
4185 if ($email = clean_param($username, PARAM_EMAIL)) {
4186 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4187 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4188 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4189 if (count($users) === 1) {
4190 // Use email for login only if unique.
4191 $user = reset($users);
4192 $user = get_complete_user_data('id', $user->id);
4193 $username = $user->username;
4195 unset($users);
4199 $authsenabled = get_enabled_auth_plugins();
4201 if ($user) {
4202 // Use manual if auth not set.
4203 $auth = empty($user->auth) ? 'manual' : $user->auth;
4205 if (in_array($user->auth, $authsenabled)) {
4206 $authplugin = get_auth_plugin($user->auth);
4207 $authplugin->pre_user_login_hook($user);
4210 if (!empty($user->suspended)) {
4211 $failurereason = AUTH_LOGIN_SUSPENDED;
4213 // Trigger login failed event.
4214 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4215 'other' => array('username' => $username, 'reason' => $failurereason)));
4216 $event->trigger();
4217 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4218 return false;
4220 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4221 // Legacy way to suspend user.
4222 $failurereason = AUTH_LOGIN_SUSPENDED;
4224 // Trigger login failed event.
4225 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4226 'other' => array('username' => $username, 'reason' => $failurereason)));
4227 $event->trigger();
4228 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4229 return false;
4231 $auths = array($auth);
4233 } else {
4234 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4235 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4236 $failurereason = AUTH_LOGIN_NOUSER;
4238 // Trigger login failed event.
4239 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4240 'reason' => $failurereason)));
4241 $event->trigger();
4242 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4243 return false;
4246 // User does not exist.
4247 $auths = $authsenabled;
4248 $user = new stdClass();
4249 $user->id = 0;
4252 if ($ignorelockout) {
4253 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4254 // or this function is called from a SSO script.
4255 } else if ($user->id) {
4256 // Verify login lockout after other ways that may prevent user login.
4257 if (login_is_lockedout($user)) {
4258 $failurereason = AUTH_LOGIN_LOCKOUT;
4260 // Trigger login failed event.
4261 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4262 'other' => array('username' => $username, 'reason' => $failurereason)));
4263 $event->trigger();
4265 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4266 return false;
4268 } else {
4269 // We can not lockout non-existing accounts.
4272 foreach ($auths as $auth) {
4273 $authplugin = get_auth_plugin($auth);
4275 // On auth fail fall through to the next plugin.
4276 if (!$authplugin->user_login($username, $password)) {
4277 continue;
4280 // Successful authentication.
4281 if ($user->id) {
4282 // User already exists in database.
4283 if (empty($user->auth)) {
4284 // For some reason auth isn't set yet.
4285 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4286 $user->auth = $auth;
4289 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4290 // the current hash algorithm while we have access to the user's password.
4291 update_internal_user_password($user, $password);
4293 if ($authplugin->is_synchronised_with_external()) {
4294 // Update user record from external DB.
4295 $user = update_user_record_by_id($user->id);
4297 } else {
4298 // The user is authenticated but user creation may be disabled.
4299 if (!empty($CFG->authpreventaccountcreation)) {
4300 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4302 // Trigger login failed event.
4303 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4304 'reason' => $failurereason)));
4305 $event->trigger();
4307 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4308 $_SERVER['HTTP_USER_AGENT']);
4309 return false;
4310 } else {
4311 $user = create_user_record($username, $password, $auth);
4315 $authplugin->sync_roles($user);
4317 foreach ($authsenabled as $hau) {
4318 $hauth = get_auth_plugin($hau);
4319 $hauth->user_authenticated_hook($user, $username, $password);
4322 if (empty($user->id)) {
4323 $failurereason = AUTH_LOGIN_NOUSER;
4324 // Trigger login failed event.
4325 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4326 'reason' => $failurereason)));
4327 $event->trigger();
4328 return false;
4331 if (!empty($user->suspended)) {
4332 // Just in case some auth plugin suspended account.
4333 $failurereason = AUTH_LOGIN_SUSPENDED;
4334 // Trigger login failed event.
4335 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4336 'other' => array('username' => $username, 'reason' => $failurereason)));
4337 $event->trigger();
4338 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4339 return false;
4342 login_attempt_valid($user);
4343 $failurereason = AUTH_LOGIN_OK;
4344 return $user;
4347 // Failed if all the plugins have failed.
4348 if (debugging('', DEBUG_ALL)) {
4349 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4352 if ($user->id) {
4353 login_attempt_failed($user);
4354 $failurereason = AUTH_LOGIN_FAILED;
4355 // Trigger login failed event.
4356 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4357 'other' => array('username' => $username, 'reason' => $failurereason)));
4358 $event->trigger();
4359 } else {
4360 $failurereason = AUTH_LOGIN_NOUSER;
4361 // Trigger login failed event.
4362 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4363 'reason' => $failurereason)));
4364 $event->trigger();
4367 return false;
4371 * Call to complete the user login process after authenticate_user_login()
4372 * has succeeded. It will setup the $USER variable and other required bits
4373 * and pieces.
4375 * NOTE:
4376 * - It will NOT log anything -- up to the caller to decide what to log.
4377 * - this function does not set any cookies any more!
4379 * @param stdClass $user
4380 * @return stdClass A {@link $USER} object - BC only, do not use
4382 function complete_user_login($user) {
4383 global $CFG, $USER, $SESSION;
4385 \core\session\manager::login_user($user);
4387 // Reload preferences from DB.
4388 unset($USER->preference);
4389 check_user_preferences_loaded($USER);
4391 // Update login times.
4392 update_user_login_times();
4394 // Extra session prefs init.
4395 set_login_session_preferences();
4397 // Trigger login event.
4398 $event = \core\event\user_loggedin::create(
4399 array(
4400 'userid' => $USER->id,
4401 'objectid' => $USER->id,
4402 'other' => array('username' => $USER->username),
4405 $event->trigger();
4407 if (isguestuser()) {
4408 // No need to continue when user is THE guest.
4409 return $USER;
4412 if (CLI_SCRIPT) {
4413 // We can redirect to password change URL only in browser.
4414 return $USER;
4417 // Select password change url.
4418 $userauth = get_auth_plugin($USER->auth);
4420 // Check whether the user should be changing password.
4421 if (get_user_preferences('auth_forcepasswordchange', false)) {
4422 if ($userauth->can_change_password()) {
4423 if ($changeurl = $userauth->change_password_url()) {
4424 redirect($changeurl);
4425 } else {
4426 $SESSION->wantsurl = core_login_get_return_url();
4427 redirect($CFG->httpswwwroot.'/login/change_password.php');
4429 } else {
4430 print_error('nopasswordchangeforced', 'auth');
4433 return $USER;
4437 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4439 * @param string $password String to check.
4440 * @return boolean True if the $password matches the format of an md5 sum.
4442 function password_is_legacy_hash($password) {
4443 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4447 * Compare password against hash stored in user object to determine if it is valid.
4449 * If necessary it also updates the stored hash to the current format.
4451 * @param stdClass $user (Password property may be updated).
4452 * @param string $password Plain text password.
4453 * @return bool True if password is valid.
4455 function validate_internal_user_password($user, $password) {
4456 global $CFG;
4458 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4459 // Internal password is not used at all, it can not validate.
4460 return false;
4463 // If hash isn't a legacy (md5) hash, validate using the library function.
4464 if (!password_is_legacy_hash($user->password)) {
4465 return password_verify($password, $user->password);
4468 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4469 // is valid we can then update it to the new algorithm.
4471 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4472 $validated = false;
4474 if ($user->password === md5($password.$sitesalt)
4475 or $user->password === md5($password)
4476 or $user->password === md5(addslashes($password).$sitesalt)
4477 or $user->password === md5(addslashes($password))) {
4478 // Note: we are intentionally using the addslashes() here because we
4479 // need to accept old password hashes of passwords with magic quotes.
4480 $validated = true;
4482 } else {
4483 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4484 $alt = 'passwordsaltalt'.$i;
4485 if (!empty($CFG->$alt)) {
4486 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4487 $validated = true;
4488 break;
4494 if ($validated) {
4495 // If the password matches the existing md5 hash, update to the
4496 // current hash algorithm while we have access to the user's password.
4497 update_internal_user_password($user, $password);
4500 return $validated;
4504 * Calculate hash for a plain text password.
4506 * @param string $password Plain text password to be hashed.
4507 * @param bool $fasthash If true, use a low cost factor when generating the hash
4508 * This is much faster to generate but makes the hash
4509 * less secure. It is used when lots of hashes need to
4510 * be generated quickly.
4511 * @return string The hashed password.
4513 * @throws moodle_exception If a problem occurs while generating the hash.
4515 function hash_internal_user_password($password, $fasthash = false) {
4516 global $CFG;
4518 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4519 $options = ($fasthash) ? array('cost' => 4) : array();
4521 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4523 if ($generatedhash === false || $generatedhash === null) {
4524 throw new moodle_exception('Failed to generate password hash.');
4527 return $generatedhash;
4531 * Update password hash in user object (if necessary).
4533 * The password is updated if:
4534 * 1. The password has changed (the hash of $user->password is different
4535 * to the hash of $password).
4536 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4537 * md5 algorithm).
4539 * Updating the password will modify the $user object and the database
4540 * record to use the current hashing algorithm.
4541 * It will remove Web Services user tokens too.
4543 * @param stdClass $user User object (password property may be updated).
4544 * @param string $password Plain text password.
4545 * @param bool $fasthash If true, use a low cost factor when generating the hash
4546 * This is much faster to generate but makes the hash
4547 * less secure. It is used when lots of hashes need to
4548 * be generated quickly.
4549 * @return bool Always returns true.
4551 function update_internal_user_password($user, $password, $fasthash = false) {
4552 global $CFG, $DB;
4554 // Figure out what the hashed password should be.
4555 if (!isset($user->auth)) {
4556 debugging('User record in update_internal_user_password() must include field auth',
4557 DEBUG_DEVELOPER);
4558 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4560 $authplugin = get_auth_plugin($user->auth);
4561 if ($authplugin->prevent_local_passwords()) {
4562 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4563 } else {
4564 $hashedpassword = hash_internal_user_password($password, $fasthash);
4567 $algorithmchanged = false;
4569 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4570 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4571 $passwordchanged = ($user->password !== $hashedpassword);
4573 } else if (isset($user->password)) {
4574 // If verification fails then it means the password has changed.
4575 $passwordchanged = !password_verify($password, $user->password);
4576 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4577 } else {
4578 // While creating new user, password in unset in $user object, to avoid
4579 // saving it with user_create()
4580 $passwordchanged = true;
4583 if ($passwordchanged || $algorithmchanged) {
4584 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4585 $user->password = $hashedpassword;
4587 // Trigger event.
4588 $user = $DB->get_record('user', array('id' => $user->id));
4589 \core\event\user_password_updated::create_from_user($user)->trigger();
4591 // Remove WS user tokens.
4592 if (!empty($CFG->passwordchangetokendeletion)) {
4593 require_once($CFG->dirroot.'/webservice/lib.php');
4594 webservice::delete_user_ws_tokens($user->id);
4598 return true;
4602 * Get a complete user record, which includes all the info in the user record.
4604 * Intended for setting as $USER session variable
4606 * @param string $field The user field to be checked for a given value.
4607 * @param string $value The value to match for $field.
4608 * @param int $mnethostid
4609 * @return mixed False, or A {@link $USER} object.
4611 function get_complete_user_data($field, $value, $mnethostid = null) {
4612 global $CFG, $DB;
4614 if (!$field || !$value) {
4615 return false;
4618 // Build the WHERE clause for an SQL query.
4619 $params = array('fieldval' => $value);
4620 $constraints = "$field = :fieldval AND deleted <> 1";
4622 // If we are loading user data based on anything other than id,
4623 // we must also restrict our search based on mnet host.
4624 if ($field != 'id') {
4625 if (empty($mnethostid)) {
4626 // If empty, we restrict to local users.
4627 $mnethostid = $CFG->mnet_localhost_id;
4630 if (!empty($mnethostid)) {
4631 $params['mnethostid'] = $mnethostid;
4632 $constraints .= " AND mnethostid = :mnethostid";
4635 // Get all the basic user data.
4636 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4637 return false;
4640 // Get various settings and preferences.
4642 // Preload preference cache.
4643 check_user_preferences_loaded($user);
4645 // Load course enrolment related stuff.
4646 $user->lastcourseaccess = array(); // During last session.
4647 $user->currentcourseaccess = array(); // During current session.
4648 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4649 foreach ($lastaccesses as $lastaccess) {
4650 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4654 $sql = "SELECT g.id, g.courseid
4655 FROM {groups} g, {groups_members} gm
4656 WHERE gm.groupid=g.id AND gm.userid=?";
4658 // This is a special hack to speedup calendar display.
4659 $user->groupmember = array();
4660 if (!isguestuser($user)) {
4661 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4662 foreach ($groups as $group) {
4663 if (!array_key_exists($group->courseid, $user->groupmember)) {
4664 $user->groupmember[$group->courseid] = array();
4666 $user->groupmember[$group->courseid][$group->id] = $group->id;
4671 // Add the custom profile fields to the user record.
4672 $user->profile = array();
4673 if (!isguestuser($user)) {
4674 require_once($CFG->dirroot.'/user/profile/lib.php');
4675 profile_load_custom_fields($user);
4678 // Rewrite some variables if necessary.
4679 if (!empty($user->description)) {
4680 // No need to cart all of it around.
4681 $user->description = true;
4683 if (isguestuser($user)) {
4684 // Guest language always same as site.
4685 $user->lang = $CFG->lang;
4686 // Name always in current language.
4687 $user->firstname = get_string('guestuser');
4688 $user->lastname = ' ';
4691 return $user;
4695 * Validate a password against the configured password policy
4697 * @param string $password the password to be checked against the password policy
4698 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4699 * @return bool true if the password is valid according to the policy. false otherwise.
4701 function check_password_policy($password, &$errmsg) {
4702 global $CFG;
4704 if (empty($CFG->passwordpolicy)) {
4705 return true;
4708 $errmsg = '';
4709 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4710 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4713 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4714 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4717 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4718 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4721 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4722 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4725 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4726 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4728 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4729 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4732 if ($errmsg == '') {
4733 return true;
4734 } else {
4735 return false;
4741 * When logging in, this function is run to set certain preferences for the current SESSION.
4743 function set_login_session_preferences() {
4744 global $SESSION;
4746 $SESSION->justloggedin = true;
4748 unset($SESSION->lang);
4749 unset($SESSION->forcelang);
4750 unset($SESSION->load_navigation_admin);
4755 * Delete a course, including all related data from the database, and any associated files.
4757 * @param mixed $courseorid The id of the course or course object to delete.
4758 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4759 * @return bool true if all the removals succeeded. false if there were any failures. If this
4760 * method returns false, some of the removals will probably have succeeded, and others
4761 * failed, but you have no way of knowing which.
4763 function delete_course($courseorid, $showfeedback = true) {
4764 global $DB;
4766 if (is_object($courseorid)) {
4767 $courseid = $courseorid->id;
4768 $course = $courseorid;
4769 } else {
4770 $courseid = $courseorid;
4771 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4772 return false;
4775 $context = context_course::instance($courseid);
4777 // Frontpage course can not be deleted!!
4778 if ($courseid == SITEID) {
4779 return false;
4782 // Allow plugins to use this course before we completely delete it.
4783 if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4784 foreach ($pluginsfunction as $plugintype => $plugins) {
4785 foreach ($plugins as $pluginfunction) {
4786 $pluginfunction($course);
4791 // Make the course completely empty.
4792 remove_course_contents($courseid, $showfeedback);
4794 // Delete the course and related context instance.
4795 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4797 $DB->delete_records("course", array("id" => $courseid));
4798 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4800 // Reset all course related caches here.
4801 if (class_exists('format_base', false)) {
4802 format_base::reset_course_cache($courseid);
4805 // Trigger a course deleted event.
4806 $event = \core\event\course_deleted::create(array(
4807 'objectid' => $course->id,
4808 'context' => $context,
4809 'other' => array(
4810 'shortname' => $course->shortname,
4811 'fullname' => $course->fullname,
4812 'idnumber' => $course->idnumber
4815 $event->add_record_snapshot('course', $course);
4816 $event->trigger();
4818 return true;
4822 * Clear a course out completely, deleting all content but don't delete the course itself.
4824 * This function does not verify any permissions.
4826 * Please note this function also deletes all user enrolments,
4827 * enrolment instances and role assignments by default.
4829 * $options:
4830 * - 'keep_roles_and_enrolments' - false by default
4831 * - 'keep_groups_and_groupings' - false by default
4833 * @param int $courseid The id of the course that is being deleted
4834 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4835 * @param array $options extra options
4836 * @return bool true if all the removals succeeded. false if there were any failures. If this
4837 * method returns false, some of the removals will probably have succeeded, and others
4838 * failed, but you have no way of knowing which.
4840 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4841 global $CFG, $DB, $OUTPUT;
4843 require_once($CFG->libdir.'/badgeslib.php');
4844 require_once($CFG->libdir.'/completionlib.php');
4845 require_once($CFG->libdir.'/questionlib.php');
4846 require_once($CFG->libdir.'/gradelib.php');
4847 require_once($CFG->dirroot.'/group/lib.php');
4848 require_once($CFG->dirroot.'/comment/lib.php');
4849 require_once($CFG->dirroot.'/rating/lib.php');
4850 require_once($CFG->dirroot.'/notes/lib.php');
4852 // Handle course badges.
4853 badges_handle_course_deletion($courseid);
4855 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4856 $strdeleted = get_string('deleted').' - ';
4858 // Some crazy wishlist of stuff we should skip during purging of course content.
4859 $options = (array)$options;
4861 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4862 $coursecontext = context_course::instance($courseid);
4863 $fs = get_file_storage();
4865 // Delete course completion information, this has to be done before grades and enrols.
4866 $cc = new completion_info($course);
4867 $cc->clear_criteria();
4868 if ($showfeedback) {
4869 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4872 // Remove all data from gradebook - this needs to be done before course modules
4873 // because while deleting this information, the system may need to reference
4874 // the course modules that own the grades.
4875 remove_course_grades($courseid, $showfeedback);
4876 remove_grade_letters($coursecontext, $showfeedback);
4878 // Delete course blocks in any all child contexts,
4879 // they may depend on modules so delete them first.
4880 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4881 foreach ($childcontexts as $childcontext) {
4882 blocks_delete_all_for_context($childcontext->id);
4884 unset($childcontexts);
4885 blocks_delete_all_for_context($coursecontext->id);
4886 if ($showfeedback) {
4887 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4890 // Get the list of all modules that are properly installed.
4891 $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
4893 // Delete every instance of every module,
4894 // this has to be done before deleting of course level stuff.
4895 $locations = core_component::get_plugin_list('mod');
4896 foreach ($locations as $modname => $moddir) {
4897 if ($modname === 'NEWMODULE') {
4898 continue;
4900 if (array_key_exists($modname, $allmodules)) {
4901 $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
4902 FROM {".$modname."} m
4903 LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
4904 WHERE m.course = :courseid";
4905 $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
4906 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
4908 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
4909 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
4910 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
4912 if ($instances) {
4913 foreach ($instances as $cm) {
4914 if ($cm->id) {
4915 // Delete activity context questions and question categories.
4916 question_delete_activity($cm, $showfeedback);
4917 // Notify the competency subsystem.
4918 \core_competency\api::hook_course_module_deleted($cm);
4920 if (function_exists($moddelete)) {
4921 // This purges all module data in related tables, extra user prefs, settings, etc.
4922 $moddelete($cm->modinstance);
4923 } else {
4924 // NOTE: we should not allow installation of modules with missing delete support!
4925 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4926 $DB->delete_records($modname, array('id' => $cm->modinstance));
4929 if ($cm->id) {
4930 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
4931 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4932 $DB->delete_records('course_modules', array('id' => $cm->id));
4936 if (function_exists($moddeletecourse)) {
4937 // Execute optional course cleanup callback. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
4938 debugging("Callback delete_course is deprecated. Function $moddeletecourse should be converted " .
4939 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
4940 $moddeletecourse($course, $showfeedback);
4942 if ($instances and $showfeedback) {
4943 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4945 } else {
4946 // Ooops, this module is not properly installed, force-delete it in the next block.
4950 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
4952 // Remove all data from availability and completion tables that is associated
4953 // with course-modules belonging to this course. Note this is done even if the
4954 // features are not enabled now, in case they were enabled previously.
4955 $DB->delete_records_select('course_modules_completion',
4956 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4957 array($courseid));
4959 // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
4960 $cms = $DB->get_records('course_modules', array('course' => $course->id));
4961 $allmodulesbyid = array_flip($allmodules);
4962 foreach ($cms as $cm) {
4963 if (array_key_exists($cm->module, $allmodulesbyid)) {
4964 try {
4965 $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
4966 } catch (Exception $e) {
4967 // Ignore weird or missing table problems.
4970 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4971 $DB->delete_records('course_modules', array('id' => $cm->id));
4974 if ($showfeedback) {
4975 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
4978 // Cleanup the rest of plugins. Deprecated since Moodle 3.2. TODO MDL-53297 remove in 3.6.
4979 $cleanuplugintypes = array('report', 'coursereport', 'format');
4980 $callbacks = get_plugins_with_function('delete_course', 'lib.php');
4981 foreach ($cleanuplugintypes as $type) {
4982 if (!empty($callbacks[$type])) {
4983 foreach ($callbacks[$type] as $pluginfunction) {
4984 debugging("Callback delete_course is deprecated. Function $pluginfunction should be converted " .
4985 'to observer of event \core\event\course_content_deleted', DEBUG_DEVELOPER);
4986 $pluginfunction($course->id, $showfeedback);
4988 if ($showfeedback) {
4989 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
4994 // Delete questions and question categories.
4995 question_delete_course($course, $showfeedback);
4996 if ($showfeedback) {
4997 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5000 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5001 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5002 foreach ($childcontexts as $childcontext) {
5003 $childcontext->delete();
5005 unset($childcontexts);
5007 // Remove all roles and enrolments by default.
5008 if (empty($options['keep_roles_and_enrolments'])) {
5009 // This hack is used in restore when deleting contents of existing course.
5010 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5011 enrol_course_delete($course);
5012 if ($showfeedback) {
5013 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5017 // Delete any groups, removing members and grouping/course links first.
5018 if (empty($options['keep_groups_and_groupings'])) {
5019 groups_delete_groupings($course->id, $showfeedback);
5020 groups_delete_groups($course->id, $showfeedback);
5023 // Filters be gone!
5024 filter_delete_all_for_context($coursecontext->id);
5026 // Notes, you shall not pass!
5027 note_delete_all($course->id);
5029 // Die comments!
5030 comment::delete_comments($coursecontext->id);
5032 // Ratings are history too.
5033 $delopt = new stdclass();
5034 $delopt->contextid = $coursecontext->id;
5035 $rm = new rating_manager();
5036 $rm->delete_ratings($delopt);
5038 // Delete course tags.
5039 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5041 // Notify the competency subsystem.
5042 \core_competency\api::hook_course_deleted($course);
5044 // Delete calendar events.
5045 $DB->delete_records('event', array('courseid' => $course->id));
5046 $fs->delete_area_files($coursecontext->id, 'calendar');
5048 // Delete all related records in other core tables that may have a courseid
5049 // This array stores the tables that need to be cleared, as
5050 // table_name => column_name that contains the course id.
5051 $tablestoclear = array(
5052 'backup_courses' => 'courseid', // Scheduled backup stuff.
5053 'user_lastaccess' => 'courseid', // User access info.
5055 foreach ($tablestoclear as $table => $col) {
5056 $DB->delete_records($table, array($col => $course->id));
5059 // Delete all course backup files.
5060 $fs->delete_area_files($coursecontext->id, 'backup');
5062 // Cleanup course record - remove links to deleted stuff.
5063 $oldcourse = new stdClass();
5064 $oldcourse->id = $course->id;
5065 $oldcourse->summary = '';
5066 $oldcourse->cacherev = 0;
5067 $oldcourse->legacyfiles = 0;
5068 if (!empty($options['keep_groups_and_groupings'])) {
5069 $oldcourse->defaultgroupingid = 0;
5071 $DB->update_record('course', $oldcourse);
5073 // Delete course sections.
5074 $DB->delete_records('course_sections', array('course' => $course->id));
5076 // Delete legacy, section and any other course files.
5077 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5079 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5080 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5081 // Easy, do not delete the context itself...
5082 $coursecontext->delete_content();
5083 } else {
5084 // Hack alert!!!!
5085 // We can not drop all context stuff because it would bork enrolments and roles,
5086 // there might be also files used by enrol plugins...
5089 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5090 // also some non-standard unsupported plugins may try to store something there.
5091 fulldelete($CFG->dataroot.'/'.$course->id);
5093 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5094 $cachemodinfo = cache::make('core', 'coursemodinfo');
5095 $cachemodinfo->delete($courseid);
5097 // Trigger a course content deleted event.
5098 $event = \core\event\course_content_deleted::create(array(
5099 'objectid' => $course->id,
5100 'context' => $coursecontext,
5101 'other' => array('shortname' => $course->shortname,
5102 'fullname' => $course->fullname,
5103 'options' => $options) // Passing this for legacy reasons.
5105 $event->add_record_snapshot('course', $course);
5106 $event->trigger();
5108 return true;
5112 * Change dates in module - used from course reset.
5114 * @param string $modname forum, assignment, etc
5115 * @param array $fields array of date fields from mod table
5116 * @param int $timeshift time difference
5117 * @param int $courseid
5118 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5119 * @return bool success
5121 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5122 global $CFG, $DB;
5123 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5125 $return = true;
5126 $params = array($timeshift, $courseid);
5127 foreach ($fields as $field) {
5128 $updatesql = "UPDATE {".$modname."}
5129 SET $field = $field + ?
5130 WHERE course=? AND $field<>0";
5131 if ($modid) {
5132 $updatesql .= ' AND id=?';
5133 $params[] = $modid;
5135 $return = $DB->execute($updatesql, $params) && $return;
5138 $refreshfunction = $modname.'_refresh_events';
5139 if (function_exists($refreshfunction)) {
5140 $refreshfunction($courseid);
5143 return $return;
5147 * This function will empty a course of user data.
5148 * It will retain the activities and the structure of the course.
5150 * @param object $data an object containing all the settings including courseid (without magic quotes)
5151 * @return array status array of array component, item, error
5153 function reset_course_userdata($data) {
5154 global $CFG, $DB;
5155 require_once($CFG->libdir.'/gradelib.php');
5156 require_once($CFG->libdir.'/completionlib.php');
5157 require_once($CFG->dirroot.'/group/lib.php');
5159 $data->courseid = $data->id;
5160 $context = context_course::instance($data->courseid);
5162 $eventparams = array(
5163 'context' => $context,
5164 'courseid' => $data->id,
5165 'other' => array(
5166 'reset_options' => (array) $data
5169 $event = \core\event\course_reset_started::create($eventparams);
5170 $event->trigger();
5172 // Calculate the time shift of dates.
5173 if (!empty($data->reset_start_date)) {
5174 // Time part of course startdate should be zero.
5175 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5176 } else {
5177 $data->timeshift = 0;
5180 // Result array: component, item, error.
5181 $status = array();
5183 // Start the resetting.
5184 $componentstr = get_string('general');
5186 // Move the course start time.
5187 if (!empty($data->reset_start_date) and $data->timeshift) {
5188 // Change course start data.
5189 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5190 // Update all course and group events - do not move activity events.
5191 $updatesql = "UPDATE {event}
5192 SET timestart = timestart + ?
5193 WHERE courseid=? AND instance=0";
5194 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5196 // Update any date activity restrictions.
5197 if ($CFG->enableavailability) {
5198 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5201 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5204 if (!empty($data->reset_end_date)) {
5205 // If the user set a end date value respect it.
5206 $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5207 } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5208 // If there is a time shift apply it to the end date as well.
5209 $enddate = $data->reset_end_date_old + $data->timeshift;
5210 $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5213 if (!empty($data->reset_events)) {
5214 $DB->delete_records('event', array('courseid' => $data->courseid));
5215 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5218 if (!empty($data->reset_notes)) {
5219 require_once($CFG->dirroot.'/notes/lib.php');
5220 note_delete_all($data->courseid);
5221 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5224 if (!empty($data->delete_blog_associations)) {
5225 require_once($CFG->dirroot.'/blog/lib.php');
5226 blog_remove_associations_for_course($data->courseid);
5227 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5230 if (!empty($data->reset_completion)) {
5231 // Delete course and activity completion information.
5232 $course = $DB->get_record('course', array('id' => $data->courseid));
5233 $cc = new completion_info($course);
5234 $cc->delete_all_completion_data();
5235 $status[] = array('component' => $componentstr,
5236 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5239 if (!empty($data->reset_competency_ratings)) {
5240 \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5241 $status[] = array('component' => $componentstr,
5242 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5245 $componentstr = get_string('roles');
5247 if (!empty($data->reset_roles_overrides)) {
5248 $children = $context->get_child_contexts();
5249 foreach ($children as $child) {
5250 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5252 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5253 // Force refresh for logged in users.
5254 $context->mark_dirty();
5255 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5258 if (!empty($data->reset_roles_local)) {
5259 $children = $context->get_child_contexts();
5260 foreach ($children as $child) {
5261 role_unassign_all(array('contextid' => $child->id));
5263 // Force refresh for logged in users.
5264 $context->mark_dirty();
5265 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5268 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5269 $data->unenrolled = array();
5270 if (!empty($data->unenrol_users)) {
5271 $plugins = enrol_get_plugins(true);
5272 $instances = enrol_get_instances($data->courseid, true);
5273 foreach ($instances as $key => $instance) {
5274 if (!isset($plugins[$instance->enrol])) {
5275 unset($instances[$key]);
5276 continue;
5280 foreach ($data->unenrol_users as $withroleid) {
5281 if ($withroleid) {
5282 $sql = "SELECT ue.*
5283 FROM {user_enrolments} ue
5284 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5285 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5286 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5287 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5289 } else {
5290 // Without any role assigned at course context.
5291 $sql = "SELECT ue.*
5292 FROM {user_enrolments} ue
5293 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5294 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5295 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5296 WHERE ra.id IS null";
5297 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5300 $rs = $DB->get_recordset_sql($sql, $params);
5301 foreach ($rs as $ue) {
5302 if (!isset($instances[$ue->enrolid])) {
5303 continue;
5305 $instance = $instances[$ue->enrolid];
5306 $plugin = $plugins[$instance->enrol];
5307 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5308 continue;
5311 $plugin->unenrol_user($instance, $ue->userid);
5312 $data->unenrolled[$ue->userid] = $ue->userid;
5314 $rs->close();
5317 if (!empty($data->unenrolled)) {
5318 $status[] = array(
5319 'component' => $componentstr,
5320 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5321 'error' => false
5325 $componentstr = get_string('groups');
5327 // Remove all group members.
5328 if (!empty($data->reset_groups_members)) {
5329 groups_delete_group_members($data->courseid);
5330 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5333 // Remove all groups.
5334 if (!empty($data->reset_groups_remove)) {
5335 groups_delete_groups($data->courseid, false);
5336 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5339 // Remove all grouping members.
5340 if (!empty($data->reset_groupings_members)) {
5341 groups_delete_groupings_groups($data->courseid, false);
5342 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5345 // Remove all groupings.
5346 if (!empty($data->reset_groupings_remove)) {
5347 groups_delete_groupings($data->courseid, false);
5348 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5351 // Look in every instance of every module for data to delete.
5352 $unsupportedmods = array();
5353 if ($allmods = $DB->get_records('modules') ) {
5354 foreach ($allmods as $mod) {
5355 $modname = $mod->name;
5356 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5357 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5358 if (file_exists($modfile)) {
5359 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5360 continue; // Skip mods with no instances.
5362 include_once($modfile);
5363 if (function_exists($moddeleteuserdata)) {
5364 $modstatus = $moddeleteuserdata($data);
5365 if (is_array($modstatus)) {
5366 $status = array_merge($status, $modstatus);
5367 } else {
5368 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5370 } else {
5371 $unsupportedmods[] = $mod;
5373 } else {
5374 debugging('Missing lib.php in '.$modname.' module!');
5379 // Mention unsupported mods.
5380 if (!empty($unsupportedmods)) {
5381 foreach ($unsupportedmods as $mod) {
5382 $status[] = array(
5383 'component' => get_string('modulenameplural', $mod->name),
5384 'item' => '',
5385 'error' => get_string('resetnotimplemented')
5390 $componentstr = get_string('gradebook', 'grades');
5391 // Reset gradebook,.
5392 if (!empty($data->reset_gradebook_items)) {
5393 remove_course_grades($data->courseid, false);
5394 grade_grab_course_grades($data->courseid);
5395 grade_regrade_final_grades($data->courseid);
5396 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5398 } else if (!empty($data->reset_gradebook_grades)) {
5399 grade_course_reset($data->courseid);
5400 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5402 // Reset comments.
5403 if (!empty($data->reset_comments)) {
5404 require_once($CFG->dirroot.'/comment/lib.php');
5405 comment::reset_course_page_comments($context);
5408 $event = \core\event\course_reset_ended::create($eventparams);
5409 $event->trigger();
5411 return $status;
5415 * Generate an email processing address.
5417 * @param int $modid
5418 * @param string $modargs
5419 * @return string Returns email processing address
5421 function generate_email_processing_address($modid, $modargs) {
5422 global $CFG;
5424 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5425 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5431 * @todo Finish documenting this function
5433 * @param string $modargs
5434 * @param string $body Currently unused
5436 function moodle_process_email($modargs, $body) {
5437 global $DB;
5439 // The first char should be an unencoded letter. We'll take this as an action.
5440 switch ($modargs{0}) {
5441 case 'B': { // Bounce.
5442 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5443 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5444 // Check the half md5 of their email.
5445 $md5check = substr(md5($user->email), 0, 16);
5446 if ($md5check == substr($modargs, -16)) {
5447 set_bounce_count($user);
5449 // Else maybe they've already changed it?
5452 break;
5453 // Maybe more later?
5457 // CORRESPONDENCE.
5460 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5462 * @param string $action 'get', 'buffer', 'close' or 'flush'
5463 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5465 function get_mailer($action='get') {
5466 global $CFG;
5468 /** @var moodle_phpmailer $mailer */
5469 static $mailer = null;
5470 static $counter = 0;
5472 if (!isset($CFG->smtpmaxbulk)) {
5473 $CFG->smtpmaxbulk = 1;
5476 if ($action == 'get') {
5477 $prevkeepalive = false;
5479 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5480 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5481 $counter++;
5482 // Reset the mailer.
5483 $mailer->Priority = 3;
5484 $mailer->CharSet = 'UTF-8'; // Our default.
5485 $mailer->ContentType = "text/plain";
5486 $mailer->Encoding = "8bit";
5487 $mailer->From = "root@localhost";
5488 $mailer->FromName = "Root User";
5489 $mailer->Sender = "";
5490 $mailer->Subject = "";
5491 $mailer->Body = "";
5492 $mailer->AltBody = "";
5493 $mailer->ConfirmReadingTo = "";
5495 $mailer->clearAllRecipients();
5496 $mailer->clearReplyTos();
5497 $mailer->clearAttachments();
5498 $mailer->clearCustomHeaders();
5499 return $mailer;
5502 $prevkeepalive = $mailer->SMTPKeepAlive;
5503 get_mailer('flush');
5506 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5507 $mailer = new moodle_phpmailer();
5509 $counter = 1;
5511 if ($CFG->smtphosts == 'qmail') {
5512 // Use Qmail system.
5513 $mailer->isQmail();
5515 } else if (empty($CFG->smtphosts)) {
5516 // Use PHP mail() = sendmail.
5517 $mailer->isMail();
5519 } else {
5520 // Use SMTP directly.
5521 $mailer->isSMTP();
5522 if (!empty($CFG->debugsmtp)) {
5523 $mailer->SMTPDebug = true;
5525 // Specify main and backup servers.
5526 $mailer->Host = $CFG->smtphosts;
5527 // Specify secure connection protocol.
5528 $mailer->SMTPSecure = $CFG->smtpsecure;
5529 // Use previous keepalive.
5530 $mailer->SMTPKeepAlive = $prevkeepalive;
5532 if ($CFG->smtpuser) {
5533 // Use SMTP authentication.
5534 $mailer->SMTPAuth = true;
5535 $mailer->Username = $CFG->smtpuser;
5536 $mailer->Password = $CFG->smtppass;
5540 return $mailer;
5543 $nothing = null;
5545 // Keep smtp session open after sending.
5546 if ($action == 'buffer') {
5547 if (!empty($CFG->smtpmaxbulk)) {
5548 get_mailer('flush');
5549 $m = get_mailer();
5550 if ($m->Mailer == 'smtp') {
5551 $m->SMTPKeepAlive = true;
5554 return $nothing;
5557 // Close smtp session, but continue buffering.
5558 if ($action == 'flush') {
5559 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5560 if (!empty($mailer->SMTPDebug)) {
5561 echo '<pre>'."\n";
5563 $mailer->SmtpClose();
5564 if (!empty($mailer->SMTPDebug)) {
5565 echo '</pre>';
5568 return $nothing;
5571 // Close smtp session, do not buffer anymore.
5572 if ($action == 'close') {
5573 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5574 get_mailer('flush');
5575 $mailer->SMTPKeepAlive = false;
5577 $mailer = null; // Better force new instance.
5578 return $nothing;
5583 * A helper function to test for email diversion
5585 * @param string $email
5586 * @return bool Returns true if the email should be diverted
5588 function email_should_be_diverted($email) {
5589 global $CFG;
5591 if (empty($CFG->divertallemailsto)) {
5592 return false;
5595 if (empty($CFG->divertallemailsexcept)) {
5596 return true;
5599 $patterns = array_map('trim', explode(',', $CFG->divertallemailsexcept));
5600 foreach ($patterns as $pattern) {
5601 if (preg_match("/$pattern/", $email)) {
5602 return false;
5606 return true;
5610 * Generate a unique email Message-ID using the moodle domain and install path
5612 * @param string $localpart An optional unique message id prefix.
5613 * @return string The formatted ID ready for appending to the email headers.
5615 function generate_email_messageid($localpart = null) {
5616 global $CFG;
5618 $urlinfo = parse_url($CFG->wwwroot);
5619 $base = '@' . $urlinfo['host'];
5621 // If multiple moodles are on the same domain we want to tell them
5622 // apart so we add the install path to the local part. This means
5623 // that the id local part should never contain a / character so
5624 // we can correctly parse the id to reassemble the wwwroot.
5625 if (isset($urlinfo['path'])) {
5626 $base = $urlinfo['path'] . $base;
5629 if (empty($localpart)) {
5630 $localpart = uniqid('', true);
5633 // Because we may have an option /installpath suffix to the local part
5634 // of the id we need to escape any / chars which are in the $localpart.
5635 $localpart = str_replace('/', '%2F', $localpart);
5637 return '<' . $localpart . $base . '>';
5641 * Send an email to a specified user
5643 * @param stdClass $user A {@link $USER} object
5644 * @param stdClass $from A {@link $USER} object
5645 * @param string $subject plain text subject line of the email
5646 * @param string $messagetext plain text version of the message
5647 * @param string $messagehtml complete html version of the message (optional)
5648 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5649 * @param string $attachname the name of the file (extension indicates MIME)
5650 * @param bool $usetrueaddress determines whether $from email address should
5651 * be sent out. Will be overruled by user profile setting for maildisplay
5652 * @param string $replyto Email address to reply to
5653 * @param string $replytoname Name of reply to recipient
5654 * @param int $wordwrapwidth custom word wrap width, default 79
5655 * @return bool Returns true if mail was sent OK and false if there was an error.
5657 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5658 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5660 global $CFG, $PAGE, $SITE;
5662 if (empty($user) or empty($user->id)) {
5663 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5664 return false;
5667 if (empty($user->email)) {
5668 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5669 return false;
5672 if (!empty($user->deleted)) {
5673 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5674 return false;
5677 if (defined('BEHAT_SITE_RUNNING')) {
5678 // Fake email sending in behat.
5679 return true;
5682 if (!empty($CFG->noemailever)) {
5683 // Hidden setting for development sites, set in config.php if needed.
5684 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5685 return true;
5688 if (email_should_be_diverted($user->email)) {
5689 $subject = "[DIVERTED {$user->email}] $subject";
5690 $user = clone($user);
5691 $user->email = $CFG->divertallemailsto;
5694 // Skip mail to suspended users.
5695 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5696 return true;
5699 if (!validate_email($user->email)) {
5700 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5701 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5702 return false;
5705 if (over_bounce_threshold($user)) {
5706 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5707 return false;
5710 // TLD .invalid is specifically reserved for invalid domain names.
5711 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5712 if (substr($user->email, -8) == '.invalid') {
5713 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5714 return true; // This is not an error.
5717 // If the user is a remote mnet user, parse the email text for URL to the
5718 // wwwroot and modify the url to direct the user's browser to login at their
5719 // home site (identity provider - idp) before hitting the link itself.
5720 if (is_mnet_remote_user($user)) {
5721 require_once($CFG->dirroot.'/mnet/lib.php');
5723 $jumpurl = mnet_get_idp_jump_url($user);
5724 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5726 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5727 $callback,
5728 $messagetext);
5729 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5730 $callback,
5731 $messagehtml);
5733 $mail = get_mailer();
5735 if (!empty($mail->SMTPDebug)) {
5736 echo '<pre>' . "\n";
5739 $temprecipients = array();
5740 $tempreplyto = array();
5742 $supportuser = core_user::get_support_user();
5744 // Make up an email address for handling bounces.
5745 if (!empty($CFG->handlebounces)) {
5746 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5747 $mail->Sender = generate_email_processing_address(0, $modargs);
5748 } else {
5749 $mail->Sender = $supportuser->email;
5752 if (!empty($CFG->emailonlyfromnoreplyaddress)) {
5753 $usetrueaddress = false;
5754 if (empty($replyto) && $from->maildisplay) {
5755 $replyto = $from->email;
5756 $replytoname = fullname($from);
5760 if (is_string($from)) { // So we can pass whatever we want if there is need.
5761 $mail->From = $CFG->noreplyaddress;
5762 $mail->FromName = $from;
5763 } else if ($usetrueaddress and $from->maildisplay) {
5764 $mail->From = $from->email;
5765 $mail->FromName = fullname($from);
5766 } else {
5767 $mail->From = $CFG->noreplyaddress;
5768 $mail->FromName = fullname($from);
5769 if (empty($replyto)) {
5770 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5774 if (!empty($replyto)) {
5775 $tempreplyto[] = array($replyto, $replytoname);
5778 $temprecipients[] = array($user->email, fullname($user));
5780 // Set word wrap.
5781 $mail->WordWrap = $wordwrapwidth;
5783 if (!empty($from->customheaders)) {
5784 // Add custom headers.
5785 if (is_array($from->customheaders)) {
5786 foreach ($from->customheaders as $customheader) {
5787 $mail->addCustomHeader($customheader);
5789 } else {
5790 $mail->addCustomHeader($from->customheaders);
5794 // If the X-PHP-Originating-Script email header is on then also add an additional
5795 // header with details of where exactly in moodle the email was triggered from,
5796 // either a call to message_send() or to email_to_user().
5797 if (ini_get('mail.add_x_header')) {
5799 $stack = debug_backtrace(false);
5800 $origin = $stack[0];
5802 foreach ($stack as $depth => $call) {
5803 if ($call['function'] == 'message_send') {
5804 $origin = $call;
5808 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
5809 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
5810 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
5813 if (!empty($from->priority)) {
5814 $mail->Priority = $from->priority;
5817 $renderer = $PAGE->get_renderer('core');
5818 $context = array(
5819 'sitefullname' => $SITE->fullname,
5820 'siteshortname' => $SITE->shortname,
5821 'sitewwwroot' => $CFG->wwwroot,
5822 'subject' => $subject,
5823 'to' => $user->email,
5824 'toname' => fullname($user),
5825 'from' => $mail->From,
5826 'fromname' => $mail->FromName,
5828 if (!empty($tempreplyto[0])) {
5829 $context['replyto'] = $tempreplyto[0][0];
5830 $context['replytoname'] = $tempreplyto[0][1];
5832 if ($user->id > 0) {
5833 $context['touserid'] = $user->id;
5834 $context['tousername'] = $user->username;
5837 if (!empty($user->mailformat) && $user->mailformat == 1) {
5838 // Only process html templates if the user preferences allow html email.
5840 if ($messagehtml) {
5841 // If html has been given then pass it through the template.
5842 $context['body'] = $messagehtml;
5843 $messagehtml = $renderer->render_from_template('core/email_html', $context);
5845 } else {
5846 // If no html has been given, BUT there is an html wrapping template then
5847 // auto convert the text to html and then wrap it.
5848 $autohtml = trim(text_to_html($messagetext));
5849 $context['body'] = $autohtml;
5850 $temphtml = $renderer->render_from_template('core/email_html', $context);
5851 if ($autohtml != $temphtml) {
5852 $messagehtml = $temphtml;
5857 $context['body'] = $messagetext;
5858 $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
5859 $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
5860 $messagetext = $renderer->render_from_template('core/email_text', $context);
5862 // Autogenerate a MessageID if it's missing.
5863 if (empty($mail->MessageID)) {
5864 $mail->MessageID = generate_email_messageid();
5867 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5868 // Don't ever send HTML to users who don't want it.
5869 $mail->isHTML(true);
5870 $mail->Encoding = 'quoted-printable';
5871 $mail->Body = $messagehtml;
5872 $mail->AltBody = "\n$messagetext\n";
5873 } else {
5874 $mail->IsHTML(false);
5875 $mail->Body = "\n$messagetext\n";
5878 if ($attachment && $attachname) {
5879 if (preg_match( "~\\.\\.~" , $attachment )) {
5880 // Security check for ".." in dir path.
5881 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5882 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5883 } else {
5884 require_once($CFG->libdir.'/filelib.php');
5885 $mimetype = mimeinfo('type', $attachname);
5887 $attachmentpath = $attachment;
5889 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5890 $attachpath = str_replace('\\', '/', $attachmentpath);
5891 // Make sure both variables are normalised before comparing.
5892 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
5894 // If the attachment is a full path to a file in the tempdir, use it as is,
5895 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5896 if (strpos($attachpath, $temppath) !== 0) {
5897 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5900 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5904 // Check if the email should be sent in an other charset then the default UTF-8.
5905 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5907 // Use the defined site mail charset or eventually the one preferred by the recipient.
5908 $charset = $CFG->sitemailcharset;
5909 if (!empty($CFG->allowusermailcharset)) {
5910 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5911 $charset = $useremailcharset;
5915 // Convert all the necessary strings if the charset is supported.
5916 $charsets = get_list_of_charsets();
5917 unset($charsets['UTF-8']);
5918 if (in_array($charset, $charsets)) {
5919 $mail->CharSet = $charset;
5920 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5921 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5922 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5923 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5925 foreach ($temprecipients as $key => $values) {
5926 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5928 foreach ($tempreplyto as $key => $values) {
5929 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5934 foreach ($temprecipients as $values) {
5935 $mail->addAddress($values[0], $values[1]);
5937 foreach ($tempreplyto as $values) {
5938 $mail->addReplyTo($values[0], $values[1]);
5941 if ($mail->send()) {
5942 set_send_count($user);
5943 if (!empty($mail->SMTPDebug)) {
5944 echo '</pre>';
5946 return true;
5947 } else {
5948 // Trigger event for failing to send email.
5949 $event = \core\event\email_failed::create(array(
5950 'context' => context_system::instance(),
5951 'userid' => $from->id,
5952 'relateduserid' => $user->id,
5953 'other' => array(
5954 'subject' => $subject,
5955 'message' => $messagetext,
5956 'errorinfo' => $mail->ErrorInfo
5959 $event->trigger();
5960 if (CLI_SCRIPT) {
5961 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5963 if (!empty($mail->SMTPDebug)) {
5964 echo '</pre>';
5966 return false;
5971 * Generate a signoff for emails based on support settings
5973 * @return string
5975 function generate_email_signoff() {
5976 global $CFG;
5978 $signoff = "\n";
5979 if (!empty($CFG->supportname)) {
5980 $signoff .= $CFG->supportname."\n";
5982 if (!empty($CFG->supportemail)) {
5983 $signoff .= $CFG->supportemail."\n";
5985 if (!empty($CFG->supportpage)) {
5986 $signoff .= $CFG->supportpage."\n";
5988 return $signoff;
5992 * Sets specified user's password and send the new password to the user via email.
5994 * @param stdClass $user A {@link $USER} object
5995 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
5996 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
5998 function setnew_password_and_mail($user, $fasthash = false) {
5999 global $CFG, $DB;
6001 // We try to send the mail in language the user understands,
6002 // unfortunately the filter_string() does not support alternative langs yet
6003 // so multilang will not work properly for site->fullname.
6004 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6006 $site = get_site();
6008 $supportuser = core_user::get_support_user();
6010 $newpassword = generate_password();
6012 update_internal_user_password($user, $newpassword, $fasthash);
6014 $a = new stdClass();
6015 $a->firstname = fullname($user, true);
6016 $a->sitename = format_string($site->fullname);
6017 $a->username = $user->username;
6018 $a->newpassword = $newpassword;
6019 $a->link = $CFG->wwwroot .'/login/';
6020 $a->signoff = generate_email_signoff();
6022 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6024 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6026 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6027 return email_to_user($user, $supportuser, $subject, $message);
6032 * Resets specified user's password and send the new password to the user via email.
6034 * @param stdClass $user A {@link $USER} object
6035 * @return bool Returns true if mail was sent OK and false if there was an error.
6037 function reset_password_and_mail($user) {
6038 global $CFG;
6040 $site = get_site();
6041 $supportuser = core_user::get_support_user();
6043 $userauth = get_auth_plugin($user->auth);
6044 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6045 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6046 return false;
6049 $newpassword = generate_password();
6051 if (!$userauth->user_update_password($user, $newpassword)) {
6052 print_error("cannotsetpassword");
6055 $a = new stdClass();
6056 $a->firstname = $user->firstname;
6057 $a->lastname = $user->lastname;
6058 $a->sitename = format_string($site->fullname);
6059 $a->username = $user->username;
6060 $a->newpassword = $newpassword;
6061 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
6062 $a->signoff = generate_email_signoff();
6064 $message = get_string('newpasswordtext', '', $a);
6066 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6068 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6070 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6071 return email_to_user($user, $supportuser, $subject, $message);
6075 * Send email to specified user with confirmation text and activation link.
6077 * @param stdClass $user A {@link $USER} object
6078 * @return bool Returns true if mail was sent OK and false if there was an error.
6080 function send_confirmation_email($user) {
6081 global $CFG;
6083 $site = get_site();
6084 $supportuser = core_user::get_support_user();
6086 $data = new stdClass();
6087 $data->firstname = fullname($user);
6088 $data->sitename = format_string($site->fullname);
6089 $data->admin = generate_email_signoff();
6091 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6093 $username = urlencode($user->username);
6094 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
6095 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
6096 $message = get_string('emailconfirmation', '', $data);
6097 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6099 $user->mailformat = 1; // Always send HTML version as well.
6101 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6102 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6106 * Sends a password change confirmation email.
6108 * @param stdClass $user A {@link $USER} object
6109 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6110 * @return bool Returns true if mail was sent OK and false if there was an error.
6112 function send_password_change_confirmation_email($user, $resetrecord) {
6113 global $CFG;
6115 $site = get_site();
6116 $supportuser = core_user::get_support_user();
6117 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6119 $data = new stdClass();
6120 $data->firstname = $user->firstname;
6121 $data->lastname = $user->lastname;
6122 $data->username = $user->username;
6123 $data->sitename = format_string($site->fullname);
6124 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6125 $data->admin = generate_email_signoff();
6126 $data->resetminutes = $pwresetmins;
6128 $message = get_string('emailresetconfirmation', '', $data);
6129 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6131 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6132 return email_to_user($user, $supportuser, $subject, $message);
6137 * Sends an email containinginformation on how to change your password.
6139 * @param stdClass $user A {@link $USER} object
6140 * @return bool Returns true if mail was sent OK and false if there was an error.
6142 function send_password_change_info($user) {
6143 global $CFG;
6145 $site = get_site();
6146 $supportuser = core_user::get_support_user();
6147 $systemcontext = context_system::instance();
6149 $data = new stdClass();
6150 $data->firstname = $user->firstname;
6151 $data->lastname = $user->lastname;
6152 $data->sitename = format_string($site->fullname);
6153 $data->admin = generate_email_signoff();
6155 $userauth = get_auth_plugin($user->auth);
6157 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6158 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6159 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6160 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6161 return email_to_user($user, $supportuser, $subject, $message);
6164 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6165 // We have some external url for password changing.
6166 $data->link .= $userauth->change_password_url();
6168 } else {
6169 // No way to change password, sorry.
6170 $data->link = '';
6173 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6174 $message = get_string('emailpasswordchangeinfo', '', $data);
6175 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6176 } else {
6177 $message = get_string('emailpasswordchangeinfofail', '', $data);
6178 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6181 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6182 return email_to_user($user, $supportuser, $subject, $message);
6187 * Check that an email is allowed. It returns an error message if there was a problem.
6189 * @param string $email Content of email
6190 * @return string|false
6192 function email_is_not_allowed($email) {
6193 global $CFG;
6195 if (!empty($CFG->allowemailaddresses)) {
6196 $allowed = explode(' ', $CFG->allowemailaddresses);
6197 foreach ($allowed as $allowedpattern) {
6198 $allowedpattern = trim($allowedpattern);
6199 if (!$allowedpattern) {
6200 continue;
6202 if (strpos($allowedpattern, '.') === 0) {
6203 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6204 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6205 return false;
6208 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6209 return false;
6212 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6214 } else if (!empty($CFG->denyemailaddresses)) {
6215 $denied = explode(' ', $CFG->denyemailaddresses);
6216 foreach ($denied as $deniedpattern) {
6217 $deniedpattern = trim($deniedpattern);
6218 if (!$deniedpattern) {
6219 continue;
6221 if (strpos($deniedpattern, '.') === 0) {
6222 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6223 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6224 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6227 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6228 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6233 return false;
6236 // FILE HANDLING.
6239 * Returns local file storage instance
6241 * @return file_storage
6243 function get_file_storage() {
6244 global $CFG;
6246 static $fs = null;
6248 if ($fs) {
6249 return $fs;
6252 require_once("$CFG->libdir/filelib.php");
6254 if (isset($CFG->filedir)) {
6255 $filedir = $CFG->filedir;
6256 } else {
6257 $filedir = $CFG->dataroot.'/filedir';
6260 if (isset($CFG->trashdir)) {
6261 $trashdirdir = $CFG->trashdir;
6262 } else {
6263 $trashdirdir = $CFG->dataroot.'/trashdir';
6266 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6268 return $fs;
6272 * Returns local file storage instance
6274 * @return file_browser
6276 function get_file_browser() {
6277 global $CFG;
6279 static $fb = null;
6281 if ($fb) {
6282 return $fb;
6285 require_once("$CFG->libdir/filelib.php");
6287 $fb = new file_browser();
6289 return $fb;
6293 * Returns file packer
6295 * @param string $mimetype default application/zip
6296 * @return file_packer
6298 function get_file_packer($mimetype='application/zip') {
6299 global $CFG;
6301 static $fp = array();
6303 if (isset($fp[$mimetype])) {
6304 return $fp[$mimetype];
6307 switch ($mimetype) {
6308 case 'application/zip':
6309 case 'application/vnd.moodle.profiling':
6310 $classname = 'zip_packer';
6311 break;
6313 case 'application/x-gzip' :
6314 $classname = 'tgz_packer';
6315 break;
6317 case 'application/vnd.moodle.backup':
6318 $classname = 'mbz_packer';
6319 break;
6321 default:
6322 return false;
6325 require_once("$CFG->libdir/filestorage/$classname.php");
6326 $fp[$mimetype] = new $classname();
6328 return $fp[$mimetype];
6332 * Returns current name of file on disk if it exists.
6334 * @param string $newfile File to be verified
6335 * @return string Current name of file on disk if true
6337 function valid_uploaded_file($newfile) {
6338 if (empty($newfile)) {
6339 return '';
6341 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6342 return $newfile['tmp_name'];
6343 } else {
6344 return '';
6349 * Returns the maximum size for uploading files.
6351 * There are seven possible upload limits:
6352 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6353 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6354 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6355 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6356 * 5. by the Moodle admin in $CFG->maxbytes
6357 * 6. by the teacher in the current course $course->maxbytes
6358 * 7. by the teacher for the current module, eg $assignment->maxbytes
6360 * These last two are passed to this function as arguments (in bytes).
6361 * Anything defined as 0 is ignored.
6362 * The smallest of all the non-zero numbers is returned.
6364 * @todo Finish documenting this function
6366 * @param int $sitebytes Set maximum size
6367 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6368 * @param int $modulebytes Current module ->maxbytes (in bytes)
6369 * @param bool $unused This parameter has been deprecated and is not used any more.
6370 * @return int The maximum size for uploading files.
6372 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6374 if (! $filesize = ini_get('upload_max_filesize')) {
6375 $filesize = '5M';
6377 $minimumsize = get_real_size($filesize);
6379 if ($postsize = ini_get('post_max_size')) {
6380 $postsize = get_real_size($postsize);
6381 if ($postsize < $minimumsize) {
6382 $minimumsize = $postsize;
6386 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6387 $minimumsize = $sitebytes;
6390 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6391 $minimumsize = $coursebytes;
6394 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6395 $minimumsize = $modulebytes;
6398 return $minimumsize;
6402 * Returns the maximum size for uploading files for the current user
6404 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6406 * @param context $context The context in which to check user capabilities
6407 * @param int $sitebytes Set maximum size
6408 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6409 * @param int $modulebytes Current module ->maxbytes (in bytes)
6410 * @param stdClass $user The user
6411 * @param bool $unused This parameter has been deprecated and is not used any more.
6412 * @return int The maximum size for uploading files.
6414 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6415 $unused = false) {
6416 global $USER;
6418 if (empty($user)) {
6419 $user = $USER;
6422 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6423 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6426 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6430 * Returns an array of possible sizes in local language
6432 * Related to {@link get_max_upload_file_size()} - this function returns an
6433 * array of possible sizes in an array, translated to the
6434 * local language.
6436 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6438 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6439 * with the value set to 0. This option will be the first in the list.
6441 * @uses SORT_NUMERIC
6442 * @param int $sitebytes Set maximum size
6443 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6444 * @param int $modulebytes Current module ->maxbytes (in bytes)
6445 * @param int|array $custombytes custom upload size/s which will be added to list,
6446 * Only value/s smaller then maxsize will be added to list.
6447 * @return array
6449 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6450 global $CFG;
6452 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6453 return array();
6456 if ($sitebytes == 0) {
6457 // Will get the minimum of upload_max_filesize or post_max_size.
6458 $sitebytes = get_max_upload_file_size();
6461 $filesize = array();
6462 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6463 5242880, 10485760, 20971520, 52428800, 104857600);
6465 // If custombytes is given and is valid then add it to the list.
6466 if (is_number($custombytes) and $custombytes > 0) {
6467 $custombytes = (int)$custombytes;
6468 if (!in_array($custombytes, $sizelist)) {
6469 $sizelist[] = $custombytes;
6471 } else if (is_array($custombytes)) {
6472 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6475 // Allow maxbytes to be selected if it falls outside the above boundaries.
6476 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6477 // Note: get_real_size() is used in order to prevent problems with invalid values.
6478 $sizelist[] = get_real_size($CFG->maxbytes);
6481 foreach ($sizelist as $sizebytes) {
6482 if ($sizebytes < $maxsize && $sizebytes > 0) {
6483 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6487 $limitlevel = '';
6488 $displaysize = '';
6489 if ($modulebytes &&
6490 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6491 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6492 $limitlevel = get_string('activity', 'core');
6493 $displaysize = display_size($modulebytes);
6494 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6496 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6497 $limitlevel = get_string('course', 'core');
6498 $displaysize = display_size($coursebytes);
6499 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6501 } else if ($sitebytes) {
6502 $limitlevel = get_string('site', 'core');
6503 $displaysize = display_size($sitebytes);
6504 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6507 krsort($filesize, SORT_NUMERIC);
6508 if ($limitlevel) {
6509 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6510 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6513 return $filesize;
6517 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6519 * If excludefiles is defined, then that file/directory is ignored
6520 * If getdirs is true, then (sub)directories are included in the output
6521 * If getfiles is true, then files are included in the output
6522 * (at least one of these must be true!)
6524 * @todo Finish documenting this function. Add examples of $excludefile usage.
6526 * @param string $rootdir A given root directory to start from
6527 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6528 * @param bool $descend If true then subdirectories are recursed as well
6529 * @param bool $getdirs If true then (sub)directories are included in the output
6530 * @param bool $getfiles If true then files are included in the output
6531 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6533 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6535 $dirs = array();
6537 if (!$getdirs and !$getfiles) { // Nothing to show.
6538 return $dirs;
6541 if (!is_dir($rootdir)) { // Must be a directory.
6542 return $dirs;
6545 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6546 return $dirs;
6549 if (!is_array($excludefiles)) {
6550 $excludefiles = array($excludefiles);
6553 while (false !== ($file = readdir($dir))) {
6554 $firstchar = substr($file, 0, 1);
6555 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6556 continue;
6558 $fullfile = $rootdir .'/'. $file;
6559 if (filetype($fullfile) == 'dir') {
6560 if ($getdirs) {
6561 $dirs[] = $file;
6563 if ($descend) {
6564 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6565 foreach ($subdirs as $subdir) {
6566 $dirs[] = $file .'/'. $subdir;
6569 } else if ($getfiles) {
6570 $dirs[] = $file;
6573 closedir($dir);
6575 asort($dirs);
6577 return $dirs;
6582 * Adds up all the files in a directory and works out the size.
6584 * @param string $rootdir The directory to start from
6585 * @param string $excludefile A file to exclude when summing directory size
6586 * @return int The summed size of all files and subfiles within the root directory
6588 function get_directory_size($rootdir, $excludefile='') {
6589 global $CFG;
6591 // Do it this way if we can, it's much faster.
6592 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6593 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6594 $output = null;
6595 $return = null;
6596 exec($command, $output, $return);
6597 if (is_array($output)) {
6598 // We told it to return k.
6599 return get_real_size(intval($output[0]).'k');
6603 if (!is_dir($rootdir)) {
6604 // Must be a directory.
6605 return 0;
6608 if (!$dir = @opendir($rootdir)) {
6609 // Can't open it for some reason.
6610 return 0;
6613 $size = 0;
6615 while (false !== ($file = readdir($dir))) {
6616 $firstchar = substr($file, 0, 1);
6617 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6618 continue;
6620 $fullfile = $rootdir .'/'. $file;
6621 if (filetype($fullfile) == 'dir') {
6622 $size += get_directory_size($fullfile, $excludefile);
6623 } else {
6624 $size += filesize($fullfile);
6627 closedir($dir);
6629 return $size;
6633 * Converts bytes into display form
6635 * @static string $gb Localized string for size in gigabytes
6636 * @static string $mb Localized string for size in megabytes
6637 * @static string $kb Localized string for size in kilobytes
6638 * @static string $b Localized string for size in bytes
6639 * @param int $size The size to convert to human readable form
6640 * @return string
6642 function display_size($size) {
6644 static $gb, $mb, $kb, $b;
6646 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6647 return get_string('unlimited');
6650 if (empty($gb)) {
6651 $gb = get_string('sizegb');
6652 $mb = get_string('sizemb');
6653 $kb = get_string('sizekb');
6654 $b = get_string('sizeb');
6657 if ($size >= 1073741824) {
6658 $size = round($size / 1073741824 * 10) / 10 . $gb;
6659 } else if ($size >= 1048576) {
6660 $size = round($size / 1048576 * 10) / 10 . $mb;
6661 } else if ($size >= 1024) {
6662 $size = round($size / 1024 * 10) / 10 . $kb;
6663 } else {
6664 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6666 return $size;
6670 * Cleans a given filename by removing suspicious or troublesome characters
6672 * @see clean_param()
6673 * @param string $string file name
6674 * @return string cleaned file name
6676 function clean_filename($string) {
6677 return clean_param($string, PARAM_FILE);
6681 // STRING TRANSLATION.
6684 * Returns the code for the current language
6686 * @category string
6687 * @return string
6689 function current_language() {
6690 global $CFG, $USER, $SESSION, $COURSE;
6692 if (!empty($SESSION->forcelang)) {
6693 // Allows overriding course-forced language (useful for admins to check
6694 // issues in courses whose language they don't understand).
6695 // Also used by some code to temporarily get language-related information in a
6696 // specific language (see force_current_language()).
6697 $return = $SESSION->forcelang;
6699 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6700 // Course language can override all other settings for this page.
6701 $return = $COURSE->lang;
6703 } else if (!empty($SESSION->lang)) {
6704 // Session language can override other settings.
6705 $return = $SESSION->lang;
6707 } else if (!empty($USER->lang)) {
6708 $return = $USER->lang;
6710 } else if (isset($CFG->lang)) {
6711 $return = $CFG->lang;
6713 } else {
6714 $return = 'en';
6717 // Just in case this slipped in from somewhere by accident.
6718 $return = str_replace('_utf8', '', $return);
6720 return $return;
6724 * Returns parent language of current active language if defined
6726 * @category string
6727 * @param string $lang null means current language
6728 * @return string
6730 function get_parent_language($lang=null) {
6732 // Let's hack around the current language.
6733 if (!empty($lang)) {
6734 $oldforcelang = force_current_language($lang);
6737 $parentlang = get_string('parentlanguage', 'langconfig');
6738 if ($parentlang === 'en') {
6739 $parentlang = '';
6742 // Let's hack around the current language.
6743 if (!empty($lang)) {
6744 force_current_language($oldforcelang);
6747 return $parentlang;
6751 * Force the current language to get strings and dates localised in the given language.
6753 * After calling this function, all strings will be provided in the given language
6754 * until this function is called again, or equivalent code is run.
6756 * @param string $language
6757 * @return string previous $SESSION->forcelang value
6759 function force_current_language($language) {
6760 global $SESSION;
6761 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6762 if ($language !== $sessionforcelang) {
6763 // Seting forcelang to null or an empty string disables it's effect.
6764 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6765 $SESSION->forcelang = $language;
6766 moodle_setlocale();
6769 return $sessionforcelang;
6773 * Returns current string_manager instance.
6775 * The param $forcereload is needed for CLI installer only where the string_manager instance
6776 * must be replaced during the install.php script life time.
6778 * @category string
6779 * @param bool $forcereload shall the singleton be released and new instance created instead?
6780 * @return core_string_manager
6782 function get_string_manager($forcereload=false) {
6783 global $CFG;
6785 static $singleton = null;
6787 if ($forcereload) {
6788 $singleton = null;
6790 if ($singleton === null) {
6791 if (empty($CFG->early_install_lang)) {
6793 if (empty($CFG->langlist)) {
6794 $translist = array();
6795 } else {
6796 $translist = explode(',', $CFG->langlist);
6799 if (!empty($CFG->config_php_settings['customstringmanager'])) {
6800 $classname = $CFG->config_php_settings['customstringmanager'];
6802 if (class_exists($classname)) {
6803 $implements = class_implements($classname);
6805 if (isset($implements['core_string_manager'])) {
6806 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
6807 return $singleton;
6809 } else {
6810 debugging('Unable to instantiate custom string manager: class '.$classname.
6811 ' does not implement the core_string_manager interface.');
6814 } else {
6815 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6819 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6821 } else {
6822 $singleton = new core_string_manager_install();
6826 return $singleton;
6830 * Returns a localized string.
6832 * Returns the translated string specified by $identifier as
6833 * for $module. Uses the same format files as STphp.
6834 * $a is an object, string or number that can be used
6835 * within translation strings
6837 * eg 'hello {$a->firstname} {$a->lastname}'
6838 * or 'hello {$a}'
6840 * If you would like to directly echo the localized string use
6841 * the function {@link print_string()}
6843 * Example usage of this function involves finding the string you would
6844 * like a local equivalent of and using its identifier and module information
6845 * to retrieve it.<br/>
6846 * If you open moodle/lang/en/moodle.php and look near line 278
6847 * you will find a string to prompt a user for their word for 'course'
6848 * <code>
6849 * $string['course'] = 'Course';
6850 * </code>
6851 * So if you want to display the string 'Course'
6852 * in any language that supports it on your site
6853 * you just need to use the identifier 'course'
6854 * <code>
6855 * $mystring = '<strong>'. get_string('course') .'</strong>';
6856 * or
6857 * </code>
6858 * If the string you want is in another file you'd take a slightly
6859 * different approach. Looking in moodle/lang/en/calendar.php you find
6860 * around line 75:
6861 * <code>
6862 * $string['typecourse'] = 'Course event';
6863 * </code>
6864 * If you want to display the string "Course event" in any language
6865 * supported you would use the identifier 'typecourse' and the module 'calendar'
6866 * (because it is in the file calendar.php):
6867 * <code>
6868 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6869 * </code>
6871 * As a last resort, should the identifier fail to map to a string
6872 * the returned string will be [[ $identifier ]]
6874 * In Moodle 2.3 there is a new argument to this function $lazyload.
6875 * Setting $lazyload to true causes get_string to return a lang_string object
6876 * rather than the string itself. The fetching of the string is then put off until
6877 * the string object is first used. The object can be used by calling it's out
6878 * method or by casting the object to a string, either directly e.g.
6879 * (string)$stringobject
6880 * or indirectly by using the string within another string or echoing it out e.g.
6881 * echo $stringobject
6882 * return "<p>{$stringobject}</p>";
6883 * It is worth noting that using $lazyload and attempting to use the string as an
6884 * array key will cause a fatal error as objects cannot be used as array keys.
6885 * But you should never do that anyway!
6886 * For more information {@link lang_string}
6888 * @category string
6889 * @param string $identifier The key identifier for the localized string
6890 * @param string $component The module where the key identifier is stored,
6891 * usually expressed as the filename in the language pack without the
6892 * .php on the end but can also be written as mod/forum or grade/export/xls.
6893 * If none is specified then moodle.php is used.
6894 * @param string|object|array $a An object, string or number that can be used
6895 * within translation strings
6896 * @param bool $lazyload If set to true a string object is returned instead of
6897 * the string itself. The string then isn't calculated until it is first used.
6898 * @return string The localized string.
6899 * @throws coding_exception
6901 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6902 global $CFG;
6904 // If the lazy load argument has been supplied return a lang_string object
6905 // instead.
6906 // We need to make sure it is true (and a bool) as you will see below there
6907 // used to be a forth argument at one point.
6908 if ($lazyload === true) {
6909 return new lang_string($identifier, $component, $a);
6912 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6913 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6916 // There is now a forth argument again, this time it is a boolean however so
6917 // we can still check for the old extralocations parameter.
6918 if (!is_bool($lazyload) && !empty($lazyload)) {
6919 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6922 if (strpos($component, '/') !== false) {
6923 debugging('The module name you passed to get_string is the deprecated format ' .
6924 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6925 $componentpath = explode('/', $component);
6927 switch ($componentpath[0]) {
6928 case 'mod':
6929 $component = $componentpath[1];
6930 break;
6931 case 'blocks':
6932 case 'block':
6933 $component = 'block_'.$componentpath[1];
6934 break;
6935 case 'enrol':
6936 $component = 'enrol_'.$componentpath[1];
6937 break;
6938 case 'format':
6939 $component = 'format_'.$componentpath[1];
6940 break;
6941 case 'grade':
6942 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6943 break;
6947 $result = get_string_manager()->get_string($identifier, $component, $a);
6949 // Debugging feature lets you display string identifier and component.
6950 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6951 $result .= ' {' . $identifier . '/' . $component . '}';
6953 return $result;
6957 * Converts an array of strings to their localized value.
6959 * @param array $array An array of strings
6960 * @param string $component The language module that these strings can be found in.
6961 * @return stdClass translated strings.
6963 function get_strings($array, $component = '') {
6964 $string = new stdClass;
6965 foreach ($array as $item) {
6966 $string->$item = get_string($item, $component);
6968 return $string;
6972 * Prints out a translated string.
6974 * Prints out a translated string using the return value from the {@link get_string()} function.
6976 * Example usage of this function when the string is in the moodle.php file:<br/>
6977 * <code>
6978 * echo '<strong>';
6979 * print_string('course');
6980 * echo '</strong>';
6981 * </code>
6983 * Example usage of this function when the string is not in the moodle.php file:<br/>
6984 * <code>
6985 * echo '<h1>';
6986 * print_string('typecourse', 'calendar');
6987 * echo '</h1>';
6988 * </code>
6990 * @category string
6991 * @param string $identifier The key identifier for the localized string
6992 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6993 * @param string|object|array $a An object, string or number that can be used within translation strings
6995 function print_string($identifier, $component = '', $a = null) {
6996 echo get_string($identifier, $component, $a);
7000 * Returns a list of charset codes
7002 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7003 * (checking that such charset is supported by the texlib library!)
7005 * @return array And associative array with contents in the form of charset => charset
7007 function get_list_of_charsets() {
7009 $charsets = array(
7010 'EUC-JP' => 'EUC-JP',
7011 'ISO-2022-JP'=> 'ISO-2022-JP',
7012 'ISO-8859-1' => 'ISO-8859-1',
7013 'SHIFT-JIS' => 'SHIFT-JIS',
7014 'GB2312' => 'GB2312',
7015 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7016 'UTF-8' => 'UTF-8');
7018 asort($charsets);
7020 return $charsets;
7024 * Returns a list of valid and compatible themes
7026 * @return array
7028 function get_list_of_themes() {
7029 global $CFG;
7031 $themes = array();
7033 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7034 $themelist = explode(',', $CFG->themelist);
7035 } else {
7036 $themelist = array_keys(core_component::get_plugin_list("theme"));
7039 foreach ($themelist as $key => $themename) {
7040 $theme = theme_config::load($themename);
7041 $themes[$themename] = $theme;
7044 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7046 return $themes;
7050 * Factory function for emoticon_manager
7052 * @return emoticon_manager singleton
7054 function get_emoticon_manager() {
7055 static $singleton = null;
7057 if (is_null($singleton)) {
7058 $singleton = new emoticon_manager();
7061 return $singleton;
7065 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7067 * Whenever this manager mentiones 'emoticon object', the following data
7068 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7069 * altidentifier and altcomponent
7071 * @see admin_setting_emoticons
7073 * @copyright 2010 David Mudrak
7074 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7076 class emoticon_manager {
7079 * Returns the currently enabled emoticons
7081 * @return array of emoticon objects
7083 public function get_emoticons() {
7084 global $CFG;
7086 if (empty($CFG->emoticons)) {
7087 return array();
7090 $emoticons = $this->decode_stored_config($CFG->emoticons);
7092 if (!is_array($emoticons)) {
7093 // Something is wrong with the format of stored setting.
7094 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7095 return array();
7098 return $emoticons;
7102 * Converts emoticon object into renderable pix_emoticon object
7104 * @param stdClass $emoticon emoticon object
7105 * @param array $attributes explicit HTML attributes to set
7106 * @return pix_emoticon
7108 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7109 $stringmanager = get_string_manager();
7110 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7111 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7112 } else {
7113 $alt = s($emoticon->text);
7115 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7119 * Encodes the array of emoticon objects into a string storable in config table
7121 * @see self::decode_stored_config()
7122 * @param array $emoticons array of emtocion objects
7123 * @return string
7125 public function encode_stored_config(array $emoticons) {
7126 return json_encode($emoticons);
7130 * Decodes the string into an array of emoticon objects
7132 * @see self::encode_stored_config()
7133 * @param string $encoded
7134 * @return string|null
7136 public function decode_stored_config($encoded) {
7137 $decoded = json_decode($encoded);
7138 if (!is_array($decoded)) {
7139 return null;
7141 return $decoded;
7145 * Returns default set of emoticons supported by Moodle
7147 * @return array of sdtClasses
7149 public function default_emoticons() {
7150 return array(
7151 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7152 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7153 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7154 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7155 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7156 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7157 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7158 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7159 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7160 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7161 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7162 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7163 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7164 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7165 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7166 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7167 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7168 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7169 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7170 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7171 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7172 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7173 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7174 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7175 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7176 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7177 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7178 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7179 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7180 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7185 * Helper method preparing the stdClass with the emoticon properties
7187 * @param string|array $text or array of strings
7188 * @param string $imagename to be used by {@link pix_emoticon}
7189 * @param string $altidentifier alternative string identifier, null for no alt
7190 * @param string $altcomponent where the alternative string is defined
7191 * @param string $imagecomponent to be used by {@link pix_emoticon}
7192 * @return stdClass
7194 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7195 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7196 return (object)array(
7197 'text' => $text,
7198 'imagename' => $imagename,
7199 'imagecomponent' => $imagecomponent,
7200 'altidentifier' => $altidentifier,
7201 'altcomponent' => $altcomponent,
7206 // ENCRYPTION.
7209 * rc4encrypt
7211 * @param string $data Data to encrypt.
7212 * @return string The now encrypted data.
7214 function rc4encrypt($data) {
7215 return endecrypt(get_site_identifier(), $data, '');
7219 * rc4decrypt
7221 * @param string $data Data to decrypt.
7222 * @return string The now decrypted data.
7224 function rc4decrypt($data) {
7225 return endecrypt(get_site_identifier(), $data, 'de');
7229 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7231 * @todo Finish documenting this function
7233 * @param string $pwd The password to use when encrypting or decrypting
7234 * @param string $data The data to be decrypted/encrypted
7235 * @param string $case Either 'de' for decrypt or '' for encrypt
7236 * @return string
7238 function endecrypt ($pwd, $data, $case) {
7240 if ($case == 'de') {
7241 $data = urldecode($data);
7244 $key[] = '';
7245 $box[] = '';
7246 $pwdlength = strlen($pwd);
7248 for ($i = 0; $i <= 255; $i++) {
7249 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7250 $box[$i] = $i;
7253 $x = 0;
7255 for ($i = 0; $i <= 255; $i++) {
7256 $x = ($x + $box[$i] + $key[$i]) % 256;
7257 $tempswap = $box[$i];
7258 $box[$i] = $box[$x];
7259 $box[$x] = $tempswap;
7262 $cipher = '';
7264 $a = 0;
7265 $j = 0;
7267 for ($i = 0; $i < strlen($data); $i++) {
7268 $a = ($a + 1) % 256;
7269 $j = ($j + $box[$a]) % 256;
7270 $temp = $box[$a];
7271 $box[$a] = $box[$j];
7272 $box[$j] = $temp;
7273 $k = $box[(($box[$a] + $box[$j]) % 256)];
7274 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7275 $cipher .= chr($cipherby);
7278 if ($case == 'de') {
7279 $cipher = urldecode(urlencode($cipher));
7280 } else {
7281 $cipher = urlencode($cipher);
7284 return $cipher;
7287 // ENVIRONMENT CHECKING.
7290 * This method validates a plug name. It is much faster than calling clean_param.
7292 * @param string $name a string that might be a plugin name.
7293 * @return bool if this string is a valid plugin name.
7295 function is_valid_plugin_name($name) {
7296 // This does not work for 'mod', bad luck, use any other type.
7297 return core_component::is_valid_plugin_name('tool', $name);
7301 * Get a list of all the plugins of a given type that define a certain API function
7302 * in a certain file. The plugin component names and function names are returned.
7304 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7305 * @param string $function the part of the name of the function after the
7306 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7307 * names like report_courselist_hook.
7308 * @param string $file the name of file within the plugin that defines the
7309 * function. Defaults to lib.php.
7310 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7311 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7313 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7314 global $CFG;
7316 // We don't include here as all plugin types files would be included.
7317 $plugins = get_plugins_with_function($function, $file, false);
7319 if (empty($plugins[$plugintype])) {
7320 return array();
7323 $allplugins = core_component::get_plugin_list($plugintype);
7325 // Reformat the array and include the files.
7326 $pluginfunctions = array();
7327 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7329 // Check that it has not been removed and the file is still available.
7330 if (!empty($allplugins[$pluginname])) {
7332 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7333 if (file_exists($filepath)) {
7334 include_once($filepath);
7335 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7340 return $pluginfunctions;
7344 * Get a list of all the plugins that define a certain API function in a certain file.
7346 * @param string $function the part of the name of the function after the
7347 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7348 * names like report_courselist_hook.
7349 * @param string $file the name of file within the plugin that defines the
7350 * function. Defaults to lib.php.
7351 * @param bool $include Whether to include the files that contain the functions or not.
7352 * @return array with [plugintype][plugin] = functionname
7354 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7355 global $CFG;
7357 $cache = \cache::make('core', 'plugin_functions');
7359 // Including both although I doubt that we will find two functions definitions with the same name.
7360 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7361 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7363 if ($pluginfunctions = $cache->get($key)) {
7365 // Checking that the files are still available.
7366 foreach ($pluginfunctions as $plugintype => $plugins) {
7368 $allplugins = \core_component::get_plugin_list($plugintype);
7369 foreach ($plugins as $plugin => $fullpath) {
7371 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7372 if (empty($allplugins[$plugin])) {
7373 unset($pluginfunctions[$plugintype][$plugin]);
7374 continue;
7377 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7378 if ($include && $fileexists) {
7379 // Include the files if it was requested.
7380 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7381 } else if (!$fileexists) {
7382 // If the file is not available any more it should not be returned.
7383 unset($pluginfunctions[$plugintype][$plugin]);
7387 return $pluginfunctions;
7390 $pluginfunctions = array();
7392 // To fill the cached. Also, everything should continue working with cache disabled.
7393 $plugintypes = \core_component::get_plugin_types();
7394 foreach ($plugintypes as $plugintype => $unused) {
7396 // We need to include files here.
7397 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7398 foreach ($pluginswithfile as $plugin => $notused) {
7400 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7402 $pluginfunction = false;
7403 if (function_exists($fullfunction)) {
7404 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7405 $pluginfunction = $fullfunction;
7407 } else if ($plugintype === 'mod') {
7408 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7409 $shortfunction = $plugin . '_' . $function;
7410 if (function_exists($shortfunction)) {
7411 $pluginfunction = $shortfunction;
7415 if ($pluginfunction) {
7416 if (empty($pluginfunctions[$plugintype])) {
7417 $pluginfunctions[$plugintype] = array();
7419 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7424 $cache->set($key, $pluginfunctions);
7426 return $pluginfunctions;
7431 * Lists plugin-like directories within specified directory
7433 * This function was originally used for standard Moodle plugins, please use
7434 * new core_component::get_plugin_list() now.
7436 * This function is used for general directory listing and backwards compatility.
7438 * @param string $directory relative directory from root
7439 * @param string $exclude dir name to exclude from the list (defaults to none)
7440 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7441 * @return array Sorted array of directory names found under the requested parameters
7443 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7444 global $CFG;
7446 $plugins = array();
7448 if (empty($basedir)) {
7449 $basedir = $CFG->dirroot .'/'. $directory;
7451 } else {
7452 $basedir = $basedir .'/'. $directory;
7455 if ($CFG->debugdeveloper and empty($exclude)) {
7456 // Make sure devs do not use this to list normal plugins,
7457 // this is intended for general directories that are not plugins!
7459 $subtypes = core_component::get_plugin_types();
7460 if (in_array($basedir, $subtypes)) {
7461 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7463 unset($subtypes);
7466 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7467 if (!$dirhandle = opendir($basedir)) {
7468 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7469 return array();
7471 while (false !== ($dir = readdir($dirhandle))) {
7472 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7473 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7474 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7475 continue;
7477 if (filetype($basedir .'/'. $dir) != 'dir') {
7478 continue;
7480 $plugins[] = $dir;
7482 closedir($dirhandle);
7484 if ($plugins) {
7485 asort($plugins);
7487 return $plugins;
7491 * Invoke plugin's callback functions
7493 * @param string $type plugin type e.g. 'mod'
7494 * @param string $name plugin name
7495 * @param string $feature feature name
7496 * @param string $action feature's action
7497 * @param array $params parameters of callback function, should be an array
7498 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7499 * @return mixed
7501 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7503 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7504 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7508 * Invoke component's callback functions
7510 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7511 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7512 * @param array $params parameters of callback function
7513 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7514 * @return mixed
7516 function component_callback($component, $function, array $params = array(), $default = null) {
7518 $functionname = component_callback_exists($component, $function);
7520 if ($functionname) {
7521 // Function exists, so just return function result.
7522 $ret = call_user_func_array($functionname, $params);
7523 if (is_null($ret)) {
7524 return $default;
7525 } else {
7526 return $ret;
7529 return $default;
7533 * Determine if a component callback exists and return the function name to call. Note that this
7534 * function will include the required library files so that the functioname returned can be
7535 * called directly.
7537 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7538 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7539 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7540 * @throws coding_exception if invalid component specfied
7542 function component_callback_exists($component, $function) {
7543 global $CFG; // This is needed for the inclusions.
7545 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7546 if (empty($cleancomponent)) {
7547 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7549 $component = $cleancomponent;
7551 list($type, $name) = core_component::normalize_component($component);
7552 $component = $type . '_' . $name;
7554 $oldfunction = $name.'_'.$function;
7555 $function = $component.'_'.$function;
7557 $dir = core_component::get_component_directory($component);
7558 if (empty($dir)) {
7559 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7562 // Load library and look for function.
7563 if (file_exists($dir.'/lib.php')) {
7564 require_once($dir.'/lib.php');
7567 if (!function_exists($function) and function_exists($oldfunction)) {
7568 if ($type !== 'mod' and $type !== 'core') {
7569 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7571 $function = $oldfunction;
7574 if (function_exists($function)) {
7575 return $function;
7577 return false;
7581 * Checks whether a plugin supports a specified feature.
7583 * @param string $type Plugin type e.g. 'mod'
7584 * @param string $name Plugin name e.g. 'forum'
7585 * @param string $feature Feature code (FEATURE_xx constant)
7586 * @param mixed $default default value if feature support unknown
7587 * @return mixed Feature result (false if not supported, null if feature is unknown,
7588 * otherwise usually true but may have other feature-specific value such as array)
7589 * @throws coding_exception
7591 function plugin_supports($type, $name, $feature, $default = null) {
7592 global $CFG;
7594 if ($type === 'mod' and $name === 'NEWMODULE') {
7595 // Somebody forgot to rename the module template.
7596 return false;
7599 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7600 if (empty($component)) {
7601 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7604 $function = null;
7606 if ($type === 'mod') {
7607 // We need this special case because we support subplugins in modules,
7608 // otherwise it would end up in infinite loop.
7609 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7610 include_once("$CFG->dirroot/mod/$name/lib.php");
7611 $function = $component.'_supports';
7612 if (!function_exists($function)) {
7613 // Legacy non-frankenstyle function name.
7614 $function = $name.'_supports';
7618 } else {
7619 if (!$path = core_component::get_plugin_directory($type, $name)) {
7620 // Non existent plugin type.
7621 return false;
7623 if (file_exists("$path/lib.php")) {
7624 include_once("$path/lib.php");
7625 $function = $component.'_supports';
7629 if ($function and function_exists($function)) {
7630 $supports = $function($feature);
7631 if (is_null($supports)) {
7632 // Plugin does not know - use default.
7633 return $default;
7634 } else {
7635 return $supports;
7639 // Plugin does not care, so use default.
7640 return $default;
7644 * Returns true if the current version of PHP is greater that the specified one.
7646 * @todo Check PHP version being required here is it too low?
7648 * @param string $version The version of php being tested.
7649 * @return bool
7651 function check_php_version($version='5.2.4') {
7652 return (version_compare(phpversion(), $version) >= 0);
7656 * Determine if moodle installation requires update.
7658 * Checks version numbers of main code and all plugins to see
7659 * if there are any mismatches.
7661 * @return bool
7663 function moodle_needs_upgrading() {
7664 global $CFG;
7666 if (empty($CFG->version)) {
7667 return true;
7670 // There is no need to purge plugininfo caches here because
7671 // these caches are not used during upgrade and they are purged after
7672 // every upgrade.
7674 if (empty($CFG->allversionshash)) {
7675 return true;
7678 $hash = core_component::get_all_versions_hash();
7680 return ($hash !== $CFG->allversionshash);
7684 * Returns the major version of this site
7686 * Moodle version numbers consist of three numbers separated by a dot, for
7687 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7688 * called major version. This function extracts the major version from either
7689 * $CFG->release (default) or eventually from the $release variable defined in
7690 * the main version.php.
7692 * @param bool $fromdisk should the version if source code files be used
7693 * @return string|false the major version like '2.3', false if could not be determined
7695 function moodle_major_version($fromdisk = false) {
7696 global $CFG;
7698 if ($fromdisk) {
7699 $release = null;
7700 require($CFG->dirroot.'/version.php');
7701 if (empty($release)) {
7702 return false;
7705 } else {
7706 if (empty($CFG->release)) {
7707 return false;
7709 $release = $CFG->release;
7712 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7713 return $matches[0];
7714 } else {
7715 return false;
7719 // MISCELLANEOUS.
7722 * Sets the system locale
7724 * @category string
7725 * @param string $locale Can be used to force a locale
7727 function moodle_setlocale($locale='') {
7728 global $CFG;
7730 static $currentlocale = ''; // Last locale caching.
7732 $oldlocale = $currentlocale;
7734 // Fetch the correct locale based on ostype.
7735 if ($CFG->ostype == 'WINDOWS') {
7736 $stringtofetch = 'localewin';
7737 } else {
7738 $stringtofetch = 'locale';
7741 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7742 if (!empty($locale)) {
7743 $currentlocale = $locale;
7744 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7745 $currentlocale = $CFG->locale;
7746 } else {
7747 $currentlocale = get_string($stringtofetch, 'langconfig');
7750 // Do nothing if locale already set up.
7751 if ($oldlocale == $currentlocale) {
7752 return;
7755 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7756 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7757 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7759 // Get current values.
7760 $monetary= setlocale (LC_MONETARY, 0);
7761 $numeric = setlocale (LC_NUMERIC, 0);
7762 $ctype = setlocale (LC_CTYPE, 0);
7763 if ($CFG->ostype != 'WINDOWS') {
7764 $messages= setlocale (LC_MESSAGES, 0);
7766 // Set locale to all.
7767 $result = setlocale (LC_ALL, $currentlocale);
7768 // If setting of locale fails try the other utf8 or utf-8 variant,
7769 // some operating systems support both (Debian), others just one (OSX).
7770 if ($result === false) {
7771 if (stripos($currentlocale, '.UTF-8') !== false) {
7772 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7773 setlocale (LC_ALL, $newlocale);
7774 } else if (stripos($currentlocale, '.UTF8') !== false) {
7775 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7776 setlocale (LC_ALL, $newlocale);
7779 // Set old values.
7780 setlocale (LC_MONETARY, $monetary);
7781 setlocale (LC_NUMERIC, $numeric);
7782 if ($CFG->ostype != 'WINDOWS') {
7783 setlocale (LC_MESSAGES, $messages);
7785 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7786 // To workaround a well-known PHP problem with Turkish letter Ii.
7787 setlocale (LC_CTYPE, $ctype);
7792 * Count words in a string.
7794 * Words are defined as things between whitespace.
7796 * @category string
7797 * @param string $string The text to be searched for words.
7798 * @return int The count of words in the specified string
7800 function count_words($string) {
7801 $string = strip_tags($string);
7802 // Decode HTML entities.
7803 $string = html_entity_decode($string);
7804 // Replace underscores (which are classed as word characters) with spaces.
7805 $string = preg_replace('/_/u', ' ', $string);
7806 // Remove any characters that shouldn't be treated as word boundaries.
7807 $string = preg_replace('/[\'"’-]/u', '', $string);
7808 // Remove dots and commas from within numbers only.
7809 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7811 return count(preg_split('/\w\b/u', $string)) - 1;
7815 * Count letters in a string.
7817 * Letters are defined as chars not in tags and different from whitespace.
7819 * @category string
7820 * @param string $string The text to be searched for letters.
7821 * @return int The count of letters in the specified text.
7823 function count_letters($string) {
7824 $string = strip_tags($string); // Tags are out now.
7825 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7827 return core_text::strlen($string);
7831 * Generate and return a random string of the specified length.
7833 * @param int $length The length of the string to be created.
7834 * @return string
7836 function random_string($length=15) {
7837 $randombytes = random_bytes_emulate($length);
7838 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7839 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7840 $pool .= '0123456789';
7841 $poollen = strlen($pool);
7842 $string = '';
7843 for ($i = 0; $i < $length; $i++) {
7844 $rand = ord($randombytes[$i]);
7845 $string .= substr($pool, ($rand%($poollen)), 1);
7847 return $string;
7851 * Generate a complex random string (useful for md5 salts)
7853 * This function is based on the above {@link random_string()} however it uses a
7854 * larger pool of characters and generates a string between 24 and 32 characters
7856 * @param int $length Optional if set generates a string to exactly this length
7857 * @return string
7859 function complex_random_string($length=null) {
7860 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7861 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7862 $poollen = strlen($pool);
7863 if ($length===null) {
7864 $length = floor(rand(24, 32));
7866 $randombytes = random_bytes_emulate($length);
7867 $string = '';
7868 for ($i = 0; $i < $length; $i++) {
7869 $rand = ord($randombytes[$i]);
7870 $string .= $pool[($rand%$poollen)];
7872 return $string;
7876 * Try to generates cryptographically secure pseudo-random bytes.
7878 * Note this is achieved by fallbacking between:
7879 * - PHP 7 random_bytes().
7880 * - OpenSSL openssl_random_pseudo_bytes().
7881 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
7883 * @param int $length requested length in bytes
7884 * @return string binary data
7886 function random_bytes_emulate($length) {
7887 global $CFG;
7888 if ($length <= 0) {
7889 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
7890 return '';
7892 if (function_exists('random_bytes')) {
7893 // Use PHP 7 goodness.
7894 $hash = @random_bytes($length);
7895 if ($hash !== false) {
7896 return $hash;
7899 if (function_exists('openssl_random_pseudo_bytes')) {
7900 // If you have the openssl extension enabled.
7901 $hash = openssl_random_pseudo_bytes($length);
7902 if ($hash !== false) {
7903 return $hash;
7907 // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
7908 $staticdata = serialize($CFG) . serialize($_SERVER);
7909 $hash = '';
7910 do {
7911 $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
7912 } while (strlen($hash) < $length);
7914 return substr($hash, 0, $length);
7918 * Given some text (which may contain HTML) and an ideal length,
7919 * this function truncates the text neatly on a word boundary if possible
7921 * @category string
7922 * @param string $text text to be shortened
7923 * @param int $ideal ideal string length
7924 * @param boolean $exact if false, $text will not be cut mid-word
7925 * @param string $ending The string to append if the passed string is truncated
7926 * @return string $truncate shortened string
7928 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7929 // If the plain text is shorter than the maximum length, return the whole text.
7930 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7931 return $text;
7934 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7935 // and only tag in its 'line'.
7936 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7938 $totallength = core_text::strlen($ending);
7939 $truncate = '';
7941 // This array stores information about open and close tags and their position
7942 // in the truncated string. Each item in the array is an object with fields
7943 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7944 // (byte position in truncated text).
7945 $tagdetails = array();
7947 foreach ($lines as $linematchings) {
7948 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7949 if (!empty($linematchings[1])) {
7950 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7951 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7952 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7953 // Record closing tag.
7954 $tagdetails[] = (object) array(
7955 'open' => false,
7956 'tag' => core_text::strtolower($tagmatchings[1]),
7957 'pos' => core_text::strlen($truncate),
7960 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7961 // Record opening tag.
7962 $tagdetails[] = (object) array(
7963 'open' => true,
7964 'tag' => core_text::strtolower($tagmatchings[1]),
7965 'pos' => core_text::strlen($truncate),
7967 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
7968 $tagdetails[] = (object) array(
7969 'open' => true,
7970 'tag' => core_text::strtolower('if'),
7971 'pos' => core_text::strlen($truncate),
7973 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
7974 $tagdetails[] = (object) array(
7975 'open' => false,
7976 'tag' => core_text::strtolower('if'),
7977 'pos' => core_text::strlen($truncate),
7981 // Add html-tag to $truncate'd text.
7982 $truncate .= $linematchings[1];
7985 // Calculate the length of the plain text part of the line; handle entities as one character.
7986 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7987 if ($totallength + $contentlength > $ideal) {
7988 // The number of characters which are left.
7989 $left = $ideal - $totallength;
7990 $entitieslength = 0;
7991 // Search for html entities.
7992 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)) {
7993 // Calculate the real length of all entities in the legal range.
7994 foreach ($entities[0] as $entity) {
7995 if ($entity[1]+1-$entitieslength <= $left) {
7996 $left--;
7997 $entitieslength += core_text::strlen($entity[0]);
7998 } else {
7999 // No more characters left.
8000 break;
8004 $breakpos = $left + $entitieslength;
8006 // If the words shouldn't be cut in the middle...
8007 if (!$exact) {
8008 // Search the last occurence of a space.
8009 for (; $breakpos > 0; $breakpos--) {
8010 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8011 if ($char === '.' or $char === ' ') {
8012 $breakpos += 1;
8013 break;
8014 } else if (strlen($char) > 2) {
8015 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8016 $breakpos += 1;
8017 break;
8022 if ($breakpos == 0) {
8023 // This deals with the test_shorten_text_no_spaces case.
8024 $breakpos = $left + $entitieslength;
8025 } else if ($breakpos > $left + $entitieslength) {
8026 // This deals with the previous for loop breaking on the first char.
8027 $breakpos = $left + $entitieslength;
8030 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8031 // Maximum length is reached, so get off the loop.
8032 break;
8033 } else {
8034 $truncate .= $linematchings[2];
8035 $totallength += $contentlength;
8038 // If the maximum length is reached, get off the loop.
8039 if ($totallength >= $ideal) {
8040 break;
8044 // Add the defined ending to the text.
8045 $truncate .= $ending;
8047 // Now calculate the list of open html tags based on the truncate position.
8048 $opentags = array();
8049 foreach ($tagdetails as $taginfo) {
8050 if ($taginfo->open) {
8051 // Add tag to the beginning of $opentags list.
8052 array_unshift($opentags, $taginfo->tag);
8053 } else {
8054 // Can have multiple exact same open tags, close the last one.
8055 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8056 if ($pos !== false) {
8057 unset($opentags[$pos]);
8062 // Close all unclosed html-tags.
8063 foreach ($opentags as $tag) {
8064 if ($tag === 'if') {
8065 $truncate .= '<!--<![endif]-->';
8066 } else {
8067 $truncate .= '</' . $tag . '>';
8071 return $truncate;
8076 * Given dates in seconds, how many weeks is the date from startdate
8077 * The first week is 1, the second 2 etc ...
8079 * @param int $startdate Timestamp for the start date
8080 * @param int $thedate Timestamp for the end date
8081 * @return string
8083 function getweek ($startdate, $thedate) {
8084 if ($thedate < $startdate) {
8085 return 0;
8088 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8092 * Returns a randomly generated password of length $maxlen. inspired by
8094 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8095 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8097 * @param int $maxlen The maximum size of the password being generated.
8098 * @return string
8100 function generate_password($maxlen=10) {
8101 global $CFG;
8103 if (empty($CFG->passwordpolicy)) {
8104 $fillers = PASSWORD_DIGITS;
8105 $wordlist = file($CFG->wordlist);
8106 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8107 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8108 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8109 $password = $word1 . $filler1 . $word2;
8110 } else {
8111 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8112 $digits = $CFG->minpassworddigits;
8113 $lower = $CFG->minpasswordlower;
8114 $upper = $CFG->minpasswordupper;
8115 $nonalphanum = $CFG->minpasswordnonalphanum;
8116 $total = $lower + $upper + $digits + $nonalphanum;
8117 // Var minlength should be the greater one of the two ( $minlen and $total ).
8118 $minlen = $minlen < $total ? $total : $minlen;
8119 // Var maxlen can never be smaller than minlen.
8120 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8121 $additional = $maxlen - $total;
8123 // Make sure we have enough characters to fulfill
8124 // complexity requirements.
8125 $passworddigits = PASSWORD_DIGITS;
8126 while ($digits > strlen($passworddigits)) {
8127 $passworddigits .= PASSWORD_DIGITS;
8129 $passwordlower = PASSWORD_LOWER;
8130 while ($lower > strlen($passwordlower)) {
8131 $passwordlower .= PASSWORD_LOWER;
8133 $passwordupper = PASSWORD_UPPER;
8134 while ($upper > strlen($passwordupper)) {
8135 $passwordupper .= PASSWORD_UPPER;
8137 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8138 while ($nonalphanum > strlen($passwordnonalphanum)) {
8139 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8142 // Now mix and shuffle it all.
8143 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8144 substr(str_shuffle ($passwordupper), 0, $upper) .
8145 substr(str_shuffle ($passworddigits), 0, $digits) .
8146 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8147 substr(str_shuffle ($passwordlower .
8148 $passwordupper .
8149 $passworddigits .
8150 $passwordnonalphanum), 0 , $additional));
8153 return substr ($password, 0, $maxlen);
8157 * Given a float, prints it nicely.
8158 * Localized floats must not be used in calculations!
8160 * The stripzeros feature is intended for making numbers look nicer in small
8161 * areas where it is not necessary to indicate the degree of accuracy by showing
8162 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8163 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8165 * @param float $float The float to print
8166 * @param int $decimalpoints The number of decimal places to print.
8167 * @param bool $localized use localized decimal separator
8168 * @param bool $stripzeros If true, removes final zeros after decimal point
8169 * @return string locale float
8171 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8172 if (is_null($float)) {
8173 return '';
8175 if ($localized) {
8176 $separator = get_string('decsep', 'langconfig');
8177 } else {
8178 $separator = '.';
8180 $result = number_format($float, $decimalpoints, $separator, '');
8181 if ($stripzeros) {
8182 // Remove zeros and final dot if not needed.
8183 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8185 return $result;
8189 * Converts locale specific floating point/comma number back to standard PHP float value
8190 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8192 * @param string $localefloat locale aware float representation
8193 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8194 * @return mixed float|bool - false or the parsed float.
8196 function unformat_float($localefloat, $strict = false) {
8197 $localefloat = trim($localefloat);
8199 if ($localefloat == '') {
8200 return null;
8203 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8204 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8206 if ($strict && !is_numeric($localefloat)) {
8207 return false;
8210 return (float)$localefloat;
8214 * Given a simple array, this shuffles it up just like shuffle()
8215 * Unlike PHP's shuffle() this function works on any machine.
8217 * @param array $array The array to be rearranged
8218 * @return array
8220 function swapshuffle($array) {
8222 $last = count($array) - 1;
8223 for ($i = 0; $i <= $last; $i++) {
8224 $from = rand(0, $last);
8225 $curr = $array[$i];
8226 $array[$i] = $array[$from];
8227 $array[$from] = $curr;
8229 return $array;
8233 * Like {@link swapshuffle()}, but works on associative arrays
8235 * @param array $array The associative array to be rearranged
8236 * @return array
8238 function swapshuffle_assoc($array) {
8240 $newarray = array();
8241 $newkeys = swapshuffle(array_keys($array));
8243 foreach ($newkeys as $newkey) {
8244 $newarray[$newkey] = $array[$newkey];
8246 return $newarray;
8250 * Given an arbitrary array, and a number of draws,
8251 * this function returns an array with that amount
8252 * of items. The indexes are retained.
8254 * @todo Finish documenting this function
8256 * @param array $array
8257 * @param int $draws
8258 * @return array
8260 function draw_rand_array($array, $draws) {
8262 $return = array();
8264 $last = count($array);
8266 if ($draws > $last) {
8267 $draws = $last;
8270 while ($draws > 0) {
8271 $last--;
8273 $keys = array_keys($array);
8274 $rand = rand(0, $last);
8276 $return[$keys[$rand]] = $array[$keys[$rand]];
8277 unset($array[$keys[$rand]]);
8279 $draws--;
8282 return $return;
8286 * Calculate the difference between two microtimes
8288 * @param string $a The first Microtime
8289 * @param string $b The second Microtime
8290 * @return string
8292 function microtime_diff($a, $b) {
8293 list($adec, $asec) = explode(' ', $a);
8294 list($bdec, $bsec) = explode(' ', $b);
8295 return $bsec - $asec + $bdec - $adec;
8299 * Given a list (eg a,b,c,d,e) this function returns
8300 * an array of 1->a, 2->b, 3->c etc
8302 * @param string $list The string to explode into array bits
8303 * @param string $separator The separator used within the list string
8304 * @return array The now assembled array
8306 function make_menu_from_list($list, $separator=',') {
8308 $array = array_reverse(explode($separator, $list), true);
8309 foreach ($array as $key => $item) {
8310 $outarray[$key+1] = trim($item);
8312 return $outarray;
8316 * Creates an array that represents all the current grades that
8317 * can be chosen using the given grading type.
8319 * Negative numbers
8320 * are scales, zero is no grade, and positive numbers are maximum
8321 * grades.
8323 * @todo Finish documenting this function or better deprecated this completely!
8325 * @param int $gradingtype
8326 * @return array
8328 function make_grades_menu($gradingtype) {
8329 global $DB;
8331 $grades = array();
8332 if ($gradingtype < 0) {
8333 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8334 return make_menu_from_list($scale->scale);
8336 } else if ($gradingtype > 0) {
8337 for ($i=$gradingtype; $i>=0; $i--) {
8338 $grades[$i] = $i .' / '. $gradingtype;
8340 return $grades;
8342 return $grades;
8346 * make_unique_id_code
8348 * @todo Finish documenting this function
8350 * @uses $_SERVER
8351 * @param string $extra Extra string to append to the end of the code
8352 * @return string
8354 function make_unique_id_code($extra = '') {
8356 $hostname = 'unknownhost';
8357 if (!empty($_SERVER['HTTP_HOST'])) {
8358 $hostname = $_SERVER['HTTP_HOST'];
8359 } else if (!empty($_ENV['HTTP_HOST'])) {
8360 $hostname = $_ENV['HTTP_HOST'];
8361 } else if (!empty($_SERVER['SERVER_NAME'])) {
8362 $hostname = $_SERVER['SERVER_NAME'];
8363 } else if (!empty($_ENV['SERVER_NAME'])) {
8364 $hostname = $_ENV['SERVER_NAME'];
8367 $date = gmdate("ymdHis");
8369 $random = random_string(6);
8371 if ($extra) {
8372 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8373 } else {
8374 return $hostname .'+'. $date .'+'. $random;
8380 * Function to check the passed address is within the passed subnet
8382 * The parameter is a comma separated string of subnet definitions.
8383 * Subnet strings can be in one of three formats:
8384 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8385 * 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)
8386 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8387 * Code for type 1 modified from user posted comments by mediator at
8388 * {@link http://au.php.net/manual/en/function.ip2long.php}
8390 * @param string $addr The address you are checking
8391 * @param string $subnetstr The string of subnet addresses
8392 * @return bool
8394 function address_in_subnet($addr, $subnetstr) {
8396 if ($addr == '0.0.0.0') {
8397 return false;
8399 $subnets = explode(',', $subnetstr);
8400 $found = false;
8401 $addr = trim($addr);
8402 $addr = cleanremoteaddr($addr, false); // Normalise.
8403 if ($addr === null) {
8404 return false;
8406 $addrparts = explode(':', $addr);
8408 $ipv6 = strpos($addr, ':');
8410 foreach ($subnets as $subnet) {
8411 $subnet = trim($subnet);
8412 if ($subnet === '') {
8413 continue;
8416 if (strpos($subnet, '/') !== false) {
8417 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8418 list($ip, $mask) = explode('/', $subnet);
8419 $mask = trim($mask);
8420 if (!is_number($mask)) {
8421 continue; // Incorect mask number, eh?
8423 $ip = cleanremoteaddr($ip, false); // Normalise.
8424 if ($ip === null) {
8425 continue;
8427 if (strpos($ip, ':') !== false) {
8428 // IPv6.
8429 if (!$ipv6) {
8430 continue;
8432 if ($mask > 128 or $mask < 0) {
8433 continue; // Nonsense.
8435 if ($mask == 0) {
8436 return true; // Any address.
8438 if ($mask == 128) {
8439 if ($ip === $addr) {
8440 return true;
8442 continue;
8444 $ipparts = explode(':', $ip);
8445 $modulo = $mask % 16;
8446 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8447 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8448 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8449 if ($modulo == 0) {
8450 return true;
8452 $pos = ($mask-$modulo)/16;
8453 $ipnet = hexdec($ipparts[$pos]);
8454 $addrnet = hexdec($addrparts[$pos]);
8455 $mask = 0xffff << (16 - $modulo);
8456 if (($addrnet & $mask) == ($ipnet & $mask)) {
8457 return true;
8461 } else {
8462 // IPv4.
8463 if ($ipv6) {
8464 continue;
8466 if ($mask > 32 or $mask < 0) {
8467 continue; // Nonsense.
8469 if ($mask == 0) {
8470 return true;
8472 if ($mask == 32) {
8473 if ($ip === $addr) {
8474 return true;
8476 continue;
8478 $mask = 0xffffffff << (32 - $mask);
8479 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8480 return true;
8484 } else if (strpos($subnet, '-') !== false) {
8485 // 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.
8486 $parts = explode('-', $subnet);
8487 if (count($parts) != 2) {
8488 continue;
8491 if (strpos($subnet, ':') !== false) {
8492 // IPv6.
8493 if (!$ipv6) {
8494 continue;
8496 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8497 if ($ipstart === null) {
8498 continue;
8500 $ipparts = explode(':', $ipstart);
8501 $start = hexdec(array_pop($ipparts));
8502 $ipparts[] = trim($parts[1]);
8503 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8504 if ($ipend === null) {
8505 continue;
8507 $ipparts[7] = '';
8508 $ipnet = implode(':', $ipparts);
8509 if (strpos($addr, $ipnet) !== 0) {
8510 continue;
8512 $ipparts = explode(':', $ipend);
8513 $end = hexdec($ipparts[7]);
8515 $addrend = hexdec($addrparts[7]);
8517 if (($addrend >= $start) and ($addrend <= $end)) {
8518 return true;
8521 } else {
8522 // IPv4.
8523 if ($ipv6) {
8524 continue;
8526 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8527 if ($ipstart === null) {
8528 continue;
8530 $ipparts = explode('.', $ipstart);
8531 $ipparts[3] = trim($parts[1]);
8532 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8533 if ($ipend === null) {
8534 continue;
8537 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8538 return true;
8542 } else {
8543 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8544 if (strpos($subnet, ':') !== false) {
8545 // IPv6.
8546 if (!$ipv6) {
8547 continue;
8549 $parts = explode(':', $subnet);
8550 $count = count($parts);
8551 if ($parts[$count-1] === '') {
8552 unset($parts[$count-1]); // Trim trailing :'s.
8553 $count--;
8554 $subnet = implode('.', $parts);
8556 $isip = cleanremoteaddr($subnet, false); // Normalise.
8557 if ($isip !== null) {
8558 if ($isip === $addr) {
8559 return true;
8561 continue;
8562 } else if ($count > 8) {
8563 continue;
8565 $zeros = array_fill(0, 8-$count, '0');
8566 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8567 if (address_in_subnet($addr, $subnet)) {
8568 return true;
8571 } else {
8572 // IPv4.
8573 if ($ipv6) {
8574 continue;
8576 $parts = explode('.', $subnet);
8577 $count = count($parts);
8578 if ($parts[$count-1] === '') {
8579 unset($parts[$count-1]); // Trim trailing .
8580 $count--;
8581 $subnet = implode('.', $parts);
8583 if ($count == 4) {
8584 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8585 if ($subnet === $addr) {
8586 return true;
8588 continue;
8589 } else if ($count > 4) {
8590 continue;
8592 $zeros = array_fill(0, 4-$count, '0');
8593 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8594 if (address_in_subnet($addr, $subnet)) {
8595 return true;
8601 return false;
8605 * For outputting debugging info
8607 * @param string $string The string to write
8608 * @param string $eol The end of line char(s) to use
8609 * @param string $sleep Period to make the application sleep
8610 * This ensures any messages have time to display before redirect
8612 function mtrace($string, $eol="\n", $sleep=0) {
8614 if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
8615 fwrite(STDOUT, $string.$eol);
8616 } else {
8617 echo $string . $eol;
8620 flush();
8622 // Delay to keep message on user's screen in case of subsequent redirect.
8623 if ($sleep) {
8624 sleep($sleep);
8629 * Replace 1 or more slashes or backslashes to 1 slash
8631 * @param string $path The path to strip
8632 * @return string the path with double slashes removed
8634 function cleardoubleslashes ($path) {
8635 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8639 * Is current ip in give list?
8641 * @param string $list
8642 * @return bool
8644 function remoteip_in_list($list) {
8645 $inlist = false;
8646 $clientip = getremoteaddr(null);
8648 if (!$clientip) {
8649 // Ensure access on cli.
8650 return true;
8653 $list = explode("\n", $list);
8654 foreach ($list as $subnet) {
8655 $subnet = trim($subnet);
8656 if (address_in_subnet($clientip, $subnet)) {
8657 $inlist = true;
8658 break;
8661 return $inlist;
8665 * Returns most reliable client address
8667 * @param string $default If an address can't be determined, then return this
8668 * @return string The remote IP address
8670 function getremoteaddr($default='0.0.0.0') {
8671 global $CFG;
8673 if (empty($CFG->getremoteaddrconf)) {
8674 // This will happen, for example, before just after the upgrade, as the
8675 // user is redirected to the admin screen.
8676 $variablestoskip = 0;
8677 } else {
8678 $variablestoskip = $CFG->getremoteaddrconf;
8680 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8681 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8682 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8683 return $address ? $address : $default;
8686 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8687 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8688 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8689 $address = $forwardedaddresses[0];
8691 if (substr_count($address, ":") > 1) {
8692 // Remove port and brackets from IPv6.
8693 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8694 $address = $matches[1];
8696 } else {
8697 // Remove port from IPv4.
8698 if (substr_count($address, ":") == 1) {
8699 $parts = explode(":", $address);
8700 $address = $parts[0];
8704 $address = cleanremoteaddr($address);
8705 return $address ? $address : $default;
8708 if (!empty($_SERVER['REMOTE_ADDR'])) {
8709 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8710 return $address ? $address : $default;
8711 } else {
8712 return $default;
8717 * Cleans an ip address. Internal addresses are now allowed.
8718 * (Originally local addresses were not allowed.)
8720 * @param string $addr IPv4 or IPv6 address
8721 * @param bool $compress use IPv6 address compression
8722 * @return string normalised ip address string, null if error
8724 function cleanremoteaddr($addr, $compress=false) {
8725 $addr = trim($addr);
8727 if (strpos($addr, ':') !== false) {
8728 // Can be only IPv6.
8729 $parts = explode(':', $addr);
8730 $count = count($parts);
8732 if (strpos($parts[$count-1], '.') !== false) {
8733 // Legacy ipv4 notation.
8734 $last = array_pop($parts);
8735 $ipv4 = cleanremoteaddr($last, true);
8736 if ($ipv4 === null) {
8737 return null;
8739 $bits = explode('.', $ipv4);
8740 $parts[] = dechex($bits[0]).dechex($bits[1]);
8741 $parts[] = dechex($bits[2]).dechex($bits[3]);
8742 $count = count($parts);
8743 $addr = implode(':', $parts);
8746 if ($count < 3 or $count > 8) {
8747 return null; // Severly malformed.
8750 if ($count != 8) {
8751 if (strpos($addr, '::') === false) {
8752 return null; // Malformed.
8754 // Uncompress.
8755 $insertat = array_search('', $parts, true);
8756 $missing = array_fill(0, 1 + 8 - $count, '0');
8757 array_splice($parts, $insertat, 1, $missing);
8758 foreach ($parts as $key => $part) {
8759 if ($part === '') {
8760 $parts[$key] = '0';
8765 $adr = implode(':', $parts);
8766 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8767 return null; // Incorrect format - sorry.
8770 // Normalise 0s and case.
8771 $parts = array_map('hexdec', $parts);
8772 $parts = array_map('dechex', $parts);
8774 $result = implode(':', $parts);
8776 if (!$compress) {
8777 return $result;
8780 if ($result === '0:0:0:0:0:0:0:0') {
8781 return '::'; // All addresses.
8784 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8785 if ($compressed !== $result) {
8786 return $compressed;
8789 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8790 if ($compressed !== $result) {
8791 return $compressed;
8794 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8795 if ($compressed !== $result) {
8796 return $compressed;
8799 return $result;
8802 // First get all things that look like IPv4 addresses.
8803 $parts = array();
8804 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8805 return null;
8807 unset($parts[0]);
8809 foreach ($parts as $key => $match) {
8810 if ($match > 255) {
8811 return null;
8813 $parts[$key] = (int)$match; // Normalise 0s.
8816 return implode('.', $parts);
8821 * Is IP address a public address?
8823 * @param string $ip The ip to check
8824 * @return bool true if the ip is public
8826 function ip_is_public($ip) {
8827 return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
8831 * This function will make a complete copy of anything it's given,
8832 * regardless of whether it's an object or not.
8834 * @param mixed $thing Something you want cloned
8835 * @return mixed What ever it is you passed it
8837 function fullclone($thing) {
8838 return unserialize(serialize($thing));
8842 * Used to make sure that $min <= $value <= $max
8844 * Make sure that value is between min, and max
8846 * @param int $min The minimum value
8847 * @param int $value The value to check
8848 * @param int $max The maximum value
8849 * @return int
8851 function bounded_number($min, $value, $max) {
8852 if ($value < $min) {
8853 return $min;
8855 if ($value > $max) {
8856 return $max;
8858 return $value;
8862 * Check if there is a nested array within the passed array
8864 * @param array $array
8865 * @return bool true if there is a nested array false otherwise
8867 function array_is_nested($array) {
8868 foreach ($array as $value) {
8869 if (is_array($value)) {
8870 return true;
8873 return false;
8877 * get_performance_info() pairs up with init_performance_info()
8878 * loaded in setup.php. Returns an array with 'html' and 'txt'
8879 * values ready for use, and each of the individual stats provided
8880 * separately as well.
8882 * @return array
8884 function get_performance_info() {
8885 global $CFG, $PERF, $DB, $PAGE;
8887 $info = array();
8888 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8890 $info['html'] = '';
8891 if (!empty($CFG->themedesignermode)) {
8892 // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
8893 $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
8895 $info['html'] .= '<ul class="list-unstyled m-l-1">'; // Holds userfriendly HTML representation.
8897 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8899 $info['html'] .= '<li class="timeused">'.$info['realtime'].' secs</li> ';
8900 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8902 if (function_exists('memory_get_usage')) {
8903 $info['memory_total'] = memory_get_usage();
8904 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8905 $info['html'] .= '<li class="memoryused">RAM: '.display_size($info['memory_total']).'</li> ';
8906 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8907 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8910 if (function_exists('memory_get_peak_usage')) {
8911 $info['memory_peak'] = memory_get_peak_usage();
8912 $info['html'] .= '<li class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</li> ';
8913 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8916 $inc = get_included_files();
8917 $info['includecount'] = count($inc);
8918 $info['html'] .= '<li class="included">Included '.$info['includecount'].' files</li> ';
8919 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8921 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8922 // We can not track more performance before installation or before PAGE init, sorry.
8923 return $info;
8926 $filtermanager = filter_manager::instance();
8927 if (method_exists($filtermanager, 'get_performance_summary')) {
8928 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8929 $info = array_merge($filterinfo, $info);
8930 foreach ($filterinfo as $key => $value) {
8931 $info['html'] .= "<li class='$key'>$nicenames[$key]: $value </li> ";
8932 $info['txt'] .= "$key: $value ";
8936 $stringmanager = get_string_manager();
8937 if (method_exists($stringmanager, 'get_performance_summary')) {
8938 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8939 $info = array_merge($filterinfo, $info);
8940 foreach ($filterinfo as $key => $value) {
8941 $info['html'] .= "<li class='$key'>$nicenames[$key]: $value </li> ";
8942 $info['txt'] .= "$key: $value ";
8946 if (!empty($PERF->logwrites)) {
8947 $info['logwrites'] = $PERF->logwrites;
8948 $info['html'] .= '<li class="logwrites">Log DB writes '.$info['logwrites'].'</li> ';
8949 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8952 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
8953 $info['html'] .= '<li class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</li> ';
8954 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8956 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
8957 $info['html'] .= '<li class="dbtime">DB queries time: '.$info['dbtime'].' secs</li> ';
8958 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
8960 if (function_exists('posix_times')) {
8961 $ptimes = posix_times();
8962 if (is_array($ptimes)) {
8963 foreach ($ptimes as $key => $val) {
8964 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
8966 $info['html'] .= "<li class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
8967 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8971 // Grab the load average for the last minute.
8972 // /proc will only work under some linux configurations
8973 // while uptime is there under MacOSX/Darwin and other unices.
8974 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
8975 list($serverload) = explode(' ', $loadavg[0]);
8976 unset($loadavg);
8977 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
8978 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
8979 $serverload = $matches[1];
8980 } else {
8981 trigger_error('Could not parse uptime output!');
8984 if (!empty($serverload)) {
8985 $info['serverload'] = $serverload;
8986 $info['html'] .= '<li class="serverload">Load average: '.$info['serverload'].'</li> ';
8987 $info['txt'] .= "serverload: {$info['serverload']} ";
8990 // Display size of session if session started.
8991 if ($si = \core\session\manager::get_performance_info()) {
8992 $info['sessionsize'] = $si['size'];
8993 $info['html'] .= $si['html'];
8994 $info['txt'] .= $si['txt'];
8997 if ($stats = cache_helper::get_stats()) {
8998 $html = '<ul class="cachesused list-unstyled m-l-1">';
8999 $html .= '<li class="cache-stats-heading">Caches used (hits/misses/sets)</li>';
9000 $text = 'Caches used (hits/misses/sets): ';
9001 $hits = 0;
9002 $misses = 0;
9003 $sets = 0;
9004 foreach ($stats as $definition => $details) {
9005 switch ($details['mode']) {
9006 case cache_store::MODE_APPLICATION:
9007 $modeclass = 'application';
9008 $mode = ' <span title="application cache">[a]</span>';
9009 break;
9010 case cache_store::MODE_SESSION:
9011 $modeclass = 'session';
9012 $mode = ' <span title="session cache">[s]</span>';
9013 break;
9014 case cache_store::MODE_REQUEST:
9015 $modeclass = 'request';
9016 $mode = ' <span title="request cache">[r]</span>';
9017 break;
9019 $html .= '<ul class="cache-definition-stats list-unstyled m-l-1 cache-mode-'.$modeclass.'">';
9020 $html .= '<li class="cache-definition-stats-heading p-t-1">'.$definition.$mode.'</li>';
9021 $text .= "$definition {";
9022 foreach ($details['stores'] as $store => $data) {
9023 $hits += $data['hits'];
9024 $misses += $data['misses'];
9025 $sets += $data['sets'];
9026 if ($data['hits'] == 0 and $data['misses'] > 0) {
9027 $cachestoreclass = 'nohits text-danger';
9028 } else if ($data['hits'] < $data['misses']) {
9029 $cachestoreclass = 'lowhits text-warning';
9030 } else {
9031 $cachestoreclass = 'hihits text-success';
9033 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9034 $html .= "<li class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</li>";
9036 $html .= '</ul>';
9037 $text .= '} ';
9039 $html .= '</ul> ';
9040 $html .= "<div class='cache-total-stats row'>Total: $hits / $misses / $sets</div>";
9041 $info['cachesused'] = "$hits / $misses / $sets";
9042 $info['html'] .= $html;
9043 $info['txt'] .= $text.'. ';
9044 } else {
9045 $info['cachesused'] = '0 / 0 / 0';
9046 $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9047 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9050 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
9051 return $info;
9055 * Delete directory or only its content
9057 * @param string $dir directory path
9058 * @param bool $contentonly
9059 * @return bool success, true also if dir does not exist
9061 function remove_dir($dir, $contentonly=false) {
9062 if (!file_exists($dir)) {
9063 // Nothing to do.
9064 return true;
9066 if (!$handle = opendir($dir)) {
9067 return false;
9069 $result = true;
9070 while (false!==($item = readdir($handle))) {
9071 if ($item != '.' && $item != '..') {
9072 if (is_dir($dir.'/'.$item)) {
9073 $result = remove_dir($dir.'/'.$item) && $result;
9074 } else {
9075 $result = unlink($dir.'/'.$item) && $result;
9079 closedir($handle);
9080 if ($contentonly) {
9081 clearstatcache(); // Make sure file stat cache is properly invalidated.
9082 return $result;
9084 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9085 clearstatcache(); // Make sure file stat cache is properly invalidated.
9086 return $result;
9090 * Detect if an object or a class contains a given property
9091 * will take an actual object or the name of a class
9093 * @param mix $obj Name of class or real object to test
9094 * @param string $property name of property to find
9095 * @return bool true if property exists
9097 function object_property_exists( $obj, $property ) {
9098 if (is_string( $obj )) {
9099 $properties = get_class_vars( $obj );
9100 } else {
9101 $properties = get_object_vars( $obj );
9103 return array_key_exists( $property, $properties );
9107 * Converts an object into an associative array
9109 * This function converts an object into an associative array by iterating
9110 * over its public properties. Because this function uses the foreach
9111 * construct, Iterators are respected. It works recursively on arrays of objects.
9112 * Arrays and simple values are returned as is.
9114 * If class has magic properties, it can implement IteratorAggregate
9115 * and return all available properties in getIterator()
9117 * @param mixed $var
9118 * @return array
9120 function convert_to_array($var) {
9121 $result = array();
9123 // Loop over elements/properties.
9124 foreach ($var as $key => $value) {
9125 // Recursively convert objects.
9126 if (is_object($value) || is_array($value)) {
9127 $result[$key] = convert_to_array($value);
9128 } else {
9129 // Simple values are untouched.
9130 $result[$key] = $value;
9133 return $result;
9137 * Detect a custom script replacement in the data directory that will
9138 * replace an existing moodle script
9140 * @return string|bool full path name if a custom script exists, false if no custom script exists
9142 function custom_script_path() {
9143 global $CFG, $SCRIPT;
9145 if ($SCRIPT === null) {
9146 // Probably some weird external script.
9147 return false;
9150 $scriptpath = $CFG->customscripts . $SCRIPT;
9152 // Check the custom script exists.
9153 if (file_exists($scriptpath) and is_file($scriptpath)) {
9154 return $scriptpath;
9155 } else {
9156 return false;
9161 * Returns whether or not the user object is a remote MNET user. This function
9162 * is in moodlelib because it does not rely on loading any of the MNET code.
9164 * @param object $user A valid user object
9165 * @return bool True if the user is from a remote Moodle.
9167 function is_mnet_remote_user($user) {
9168 global $CFG;
9170 if (!isset($CFG->mnet_localhost_id)) {
9171 include_once($CFG->dirroot . '/mnet/lib.php');
9172 $env = new mnet_environment();
9173 $env->init();
9174 unset($env);
9177 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9181 * This function will search for browser prefereed languages, setting Moodle
9182 * to use the best one available if $SESSION->lang is undefined
9184 function setup_lang_from_browser() {
9185 global $CFG, $SESSION, $USER;
9187 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9188 // Lang is defined in session or user profile, nothing to do.
9189 return;
9192 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9193 return;
9196 // Extract and clean langs from headers.
9197 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9198 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9199 $rawlangs = explode(',', $rawlangs); // Convert to array.
9200 $langs = array();
9202 $order = 1.0;
9203 foreach ($rawlangs as $lang) {
9204 if (strpos($lang, ';') === false) {
9205 $langs[(string)$order] = $lang;
9206 $order = $order-0.01;
9207 } else {
9208 $parts = explode(';', $lang);
9209 $pos = strpos($parts[1], '=');
9210 $langs[substr($parts[1], $pos+1)] = $parts[0];
9213 krsort($langs, SORT_NUMERIC);
9215 // Look for such langs under standard locations.
9216 foreach ($langs as $lang) {
9217 // Clean it properly for include.
9218 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9219 if (get_string_manager()->translation_exists($lang, false)) {
9220 // Lang exists, set it in session.
9221 $SESSION->lang = $lang;
9222 // We have finished. Go out.
9223 break;
9226 return;
9230 * Check if $url matches anything in proxybypass list
9232 * Any errors just result in the proxy being used (least bad)
9234 * @param string $url url to check
9235 * @return boolean true if we should bypass the proxy
9237 function is_proxybypass( $url ) {
9238 global $CFG;
9240 // Sanity check.
9241 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9242 return false;
9245 // Get the host part out of the url.
9246 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9247 return false;
9250 // Get the possible bypass hosts into an array.
9251 $matches = explode( ',', $CFG->proxybypass );
9253 // Check for a match.
9254 // (IPs need to match the left hand side and hosts the right of the url,
9255 // but we can recklessly check both as there can't be a false +ve).
9256 foreach ($matches as $match) {
9257 $match = trim($match);
9259 // Try for IP match (Left side).
9260 $lhs = substr($host, 0, strlen($match));
9261 if (strcasecmp($match, $lhs)==0) {
9262 return true;
9265 // Try for host match (Right side).
9266 $rhs = substr($host, -strlen($match));
9267 if (strcasecmp($match, $rhs)==0) {
9268 return true;
9272 // Nothing matched.
9273 return false;
9277 * Check if the passed navigation is of the new style
9279 * @param mixed $navigation
9280 * @return bool true for yes false for no
9282 function is_newnav($navigation) {
9283 if (is_array($navigation) && !empty($navigation['newnav'])) {
9284 return true;
9285 } else {
9286 return false;
9291 * Checks whether the given variable name is defined as a variable within the given object.
9293 * This will NOT work with stdClass objects, which have no class variables.
9295 * @param string $var The variable name
9296 * @param object $object The object to check
9297 * @return boolean
9299 function in_object_vars($var, $object) {
9300 $classvars = get_class_vars(get_class($object));
9301 $classvars = array_keys($classvars);
9302 return in_array($var, $classvars);
9306 * Returns an array without repeated objects.
9307 * This function is similar to array_unique, but for arrays that have objects as values
9309 * @param array $array
9310 * @param bool $keepkeyassoc
9311 * @return array
9313 function object_array_unique($array, $keepkeyassoc = true) {
9314 $duplicatekeys = array();
9315 $tmp = array();
9317 foreach ($array as $key => $val) {
9318 // Convert objects to arrays, in_array() does not support objects.
9319 if (is_object($val)) {
9320 $val = (array)$val;
9323 if (!in_array($val, $tmp)) {
9324 $tmp[] = $val;
9325 } else {
9326 $duplicatekeys[] = $key;
9330 foreach ($duplicatekeys as $key) {
9331 unset($array[$key]);
9334 return $keepkeyassoc ? $array : array_values($array);
9338 * Is a userid the primary administrator?
9340 * @param int $userid int id of user to check
9341 * @return boolean
9343 function is_primary_admin($userid) {
9344 $primaryadmin = get_admin();
9346 if ($userid == $primaryadmin->id) {
9347 return true;
9348 } else {
9349 return false;
9354 * Returns the site identifier
9356 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9358 function get_site_identifier() {
9359 global $CFG;
9360 // Check to see if it is missing. If so, initialise it.
9361 if (empty($CFG->siteidentifier)) {
9362 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9364 // Return it.
9365 return $CFG->siteidentifier;
9369 * Check whether the given password has no more than the specified
9370 * number of consecutive identical characters.
9372 * @param string $password password to be checked against the password policy
9373 * @param integer $maxchars maximum number of consecutive identical characters
9374 * @return bool
9376 function check_consecutive_identical_characters($password, $maxchars) {
9378 if ($maxchars < 1) {
9379 return true; // Zero 0 is to disable this check.
9381 if (strlen($password) <= $maxchars) {
9382 return true; // Too short to fail this test.
9385 $previouschar = '';
9386 $consecutivecount = 1;
9387 foreach (str_split($password) as $char) {
9388 if ($char != $previouschar) {
9389 $consecutivecount = 1;
9390 } else {
9391 $consecutivecount++;
9392 if ($consecutivecount > $maxchars) {
9393 return false; // Check failed already.
9397 $previouschar = $char;
9400 return true;
9404 * Helper function to do partial function binding.
9405 * so we can use it for preg_replace_callback, for example
9406 * this works with php functions, user functions, static methods and class methods
9407 * it returns you a callback that you can pass on like so:
9409 * $callback = partial('somefunction', $arg1, $arg2);
9410 * or
9411 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9412 * or even
9413 * $obj = new someclass();
9414 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9416 * and then the arguments that are passed through at calltime are appended to the argument list.
9418 * @param mixed $function a php callback
9419 * @param mixed $arg1,... $argv arguments to partially bind with
9420 * @return array Array callback
9422 function partial() {
9423 if (!class_exists('partial')) {
9425 * Used to manage function binding.
9426 * @copyright 2009 Penny Leach
9427 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9429 class partial{
9430 /** @var array */
9431 public $values = array();
9432 /** @var string The function to call as a callback. */
9433 public $func;
9435 * Constructor
9436 * @param string $func
9437 * @param array $args
9439 public function __construct($func, $args) {
9440 $this->values = $args;
9441 $this->func = $func;
9444 * Calls the callback function.
9445 * @return mixed
9447 public function method() {
9448 $args = func_get_args();
9449 return call_user_func_array($this->func, array_merge($this->values, $args));
9453 $args = func_get_args();
9454 $func = array_shift($args);
9455 $p = new partial($func, $args);
9456 return array($p, 'method');
9460 * helper function to load up and initialise the mnet environment
9461 * this must be called before you use mnet functions.
9463 * @return mnet_environment the equivalent of old $MNET global
9465 function get_mnet_environment() {
9466 global $CFG;
9467 require_once($CFG->dirroot . '/mnet/lib.php');
9468 static $instance = null;
9469 if (empty($instance)) {
9470 $instance = new mnet_environment();
9471 $instance->init();
9473 return $instance;
9477 * during xmlrpc server code execution, any code wishing to access
9478 * information about the remote peer must use this to get it.
9480 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9482 function get_mnet_remote_client() {
9483 if (!defined('MNET_SERVER')) {
9484 debugging(get_string('notinxmlrpcserver', 'mnet'));
9485 return false;
9487 global $MNET_REMOTE_CLIENT;
9488 if (isset($MNET_REMOTE_CLIENT)) {
9489 return $MNET_REMOTE_CLIENT;
9491 return false;
9495 * during the xmlrpc server code execution, this will be called
9496 * to setup the object returned by {@link get_mnet_remote_client}
9498 * @param mnet_remote_client $client the client to set up
9499 * @throws moodle_exception
9501 function set_mnet_remote_client($client) {
9502 if (!defined('MNET_SERVER')) {
9503 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9505 global $MNET_REMOTE_CLIENT;
9506 $MNET_REMOTE_CLIENT = $client;
9510 * return the jump url for a given remote user
9511 * this is used for rewriting forum post links in emails, etc
9513 * @param stdclass $user the user to get the idp url for
9515 function mnet_get_idp_jump_url($user) {
9516 global $CFG;
9518 static $mnetjumps = array();
9519 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9520 $idp = mnet_get_peer_host($user->mnethostid);
9521 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9522 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9524 return $mnetjumps[$user->mnethostid];
9528 * Gets the homepage to use for the current user
9530 * @return int One of HOMEPAGE_*
9532 function get_home_page() {
9533 global $CFG;
9535 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9536 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9537 return HOMEPAGE_MY;
9538 } else {
9539 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9542 return HOMEPAGE_SITE;
9546 * Gets the name of a course to be displayed when showing a list of courses.
9547 * By default this is just $course->fullname but user can configure it. The
9548 * result of this function should be passed through print_string.
9549 * @param stdClass|course_in_list $course Moodle course object
9550 * @return string Display name of course (either fullname or short + fullname)
9552 function get_course_display_name_for_list($course) {
9553 global $CFG;
9554 if (!empty($CFG->courselistshortnames)) {
9555 if (!($course instanceof stdClass)) {
9556 $course = (object)convert_to_array($course);
9558 return get_string('courseextendednamedisplay', '', $course);
9559 } else {
9560 return $course->fullname;
9565 * The lang_string class
9567 * This special class is used to create an object representation of a string request.
9568 * It is special because processing doesn't occur until the object is first used.
9569 * The class was created especially to aid performance in areas where strings were
9570 * required to be generated but were not necessarily used.
9571 * As an example the admin tree when generated uses over 1500 strings, of which
9572 * normally only 1/3 are ever actually printed at any time.
9573 * The performance advantage is achieved by not actually processing strings that
9574 * arn't being used, as such reducing the processing required for the page.
9576 * How to use the lang_string class?
9577 * There are two methods of using the lang_string class, first through the
9578 * forth argument of the get_string function, and secondly directly.
9579 * The following are examples of both.
9580 * 1. Through get_string calls e.g.
9581 * $string = get_string($identifier, $component, $a, true);
9582 * $string = get_string('yes', 'moodle', null, true);
9583 * 2. Direct instantiation
9584 * $string = new lang_string($identifier, $component, $a, $lang);
9585 * $string = new lang_string('yes');
9587 * How do I use a lang_string object?
9588 * The lang_string object makes use of a magic __toString method so that you
9589 * are able to use the object exactly as you would use a string in most cases.
9590 * This means you are able to collect it into a variable and then directly
9591 * echo it, or concatenate it into another string, or similar.
9592 * The other thing you can do is manually get the string by calling the
9593 * lang_strings out method e.g.
9594 * $string = new lang_string('yes');
9595 * $string->out();
9596 * Also worth noting is that the out method can take one argument, $lang which
9597 * allows the developer to change the language on the fly.
9599 * When should I use a lang_string object?
9600 * The lang_string object is designed to be used in any situation where a
9601 * string may not be needed, but needs to be generated.
9602 * The admin tree is a good example of where lang_string objects should be
9603 * used.
9604 * A more practical example would be any class that requries strings that may
9605 * not be printed (after all classes get renderer by renderers and who knows
9606 * what they will do ;))
9608 * When should I not use a lang_string object?
9609 * Don't use lang_strings when you are going to use a string immediately.
9610 * There is no need as it will be processed immediately and there will be no
9611 * advantage, and in fact perhaps a negative hit as a class has to be
9612 * instantiated for a lang_string object, however get_string won't require
9613 * that.
9615 * Limitations:
9616 * 1. You cannot use a lang_string object as an array offset. Doing so will
9617 * result in PHP throwing an error. (You can use it as an object property!)
9619 * @package core
9620 * @category string
9621 * @copyright 2011 Sam Hemelryk
9622 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9624 class lang_string {
9626 /** @var string The strings identifier */
9627 protected $identifier;
9628 /** @var string The strings component. Default '' */
9629 protected $component = '';
9630 /** @var array|stdClass Any arguments required for the string. Default null */
9631 protected $a = null;
9632 /** @var string The language to use when processing the string. Default null */
9633 protected $lang = null;
9635 /** @var string The processed string (once processed) */
9636 protected $string = null;
9639 * A special boolean. If set to true then the object has been woken up and
9640 * cannot be regenerated. If this is set then $this->string MUST be used.
9641 * @var bool
9643 protected $forcedstring = false;
9646 * Constructs a lang_string object
9648 * This function should do as little processing as possible to ensure the best
9649 * performance for strings that won't be used.
9651 * @param string $identifier The strings identifier
9652 * @param string $component The strings component
9653 * @param stdClass|array $a Any arguments the string requires
9654 * @param string $lang The language to use when processing the string.
9655 * @throws coding_exception
9657 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9658 if (empty($component)) {
9659 $component = 'moodle';
9662 $this->identifier = $identifier;
9663 $this->component = $component;
9664 $this->lang = $lang;
9666 // We MUST duplicate $a to ensure that it if it changes by reference those
9667 // changes are not carried across.
9668 // To do this we always ensure $a or its properties/values are strings
9669 // and that any properties/values that arn't convertable are forgotten.
9670 if (!empty($a)) {
9671 if (is_scalar($a)) {
9672 $this->a = $a;
9673 } else if ($a instanceof lang_string) {
9674 $this->a = $a->out();
9675 } else if (is_object($a) or is_array($a)) {
9676 $a = (array)$a;
9677 $this->a = array();
9678 foreach ($a as $key => $value) {
9679 // Make sure conversion errors don't get displayed (results in '').
9680 if (is_array($value)) {
9681 $this->a[$key] = '';
9682 } else if (is_object($value)) {
9683 if (method_exists($value, '__toString')) {
9684 $this->a[$key] = $value->__toString();
9685 } else {
9686 $this->a[$key] = '';
9688 } else {
9689 $this->a[$key] = (string)$value;
9695 if (debugging(false, DEBUG_DEVELOPER)) {
9696 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9697 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9699 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9700 throw new coding_exception('Invalid string compontent. Please check your string definition');
9702 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9703 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9709 * Processes the string.
9711 * This function actually processes the string, stores it in the string property
9712 * and then returns it.
9713 * You will notice that this function is VERY similar to the get_string method.
9714 * That is because it is pretty much doing the same thing.
9715 * However as this function is an upgrade it isn't as tolerant to backwards
9716 * compatibility.
9718 * @return string
9719 * @throws coding_exception
9721 protected function get_string() {
9722 global $CFG;
9724 // Check if we need to process the string.
9725 if ($this->string === null) {
9726 // Check the quality of the identifier.
9727 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9728 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);
9731 // Process the string.
9732 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9733 // Debugging feature lets you display string identifier and component.
9734 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9735 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9738 // Return the string.
9739 return $this->string;
9743 * Returns the string
9745 * @param string $lang The langauge to use when processing the string
9746 * @return string
9748 public function out($lang = null) {
9749 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9750 if ($this->forcedstring) {
9751 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9752 return $this->get_string();
9754 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9755 return $translatedstring->out();
9757 return $this->get_string();
9761 * Magic __toString method for printing a string
9763 * @return string
9765 public function __toString() {
9766 return $this->get_string();
9770 * Magic __set_state method used for var_export
9772 * @return string
9774 public function __set_state() {
9775 return $this->get_string();
9779 * Prepares the lang_string for sleep and stores only the forcedstring and
9780 * string properties... the string cannot be regenerated so we need to ensure
9781 * it is generated for this.
9783 * @return string
9785 public function __sleep() {
9786 $this->get_string();
9787 $this->forcedstring = true;
9788 return array('forcedstring', 'string', 'lang');