MDL-48495 curl: Limit usage of curl to HTTP and HTTPS protocols
[moodle.git] / lib / moodlelib.php
blob6eea8812edd8a300dea98bd031529aed39d9a0d0
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', 'radius', '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 if module supports outcomes */
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');
417 /** True if module supports groupmembersonly */
418 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
420 /** Type of module */
421 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
422 /** True if module supports intro editor */
423 define('FEATURE_MOD_INTRO', 'mod_intro');
424 /** True if module has default completion */
425 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
427 define('FEATURE_COMMENT', 'comment');
429 define('FEATURE_RATE', 'rate');
430 /** True if module supports backup/restore of moodle2 format */
431 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
433 /** True if module can show description on course main page */
434 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
436 /** True if module uses the question bank */
437 define('FEATURE_USES_QUESTIONS', 'usesquestions');
439 /** Unspecified module archetype */
440 define('MOD_ARCHETYPE_OTHER', 0);
441 /** Resource-like type module */
442 define('MOD_ARCHETYPE_RESOURCE', 1);
443 /** Assignment module archetype */
444 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
445 /** System (not user-addable) module archetype */
446 define('MOD_ARCHETYPE_SYSTEM', 3);
448 /** Return this from modname_get_types callback to use default display in activity chooser */
449 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
452 * Security token used for allowing access
453 * from external application such as web services.
454 * Scripts do not use any session, performance is relatively
455 * low because we need to load access info in each request.
456 * Scripts are executed in parallel.
458 define('EXTERNAL_TOKEN_PERMANENT', 0);
461 * Security token used for allowing access
462 * of embedded applications, the code is executed in the
463 * active user session. Token is invalidated after user logs out.
464 * Scripts are executed serially - normal session locking is used.
466 define('EXTERNAL_TOKEN_EMBEDDED', 1);
469 * The home page should be the site home
471 define('HOMEPAGE_SITE', 0);
473 * The home page should be the users my page
475 define('HOMEPAGE_MY', 1);
477 * The home page can be chosen by the user
479 define('HOMEPAGE_USER', 2);
482 * Hub directory url (should be moodle.org)
484 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
488 * Moodle.org url (should be moodle.org)
490 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
493 * Moodle mobile app service name
495 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
498 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
500 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
503 * Course display settings: display all sections on one page.
505 define('COURSE_DISPLAY_SINGLEPAGE', 0);
507 * Course display settings: split pages into a page per section.
509 define('COURSE_DISPLAY_MULTIPAGE', 1);
512 * Authentication constant: String used in password field when password is not stored.
514 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
516 // PARAMETER HANDLING.
519 * Returns a particular value for the named variable, taken from
520 * POST or GET. If the parameter doesn't exist then an error is
521 * thrown because we require this variable.
523 * This function should be used to initialise all required values
524 * in a script that are based on parameters. Usually it will be
525 * used like this:
526 * $id = required_param('id', PARAM_INT);
528 * Please note the $type parameter is now required and the value can not be array.
530 * @param string $parname the name of the page parameter we want
531 * @param string $type expected type of parameter
532 * @return mixed
533 * @throws coding_exception
535 function required_param($parname, $type) {
536 if (func_num_args() != 2 or empty($parname) or empty($type)) {
537 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
539 // POST has precedence.
540 if (isset($_POST[$parname])) {
541 $param = $_POST[$parname];
542 } else if (isset($_GET[$parname])) {
543 $param = $_GET[$parname];
544 } else {
545 print_error('missingparam', '', '', $parname);
548 if (is_array($param)) {
549 debugging('Invalid array parameter detected in required_param(): '.$parname);
550 // TODO: switch to fatal error in Moodle 2.3.
551 return required_param_array($parname, $type);
554 return clean_param($param, $type);
558 * Returns a particular array value for the named variable, taken from
559 * POST or GET. If the parameter doesn't exist then an error is
560 * thrown because we require this variable.
562 * This function should be used to initialise all required values
563 * in a script that are based on parameters. Usually it will be
564 * used like this:
565 * $ids = required_param_array('ids', PARAM_INT);
567 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
569 * @param string $parname the name of the page parameter we want
570 * @param string $type expected type of parameter
571 * @return array
572 * @throws coding_exception
574 function required_param_array($parname, $type) {
575 if (func_num_args() != 2 or empty($parname) or empty($type)) {
576 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
578 // POST has precedence.
579 if (isset($_POST[$parname])) {
580 $param = $_POST[$parname];
581 } else if (isset($_GET[$parname])) {
582 $param = $_GET[$parname];
583 } else {
584 print_error('missingparam', '', '', $parname);
586 if (!is_array($param)) {
587 print_error('missingparam', '', '', $parname);
590 $result = array();
591 foreach ($param as $key => $value) {
592 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
593 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
594 continue;
596 $result[$key] = clean_param($value, $type);
599 return $result;
603 * Returns a particular value for the named variable, taken from
604 * POST or GET, otherwise returning a given default.
606 * This function should be used to initialise all optional values
607 * in a script that are based on parameters. Usually it will be
608 * used like this:
609 * $name = optional_param('name', 'Fred', PARAM_TEXT);
611 * Please note the $type parameter is now required and the value can not be array.
613 * @param string $parname the name of the page parameter we want
614 * @param mixed $default the default value to return if nothing is found
615 * @param string $type expected type of parameter
616 * @return mixed
617 * @throws coding_exception
619 function optional_param($parname, $default, $type) {
620 if (func_num_args() != 3 or empty($parname) or empty($type)) {
621 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
623 if (!isset($default)) {
624 $default = null;
627 // POST has precedence.
628 if (isset($_POST[$parname])) {
629 $param = $_POST[$parname];
630 } else if (isset($_GET[$parname])) {
631 $param = $_GET[$parname];
632 } else {
633 return $default;
636 if (is_array($param)) {
637 debugging('Invalid array parameter detected in required_param(): '.$parname);
638 // TODO: switch to $default in Moodle 2.3.
639 return optional_param_array($parname, $default, $type);
642 return clean_param($param, $type);
646 * Returns a particular array value for the named variable, taken from
647 * POST or GET, otherwise returning a given default.
649 * This function should be used to initialise all optional values
650 * in a script that are based on parameters. Usually it will be
651 * used like this:
652 * $ids = optional_param('id', array(), PARAM_INT);
654 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
656 * @param string $parname the name of the page parameter we want
657 * @param mixed $default the default value to return if nothing is found
658 * @param string $type expected type of parameter
659 * @return array
660 * @throws coding_exception
662 function optional_param_array($parname, $default, $type) {
663 if (func_num_args() != 3 or empty($parname) or empty($type)) {
664 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
667 // POST has precedence.
668 if (isset($_POST[$parname])) {
669 $param = $_POST[$parname];
670 } else if (isset($_GET[$parname])) {
671 $param = $_GET[$parname];
672 } else {
673 return $default;
675 if (!is_array($param)) {
676 debugging('optional_param_array() expects array parameters only: '.$parname);
677 return $default;
680 $result = array();
681 foreach ($param as $key => $value) {
682 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
683 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
684 continue;
686 $result[$key] = clean_param($value, $type);
689 return $result;
693 * Strict validation of parameter values, the values are only converted
694 * to requested PHP type. Internally it is using clean_param, the values
695 * before and after cleaning must be equal - otherwise
696 * an invalid_parameter_exception is thrown.
697 * Objects and classes are not accepted.
699 * @param mixed $param
700 * @param string $type PARAM_ constant
701 * @param bool $allownull are nulls valid value?
702 * @param string $debuginfo optional debug information
703 * @return mixed the $param value converted to PHP type
704 * @throws invalid_parameter_exception if $param is not of given type
706 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
707 if (is_null($param)) {
708 if ($allownull == NULL_ALLOWED) {
709 return null;
710 } else {
711 throw new invalid_parameter_exception($debuginfo);
714 if (is_array($param) or is_object($param)) {
715 throw new invalid_parameter_exception($debuginfo);
718 $cleaned = clean_param($param, $type);
720 if ($type == PARAM_FLOAT) {
721 // Do not detect precision loss here.
722 if (is_float($param) or is_int($param)) {
723 // These always fit.
724 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
725 throw new invalid_parameter_exception($debuginfo);
727 } else if ((string)$param !== (string)$cleaned) {
728 // Conversion to string is usually lossless.
729 throw new invalid_parameter_exception($debuginfo);
732 return $cleaned;
736 * Makes sure array contains only the allowed types, this function does not validate array key names!
738 * <code>
739 * $options = clean_param($options, PARAM_INT);
740 * </code>
742 * @param array $param the variable array we are cleaning
743 * @param string $type expected format of param after cleaning.
744 * @param bool $recursive clean recursive arrays
745 * @return array
746 * @throws coding_exception
748 function clean_param_array(array $param = null, $type, $recursive = false) {
749 // Convert null to empty array.
750 $param = (array)$param;
751 foreach ($param as $key => $value) {
752 if (is_array($value)) {
753 if ($recursive) {
754 $param[$key] = clean_param_array($value, $type, true);
755 } else {
756 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
758 } else {
759 $param[$key] = clean_param($value, $type);
762 return $param;
766 * Used by {@link optional_param()} and {@link required_param()} to
767 * clean the variables and/or cast to specific types, based on
768 * an options field.
769 * <code>
770 * $course->format = clean_param($course->format, PARAM_ALPHA);
771 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
772 * </code>
774 * @param mixed $param the variable we are cleaning
775 * @param string $type expected format of param after cleaning.
776 * @return mixed
777 * @throws coding_exception
779 function clean_param($param, $type) {
780 global $CFG;
782 if (is_array($param)) {
783 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
784 } else if (is_object($param)) {
785 if (method_exists($param, '__toString')) {
786 $param = $param->__toString();
787 } else {
788 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
792 switch ($type) {
793 case PARAM_RAW:
794 // No cleaning at all.
795 $param = fix_utf8($param);
796 return $param;
798 case PARAM_RAW_TRIMMED:
799 // No cleaning, but strip leading and trailing whitespace.
800 $param = fix_utf8($param);
801 return trim($param);
803 case PARAM_CLEAN:
804 // General HTML cleaning, try to use more specific type if possible this is deprecated!
805 // Please use more specific type instead.
806 if (is_numeric($param)) {
807 return $param;
809 $param = fix_utf8($param);
810 // Sweep for scripts, etc.
811 return clean_text($param);
813 case PARAM_CLEANHTML:
814 // Clean html fragment.
815 $param = fix_utf8($param);
816 // Sweep for scripts, etc.
817 $param = clean_text($param, FORMAT_HTML);
818 return trim($param);
820 case PARAM_INT:
821 // Convert to integer.
822 return (int)$param;
824 case PARAM_FLOAT:
825 // Convert to float.
826 return (float)$param;
828 case PARAM_ALPHA:
829 // Remove everything not `a-z`.
830 return preg_replace('/[^a-zA-Z]/i', '', $param);
832 case PARAM_ALPHAEXT:
833 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
834 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
836 case PARAM_ALPHANUM:
837 // Remove everything not `a-zA-Z0-9`.
838 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
840 case PARAM_ALPHANUMEXT:
841 // Remove everything not `a-zA-Z0-9_-`.
842 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
844 case PARAM_SEQUENCE:
845 // Remove everything not `0-9,`.
846 return preg_replace('/[^0-9,]/i', '', $param);
848 case PARAM_BOOL:
849 // Convert to 1 or 0.
850 $tempstr = strtolower($param);
851 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
852 $param = 1;
853 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
854 $param = 0;
855 } else {
856 $param = empty($param) ? 0 : 1;
858 return $param;
860 case PARAM_NOTAGS:
861 // Strip all tags.
862 $param = fix_utf8($param);
863 return strip_tags($param);
865 case PARAM_TEXT:
866 // Leave only tags needed for multilang.
867 $param = fix_utf8($param);
868 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
869 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
870 do {
871 if (strpos($param, '</lang>') !== false) {
872 // Old and future mutilang syntax.
873 $param = strip_tags($param, '<lang>');
874 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
875 break;
877 $open = false;
878 foreach ($matches[0] as $match) {
879 if ($match === '</lang>') {
880 if ($open) {
881 $open = false;
882 continue;
883 } else {
884 break 2;
887 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
888 break 2;
889 } else {
890 $open = true;
893 if ($open) {
894 break;
896 return $param;
898 } else if (strpos($param, '</span>') !== false) {
899 // Current problematic multilang syntax.
900 $param = strip_tags($param, '<span>');
901 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
902 break;
904 $open = false;
905 foreach ($matches[0] as $match) {
906 if ($match === '</span>') {
907 if ($open) {
908 $open = false;
909 continue;
910 } else {
911 break 2;
914 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
915 break 2;
916 } else {
917 $open = true;
920 if ($open) {
921 break;
923 return $param;
925 } while (false);
926 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
927 return strip_tags($param);
929 case PARAM_COMPONENT:
930 // We do not want any guessing here, either the name is correct or not
931 // please note only normalised component names are accepted.
932 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
933 return '';
935 if (strpos($param, '__') !== false) {
936 return '';
938 if (strpos($param, 'mod_') === 0) {
939 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
940 if (substr_count($param, '_') != 1) {
941 return '';
944 return $param;
946 case PARAM_PLUGIN:
947 case PARAM_AREA:
948 // We do not want any guessing here, either the name is correct or not.
949 if (!is_valid_plugin_name($param)) {
950 return '';
952 return $param;
954 case PARAM_SAFEDIR:
955 // Remove everything not a-zA-Z0-9_- .
956 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
958 case PARAM_SAFEPATH:
959 // Remove everything not a-zA-Z0-9/_- .
960 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
962 case PARAM_FILE:
963 // Strip all suspicious characters from filename.
964 $param = fix_utf8($param);
965 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
966 if ($param === '.' || $param === '..') {
967 $param = '';
969 return $param;
971 case PARAM_PATH:
972 // Strip all suspicious characters from file path.
973 $param = fix_utf8($param);
974 $param = str_replace('\\', '/', $param);
976 // Explode the path and clean each element using the PARAM_FILE rules.
977 $breadcrumb = explode('/', $param);
978 foreach ($breadcrumb as $key => $crumb) {
979 if ($crumb === '.' && $key === 0) {
980 // Special condition to allow for relative current path such as ./currentdirfile.txt.
981 } else {
982 $crumb = clean_param($crumb, PARAM_FILE);
984 $breadcrumb[$key] = $crumb;
986 $param = implode('/', $breadcrumb);
988 // Remove multiple current path (./././) and multiple slashes (///).
989 $param = preg_replace('~//+~', '/', $param);
990 $param = preg_replace('~/(\./)+~', '/', $param);
991 return $param;
993 case PARAM_HOST:
994 // Allow FQDN or IPv4 dotted quad.
995 $param = preg_replace('/[^\.\d\w-]/', '', $param );
996 // Match ipv4 dotted quad.
997 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
998 // Confirm values are ok.
999 if ( $match[0] > 255
1000 || $match[1] > 255
1001 || $match[3] > 255
1002 || $match[4] > 255 ) {
1003 // Hmmm, what kind of dotted quad is this?
1004 $param = '';
1006 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1007 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1008 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1010 // All is ok - $param is respected.
1011 } else {
1012 // All is not ok...
1013 $param='';
1015 return $param;
1017 case PARAM_URL: // Allow safe ftp, http, mailto urls.
1018 $param = fix_utf8($param);
1019 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1020 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1021 // All is ok, param is respected.
1022 } else {
1023 // Not really ok.
1024 $param ='';
1026 return $param;
1028 case PARAM_LOCALURL:
1029 // Allow http absolute, root relative and relative URLs within wwwroot.
1030 $param = clean_param($param, PARAM_URL);
1031 if (!empty($param)) {
1032 if (preg_match(':^/:', $param)) {
1033 // Root-relative, ok!
1034 } else if (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i', $param)) {
1035 // Absolute, and matches our wwwroot.
1036 } else {
1037 // Relative - let's make sure there are no tricks.
1038 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1039 // Looks ok.
1040 } else {
1041 $param = '';
1045 return $param;
1047 case PARAM_PEM:
1048 $param = trim($param);
1049 // PEM formatted strings may contain letters/numbers and the symbols:
1050 // forward slash: /
1051 // plus sign: +
1052 // equal sign: =
1053 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1054 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1055 list($wholething, $body) = $matches;
1056 unset($wholething, $matches);
1057 $b64 = clean_param($body, PARAM_BASE64);
1058 if (!empty($b64)) {
1059 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1060 } else {
1061 return '';
1064 return '';
1066 case PARAM_BASE64:
1067 if (!empty($param)) {
1068 // PEM formatted strings may contain letters/numbers and the symbols
1069 // forward slash: /
1070 // plus sign: +
1071 // equal sign: =.
1072 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1073 return '';
1075 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1076 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1077 // than (or equal to) 64 characters long.
1078 for ($i=0, $j=count($lines); $i < $j; $i++) {
1079 if ($i + 1 == $j) {
1080 if (64 < strlen($lines[$i])) {
1081 return '';
1083 continue;
1086 if (64 != strlen($lines[$i])) {
1087 return '';
1090 return implode("\n", $lines);
1091 } else {
1092 return '';
1095 case PARAM_TAG:
1096 $param = fix_utf8($param);
1097 // Please note it is not safe to use the tag name directly anywhere,
1098 // it must be processed with s(), urlencode() before embedding anywhere.
1099 // Remove some nasties.
1100 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1101 // Convert many whitespace chars into one.
1102 $param = preg_replace('/\s+/', ' ', $param);
1103 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1104 return $param;
1106 case PARAM_TAGLIST:
1107 $param = fix_utf8($param);
1108 $tags = explode(',', $param);
1109 $result = array();
1110 foreach ($tags as $tag) {
1111 $res = clean_param($tag, PARAM_TAG);
1112 if ($res !== '') {
1113 $result[] = $res;
1116 if ($result) {
1117 return implode(',', $result);
1118 } else {
1119 return '';
1122 case PARAM_CAPABILITY:
1123 if (get_capability_info($param)) {
1124 return $param;
1125 } else {
1126 return '';
1129 case PARAM_PERMISSION:
1130 $param = (int)$param;
1131 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1132 return $param;
1133 } else {
1134 return CAP_INHERIT;
1137 case PARAM_AUTH:
1138 $param = clean_param($param, PARAM_PLUGIN);
1139 if (empty($param)) {
1140 return '';
1141 } else if (exists_auth_plugin($param)) {
1142 return $param;
1143 } else {
1144 return '';
1147 case PARAM_LANG:
1148 $param = clean_param($param, PARAM_SAFEDIR);
1149 if (get_string_manager()->translation_exists($param)) {
1150 return $param;
1151 } else {
1152 // Specified language is not installed or param malformed.
1153 return '';
1156 case PARAM_THEME:
1157 $param = clean_param($param, PARAM_PLUGIN);
1158 if (empty($param)) {
1159 return '';
1160 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1161 return $param;
1162 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1163 return $param;
1164 } else {
1165 // Specified theme is not installed.
1166 return '';
1169 case PARAM_USERNAME:
1170 $param = fix_utf8($param);
1171 $param = trim($param);
1172 // Convert uppercase to lowercase MDL-16919.
1173 $param = core_text::strtolower($param);
1174 if (empty($CFG->extendedusernamechars)) {
1175 $param = str_replace(" " , "", $param);
1176 // Regular expression, eliminate all chars EXCEPT:
1177 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1178 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1180 return $param;
1182 case PARAM_EMAIL:
1183 $param = fix_utf8($param);
1184 if (validate_email($param)) {
1185 return $param;
1186 } else {
1187 return '';
1190 case PARAM_STRINGID:
1191 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1192 return $param;
1193 } else {
1194 return '';
1197 case PARAM_TIMEZONE:
1198 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1199 $param = fix_utf8($param);
1200 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1201 if (preg_match($timezonepattern, $param)) {
1202 return $param;
1203 } else {
1204 return '';
1207 default:
1208 // Doh! throw error, switched parameters in optional_param or another serious problem.
1209 print_error("unknownparamtype", '', '', $type);
1214 * Makes sure the data is using valid utf8, invalid characters are discarded.
1216 * Note: this function is not intended for full objects with methods and private properties.
1218 * @param mixed $value
1219 * @return mixed with proper utf-8 encoding
1221 function fix_utf8($value) {
1222 if (is_null($value) or $value === '') {
1223 return $value;
1225 } else if (is_string($value)) {
1226 if ((string)(int)$value === $value) {
1227 // Shortcut.
1228 return $value;
1230 // No null bytes expected in our data, so let's remove it.
1231 $value = str_replace("\0", '', $value);
1233 // Note: this duplicates min_fix_utf8() intentionally.
1234 static $buggyiconv = null;
1235 if ($buggyiconv === null) {
1236 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1239 if ($buggyiconv) {
1240 if (function_exists('mb_convert_encoding')) {
1241 $subst = mb_substitute_character();
1242 mb_substitute_character('');
1243 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1244 mb_substitute_character($subst);
1246 } else {
1247 // Warn admins on admin/index.php page.
1248 $result = $value;
1251 } else {
1252 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1255 return $result;
1257 } else if (is_array($value)) {
1258 foreach ($value as $k => $v) {
1259 $value[$k] = fix_utf8($v);
1261 return $value;
1263 } else if (is_object($value)) {
1264 // Do not modify original.
1265 $value = clone($value);
1266 foreach ($value as $k => $v) {
1267 $value->$k = fix_utf8($v);
1269 return $value;
1271 } else {
1272 // This is some other type, no utf-8 here.
1273 return $value;
1278 * Return true if given value is integer or string with integer value
1280 * @param mixed $value String or Int
1281 * @return bool true if number, false if not
1283 function is_number($value) {
1284 if (is_int($value)) {
1285 return true;
1286 } else if (is_string($value)) {
1287 return ((string)(int)$value) === $value;
1288 } else {
1289 return false;
1294 * Returns host part from url.
1296 * @param string $url full url
1297 * @return string host, null if not found
1299 function get_host_from_url($url) {
1300 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1301 if ($matches) {
1302 return $matches[1];
1304 return null;
1308 * Tests whether anything was returned by text editor
1310 * This function is useful for testing whether something you got back from
1311 * the HTML editor actually contains anything. Sometimes the HTML editor
1312 * appear to be empty, but actually you get back a <br> tag or something.
1314 * @param string $string a string containing HTML.
1315 * @return boolean does the string contain any actual content - that is text,
1316 * images, objects, etc.
1318 function html_is_blank($string) {
1319 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1323 * Set a key in global configuration
1325 * Set a key/value pair in both this session's {@link $CFG} global variable
1326 * and in the 'config' database table for future sessions.
1328 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1329 * In that case it doesn't affect $CFG.
1331 * A NULL value will delete the entry.
1333 * NOTE: this function is called from lib/db/upgrade.php
1335 * @param string $name the key to set
1336 * @param string $value the value to set (without magic quotes)
1337 * @param string $plugin (optional) the plugin scope, default null
1338 * @return bool true or exception
1340 function set_config($name, $value, $plugin=null) {
1341 global $CFG, $DB;
1343 if (empty($plugin)) {
1344 if (!array_key_exists($name, $CFG->config_php_settings)) {
1345 // So it's defined for this invocation at least.
1346 if (is_null($value)) {
1347 unset($CFG->$name);
1348 } else {
1349 // Settings from db are always strings.
1350 $CFG->$name = (string)$value;
1354 if ($DB->get_field('config', 'name', array('name' => $name))) {
1355 if ($value === null) {
1356 $DB->delete_records('config', array('name' => $name));
1357 } else {
1358 $DB->set_field('config', 'value', $value, array('name' => $name));
1360 } else {
1361 if ($value !== null) {
1362 $config = new stdClass();
1363 $config->name = $name;
1364 $config->value = $value;
1365 $DB->insert_record('config', $config, false);
1368 if ($name === 'siteidentifier') {
1369 cache_helper::update_site_identifier($value);
1371 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1372 } else {
1373 // Plugin scope.
1374 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1375 if ($value===null) {
1376 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1377 } else {
1378 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1380 } else {
1381 if ($value !== null) {
1382 $config = new stdClass();
1383 $config->plugin = $plugin;
1384 $config->name = $name;
1385 $config->value = $value;
1386 $DB->insert_record('config_plugins', $config, false);
1389 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1392 return true;
1396 * Get configuration values from the global config table
1397 * or the config_plugins table.
1399 * If called with one parameter, it will load all the config
1400 * variables for one plugin, and return them as an object.
1402 * If called with 2 parameters it will return a string single
1403 * value or false if the value is not found.
1405 * NOTE: this function is called from lib/db/upgrade.php
1407 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1408 * that we need only fetch it once per request.
1409 * @param string $plugin full component name
1410 * @param string $name default null
1411 * @return mixed hash-like object or single value, return false no config found
1412 * @throws dml_exception
1414 function get_config($plugin, $name = null) {
1415 global $CFG, $DB;
1417 static $siteidentifier = null;
1419 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1420 $forced =& $CFG->config_php_settings;
1421 $iscore = true;
1422 $plugin = 'core';
1423 } else {
1424 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1425 $forced =& $CFG->forced_plugin_settings[$plugin];
1426 } else {
1427 $forced = array();
1429 $iscore = false;
1432 if ($siteidentifier === null) {
1433 try {
1434 // This may fail during installation.
1435 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1436 // install the database.
1437 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1438 } catch (dml_exception $ex) {
1439 // Set siteidentifier to false. We don't want to trip this continually.
1440 $siteidentifier = false;
1441 throw $ex;
1445 if (!empty($name)) {
1446 if (array_key_exists($name, $forced)) {
1447 return (string)$forced[$name];
1448 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1449 return $siteidentifier;
1453 $cache = cache::make('core', 'config');
1454 $result = $cache->get($plugin);
1455 if ($result === false) {
1456 // The user is after a recordset.
1457 if (!$iscore) {
1458 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1459 } else {
1460 // This part is not really used any more, but anyway...
1461 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1463 $cache->set($plugin, $result);
1466 if (!empty($name)) {
1467 if (array_key_exists($name, $result)) {
1468 return $result[$name];
1470 return false;
1473 if ($plugin === 'core') {
1474 $result['siteidentifier'] = $siteidentifier;
1477 foreach ($forced as $key => $value) {
1478 if (is_null($value) or is_array($value) or is_object($value)) {
1479 // We do not want any extra mess here, just real settings that could be saved in db.
1480 unset($result[$key]);
1481 } else {
1482 // Convert to string as if it went through the DB.
1483 $result[$key] = (string)$value;
1487 return (object)$result;
1491 * Removes a key from global configuration.
1493 * NOTE: this function is called from lib/db/upgrade.php
1495 * @param string $name the key to set
1496 * @param string $plugin (optional) the plugin scope
1497 * @return boolean whether the operation succeeded.
1499 function unset_config($name, $plugin=null) {
1500 global $CFG, $DB;
1502 if (empty($plugin)) {
1503 unset($CFG->$name);
1504 $DB->delete_records('config', array('name' => $name));
1505 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1506 } else {
1507 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1508 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1511 return true;
1515 * Remove all the config variables for a given plugin.
1517 * NOTE: this function is called from lib/db/upgrade.php
1519 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1520 * @return boolean whether the operation succeeded.
1522 function unset_all_config_for_plugin($plugin) {
1523 global $DB;
1524 // Delete from the obvious config_plugins first.
1525 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1526 // Next delete any suspect settings from config.
1527 $like = $DB->sql_like('name', '?', true, true, false, '|');
1528 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1529 $DB->delete_records_select('config', $like, $params);
1530 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1531 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1533 return true;
1537 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1539 * All users are verified if they still have the necessary capability.
1541 * @param string $value the value of the config setting.
1542 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1543 * @param bool $includeadmins include administrators.
1544 * @return array of user objects.
1546 function get_users_from_config($value, $capability, $includeadmins = true) {
1547 if (empty($value) or $value === '$@NONE@$') {
1548 return array();
1551 // We have to make sure that users still have the necessary capability,
1552 // it should be faster to fetch them all first and then test if they are present
1553 // instead of validating them one-by-one.
1554 $users = get_users_by_capability(context_system::instance(), $capability);
1555 if ($includeadmins) {
1556 $admins = get_admins();
1557 foreach ($admins as $admin) {
1558 $users[$admin->id] = $admin;
1562 if ($value === '$@ALL@$') {
1563 return $users;
1566 $result = array(); // Result in correct order.
1567 $allowed = explode(',', $value);
1568 foreach ($allowed as $uid) {
1569 if (isset($users[$uid])) {
1570 $user = $users[$uid];
1571 $result[$user->id] = $user;
1575 return $result;
1580 * Invalidates browser caches and cached data in temp.
1582 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1583 * {@link phpunit_util::reset_dataroot()}
1585 * @return void
1587 function purge_all_caches() {
1588 global $CFG, $DB;
1590 reset_text_filters_cache();
1591 js_reset_all_caches();
1592 theme_reset_all_caches();
1593 get_string_manager()->reset_caches();
1594 core_text::reset_caches();
1595 if (class_exists('core_plugin_manager')) {
1596 core_plugin_manager::reset_caches();
1599 // Bump up cacherev field for all courses.
1600 try {
1601 increment_revision_number('course', 'cacherev', '');
1602 } catch (moodle_exception $e) {
1603 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1606 $DB->reset_caches();
1607 cache_helper::purge_all();
1609 // Purge all other caches: rss, simplepie, etc.
1610 remove_dir($CFG->cachedir.'', true);
1612 // Make sure cache dir is writable, throws exception if not.
1613 make_cache_directory('');
1615 // This is the only place where we purge local caches, we are only adding files there.
1616 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1617 remove_dir($CFG->localcachedir, true);
1618 set_config('localcachedirpurged', time());
1619 make_localcache_directory('', true);
1620 \core\task\manager::clear_static_caches();
1624 * Get volatile flags
1626 * @param string $type
1627 * @param int $changedsince default null
1628 * @return array records array
1630 function get_cache_flags($type, $changedsince = null) {
1631 global $DB;
1633 $params = array('type' => $type, 'expiry' => time());
1634 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1635 if ($changedsince !== null) {
1636 $params['changedsince'] = $changedsince;
1637 $sqlwhere .= " AND timemodified > :changedsince";
1639 $cf = array();
1640 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1641 foreach ($flags as $flag) {
1642 $cf[$flag->name] = $flag->value;
1645 return $cf;
1649 * Get volatile flags
1651 * @param string $type
1652 * @param string $name
1653 * @param int $changedsince default null
1654 * @return string|false The cache flag value or false
1656 function get_cache_flag($type, $name, $changedsince=null) {
1657 global $DB;
1659 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1661 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1662 if ($changedsince !== null) {
1663 $params['changedsince'] = $changedsince;
1664 $sqlwhere .= " AND timemodified > :changedsince";
1667 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1671 * Set a volatile flag
1673 * @param string $type the "type" namespace for the key
1674 * @param string $name the key to set
1675 * @param string $value the value to set (without magic quotes) - null will remove the flag
1676 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1677 * @return bool Always returns true
1679 function set_cache_flag($type, $name, $value, $expiry = null) {
1680 global $DB;
1682 $timemodified = time();
1683 if ($expiry === null || $expiry < $timemodified) {
1684 $expiry = $timemodified + 24 * 60 * 60;
1685 } else {
1686 $expiry = (int)$expiry;
1689 if ($value === null) {
1690 unset_cache_flag($type, $name);
1691 return true;
1694 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1695 // This is a potential problem in DEBUG_DEVELOPER.
1696 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1697 return true; // No need to update.
1699 $f->value = $value;
1700 $f->expiry = $expiry;
1701 $f->timemodified = $timemodified;
1702 $DB->update_record('cache_flags', $f);
1703 } else {
1704 $f = new stdClass();
1705 $f->flagtype = $type;
1706 $f->name = $name;
1707 $f->value = $value;
1708 $f->expiry = $expiry;
1709 $f->timemodified = $timemodified;
1710 $DB->insert_record('cache_flags', $f);
1712 return true;
1716 * Removes a single volatile flag
1718 * @param string $type the "type" namespace for the key
1719 * @param string $name the key to set
1720 * @return bool
1722 function unset_cache_flag($type, $name) {
1723 global $DB;
1724 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1725 return true;
1729 * Garbage-collect volatile flags
1731 * @return bool Always returns true
1733 function gc_cache_flags() {
1734 global $DB;
1735 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1736 return true;
1739 // USER PREFERENCE API.
1742 * Refresh user preference cache. This is used most often for $USER
1743 * object that is stored in session, but it also helps with performance in cron script.
1745 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1747 * @package core
1748 * @category preference
1749 * @access public
1750 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1751 * @param int $cachelifetime Cache life time on the current page (in seconds)
1752 * @throws coding_exception
1753 * @return null
1755 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1756 global $DB;
1757 // Static cache, we need to check on each page load, not only every 2 minutes.
1758 static $loadedusers = array();
1760 if (!isset($user->id)) {
1761 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1764 if (empty($user->id) or isguestuser($user->id)) {
1765 // No permanent storage for not-logged-in users and guest.
1766 if (!isset($user->preference)) {
1767 $user->preference = array();
1769 return;
1772 $timenow = time();
1774 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1775 // Already loaded at least once on this page. Are we up to date?
1776 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1777 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1778 return;
1780 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1781 // No change since the lastcheck on this page.
1782 $user->preference['_lastloaded'] = $timenow;
1783 return;
1787 // OK, so we have to reload all preferences.
1788 $loadedusers[$user->id] = true;
1789 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1790 $user->preference['_lastloaded'] = $timenow;
1794 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1796 * NOTE: internal function, do not call from other code.
1798 * @package core
1799 * @access private
1800 * @param integer $userid the user whose prefs were changed.
1802 function mark_user_preferences_changed($userid) {
1803 global $CFG;
1805 if (empty($userid) or isguestuser($userid)) {
1806 // No cache flags for guest and not-logged-in users.
1807 return;
1810 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1814 * Sets a preference for the specified user.
1816 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1818 * @package core
1819 * @category preference
1820 * @access public
1821 * @param string $name The key to set as preference for the specified user
1822 * @param string $value The value to set for the $name key in the specified user's
1823 * record, null means delete current value.
1824 * @param stdClass|int|null $user A moodle user object or id, null means current user
1825 * @throws coding_exception
1826 * @return bool Always true or exception
1828 function set_user_preference($name, $value, $user = null) {
1829 global $USER, $DB;
1831 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1832 throw new coding_exception('Invalid preference name in set_user_preference() call');
1835 if (is_null($value)) {
1836 // Null means delete current.
1837 return unset_user_preference($name, $user);
1838 } else if (is_object($value)) {
1839 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1840 } else if (is_array($value)) {
1841 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1843 // Value column maximum length is 1333 characters.
1844 $value = (string)$value;
1845 if (core_text::strlen($value) > 1333) {
1846 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1849 if (is_null($user)) {
1850 $user = $USER;
1851 } else if (isset($user->id)) {
1852 // It is a valid object.
1853 } else if (is_numeric($user)) {
1854 $user = (object)array('id' => (int)$user);
1855 } else {
1856 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1859 check_user_preferences_loaded($user);
1861 if (empty($user->id) or isguestuser($user->id)) {
1862 // No permanent storage for not-logged-in users and guest.
1863 $user->preference[$name] = $value;
1864 return true;
1867 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1868 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1869 // Preference already set to this value.
1870 return true;
1872 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1874 } else {
1875 $preference = new stdClass();
1876 $preference->userid = $user->id;
1877 $preference->name = $name;
1878 $preference->value = $value;
1879 $DB->insert_record('user_preferences', $preference);
1882 // Update value in cache.
1883 $user->preference[$name] = $value;
1885 // Set reload flag for other sessions.
1886 mark_user_preferences_changed($user->id);
1888 return true;
1892 * Sets a whole array of preferences for the current user
1894 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1896 * @package core
1897 * @category preference
1898 * @access public
1899 * @param array $prefarray An array of key/value pairs to be set
1900 * @param stdClass|int|null $user A moodle user object or id, null means current user
1901 * @return bool Always true or exception
1903 function set_user_preferences(array $prefarray, $user = null) {
1904 foreach ($prefarray as $name => $value) {
1905 set_user_preference($name, $value, $user);
1907 return true;
1911 * Unsets a preference completely by deleting it from the database
1913 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1915 * @package core
1916 * @category preference
1917 * @access public
1918 * @param string $name The key to unset as preference for the specified user
1919 * @param stdClass|int|null $user A moodle user object or id, null means current user
1920 * @throws coding_exception
1921 * @return bool Always true or exception
1923 function unset_user_preference($name, $user = null) {
1924 global $USER, $DB;
1926 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1927 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1930 if (is_null($user)) {
1931 $user = $USER;
1932 } else if (isset($user->id)) {
1933 // It is a valid object.
1934 } else if (is_numeric($user)) {
1935 $user = (object)array('id' => (int)$user);
1936 } else {
1937 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1940 check_user_preferences_loaded($user);
1942 if (empty($user->id) or isguestuser($user->id)) {
1943 // No permanent storage for not-logged-in user and guest.
1944 unset($user->preference[$name]);
1945 return true;
1948 // Delete from DB.
1949 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1951 // Delete the preference from cache.
1952 unset($user->preference[$name]);
1954 // Set reload flag for other sessions.
1955 mark_user_preferences_changed($user->id);
1957 return true;
1961 * Used to fetch user preference(s)
1963 * If no arguments are supplied this function will return
1964 * all of the current user preferences as an array.
1966 * If a name is specified then this function
1967 * attempts to return that particular preference value. If
1968 * none is found, then the optional value $default is returned,
1969 * otherwise null.
1971 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1973 * @package core
1974 * @category preference
1975 * @access public
1976 * @param string $name Name of the key to use in finding a preference value
1977 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1978 * @param stdClass|int|null $user A moodle user object or id, null means current user
1979 * @throws coding_exception
1980 * @return string|mixed|null A string containing the value of a single preference. An
1981 * array with all of the preferences or null
1983 function get_user_preferences($name = null, $default = null, $user = null) {
1984 global $USER;
1986 if (is_null($name)) {
1987 // All prefs.
1988 } else if (is_numeric($name) or $name === '_lastloaded') {
1989 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1992 if (is_null($user)) {
1993 $user = $USER;
1994 } else if (isset($user->id)) {
1995 // Is a valid object.
1996 } else if (is_numeric($user)) {
1997 $user = (object)array('id' => (int)$user);
1998 } else {
1999 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2002 check_user_preferences_loaded($user);
2004 if (empty($name)) {
2005 // All values.
2006 return $user->preference;
2007 } else if (isset($user->preference[$name])) {
2008 // The single string value.
2009 return $user->preference[$name];
2010 } else {
2011 // Default value (null if not specified).
2012 return $default;
2016 // FUNCTIONS FOR HANDLING TIME.
2019 * Given date parts in user time produce a GMT timestamp.
2021 * @package core
2022 * @category time
2023 * @param int $year The year part to create timestamp of
2024 * @param int $month The month part to create timestamp of
2025 * @param int $day The day part to create timestamp of
2026 * @param int $hour The hour part to create timestamp of
2027 * @param int $minute The minute part to create timestamp of
2028 * @param int $second The second part to create timestamp of
2029 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2030 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2031 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2032 * applied only if timezone is 99 or string.
2033 * @return int GMT timestamp
2035 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2037 // Save input timezone, required for dst offset check.
2038 $passedtimezone = $timezone;
2040 $timezone = get_user_timezone_offset($timezone);
2042 if (abs($timezone) > 13) {
2043 // Server time.
2044 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2045 } else {
2046 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2047 $time = usertime($time, $timezone);
2049 // Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
2050 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
2051 $time -= dst_offset_on($time, $passedtimezone);
2055 return $time;
2060 * Format a date/time (seconds) as weeks, days, hours etc as needed
2062 * Given an amount of time in seconds, returns string
2063 * formatted nicely as weeks, days, hours etc as needed
2065 * @package core
2066 * @category time
2067 * @uses MINSECS
2068 * @uses HOURSECS
2069 * @uses DAYSECS
2070 * @uses YEARSECS
2071 * @param int $totalsecs Time in seconds
2072 * @param stdClass $str Should be a time object
2073 * @return string A nicely formatted date/time string
2075 function format_time($totalsecs, $str = null) {
2077 $totalsecs = abs($totalsecs);
2079 if (!$str) {
2080 // Create the str structure the slow way.
2081 $str = new stdClass();
2082 $str->day = get_string('day');
2083 $str->days = get_string('days');
2084 $str->hour = get_string('hour');
2085 $str->hours = get_string('hours');
2086 $str->min = get_string('min');
2087 $str->mins = get_string('mins');
2088 $str->sec = get_string('sec');
2089 $str->secs = get_string('secs');
2090 $str->year = get_string('year');
2091 $str->years = get_string('years');
2094 $years = floor($totalsecs/YEARSECS);
2095 $remainder = $totalsecs - ($years*YEARSECS);
2096 $days = floor($remainder/DAYSECS);
2097 $remainder = $totalsecs - ($days*DAYSECS);
2098 $hours = floor($remainder/HOURSECS);
2099 $remainder = $remainder - ($hours*HOURSECS);
2100 $mins = floor($remainder/MINSECS);
2101 $secs = $remainder - ($mins*MINSECS);
2103 $ss = ($secs == 1) ? $str->sec : $str->secs;
2104 $sm = ($mins == 1) ? $str->min : $str->mins;
2105 $sh = ($hours == 1) ? $str->hour : $str->hours;
2106 $sd = ($days == 1) ? $str->day : $str->days;
2107 $sy = ($years == 1) ? $str->year : $str->years;
2109 $oyears = '';
2110 $odays = '';
2111 $ohours = '';
2112 $omins = '';
2113 $osecs = '';
2115 if ($years) {
2116 $oyears = $years .' '. $sy;
2118 if ($days) {
2119 $odays = $days .' '. $sd;
2121 if ($hours) {
2122 $ohours = $hours .' '. $sh;
2124 if ($mins) {
2125 $omins = $mins .' '. $sm;
2127 if ($secs) {
2128 $osecs = $secs .' '. $ss;
2131 if ($years) {
2132 return trim($oyears .' '. $odays);
2134 if ($days) {
2135 return trim($odays .' '. $ohours);
2137 if ($hours) {
2138 return trim($ohours .' '. $omins);
2140 if ($mins) {
2141 return trim($omins .' '. $osecs);
2143 if ($secs) {
2144 return $osecs;
2146 return get_string('now');
2150 * Returns a formatted string that represents a date in user time.
2152 * @package core
2153 * @category time
2154 * @param int $date the timestamp in UTC, as obtained from the database.
2155 * @param string $format strftime format. You should probably get this using
2156 * get_string('strftime...', 'langconfig');
2157 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2158 * not 99 then daylight saving will not be added.
2159 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2160 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2161 * If false then the leading zero is maintained.
2162 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2163 * @return string the formatted date/time.
2165 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2166 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2167 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2171 * Returns a formatted date ensuring it is UTF-8.
2173 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2174 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2176 * This function does not do any calculation regarding the user preferences and should
2177 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2178 * to differentiate the use of server time or not (strftime() against gmstrftime()).
2180 * @param int $date the timestamp.
2181 * @param string $format strftime format.
2182 * @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2183 * @return string the formatted date/time.
2184 * @since Moodle 2.3.3
2186 function date_format_string($date, $format, $tz = 99) {
2187 global $CFG;
2189 $localewincharset = null;
2190 // Get the calendar type user is using.
2191 if ($CFG->ostype == 'WINDOWS') {
2192 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2193 $localewincharset = $calendartype->locale_win_charset();
2196 if (abs($tz) > 13) {
2197 if ($localewincharset) {
2198 $format = core_text::convert($format, 'utf-8', $localewincharset);
2199 $datestring = strftime($format, $date);
2200 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2201 } else {
2202 $datestring = strftime($format, $date);
2204 } else {
2205 if ($localewincharset) {
2206 $format = core_text::convert($format, 'utf-8', $localewincharset);
2207 $datestring = gmstrftime($format, $date);
2208 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2209 } else {
2210 $datestring = gmstrftime($format, $date);
2213 return $datestring;
2217 * Given a $time timestamp in GMT (seconds since epoch),
2218 * returns an array that represents the date in user time
2220 * @package core
2221 * @category time
2222 * @uses HOURSECS
2223 * @param int $time Timestamp in GMT
2224 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2225 * dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
2226 * @return array An array that represents the date in user time
2228 function usergetdate($time, $timezone=99) {
2230 // Save input timezone, required for dst offset check.
2231 $passedtimezone = $timezone;
2233 $timezone = get_user_timezone_offset($timezone);
2235 if (abs($timezone) > 13) {
2236 // Server time.
2237 return getdate($time);
2240 // Add daylight saving offset for string timezones only, as we can't get dst for
2241 // float values. if timezone is 99 (user default timezone), then try update dst.
2242 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2243 $time += dst_offset_on($time, $passedtimezone);
2246 $time += intval((float)$timezone * HOURSECS);
2248 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2250 // Be careful to ensure the returned array matches that produced by getdate() above.
2251 list(
2252 $getdate['month'],
2253 $getdate['weekday'],
2254 $getdate['yday'],
2255 $getdate['year'],
2256 $getdate['mon'],
2257 $getdate['wday'],
2258 $getdate['mday'],
2259 $getdate['hours'],
2260 $getdate['minutes'],
2261 $getdate['seconds']
2262 ) = explode('_', $datestring);
2264 // Set correct datatype to match with getdate().
2265 $getdate['seconds'] = (int)$getdate['seconds'];
2266 $getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
2267 $getdate['year'] = (int)$getdate['year'];
2268 $getdate['mon'] = (int)$getdate['mon'];
2269 $getdate['wday'] = (int)$getdate['wday'];
2270 $getdate['mday'] = (int)$getdate['mday'];
2271 $getdate['hours'] = (int)$getdate['hours'];
2272 $getdate['minutes'] = (int)$getdate['minutes'];
2273 return $getdate;
2277 * Given a GMT timestamp (seconds since epoch), offsets it by
2278 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2280 * @package core
2281 * @category time
2282 * @uses HOURSECS
2283 * @param int $date Timestamp in GMT
2284 * @param float|int|string $timezone timezone to calculate GMT time offset before
2285 * calculating user time, 99 is default user timezone
2286 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2287 * @return int
2289 function usertime($date, $timezone=99) {
2291 $timezone = get_user_timezone_offset($timezone);
2293 if (abs($timezone) > 13) {
2294 return $date;
2296 return $date - (int)($timezone * HOURSECS);
2300 * Given a time, return the GMT timestamp of the most recent midnight
2301 * for the current user.
2303 * @package core
2304 * @category time
2305 * @param int $date Timestamp in GMT
2306 * @param float|int|string $timezone timezone to calculate GMT time offset before
2307 * calculating user midnight time, 99 is default user timezone
2308 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2309 * @return int Returns a GMT timestamp
2311 function usergetmidnight($date, $timezone=99) {
2313 $userdate = usergetdate($date, $timezone);
2315 // Time of midnight of this user's day, in GMT.
2316 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2321 * Returns a string that prints the user's timezone
2323 * @package core
2324 * @category time
2325 * @param float|int|string $timezone timezone to calculate GMT time offset before
2326 * calculating user timezone, 99 is default user timezone
2327 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2328 * @return string
2330 function usertimezone($timezone=99) {
2332 $tz = get_user_timezone($timezone);
2334 if (!is_float($tz)) {
2335 return $tz;
2338 if (abs($tz) > 13) {
2339 // Server time.
2340 return get_string('serverlocaltime');
2343 if ($tz == intval($tz)) {
2344 // Don't show .0 for whole hours.
2345 $tz = intval($tz);
2348 if ($tz == 0) {
2349 return 'UTC';
2350 } else if ($tz > 0) {
2351 return 'UTC+'.$tz;
2352 } else {
2353 return 'UTC'.$tz;
2359 * Returns a float which represents the user's timezone difference from GMT in hours
2360 * Checks various settings and picks the most dominant of those which have a value
2362 * @package core
2363 * @category time
2364 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2365 * 99 is default user timezone
2366 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2367 * @return float
2369 function get_user_timezone_offset($tz = 99) {
2370 $tz = get_user_timezone($tz);
2372 if (is_float($tz)) {
2373 return $tz;
2374 } else {
2375 $tzrecord = get_timezone_record($tz);
2376 if (empty($tzrecord)) {
2377 return 99.0;
2379 return (float)$tzrecord->gmtoff / HOURMINS;
2384 * Returns an int which represents the systems's timezone difference from GMT in seconds
2386 * @package core
2387 * @category time
2388 * @param float|int|string $tz timezone for which offset is required.
2389 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2390 * @return int|bool if found, false is timezone 99 or error
2392 function get_timezone_offset($tz) {
2393 if ($tz == 99) {
2394 return false;
2397 if (is_numeric($tz)) {
2398 return intval($tz * 60*60);
2401 if (!$tzrecord = get_timezone_record($tz)) {
2402 return false;
2404 return intval($tzrecord->gmtoff * 60);
2408 * Returns a float or a string which denotes the user's timezone
2409 * 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)
2410 * means that for this timezone there are also DST rules to be taken into account
2411 * Checks various settings and picks the most dominant of those which have a value
2413 * @package core
2414 * @category time
2415 * @param float|int|string $tz timezone to calculate GMT time offset before
2416 * calculating user timezone, 99 is default user timezone
2417 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2418 * @return float|string
2420 function get_user_timezone($tz = 99) {
2421 global $USER, $CFG;
2423 $timezones = array(
2424 $tz,
2425 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2426 isset($USER->timezone) ? $USER->timezone : 99,
2427 isset($CFG->timezone) ? $CFG->timezone : 99,
2430 $tz = 99;
2432 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2433 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2434 $tz = $next['value'];
2436 return is_numeric($tz) ? (float) $tz : $tz;
2440 * Returns cached timezone record for given $timezonename
2442 * @package core
2443 * @param string $timezonename name of the timezone
2444 * @return stdClass|bool timezonerecord or false
2446 function get_timezone_record($timezonename) {
2447 global $DB;
2448 static $cache = null;
2450 if ($cache === null) {
2451 $cache = array();
2454 if (isset($cache[$timezonename])) {
2455 return $cache[$timezonename];
2458 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2459 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2463 * Build and store the users Daylight Saving Time (DST) table
2465 * @package core
2466 * @param int $fromyear Start year for the table, defaults to 1971
2467 * @param int $toyear End year for the table, defaults to 2035
2468 * @param int|float|string $strtimezone timezone to check if dst should be applied.
2469 * @return bool
2471 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2472 global $SESSION, $DB;
2474 $usertz = get_user_timezone($strtimezone);
2476 if (is_float($usertz)) {
2477 // Trivial timezone, no DST.
2478 return false;
2481 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2482 // We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
2483 unset($SESSION->dst_offsets);
2484 unset($SESSION->dst_range);
2487 if (!empty($SESSION->dst_offsets) && empty($fromyear) && empty($toyear)) {
2488 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
2489 // This will be the return path most of the time, pretty light computationally.
2490 return true;
2493 // Reaching here means we either need to extend our table or create it from scratch.
2495 // Remember which TZ we calculated these changes for.
2496 $SESSION->dst_offsettz = $usertz;
2498 if (empty($SESSION->dst_offsets)) {
2499 // If we 're creating from scratch, put the two guard elements in there.
2500 $SESSION->dst_offsets = array(1 => null, 0 => null);
2502 if (empty($SESSION->dst_range)) {
2503 // If creating from scratch.
2504 $from = max((empty($fromyear) ? intval(date('Y')) - 3 : $fromyear), 1971);
2505 $to = min((empty($toyear) ? intval(date('Y')) + 3 : $toyear), 2035);
2507 // Fill in the array with the extra years we need to process.
2508 $yearstoprocess = array();
2509 for ($i = $from; $i <= $to; ++$i) {
2510 $yearstoprocess[] = $i;
2513 // Take note of which years we have processed for future calls.
2514 $SESSION->dst_range = array($from, $to);
2515 } else {
2516 // If needing to extend the table, do the same.
2517 $yearstoprocess = array();
2519 $from = max((empty($fromyear) ? $SESSION->dst_range[0] : $fromyear), 1971);
2520 $to = min((empty($toyear) ? $SESSION->dst_range[1] : $toyear), 2035);
2522 if ($from < $SESSION->dst_range[0]) {
2523 // Take note of which years we need to process and then note that we have processed them for future calls.
2524 for ($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2525 $yearstoprocess[] = $i;
2527 $SESSION->dst_range[0] = $from;
2529 if ($to > $SESSION->dst_range[1]) {
2530 // Take note of which years we need to process and then note that we have processed them for future calls.
2531 for ($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2532 $yearstoprocess[] = $i;
2534 $SESSION->dst_range[1] = $to;
2538 if (empty($yearstoprocess)) {
2539 // This means that there was a call requesting a SMALLER range than we have already calculated.
2540 return true;
2543 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2544 // Also, the array is sorted in descending timestamp order!
2546 // Get DB data.
2548 static $presetscache = array();
2549 if (!isset($presetscache[$usertz])) {
2550 $presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
2551 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
2552 'std_startday, std_weekday, std_skipweeks, std_time');
2554 if (empty($presetscache[$usertz])) {
2555 return false;
2558 // Remove ending guard (first element of the array).
2559 reset($SESSION->dst_offsets);
2560 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2562 // Add all required change timestamps.
2563 foreach ($yearstoprocess as $y) {
2564 // Find the record which is in effect for the year $y.
2565 foreach ($presetscache[$usertz] as $year => $preset) {
2566 if ($year <= $y) {
2567 break;
2571 $changes = dst_changes_for_year($y, $preset);
2573 if ($changes === null) {
2574 continue;
2576 if ($changes['dst'] != 0) {
2577 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2579 if ($changes['std'] != 0) {
2580 $SESSION->dst_offsets[$changes['std']] = 0;
2584 // Put in a guard element at the top.
2585 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2586 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = null; // DAYSECS is arbitrary, any "small" number will do.
2588 // Sort again.
2589 krsort($SESSION->dst_offsets);
2591 return true;
2595 * Calculates the required DST change and returns a Timestamp Array
2597 * @package core
2598 * @category time
2599 * @uses HOURSECS
2600 * @uses MINSECS
2601 * @param int|string $year Int or String Year to focus on
2602 * @param object $timezone Instatiated Timezone object
2603 * @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
2605 function dst_changes_for_year($year, $timezone) {
2607 if ($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 &&
2608 $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2609 return null;
2612 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2613 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2615 list($dsthour, $dstmin) = explode(':', $timezone->dst_time);
2616 list($stdhour, $stdmin) = explode(':', $timezone->std_time);
2618 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2619 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2621 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2622 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2623 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2625 $timedst += $dsthour * HOURSECS + $dstmin * MINSECS;
2626 $timestd += $stdhour * HOURSECS + $stdmin * MINSECS;
2628 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2632 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2633 * - Note: Daylight saving only works for string timezones and not for float.
2635 * @package core
2636 * @category time
2637 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2638 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2639 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2640 * @return int
2642 function dst_offset_on($time, $strtimezone = null) {
2643 global $SESSION;
2645 if (!calculate_user_dst_table(null, null, $strtimezone) || empty($SESSION->dst_offsets)) {
2646 return 0;
2649 reset($SESSION->dst_offsets);
2650 while (list($from, $offset) = each($SESSION->dst_offsets)) {
2651 if ($from <= $time) {
2652 break;
2656 // This is the normal return path.
2657 if ($offset !== null) {
2658 return $offset;
2661 // Reaching this point means we haven't calculated far enough, do it now:
2662 // Calculate extra DST changes if needed and recurse. The recursion always
2663 // moves toward the stopping condition, so will always end.
2665 if ($from == 0) {
2666 // We need a year smaller than $SESSION->dst_range[0].
2667 if ($SESSION->dst_range[0] == 1971) {
2668 return 0;
2670 calculate_user_dst_table($SESSION->dst_range[0] - 5, null, $strtimezone);
2671 return dst_offset_on($time, $strtimezone);
2672 } else {
2673 // We need a year larger than $SESSION->dst_range[1].
2674 if ($SESSION->dst_range[1] == 2035) {
2675 return 0;
2677 calculate_user_dst_table(null, $SESSION->dst_range[1] + 5, $strtimezone);
2678 return dst_offset_on($time, $strtimezone);
2683 * Calculates when the day appears in specific month
2685 * @package core
2686 * @category time
2687 * @param int $startday starting day of the month
2688 * @param int $weekday The day when week starts (normally taken from user preferences)
2689 * @param int $month The month whose day is sought
2690 * @param int $year The year of the month whose day is sought
2691 * @return int
2693 function find_day_in_month($startday, $weekday, $month, $year) {
2694 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2696 $daysinmonth = days_in_month($month, $year);
2697 $daysinweek = count($calendartype->get_weekdays());
2699 if ($weekday == -1) {
2700 // Don't care about weekday, so return:
2701 // abs($startday) if $startday != -1
2702 // $daysinmonth otherwise.
2703 return ($startday == -1) ? $daysinmonth : abs($startday);
2706 // From now on we 're looking for a specific weekday.
2707 // Give "end of month" its actual value, since we know it.
2708 if ($startday == -1) {
2709 $startday = -1 * $daysinmonth;
2712 // Starting from day $startday, the sign is the direction.
2713 if ($startday < 1) {
2714 $startday = abs($startday);
2715 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2717 // This is the last such weekday of the month.
2718 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2719 if ($lastinmonth > $daysinmonth) {
2720 $lastinmonth -= $daysinweek;
2723 // Find the first such weekday <= $startday.
2724 while ($lastinmonth > $startday) {
2725 $lastinmonth -= $daysinweek;
2728 return $lastinmonth;
2729 } else {
2730 $indexweekday = dayofweek($startday, $month, $year);
2732 $diff = $weekday - $indexweekday;
2733 if ($diff < 0) {
2734 $diff += $daysinweek;
2737 // This is the first such weekday of the month equal to or after $startday.
2738 $firstfromindex = $startday + $diff;
2740 return $firstfromindex;
2745 * Calculate the number of days in a given month
2747 * @package core
2748 * @category time
2749 * @param int $month The month whose day count is sought
2750 * @param int $year The year of the month whose day count is sought
2751 * @return int
2753 function days_in_month($month, $year) {
2754 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2755 return $calendartype->get_num_days_in_month($year, $month);
2759 * Calculate the position in the week of a specific calendar day
2761 * @package core
2762 * @category time
2763 * @param int $day The day of the date whose position in the week is sought
2764 * @param int $month The month of the date whose position in the week is sought
2765 * @param int $year The year of the date whose position in the week is sought
2766 * @return int
2768 function dayofweek($day, $month, $year) {
2769 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2770 return $calendartype->get_weekday($year, $month, $day);
2773 // USER AUTHENTICATION AND LOGIN.
2776 * Returns full login url.
2778 * @return string login url
2780 function get_login_url() {
2781 global $CFG;
2783 $url = "$CFG->wwwroot/login/index.php";
2785 if (!empty($CFG->loginhttps)) {
2786 $url = str_replace('http:', 'https:', $url);
2789 return $url;
2793 * This function checks that the current user is logged in and has the
2794 * required privileges
2796 * This function checks that the current user is logged in, and optionally
2797 * whether they are allowed to be in a particular course and view a particular
2798 * course module.
2799 * If they are not logged in, then it redirects them to the site login unless
2800 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2801 * case they are automatically logged in as guests.
2802 * If $courseid is given and the user is not enrolled in that course then the
2803 * user is redirected to the course enrolment page.
2804 * If $cm is given and the course module is hidden and the user is not a teacher
2805 * in the course then the user is redirected to the course home page.
2807 * When $cm parameter specified, this function sets page layout to 'module'.
2808 * You need to change it manually later if some other layout needed.
2810 * @package core_access
2811 * @category access
2813 * @param mixed $courseorid id of the course or course object
2814 * @param bool $autologinguest default true
2815 * @param object $cm course module object
2816 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2817 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2818 * in order to keep redirects working properly. MDL-14495
2819 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2820 * @return mixed Void, exit, and die depending on path
2821 * @throws coding_exception
2822 * @throws require_login_exception
2824 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2825 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2827 // Must not redirect when byteserving already started.
2828 if (!empty($_SERVER['HTTP_RANGE'])) {
2829 $preventredirect = true;
2832 // Setup global $COURSE, themes, language and locale.
2833 if (!empty($courseorid)) {
2834 if (is_object($courseorid)) {
2835 $course = $courseorid;
2836 } else if ($courseorid == SITEID) {
2837 $course = clone($SITE);
2838 } else {
2839 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2841 if ($cm) {
2842 if ($cm->course != $course->id) {
2843 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2845 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2846 if (!($cm instanceof cm_info)) {
2847 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2848 // db queries so this is not really a performance concern, however it is obviously
2849 // better if you use get_fast_modinfo to get the cm before calling this.
2850 $modinfo = get_fast_modinfo($course);
2851 $cm = $modinfo->get_cm($cm->id);
2853 $PAGE->set_cm($cm, $course); // Set's up global $COURSE.
2854 $PAGE->set_pagelayout('incourse');
2855 } else {
2856 $PAGE->set_course($course); // Set's up global $COURSE.
2858 } else {
2859 // Do not touch global $COURSE via $PAGE->set_course(),
2860 // the reasons is we need to be able to call require_login() at any time!!
2861 $course = $SITE;
2862 if ($cm) {
2863 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2867 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2868 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2869 // risk leading the user back to the AJAX request URL.
2870 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2871 $setwantsurltome = false;
2874 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2875 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
2876 if ($setwantsurltome) {
2877 $SESSION->wantsurl = qualified_me();
2879 redirect(get_login_url());
2882 // If the user is not even logged in yet then make sure they are.
2883 if (!isloggedin()) {
2884 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2885 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2886 // Misconfigured site guest, just redirect to login page.
2887 redirect(get_login_url());
2888 exit; // Never reached.
2890 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2891 complete_user_login($guest);
2892 $USER->autologinguest = true;
2893 $SESSION->lang = $lang;
2894 } else {
2895 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2896 if ($preventredirect) {
2897 throw new require_login_exception('You are not logged in');
2900 if ($setwantsurltome) {
2901 $SESSION->wantsurl = qualified_me();
2903 if (!empty($_SERVER['HTTP_REFERER'])) {
2904 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2906 redirect(get_login_url());
2907 exit; // Never reached.
2911 // Loginas as redirection if needed.
2912 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2913 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2914 if ($USER->loginascontext->instanceid != $course->id) {
2915 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2920 // Check whether the user should be changing password (but only if it is REALLY them).
2921 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2922 $userauth = get_auth_plugin($USER->auth);
2923 if ($userauth->can_change_password() and !$preventredirect) {
2924 if ($setwantsurltome) {
2925 $SESSION->wantsurl = qualified_me();
2927 if ($changeurl = $userauth->change_password_url()) {
2928 // Use plugin custom url.
2929 redirect($changeurl);
2930 } else {
2931 // Use moodle internal method.
2932 if (empty($CFG->loginhttps)) {
2933 redirect($CFG->wwwroot .'/login/change_password.php');
2934 } else {
2935 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2936 redirect($wwwroot .'/login/change_password.php');
2939 } else {
2940 print_error('nopasswordchangeforced', 'auth');
2944 // Check that the user account is properly set up.
2945 if (user_not_fully_set_up($USER)) {
2946 if ($preventredirect) {
2947 throw new require_login_exception('User not fully set-up');
2949 if ($setwantsurltome) {
2950 $SESSION->wantsurl = qualified_me();
2952 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2955 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2956 sesskey();
2958 // Do not bother admins with any formalities.
2959 if (is_siteadmin()) {
2960 // Set accesstime or the user will appear offline which messes up messaging.
2961 user_accesstime_log($course->id);
2962 return;
2965 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2966 if (!$USER->policyagreed and !is_siteadmin()) {
2967 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2968 if ($preventredirect) {
2969 throw new require_login_exception('Policy not agreed');
2971 if ($setwantsurltome) {
2972 $SESSION->wantsurl = qualified_me();
2974 redirect($CFG->wwwroot .'/user/policy.php');
2975 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2976 if ($preventredirect) {
2977 throw new require_login_exception('Policy not agreed');
2979 if ($setwantsurltome) {
2980 $SESSION->wantsurl = qualified_me();
2982 redirect($CFG->wwwroot .'/user/policy.php');
2986 // Fetch the system context, the course context, and prefetch its child contexts.
2987 $sysctx = context_system::instance();
2988 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2989 if ($cm) {
2990 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2991 } else {
2992 $cmcontext = null;
2995 // If the site is currently under maintenance, then print a message.
2996 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2997 if ($preventredirect) {
2998 throw new require_login_exception('Maintenance in progress');
3001 print_maintenance_message();
3004 // Make sure the course itself is not hidden.
3005 if ($course->id == SITEID) {
3006 // Frontpage can not be hidden.
3007 } else {
3008 if (is_role_switched($course->id)) {
3009 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
3010 } else {
3011 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3012 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
3013 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
3014 if ($preventredirect) {
3015 throw new require_login_exception('Course is hidden');
3017 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3018 // the navigation will mess up when trying to find it.
3019 navigation_node::override_active_url(new moodle_url('/'));
3020 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3025 // Is the user enrolled?
3026 if ($course->id == SITEID) {
3027 // Everybody is enrolled on the frontpage.
3028 } else {
3029 if (\core\session\manager::is_loggedinas()) {
3030 // Make sure the REAL person can access this course first.
3031 $realuser = \core\session\manager::get_realuser();
3032 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
3033 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
3034 if ($preventredirect) {
3035 throw new require_login_exception('Invalid course login-as access');
3037 echo $OUTPUT->header();
3038 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
3042 $access = false;
3044 if (is_role_switched($course->id)) {
3045 // Ok, user had to be inside this course before the switch.
3046 $access = true;
3048 } else if (is_viewing($coursecontext, $USER)) {
3049 // Ok, no need to mess with enrol.
3050 $access = true;
3052 } else {
3053 if (isset($USER->enrol['enrolled'][$course->id])) {
3054 if ($USER->enrol['enrolled'][$course->id] > time()) {
3055 $access = true;
3056 if (isset($USER->enrol['tempguest'][$course->id])) {
3057 unset($USER->enrol['tempguest'][$course->id]);
3058 remove_temp_course_roles($coursecontext);
3060 } else {
3061 // Expired.
3062 unset($USER->enrol['enrolled'][$course->id]);
3065 if (isset($USER->enrol['tempguest'][$course->id])) {
3066 if ($USER->enrol['tempguest'][$course->id] == 0) {
3067 $access = true;
3068 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3069 $access = true;
3070 } else {
3071 // Expired.
3072 unset($USER->enrol['tempguest'][$course->id]);
3073 remove_temp_course_roles($coursecontext);
3077 if (!$access) {
3078 // Cache not ok.
3079 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3080 if ($until !== false) {
3081 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3082 if ($until == 0) {
3083 $until = ENROL_MAX_TIMESTAMP;
3085 $USER->enrol['enrolled'][$course->id] = $until;
3086 $access = true;
3088 } else {
3089 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3090 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3091 $enrols = enrol_get_plugins(true);
3092 // First ask all enabled enrol instances in course if they want to auto enrol user.
3093 foreach ($instances as $instance) {
3094 if (!isset($enrols[$instance->enrol])) {
3095 continue;
3097 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3098 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3099 if ($until !== false) {
3100 if ($until == 0) {
3101 $until = ENROL_MAX_TIMESTAMP;
3103 $USER->enrol['enrolled'][$course->id] = $until;
3104 $access = true;
3105 break;
3108 // If not enrolled yet try to gain temporary guest access.
3109 if (!$access) {
3110 foreach ($instances as $instance) {
3111 if (!isset($enrols[$instance->enrol])) {
3112 continue;
3114 // Get a duration for the guest access, a timestamp in the future or false.
3115 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3116 if ($until !== false and $until > time()) {
3117 $USER->enrol['tempguest'][$course->id] = $until;
3118 $access = true;
3119 break;
3127 if (!$access) {
3128 if ($preventredirect) {
3129 throw new require_login_exception('Not enrolled');
3131 if ($setwantsurltome) {
3132 $SESSION->wantsurl = qualified_me();
3134 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3138 // Check visibility of activity to current user; includes visible flag, groupmembersonly, conditional availability, etc.
3139 if ($cm && !$cm->uservisible) {
3140 if ($preventredirect) {
3141 throw new require_login_exception('Activity is hidden');
3143 if ($course->id != SITEID) {
3144 $url = new moodle_url('/course/view.php', array('id' => $course->id));
3145 } else {
3146 $url = new moodle_url('/');
3148 redirect($url, get_string('activityiscurrentlyhidden'));
3151 // Finally access granted, update lastaccess times.
3152 user_accesstime_log($course->id);
3157 * This function just makes sure a user is logged out.
3159 * @package core_access
3160 * @category access
3162 function require_logout() {
3163 global $USER, $DB;
3165 if (!isloggedin()) {
3166 // This should not happen often, no need for hooks or events here.
3167 \core\session\manager::terminate_current();
3168 return;
3171 // Execute hooks before action.
3172 $authsequence = get_enabled_auth_plugins();
3173 foreach ($authsequence as $authname) {
3174 $authplugin = get_auth_plugin($authname);
3175 $authplugin->prelogout_hook();
3178 // Store info that gets removed during logout.
3179 $sid = session_id();
3180 $event = \core\event\user_loggedout::create(
3181 array(
3182 'userid' => $USER->id,
3183 'objectid' => $USER->id,
3184 'other' => array('sessionid' => $sid),
3187 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3188 $event->add_record_snapshot('sessions', $session);
3191 // Delete session record and drop $_SESSION content.
3192 \core\session\manager::terminate_current();
3194 // Trigger event AFTER action.
3195 $event->trigger();
3199 * Weaker version of require_login()
3201 * This is a weaker version of {@link require_login()} which only requires login
3202 * when called from within a course rather than the site page, unless
3203 * the forcelogin option is turned on.
3204 * @see require_login()
3206 * @package core_access
3207 * @category access
3209 * @param mixed $courseorid The course object or id in question
3210 * @param bool $autologinguest Allow autologin guests if that is wanted
3211 * @param object $cm Course activity module if known
3212 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3213 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3214 * in order to keep redirects working properly. MDL-14495
3215 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3216 * @return void
3217 * @throws coding_exception
3219 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3220 global $CFG, $PAGE, $SITE;
3221 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3222 or (!is_object($courseorid) and $courseorid == SITEID));
3223 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3224 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3225 // db queries so this is not really a performance concern, however it is obviously
3226 // better if you use get_fast_modinfo to get the cm before calling this.
3227 if (is_object($courseorid)) {
3228 $course = $courseorid;
3229 } else {
3230 $course = clone($SITE);
3232 $modinfo = get_fast_modinfo($course);
3233 $cm = $modinfo->get_cm($cm->id);
3235 if (!empty($CFG->forcelogin)) {
3236 // Login required for both SITE and courses.
3237 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3239 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3240 // Always login for hidden activities.
3241 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3243 } else if ($issite) {
3244 // Login for SITE not required.
3245 if ($cm and empty($cm->visible)) {
3246 // Hidden activities are not accessible without login.
3247 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3248 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3249 // Not-logged-in users do not have any group membership.
3250 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3251 } else {
3252 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3253 if (!empty($courseorid)) {
3254 if (is_object($courseorid)) {
3255 $course = $courseorid;
3256 } else {
3257 $course = clone($SITE);
3259 if ($cm) {
3260 if ($cm->course != $course->id) {
3261 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3263 $PAGE->set_cm($cm, $course);
3264 $PAGE->set_pagelayout('incourse');
3265 } else {
3266 $PAGE->set_course($course);
3268 } else {
3269 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3270 $PAGE->set_course($PAGE->course);
3272 // TODO: verify conditional activities here.
3273 user_accesstime_log(SITEID);
3274 return;
3277 } else {
3278 // Course login always required.
3279 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3284 * Require key login. Function terminates with error if key not found or incorrect.
3286 * @uses NO_MOODLE_COOKIES
3287 * @uses PARAM_ALPHANUM
3288 * @param string $script unique script identifier
3289 * @param int $instance optional instance id
3290 * @return int Instance ID
3292 function require_user_key_login($script, $instance=null) {
3293 global $DB;
3295 if (!NO_MOODLE_COOKIES) {
3296 print_error('sessioncookiesdisable');
3299 // Extra safety.
3300 \core\session\manager::write_close();
3302 $keyvalue = required_param('key', PARAM_ALPHANUM);
3304 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3305 print_error('invalidkey');
3308 if (!empty($key->validuntil) and $key->validuntil < time()) {
3309 print_error('expiredkey');
3312 if ($key->iprestriction) {
3313 $remoteaddr = getremoteaddr(null);
3314 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3315 print_error('ipmismatch');
3319 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3320 print_error('invaliduserid');
3323 // Emulate normal session.
3324 enrol_check_plugins($user);
3325 \core\session\manager::set_user($user);
3327 // Note we are not using normal login.
3328 if (!defined('USER_KEY_LOGIN')) {
3329 define('USER_KEY_LOGIN', true);
3332 // Return instance id - it might be empty.
3333 return $key->instance;
3337 * Creates a new private user access key.
3339 * @param string $script unique target identifier
3340 * @param int $userid
3341 * @param int $instance optional instance id
3342 * @param string $iprestriction optional ip restricted access
3343 * @param timestamp $validuntil key valid only until given data
3344 * @return string access key value
3346 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3347 global $DB;
3349 $key = new stdClass();
3350 $key->script = $script;
3351 $key->userid = $userid;
3352 $key->instance = $instance;
3353 $key->iprestriction = $iprestriction;
3354 $key->validuntil = $validuntil;
3355 $key->timecreated = time();
3357 // Something long and unique.
3358 $key->value = md5($userid.'_'.time().random_string(40));
3359 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3360 // Must be unique.
3361 $key->value = md5($userid.'_'.time().random_string(40));
3363 $DB->insert_record('user_private_key', $key);
3364 return $key->value;
3368 * Delete the user's new private user access keys for a particular script.
3370 * @param string $script unique target identifier
3371 * @param int $userid
3372 * @return void
3374 function delete_user_key($script, $userid) {
3375 global $DB;
3376 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3380 * Gets a private user access key (and creates one if one doesn't exist).
3382 * @param string $script unique target identifier
3383 * @param int $userid
3384 * @param int $instance optional instance id
3385 * @param string $iprestriction optional ip restricted access
3386 * @param timestamp $validuntil key valid only until given data
3387 * @return string access key value
3389 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3390 global $DB;
3392 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3393 'instance' => $instance, 'iprestriction' => $iprestriction,
3394 'validuntil' => $validuntil))) {
3395 return $key->value;
3396 } else {
3397 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3403 * Modify the user table by setting the currently logged in user's last login to now.
3405 * @return bool Always returns true
3407 function update_user_login_times() {
3408 global $USER, $DB;
3410 if (isguestuser()) {
3411 // Do not update guest access times/ips for performance.
3412 return true;
3415 $now = time();
3417 $user = new stdClass();
3418 $user->id = $USER->id;
3420 // Make sure all users that logged in have some firstaccess.
3421 if ($USER->firstaccess == 0) {
3422 $USER->firstaccess = $user->firstaccess = $now;
3425 // Store the previous current as lastlogin.
3426 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3428 $USER->currentlogin = $user->currentlogin = $now;
3430 // Function user_accesstime_log() may not update immediately, better do it here.
3431 $USER->lastaccess = $user->lastaccess = $now;
3432 $USER->lastip = $user->lastip = getremoteaddr();
3434 // Note: do not call user_update_user() here because this is part of the login process,
3435 // the login event means that these fields were updated.
3436 $DB->update_record('user', $user);
3437 return true;
3441 * Determines if a user has completed setting up their account.
3443 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3444 * @return bool
3446 function user_not_fully_set_up($user) {
3447 if (isguestuser($user)) {
3448 return false;
3450 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3454 * Check whether the user has exceeded the bounce threshold
3456 * @param stdClass $user A {@link $USER} object
3457 * @return bool true => User has exceeded bounce threshold
3459 function over_bounce_threshold($user) {
3460 global $CFG, $DB;
3462 if (empty($CFG->handlebounces)) {
3463 return false;
3466 if (empty($user->id)) {
3467 // No real (DB) user, nothing to do here.
3468 return false;
3471 // Set sensible defaults.
3472 if (empty($CFG->minbounces)) {
3473 $CFG->minbounces = 10;
3475 if (empty($CFG->bounceratio)) {
3476 $CFG->bounceratio = .20;
3478 $bouncecount = 0;
3479 $sendcount = 0;
3480 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3481 $bouncecount = $bounce->value;
3483 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3484 $sendcount = $send->value;
3486 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3490 * Used to increment or reset email sent count
3492 * @param stdClass $user object containing an id
3493 * @param bool $reset will reset the count to 0
3494 * @return void
3496 function set_send_count($user, $reset=false) {
3497 global $DB;
3499 if (empty($user->id)) {
3500 // No real (DB) user, nothing to do here.
3501 return;
3504 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3505 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3506 $DB->update_record('user_preferences', $pref);
3507 } else if (!empty($reset)) {
3508 // If it's not there and we're resetting, don't bother. Make a new one.
3509 $pref = new stdClass();
3510 $pref->name = 'email_send_count';
3511 $pref->value = 1;
3512 $pref->userid = $user->id;
3513 $DB->insert_record('user_preferences', $pref, false);
3518 * Increment or reset user's email bounce count
3520 * @param stdClass $user object containing an id
3521 * @param bool $reset will reset the count to 0
3523 function set_bounce_count($user, $reset=false) {
3524 global $DB;
3526 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3527 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3528 $DB->update_record('user_preferences', $pref);
3529 } else if (!empty($reset)) {
3530 // If it's not there and we're resetting, don't bother. Make a new one.
3531 $pref = new stdClass();
3532 $pref->name = 'email_bounce_count';
3533 $pref->value = 1;
3534 $pref->userid = $user->id;
3535 $DB->insert_record('user_preferences', $pref, false);
3540 * Determines if the logged in user is currently moving an activity
3542 * @param int $courseid The id of the course being tested
3543 * @return bool
3545 function ismoving($courseid) {
3546 global $USER;
3548 if (!empty($USER->activitycopy)) {
3549 return ($USER->activitycopycourse == $courseid);
3551 return false;
3555 * Returns a persons full name
3557 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3558 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3559 * specify one.
3561 * @param stdClass $user A {@link $USER} object to get full name of.
3562 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3563 * @return string
3565 function fullname($user, $override=false) {
3566 global $CFG, $SESSION;
3568 if (!isset($user->firstname) and !isset($user->lastname)) {
3569 return '';
3572 // Get all of the name fields.
3573 $allnames = get_all_user_name_fields();
3574 if ($CFG->debugdeveloper) {
3575 foreach ($allnames as $allname) {
3576 if (!array_key_exists($allname, $user)) {
3577 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3578 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3579 // Message has been sent, no point in sending the message multiple times.
3580 break;
3585 if (!$override) {
3586 if (!empty($CFG->forcefirstname)) {
3587 $user->firstname = $CFG->forcefirstname;
3589 if (!empty($CFG->forcelastname)) {
3590 $user->lastname = $CFG->forcelastname;
3594 if (!empty($SESSION->fullnamedisplay)) {
3595 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3598 $template = null;
3599 // If the fullnamedisplay setting is available, set the template to that.
3600 if (isset($CFG->fullnamedisplay)) {
3601 $template = $CFG->fullnamedisplay;
3603 // If the template is empty, or set to language, or $override is set, return the language string.
3604 if (empty($template) || $template == 'language' || $override) {
3605 return get_string('fullnamedisplay', null, $user);
3608 $requirednames = array();
3609 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3610 foreach ($allnames as $allname) {
3611 if (strpos($template, $allname) !== false) {
3612 $requirednames[] = $allname;
3616 $displayname = $template;
3617 // Switch in the actual data into the template.
3618 foreach ($requirednames as $altname) {
3619 if (isset($user->$altname)) {
3620 // Using empty() on the below if statement causes breakages.
3621 if ((string)$user->$altname == '') {
3622 $displayname = str_replace($altname, 'EMPTY', $displayname);
3623 } else {
3624 $displayname = str_replace($altname, $user->$altname, $displayname);
3626 } else {
3627 $displayname = str_replace($altname, 'EMPTY', $displayname);
3630 // Tidy up any misc. characters (Not perfect, but gets most characters).
3631 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3632 // katakana and parenthesis.
3633 $patterns = array();
3634 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3635 // filled in by a user.
3636 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3637 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3638 // This regular expression is to remove any double spaces in the display name.
3639 $patterns[] = '/\s{2,}/u';
3640 foreach ($patterns as $pattern) {
3641 $displayname = preg_replace($pattern, ' ', $displayname);
3644 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3645 $displayname = trim($displayname);
3646 if (empty($displayname)) {
3647 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3648 // people in general feel is a good setting to fall back on.
3649 $displayname = $user->firstname;
3651 return $displayname;
3655 * A centralised location for the all name fields. Returns an array / sql string snippet.
3657 * @param bool $returnsql True for an sql select field snippet.
3658 * @param string $tableprefix table query prefix to use in front of each field.
3659 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3660 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3661 * @return array|string All name fields.
3663 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null) {
3664 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3665 'lastnamephonetic' => 'lastnamephonetic',
3666 'middlename' => 'middlename',
3667 'alternatename' => 'alternatename',
3668 'firstname' => 'firstname',
3669 'lastname' => 'lastname');
3671 // Let's add a prefix to the array of user name fields if provided.
3672 if ($prefix) {
3673 foreach ($alternatenames as $key => $altname) {
3674 $alternatenames[$key] = $prefix . $altname;
3678 // Create an sql field snippet if requested.
3679 if ($returnsql) {
3680 if ($tableprefix) {
3681 if ($fieldprefix) {
3682 foreach ($alternatenames as $key => $altname) {
3683 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3685 } else {
3686 foreach ($alternatenames as $key => $altname) {
3687 $alternatenames[$key] = $tableprefix . '.' . $altname;
3691 $alternatenames = implode(',', $alternatenames);
3693 return $alternatenames;
3697 * Reduces lines of duplicated code for getting user name fields.
3699 * See also {@link user_picture::unalias()}
3701 * @param object $addtoobject Object to add user name fields to.
3702 * @param object $secondobject Object that contains user name field information.
3703 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3704 * @param array $additionalfields Additional fields to be matched with data in the second object.
3705 * The key can be set to the user table field name.
3706 * @return object User name fields.
3708 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3709 $fields = get_all_user_name_fields(false, null, $prefix);
3710 if ($additionalfields) {
3711 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3712 // the key is a number and then sets the key to the array value.
3713 foreach ($additionalfields as $key => $value) {
3714 if (is_numeric($key)) {
3715 $additionalfields[$value] = $prefix . $value;
3716 unset($additionalfields[$key]);
3717 } else {
3718 $additionalfields[$key] = $prefix . $value;
3721 $fields = array_merge($fields, $additionalfields);
3723 foreach ($fields as $key => $field) {
3724 // Important that we have all of the user name fields present in the object that we are sending back.
3725 $addtoobject->$key = '';
3726 if (isset($secondobject->$field)) {
3727 $addtoobject->$key = $secondobject->$field;
3730 return $addtoobject;
3734 * Returns an array of values in order of occurance in a provided string.
3735 * The key in the result is the character postion in the string.
3737 * @param array $values Values to be found in the string format
3738 * @param string $stringformat The string which may contain values being searched for.
3739 * @return array An array of values in order according to placement in the string format.
3741 function order_in_string($values, $stringformat) {
3742 $valuearray = array();
3743 foreach ($values as $value) {
3744 $pattern = "/$value\b/";
3745 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3746 if (preg_match($pattern, $stringformat)) {
3747 $replacement = "thing";
3748 // Replace the value with something more unique to ensure we get the right position when using strpos().
3749 $newformat = preg_replace($pattern, $replacement, $stringformat);
3750 $position = strpos($newformat, $replacement);
3751 $valuearray[$position] = $value;
3754 ksort($valuearray);
3755 return $valuearray;
3759 * Checks if current user is shown any extra fields when listing users.
3761 * @param object $context Context
3762 * @param array $already Array of fields that we're going to show anyway
3763 * so don't bother listing them
3764 * @return array Array of field names from user table, not including anything
3765 * listed in $already
3767 function get_extra_user_fields($context, $already = array()) {
3768 global $CFG;
3770 // Only users with permission get the extra fields.
3771 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3772 return array();
3775 // Split showuseridentity on comma.
3776 if (empty($CFG->showuseridentity)) {
3777 // Explode gives wrong result with empty string.
3778 $extra = array();
3779 } else {
3780 $extra = explode(',', $CFG->showuseridentity);
3782 $renumber = false;
3783 foreach ($extra as $key => $field) {
3784 if (in_array($field, $already)) {
3785 unset($extra[$key]);
3786 $renumber = true;
3789 if ($renumber) {
3790 // For consistency, if entries are removed from array, renumber it
3791 // so they are numbered as you would expect.
3792 $extra = array_merge($extra);
3794 return $extra;
3798 * If the current user is to be shown extra user fields when listing or
3799 * selecting users, returns a string suitable for including in an SQL select
3800 * clause to retrieve those fields.
3802 * @param context $context Context
3803 * @param string $alias Alias of user table, e.g. 'u' (default none)
3804 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3805 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3806 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3808 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3809 $fields = get_extra_user_fields($context, $already);
3810 $result = '';
3811 // Add punctuation for alias.
3812 if ($alias !== '') {
3813 $alias .= '.';
3815 foreach ($fields as $field) {
3816 $result .= ', ' . $alias . $field;
3817 if ($prefix) {
3818 $result .= ' AS ' . $prefix . $field;
3821 return $result;
3825 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3826 * @param string $field Field name, e.g. 'phone1'
3827 * @return string Text description taken from language file, e.g. 'Phone number'
3829 function get_user_field_name($field) {
3830 // Some fields have language strings which are not the same as field name.
3831 switch ($field) {
3832 case 'phone1' : {
3833 return get_string('phone');
3835 case 'url' : {
3836 return get_string('webpage');
3838 case 'icq' : {
3839 return get_string('icqnumber');
3841 case 'skype' : {
3842 return get_string('skypeid');
3844 case 'aim' : {
3845 return get_string('aimid');
3847 case 'yahoo' : {
3848 return get_string('yahooid');
3850 case 'msn' : {
3851 return get_string('msnid');
3854 // Otherwise just use the same lang string.
3855 return get_string($field);
3859 * Returns whether a given authentication plugin exists.
3861 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3862 * @return boolean Whether the plugin is available.
3864 function exists_auth_plugin($auth) {
3865 global $CFG;
3867 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3868 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3870 return false;
3874 * Checks if a given plugin is in the list of enabled authentication plugins.
3876 * @param string $auth Authentication plugin.
3877 * @return boolean Whether the plugin is enabled.
3879 function is_enabled_auth($auth) {
3880 if (empty($auth)) {
3881 return false;
3884 $enabled = get_enabled_auth_plugins();
3886 return in_array($auth, $enabled);
3890 * Returns an authentication plugin instance.
3892 * @param string $auth name of authentication plugin
3893 * @return auth_plugin_base An instance of the required authentication plugin.
3895 function get_auth_plugin($auth) {
3896 global $CFG;
3898 // Check the plugin exists first.
3899 if (! exists_auth_plugin($auth)) {
3900 print_error('authpluginnotfound', 'debug', '', $auth);
3903 // Return auth plugin instance.
3904 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3905 $class = "auth_plugin_$auth";
3906 return new $class;
3910 * Returns array of active auth plugins.
3912 * @param bool $fix fix $CFG->auth if needed
3913 * @return array
3915 function get_enabled_auth_plugins($fix=false) {
3916 global $CFG;
3918 $default = array('manual', 'nologin');
3920 if (empty($CFG->auth)) {
3921 $auths = array();
3922 } else {
3923 $auths = explode(',', $CFG->auth);
3926 if ($fix) {
3927 $auths = array_unique($auths);
3928 foreach ($auths as $k => $authname) {
3929 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3930 unset($auths[$k]);
3933 $newconfig = implode(',', $auths);
3934 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3935 set_config('auth', $newconfig);
3939 return (array_merge($default, $auths));
3943 * Returns true if an internal authentication method is being used.
3944 * if method not specified then, global default is assumed
3946 * @param string $auth Form of authentication required
3947 * @return bool
3949 function is_internal_auth($auth) {
3950 // Throws error if bad $auth.
3951 $authplugin = get_auth_plugin($auth);
3952 return $authplugin->is_internal();
3956 * Returns true if the user is a 'restored' one.
3958 * Used in the login process to inform the user and allow him/her to reset the password
3960 * @param string $username username to be checked
3961 * @return bool
3963 function is_restored_user($username) {
3964 global $CFG, $DB;
3966 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3970 * Returns an array of user fields
3972 * @return array User field/column names
3974 function get_user_fieldnames() {
3975 global $DB;
3977 $fieldarray = $DB->get_columns('user');
3978 unset($fieldarray['id']);
3979 $fieldarray = array_keys($fieldarray);
3981 return $fieldarray;
3985 * Creates a bare-bones user record
3987 * @todo Outline auth types and provide code example
3989 * @param string $username New user's username to add to record
3990 * @param string $password New user's password to add to record
3991 * @param string $auth Form of authentication required
3992 * @return stdClass A complete user object
3994 function create_user_record($username, $password, $auth = 'manual') {
3995 global $CFG, $DB;
3996 require_once($CFG->dirroot.'/user/profile/lib.php');
3997 require_once($CFG->dirroot.'/user/lib.php');
3999 // Just in case check text case.
4000 $username = trim(core_text::strtolower($username));
4002 $authplugin = get_auth_plugin($auth);
4003 $customfields = $authplugin->get_custom_user_profile_fields();
4004 $newuser = new stdClass();
4005 if ($newinfo = $authplugin->get_userinfo($username)) {
4006 $newinfo = truncate_userinfo($newinfo);
4007 foreach ($newinfo as $key => $value) {
4008 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
4009 $newuser->$key = $value;
4014 if (!empty($newuser->email)) {
4015 if (email_is_not_allowed($newuser->email)) {
4016 unset($newuser->email);
4020 if (!isset($newuser->city)) {
4021 $newuser->city = '';
4024 $newuser->auth = $auth;
4025 $newuser->username = $username;
4027 // Fix for MDL-8480
4028 // user CFG lang for user if $newuser->lang is empty
4029 // or $user->lang is not an installed language.
4030 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
4031 $newuser->lang = $CFG->lang;
4033 $newuser->confirmed = 1;
4034 $newuser->lastip = getremoteaddr();
4035 $newuser->timecreated = time();
4036 $newuser->timemodified = $newuser->timecreated;
4037 $newuser->mnethostid = $CFG->mnet_localhost_id;
4039 $newuser->id = user_create_user($newuser, false, false);
4041 // Save user profile data.
4042 profile_save_data($newuser);
4044 $user = get_complete_user_data('id', $newuser->id);
4045 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
4046 set_user_preference('auth_forcepasswordchange', 1, $user);
4048 // Set the password.
4049 update_internal_user_password($user, $password);
4051 // Trigger event.
4052 \core\event\user_created::create_from_userid($newuser->id)->trigger();
4054 return $user;
4058 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4060 * @param string $username user's username to update the record
4061 * @return stdClass A complete user object
4063 function update_user_record($username) {
4064 global $DB, $CFG;
4065 // Just in case check text case.
4066 $username = trim(core_text::strtolower($username));
4068 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
4069 return update_user_record_by_id($oldinfo->id);
4073 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4075 * @param int $id user id
4076 * @return stdClass A complete user object
4078 function update_user_record_by_id($id) {
4079 global $DB, $CFG;
4080 require_once($CFG->dirroot."/user/profile/lib.php");
4081 require_once($CFG->dirroot.'/user/lib.php');
4083 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
4084 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
4086 $newuser = array();
4087 $userauth = get_auth_plugin($oldinfo->auth);
4089 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
4090 $newinfo = truncate_userinfo($newinfo);
4091 $customfields = $userauth->get_custom_user_profile_fields();
4093 foreach ($newinfo as $key => $value) {
4094 $key = strtolower($key);
4095 $iscustom = in_array($key, $customfields);
4096 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4097 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4098 // Unknown or must not be changed.
4099 continue;
4101 $confval = $userauth->config->{'field_updatelocal_' . $key};
4102 $lockval = $userauth->config->{'field_lock_' . $key};
4103 if (empty($confval) || empty($lockval)) {
4104 continue;
4106 if ($confval === 'onlogin') {
4107 // MDL-4207 Don't overwrite modified user profile values with
4108 // empty LDAP values when 'unlocked if empty' is set. The purpose
4109 // of the setting 'unlocked if empty' is to allow the user to fill
4110 // in a value for the selected field _if LDAP is giving
4111 // nothing_ for this field. Thus it makes sense to let this value
4112 // stand in until LDAP is giving a value for this field.
4113 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4114 if ($iscustom || (in_array($key, $userauth->userfields) &&
4115 ((string)$oldinfo->$key !== (string)$value))) {
4116 $newuser[$key] = (string)$value;
4121 if ($newuser) {
4122 $newuser['id'] = $oldinfo->id;
4123 $newuser['timemodified'] = time();
4124 user_update_user((object) $newuser, false, false);
4126 // Save user profile data.
4127 profile_save_data((object) $newuser);
4129 // Trigger event.
4130 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4134 return get_complete_user_data('id', $oldinfo->id);
4138 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4140 * @param array $info Array of user properties to truncate if needed
4141 * @return array The now truncated information that was passed in
4143 function truncate_userinfo(array $info) {
4144 // Define the limits.
4145 $limit = array(
4146 'username' => 100,
4147 'idnumber' => 255,
4148 'firstname' => 100,
4149 'lastname' => 100,
4150 'email' => 100,
4151 'icq' => 15,
4152 'phone1' => 20,
4153 'phone2' => 20,
4154 'institution' => 255,
4155 'department' => 255,
4156 'address' => 255,
4157 'city' => 120,
4158 'country' => 2,
4159 'url' => 255,
4162 // Apply where needed.
4163 foreach (array_keys($info) as $key) {
4164 if (!empty($limit[$key])) {
4165 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4169 return $info;
4173 * Marks user deleted in internal user database and notifies the auth plugin.
4174 * Also unenrols user from all roles and does other cleanup.
4176 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4178 * @param stdClass $user full user object before delete
4179 * @return boolean success
4180 * @throws coding_exception if invalid $user parameter detected
4182 function delete_user(stdClass $user) {
4183 global $CFG, $DB;
4184 require_once($CFG->libdir.'/grouplib.php');
4185 require_once($CFG->libdir.'/gradelib.php');
4186 require_once($CFG->dirroot.'/message/lib.php');
4187 require_once($CFG->dirroot.'/tag/lib.php');
4188 require_once($CFG->dirroot.'/user/lib.php');
4190 // Make sure nobody sends bogus record type as parameter.
4191 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4192 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4195 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4196 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4197 debugging('Attempt to delete unknown user account.');
4198 return false;
4201 // There must be always exactly one guest record, originally the guest account was identified by username only,
4202 // now we use $CFG->siteguest for performance reasons.
4203 if ($user->username === 'guest' or isguestuser($user)) {
4204 debugging('Guest user account can not be deleted.');
4205 return false;
4208 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4209 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4210 if ($user->auth === 'manual' and is_siteadmin($user)) {
4211 debugging('Local administrator accounts can not be deleted.');
4212 return false;
4215 // Keep user record before updating it, as we have to pass this to user_deleted event.
4216 $olduser = clone $user;
4218 // Keep a copy of user context, we need it for event.
4219 $usercontext = context_user::instance($user->id);
4221 // Delete all grades - backup is kept in grade_grades_history table.
4222 grade_user_delete($user->id);
4224 // Move unread messages from this user to read.
4225 message_move_userfrom_unread2read($user->id);
4227 // TODO: remove from cohorts using standard API here.
4229 // Remove user tags.
4230 tag_set('user', $user->id, array(), 'core', $usercontext->id);
4232 // Unconditionally unenrol from all courses.
4233 enrol_user_delete($user);
4235 // Unenrol from all roles in all contexts.
4236 // This might be slow but it is really needed - modules might do some extra cleanup!
4237 role_unassign_all(array('userid' => $user->id));
4239 // Now do a brute force cleanup.
4241 // Remove from all cohorts.
4242 $DB->delete_records('cohort_members', array('userid' => $user->id));
4244 // Remove from all groups.
4245 $DB->delete_records('groups_members', array('userid' => $user->id));
4247 // Brute force unenrol from all courses.
4248 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4250 // Purge user preferences.
4251 $DB->delete_records('user_preferences', array('userid' => $user->id));
4253 // Purge user extra profile info.
4254 $DB->delete_records('user_info_data', array('userid' => $user->id));
4256 // Last course access not necessary either.
4257 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4258 // Remove all user tokens.
4259 $DB->delete_records('external_tokens', array('userid' => $user->id));
4261 // Unauthorise the user for all services.
4262 $DB->delete_records('external_services_users', array('userid' => $user->id));
4264 // Remove users private keys.
4265 $DB->delete_records('user_private_key', array('userid' => $user->id));
4267 // Remove users customised pages.
4268 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4270 // Force logout - may fail if file based sessions used, sorry.
4271 \core\session\manager::kill_user_sessions($user->id);
4273 // Workaround for bulk deletes of users with the same email address.
4274 $delname = clean_param($user->email . "." . time(), PARAM_USERNAME);
4275 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4276 $delname++;
4279 // Mark internal user record as "deleted".
4280 $updateuser = new stdClass();
4281 $updateuser->id = $user->id;
4282 $updateuser->deleted = 1;
4283 $updateuser->username = $delname; // Remember it just in case.
4284 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4285 $updateuser->idnumber = ''; // Clear this field to free it up.
4286 $updateuser->picture = 0;
4287 $updateuser->timemodified = time();
4289 // Don't trigger update event, as user is being deleted.
4290 user_update_user($updateuser, false, false);
4292 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4293 context_helper::delete_instance(CONTEXT_USER, $user->id);
4295 // Any plugin that needs to cleanup should register this event.
4296 // Trigger event.
4297 $event = \core\event\user_deleted::create(
4298 array(
4299 'objectid' => $user->id,
4300 'relateduserid' => $user->id,
4301 'context' => $usercontext,
4302 'other' => array(
4303 'username' => $user->username,
4304 'email' => $user->email,
4305 'idnumber' => $user->idnumber,
4306 'picture' => $user->picture,
4307 'mnethostid' => $user->mnethostid
4311 $event->add_record_snapshot('user', $olduser);
4312 $event->trigger();
4314 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4315 // should know about this updated property persisted to the user's table.
4316 $user->timemodified = $updateuser->timemodified;
4318 // Notify auth plugin - do not block the delete even when plugin fails.
4319 $authplugin = get_auth_plugin($user->auth);
4320 $authplugin->user_delete($user);
4322 return true;
4326 * Retrieve the guest user object.
4328 * @return stdClass A {@link $USER} object
4330 function guest_user() {
4331 global $CFG, $DB;
4333 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4334 $newuser->confirmed = 1;
4335 $newuser->lang = $CFG->lang;
4336 $newuser->lastip = getremoteaddr();
4339 return $newuser;
4343 * Authenticates a user against the chosen authentication mechanism
4345 * Given a username and password, this function looks them
4346 * up using the currently selected authentication mechanism,
4347 * and if the authentication is successful, it returns a
4348 * valid $user object from the 'user' table.
4350 * Uses auth_ functions from the currently active auth module
4352 * After authenticate_user_login() returns success, you will need to
4353 * log that the user has logged in, and call complete_user_login() to set
4354 * the session up.
4356 * Note: this function works only with non-mnet accounts!
4358 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4359 * @param string $password User's password
4360 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4361 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4362 * @return stdClass|false A {@link $USER} object or false if error
4364 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4365 global $CFG, $DB;
4366 require_once("$CFG->libdir/authlib.php");
4368 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4369 // we have found the user
4371 } else if (!empty($CFG->authloginviaemail)) {
4372 if ($email = clean_param($username, PARAM_EMAIL)) {
4373 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4374 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4375 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4376 if (count($users) === 1) {
4377 // Use email for login only if unique.
4378 $user = reset($users);
4379 $user = get_complete_user_data('id', $user->id);
4380 $username = $user->username;
4382 unset($users);
4386 $authsenabled = get_enabled_auth_plugins();
4388 if ($user) {
4389 // Use manual if auth not set.
4390 $auth = empty($user->auth) ? 'manual' : $user->auth;
4391 if (!empty($user->suspended)) {
4392 $failurereason = AUTH_LOGIN_SUSPENDED;
4394 // Trigger login failed event.
4395 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4396 'other' => array('username' => $username, 'reason' => $failurereason)));
4397 $event->trigger();
4398 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4399 return false;
4401 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4402 // Legacy way to suspend user.
4403 $failurereason = AUTH_LOGIN_SUSPENDED;
4405 // Trigger login failed event.
4406 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4407 'other' => array('username' => $username, 'reason' => $failurereason)));
4408 $event->trigger();
4409 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4410 return false;
4412 $auths = array($auth);
4414 } else {
4415 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4416 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4417 $failurereason = AUTH_LOGIN_NOUSER;
4419 // Trigger login failed event.
4420 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4421 'reason' => $failurereason)));
4422 $event->trigger();
4423 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4424 return false;
4427 // Do not try to authenticate non-existent accounts when user creation is disabled.
4428 if (!empty($CFG->authpreventaccountcreation)) {
4429 $failurereason = AUTH_LOGIN_NOUSER;
4431 // Trigger login failed event.
4432 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4433 'reason' => $failurereason)));
4434 $event->trigger();
4436 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4437 $_SERVER['HTTP_USER_AGENT']);
4438 return false;
4441 // User does not exist.
4442 $auths = $authsenabled;
4443 $user = new stdClass();
4444 $user->id = 0;
4447 if ($ignorelockout) {
4448 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4449 // or this function is called from a SSO script.
4450 } else if ($user->id) {
4451 // Verify login lockout after other ways that may prevent user login.
4452 if (login_is_lockedout($user)) {
4453 $failurereason = AUTH_LOGIN_LOCKOUT;
4455 // Trigger login failed event.
4456 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4457 'other' => array('username' => $username, 'reason' => $failurereason)));
4458 $event->trigger();
4460 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4461 return false;
4463 } else {
4464 // We can not lockout non-existing accounts.
4467 foreach ($auths as $auth) {
4468 $authplugin = get_auth_plugin($auth);
4470 // On auth fail fall through to the next plugin.
4471 if (!$authplugin->user_login($username, $password)) {
4472 continue;
4475 // Successful authentication.
4476 if ($user->id) {
4477 // User already exists in database.
4478 if (empty($user->auth)) {
4479 // For some reason auth isn't set yet.
4480 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4481 $user->auth = $auth;
4484 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4485 // the current hash algorithm while we have access to the user's password.
4486 update_internal_user_password($user, $password);
4488 if ($authplugin->is_synchronised_with_external()) {
4489 // Update user record from external DB.
4490 $user = update_user_record_by_id($user->id);
4492 } else {
4493 // Create account, we verified above that user creation is allowed.
4494 $user = create_user_record($username, $password, $auth);
4497 $authplugin->sync_roles($user);
4499 foreach ($authsenabled as $hau) {
4500 $hauth = get_auth_plugin($hau);
4501 $hauth->user_authenticated_hook($user, $username, $password);
4504 if (empty($user->id)) {
4505 $failurereason = AUTH_LOGIN_NOUSER;
4506 // Trigger login failed event.
4507 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4508 'reason' => $failurereason)));
4509 $event->trigger();
4510 return false;
4513 if (!empty($user->suspended)) {
4514 // Just in case some auth plugin suspended account.
4515 $failurereason = AUTH_LOGIN_SUSPENDED;
4516 // Trigger login failed event.
4517 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4518 'other' => array('username' => $username, 'reason' => $failurereason)));
4519 $event->trigger();
4520 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4521 return false;
4524 login_attempt_valid($user);
4525 $failurereason = AUTH_LOGIN_OK;
4526 return $user;
4529 // Failed if all the plugins have failed.
4530 if (debugging('', DEBUG_ALL)) {
4531 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4534 if ($user->id) {
4535 login_attempt_failed($user);
4536 $failurereason = AUTH_LOGIN_FAILED;
4537 // Trigger login failed event.
4538 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4539 'other' => array('username' => $username, 'reason' => $failurereason)));
4540 $event->trigger();
4541 } else {
4542 $failurereason = AUTH_LOGIN_NOUSER;
4543 // Trigger login failed event.
4544 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4545 'reason' => $failurereason)));
4546 $event->trigger();
4549 return false;
4553 * Call to complete the user login process after authenticate_user_login()
4554 * has succeeded. It will setup the $USER variable and other required bits
4555 * and pieces.
4557 * NOTE:
4558 * - It will NOT log anything -- up to the caller to decide what to log.
4559 * - this function does not set any cookies any more!
4561 * @param stdClass $user
4562 * @return stdClass A {@link $USER} object - BC only, do not use
4564 function complete_user_login($user) {
4565 global $CFG, $USER;
4567 \core\session\manager::login_user($user);
4569 // Reload preferences from DB.
4570 unset($USER->preference);
4571 check_user_preferences_loaded($USER);
4573 // Update login times.
4574 update_user_login_times();
4576 // Extra session prefs init.
4577 set_login_session_preferences();
4579 // Trigger login event.
4580 $event = \core\event\user_loggedin::create(
4581 array(
4582 'userid' => $USER->id,
4583 'objectid' => $USER->id,
4584 'other' => array('username' => $USER->username),
4587 $event->trigger();
4589 if (isguestuser()) {
4590 // No need to continue when user is THE guest.
4591 return $USER;
4594 if (CLI_SCRIPT) {
4595 // We can redirect to password change URL only in browser.
4596 return $USER;
4599 // Select password change url.
4600 $userauth = get_auth_plugin($USER->auth);
4602 // Check whether the user should be changing password.
4603 if (get_user_preferences('auth_forcepasswordchange', false)) {
4604 if ($userauth->can_change_password()) {
4605 if ($changeurl = $userauth->change_password_url()) {
4606 redirect($changeurl);
4607 } else {
4608 redirect($CFG->httpswwwroot.'/login/change_password.php');
4610 } else {
4611 print_error('nopasswordchangeforced', 'auth');
4614 return $USER;
4618 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4620 * @param string $password String to check.
4621 * @return boolean True if the $password matches the format of an md5 sum.
4623 function password_is_legacy_hash($password) {
4624 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4628 * Compare password against hash stored in user object to determine if it is valid.
4630 * If necessary it also updates the stored hash to the current format.
4632 * @param stdClass $user (Password property may be updated).
4633 * @param string $password Plain text password.
4634 * @return bool True if password is valid.
4636 function validate_internal_user_password($user, $password) {
4637 global $CFG;
4638 require_once($CFG->libdir.'/password_compat/lib/password.php');
4640 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4641 // Internal password is not used at all, it can not validate.
4642 return false;
4645 // If hash isn't a legacy (md5) hash, validate using the library function.
4646 if (!password_is_legacy_hash($user->password)) {
4647 return password_verify($password, $user->password);
4650 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4651 // is valid we can then update it to the new algorithm.
4653 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4654 $validated = false;
4656 if ($user->password === md5($password.$sitesalt)
4657 or $user->password === md5($password)
4658 or $user->password === md5(addslashes($password).$sitesalt)
4659 or $user->password === md5(addslashes($password))) {
4660 // Note: we are intentionally using the addslashes() here because we
4661 // need to accept old password hashes of passwords with magic quotes.
4662 $validated = true;
4664 } else {
4665 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4666 $alt = 'passwordsaltalt'.$i;
4667 if (!empty($CFG->$alt)) {
4668 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4669 $validated = true;
4670 break;
4676 if ($validated) {
4677 // If the password matches the existing md5 hash, update to the
4678 // current hash algorithm while we have access to the user's password.
4679 update_internal_user_password($user, $password);
4682 return $validated;
4686 * Calculate hash for a plain text password.
4688 * @param string $password Plain text password to be hashed.
4689 * @param bool $fasthash If true, use a low cost factor when generating the hash
4690 * This is much faster to generate but makes the hash
4691 * less secure. It is used when lots of hashes need to
4692 * be generated quickly.
4693 * @return string The hashed password.
4695 * @throws moodle_exception If a problem occurs while generating the hash.
4697 function hash_internal_user_password($password, $fasthash = false) {
4698 global $CFG;
4699 require_once($CFG->libdir.'/password_compat/lib/password.php');
4701 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4702 $options = ($fasthash) ? array('cost' => 4) : array();
4704 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4706 if ($generatedhash === false || $generatedhash === null) {
4707 throw new moodle_exception('Failed to generate password hash.');
4710 return $generatedhash;
4714 * Update password hash in user object (if necessary).
4716 * The password is updated if:
4717 * 1. The password has changed (the hash of $user->password is different
4718 * to the hash of $password).
4719 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4720 * md5 algorithm).
4722 * Updating the password will modify the $user object and the database
4723 * record to use the current hashing algorithm.
4725 * @param stdClass $user User object (password property may be updated).
4726 * @param string $password Plain text password.
4727 * @param bool $fasthash If true, use a low cost factor when generating the hash
4728 * This is much faster to generate but makes the hash
4729 * less secure. It is used when lots of hashes need to
4730 * be generated quickly.
4731 * @return bool Always returns true.
4733 function update_internal_user_password($user, $password, $fasthash = false) {
4734 global $CFG, $DB;
4735 require_once($CFG->libdir.'/password_compat/lib/password.php');
4737 // Figure out what the hashed password should be.
4738 if (!isset($user->auth)) {
4739 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4741 $authplugin = get_auth_plugin($user->auth);
4742 if ($authplugin->prevent_local_passwords()) {
4743 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4744 } else {
4745 $hashedpassword = hash_internal_user_password($password, $fasthash);
4748 $algorithmchanged = false;
4750 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4751 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4752 $passwordchanged = ($user->password !== $hashedpassword);
4754 } else if (isset($user->password)) {
4755 // If verification fails then it means the password has changed.
4756 $passwordchanged = !password_verify($password, $user->password);
4757 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4758 } else {
4759 // While creating new user, password in unset in $user object, to avoid
4760 // saving it with user_create()
4761 $passwordchanged = true;
4764 if ($passwordchanged || $algorithmchanged) {
4765 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4766 $user->password = $hashedpassword;
4768 // Trigger event.
4769 $user = $DB->get_record('user', array('id' => $user->id));
4770 \core\event\user_password_updated::create_from_user($user)->trigger();
4773 return true;
4777 * Get a complete user record, which includes all the info in the user record.
4779 * Intended for setting as $USER session variable
4781 * @param string $field The user field to be checked for a given value.
4782 * @param string $value The value to match for $field.
4783 * @param int $mnethostid
4784 * @return mixed False, or A {@link $USER} object.
4786 function get_complete_user_data($field, $value, $mnethostid = null) {
4787 global $CFG, $DB;
4789 if (!$field || !$value) {
4790 return false;
4793 // Build the WHERE clause for an SQL query.
4794 $params = array('fieldval' => $value);
4795 $constraints = "$field = :fieldval AND deleted <> 1";
4797 // If we are loading user data based on anything other than id,
4798 // we must also restrict our search based on mnet host.
4799 if ($field != 'id') {
4800 if (empty($mnethostid)) {
4801 // If empty, we restrict to local users.
4802 $mnethostid = $CFG->mnet_localhost_id;
4805 if (!empty($mnethostid)) {
4806 $params['mnethostid'] = $mnethostid;
4807 $constraints .= " AND mnethostid = :mnethostid";
4810 // Get all the basic user data.
4811 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4812 return false;
4815 // Get various settings and preferences.
4817 // Preload preference cache.
4818 check_user_preferences_loaded($user);
4820 // Load course enrolment related stuff.
4821 $user->lastcourseaccess = array(); // During last session.
4822 $user->currentcourseaccess = array(); // During current session.
4823 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4824 foreach ($lastaccesses as $lastaccess) {
4825 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4829 $sql = "SELECT g.id, g.courseid
4830 FROM {groups} g, {groups_members} gm
4831 WHERE gm.groupid=g.id AND gm.userid=?";
4833 // This is a special hack to speedup calendar display.
4834 $user->groupmember = array();
4835 if (!isguestuser($user)) {
4836 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4837 foreach ($groups as $group) {
4838 if (!array_key_exists($group->courseid, $user->groupmember)) {
4839 $user->groupmember[$group->courseid] = array();
4841 $user->groupmember[$group->courseid][$group->id] = $group->id;
4846 // Add the custom profile fields to the user record.
4847 $user->profile = array();
4848 if (!isguestuser($user)) {
4849 require_once($CFG->dirroot.'/user/profile/lib.php');
4850 profile_load_custom_fields($user);
4853 // Rewrite some variables if necessary.
4854 if (!empty($user->description)) {
4855 // No need to cart all of it around.
4856 $user->description = true;
4858 if (isguestuser($user)) {
4859 // Guest language always same as site.
4860 $user->lang = $CFG->lang;
4861 // Name always in current language.
4862 $user->firstname = get_string('guestuser');
4863 $user->lastname = ' ';
4866 return $user;
4870 * Validate a password against the configured password policy
4872 * @param string $password the password to be checked against the password policy
4873 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4874 * @return bool true if the password is valid according to the policy. false otherwise.
4876 function check_password_policy($password, &$errmsg) {
4877 global $CFG;
4879 if (empty($CFG->passwordpolicy)) {
4880 return true;
4883 $errmsg = '';
4884 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4885 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4888 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4889 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4892 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4893 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4896 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4897 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4900 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4901 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4903 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4904 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4907 if ($errmsg == '') {
4908 return true;
4909 } else {
4910 return false;
4916 * When logging in, this function is run to set certain preferences for the current SESSION.
4918 function set_login_session_preferences() {
4919 global $SESSION;
4921 $SESSION->justloggedin = true;
4923 unset($SESSION->lang);
4924 unset($SESSION->forcelang);
4925 unset($SESSION->load_navigation_admin);
4930 * Delete a course, including all related data from the database, and any associated files.
4932 * @param mixed $courseorid The id of the course or course object to delete.
4933 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4934 * @return bool true if all the removals succeeded. false if there were any failures. If this
4935 * method returns false, some of the removals will probably have succeeded, and others
4936 * failed, but you have no way of knowing which.
4938 function delete_course($courseorid, $showfeedback = true) {
4939 global $DB;
4941 if (is_object($courseorid)) {
4942 $courseid = $courseorid->id;
4943 $course = $courseorid;
4944 } else {
4945 $courseid = $courseorid;
4946 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4947 return false;
4950 $context = context_course::instance($courseid);
4952 // Frontpage course can not be deleted!!
4953 if ($courseid == SITEID) {
4954 return false;
4957 // Make the course completely empty.
4958 remove_course_contents($courseid, $showfeedback);
4960 // Delete the course and related context instance.
4961 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4963 $DB->delete_records("course", array("id" => $courseid));
4964 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4966 // Reset all course related caches here.
4967 if (class_exists('format_base', false)) {
4968 format_base::reset_course_cache($courseid);
4971 // Trigger a course deleted event.
4972 $event = \core\event\course_deleted::create(array(
4973 'objectid' => $course->id,
4974 'context' => $context,
4975 'other' => array(
4976 'shortname' => $course->shortname,
4977 'fullname' => $course->fullname,
4978 'idnumber' => $course->idnumber
4981 $event->add_record_snapshot('course', $course);
4982 $event->trigger();
4984 return true;
4988 * Clear a course out completely, deleting all content but don't delete the course itself.
4990 * This function does not verify any permissions.
4992 * Please note this function also deletes all user enrolments,
4993 * enrolment instances and role assignments by default.
4995 * $options:
4996 * - 'keep_roles_and_enrolments' - false by default
4997 * - 'keep_groups_and_groupings' - false by default
4999 * @param int $courseid The id of the course that is being deleted
5000 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5001 * @param array $options extra options
5002 * @return bool true if all the removals succeeded. false if there were any failures. If this
5003 * method returns false, some of the removals will probably have succeeded, and others
5004 * failed, but you have no way of knowing which.
5006 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5007 global $CFG, $DB, $OUTPUT;
5009 require_once($CFG->libdir.'/badgeslib.php');
5010 require_once($CFG->libdir.'/completionlib.php');
5011 require_once($CFG->libdir.'/questionlib.php');
5012 require_once($CFG->libdir.'/gradelib.php');
5013 require_once($CFG->dirroot.'/group/lib.php');
5014 require_once($CFG->dirroot.'/tag/coursetagslib.php');
5015 require_once($CFG->dirroot.'/comment/lib.php');
5016 require_once($CFG->dirroot.'/rating/lib.php');
5017 require_once($CFG->dirroot.'/notes/lib.php');
5019 // Handle course badges.
5020 badges_handle_course_deletion($courseid);
5022 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5023 $strdeleted = get_string('deleted').' - ';
5025 // Some crazy wishlist of stuff we should skip during purging of course content.
5026 $options = (array)$options;
5028 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5029 $coursecontext = context_course::instance($courseid);
5030 $fs = get_file_storage();
5032 // Delete course completion information, this has to be done before grades and enrols.
5033 $cc = new completion_info($course);
5034 $cc->clear_criteria();
5035 if ($showfeedback) {
5036 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5039 // Remove all data from gradebook - this needs to be done before course modules
5040 // because while deleting this information, the system may need to reference
5041 // the course modules that own the grades.
5042 remove_course_grades($courseid, $showfeedback);
5043 remove_grade_letters($coursecontext, $showfeedback);
5045 // Delete course blocks in any all child contexts,
5046 // they may depend on modules so delete them first.
5047 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5048 foreach ($childcontexts as $childcontext) {
5049 blocks_delete_all_for_context($childcontext->id);
5051 unset($childcontexts);
5052 blocks_delete_all_for_context($coursecontext->id);
5053 if ($showfeedback) {
5054 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5057 // Delete every instance of every module,
5058 // this has to be done before deleting of course level stuff.
5059 $locations = core_component::get_plugin_list('mod');
5060 foreach ($locations as $modname => $moddir) {
5061 if ($modname === 'NEWMODULE') {
5062 continue;
5064 if ($module = $DB->get_record('modules', array('name' => $modname))) {
5065 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5066 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5067 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
5069 if ($instances = $DB->get_records($modname, array('course' => $course->id))) {
5070 foreach ($instances as $instance) {
5071 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
5072 // Delete activity context questions and question categories.
5073 question_delete_activity($cm, $showfeedback);
5075 if (function_exists($moddelete)) {
5076 // This purges all module data in related tables, extra user prefs, settings, etc.
5077 $moddelete($instance->id);
5078 } else {
5079 // NOTE: we should not allow installation of modules with missing delete support!
5080 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5081 $DB->delete_records($modname, array('id' => $instance->id));
5084 if ($cm) {
5085 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5086 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5087 $DB->delete_records('course_modules', array('id' => $cm->id));
5091 if (function_exists($moddeletecourse)) {
5092 // Execute ptional course cleanup callback.
5093 $moddeletecourse($course, $showfeedback);
5095 if ($instances and $showfeedback) {
5096 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5098 } else {
5099 // Ooops, this module is not properly installed, force-delete it in the next block.
5103 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5105 // Remove all data from availability and completion tables that is associated
5106 // with course-modules belonging to this course. Note this is done even if the
5107 // features are not enabled now, in case they were enabled previously.
5108 $DB->delete_records_select('course_modules_completion',
5109 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5110 array($courseid));
5112 // Remove course-module data.
5113 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5114 foreach ($cms as $cm) {
5115 if ($module = $DB->get_record('modules', array('id' => $cm->module))) {
5116 try {
5117 $DB->delete_records($module->name, array('id' => $cm->instance));
5118 } catch (Exception $e) {
5119 // Ignore weird or missing table problems.
5122 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5123 $DB->delete_records('course_modules', array('id' => $cm->id));
5126 if ($showfeedback) {
5127 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5130 // Cleanup the rest of plugins.
5131 $cleanuplugintypes = array('report', 'coursereport', 'format');
5132 foreach ($cleanuplugintypes as $type) {
5133 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
5134 foreach ($plugins as $plugin => $pluginfunction) {
5135 $pluginfunction($course->id, $showfeedback);
5137 if ($showfeedback) {
5138 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5142 // Delete questions and question categories.
5143 question_delete_course($course, $showfeedback);
5144 if ($showfeedback) {
5145 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5148 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5149 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5150 foreach ($childcontexts as $childcontext) {
5151 $childcontext->delete();
5153 unset($childcontexts);
5155 // Remove all roles and enrolments by default.
5156 if (empty($options['keep_roles_and_enrolments'])) {
5157 // This hack is used in restore when deleting contents of existing course.
5158 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5159 enrol_course_delete($course);
5160 if ($showfeedback) {
5161 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5165 // Delete any groups, removing members and grouping/course links first.
5166 if (empty($options['keep_groups_and_groupings'])) {
5167 groups_delete_groupings($course->id, $showfeedback);
5168 groups_delete_groups($course->id, $showfeedback);
5171 // Filters be gone!
5172 filter_delete_all_for_context($coursecontext->id);
5174 // Notes, you shall not pass!
5175 note_delete_all($course->id);
5177 // Die comments!
5178 comment::delete_comments($coursecontext->id);
5180 // Ratings are history too.
5181 $delopt = new stdclass();
5182 $delopt->contextid = $coursecontext->id;
5183 $rm = new rating_manager();
5184 $rm->delete_ratings($delopt);
5186 // Delete course tags.
5187 coursetag_delete_course_tags($course->id, $showfeedback);
5189 // Delete calendar events.
5190 $DB->delete_records('event', array('courseid' => $course->id));
5191 $fs->delete_area_files($coursecontext->id, 'calendar');
5193 // Delete all related records in other core tables that may have a courseid
5194 // This array stores the tables that need to be cleared, as
5195 // table_name => column_name that contains the course id.
5196 $tablestoclear = array(
5197 'backup_courses' => 'courseid', // Scheduled backup stuff.
5198 'user_lastaccess' => 'courseid', // User access info.
5200 foreach ($tablestoclear as $table => $col) {
5201 $DB->delete_records($table, array($col => $course->id));
5204 // Delete all course backup files.
5205 $fs->delete_area_files($coursecontext->id, 'backup');
5207 // Cleanup course record - remove links to deleted stuff.
5208 $oldcourse = new stdClass();
5209 $oldcourse->id = $course->id;
5210 $oldcourse->summary = '';
5211 $oldcourse->cacherev = 0;
5212 $oldcourse->legacyfiles = 0;
5213 $oldcourse->enablecompletion = 0;
5214 if (!empty($options['keep_groups_and_groupings'])) {
5215 $oldcourse->defaultgroupingid = 0;
5217 $DB->update_record('course', $oldcourse);
5219 // Delete course sections.
5220 $DB->delete_records('course_sections', array('course' => $course->id));
5222 // Delete legacy, section and any other course files.
5223 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5225 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5226 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5227 // Easy, do not delete the context itself...
5228 $coursecontext->delete_content();
5229 } else {
5230 // Hack alert!!!!
5231 // We can not drop all context stuff because it would bork enrolments and roles,
5232 // there might be also files used by enrol plugins...
5235 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5236 // also some non-standard unsupported plugins may try to store something there.
5237 fulldelete($CFG->dataroot.'/'.$course->id);
5239 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5240 $cachemodinfo = cache::make('core', 'coursemodinfo');
5241 $cachemodinfo->delete($courseid);
5243 // Trigger a course content deleted event.
5244 $event = \core\event\course_content_deleted::create(array(
5245 'objectid' => $course->id,
5246 'context' => $coursecontext,
5247 'other' => array('shortname' => $course->shortname,
5248 'fullname' => $course->fullname,
5249 'options' => $options) // Passing this for legacy reasons.
5251 $event->add_record_snapshot('course', $course);
5252 $event->trigger();
5254 return true;
5258 * Change dates in module - used from course reset.
5260 * @param string $modname forum, assignment, etc
5261 * @param array $fields array of date fields from mod table
5262 * @param int $timeshift time difference
5263 * @param int $courseid
5264 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5265 * @return bool success
5267 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5268 global $CFG, $DB;
5269 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5271 $return = true;
5272 $params = array($timeshift, $courseid);
5273 foreach ($fields as $field) {
5274 $updatesql = "UPDATE {".$modname."}
5275 SET $field = $field + ?
5276 WHERE course=? AND $field<>0";
5277 if ($modid) {
5278 $updatesql .= ' AND id=?';
5279 $params[] = $modid;
5281 $return = $DB->execute($updatesql, $params) && $return;
5284 $refreshfunction = $modname.'_refresh_events';
5285 if (function_exists($refreshfunction)) {
5286 $refreshfunction($courseid);
5289 return $return;
5293 * This function will empty a course of user data.
5294 * It will retain the activities and the structure of the course.
5296 * @param object $data an object containing all the settings including courseid (without magic quotes)
5297 * @return array status array of array component, item, error
5299 function reset_course_userdata($data) {
5300 global $CFG, $DB;
5301 require_once($CFG->libdir.'/gradelib.php');
5302 require_once($CFG->libdir.'/completionlib.php');
5303 require_once($CFG->dirroot.'/group/lib.php');
5305 $data->courseid = $data->id;
5306 $context = context_course::instance($data->courseid);
5308 $eventparams = array(
5309 'context' => $context,
5310 'courseid' => $data->id,
5311 'other' => array(
5312 'reset_options' => (array) $data
5315 $event = \core\event\course_reset_started::create($eventparams);
5316 $event->trigger();
5318 // Calculate the time shift of dates.
5319 if (!empty($data->reset_start_date)) {
5320 // Time part of course startdate should be zero.
5321 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5322 } else {
5323 $data->timeshift = 0;
5326 // Result array: component, item, error.
5327 $status = array();
5329 // Start the resetting.
5330 $componentstr = get_string('general');
5332 // Move the course start time.
5333 if (!empty($data->reset_start_date) and $data->timeshift) {
5334 // Change course start data.
5335 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5336 // Update all course and group events - do not move activity events.
5337 $updatesql = "UPDATE {event}
5338 SET timestart = timestart + ?
5339 WHERE courseid=? AND instance=0";
5340 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5342 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5345 if (!empty($data->reset_events)) {
5346 $DB->delete_records('event', array('courseid' => $data->courseid));
5347 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5350 if (!empty($data->reset_notes)) {
5351 require_once($CFG->dirroot.'/notes/lib.php');
5352 note_delete_all($data->courseid);
5353 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5356 if (!empty($data->delete_blog_associations)) {
5357 require_once($CFG->dirroot.'/blog/lib.php');
5358 blog_remove_associations_for_course($data->courseid);
5359 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5362 if (!empty($data->reset_completion)) {
5363 // Delete course and activity completion information.
5364 $course = $DB->get_record('course', array('id' => $data->courseid));
5365 $cc = new completion_info($course);
5366 $cc->delete_all_completion_data();
5367 $status[] = array('component' => $componentstr,
5368 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5371 $componentstr = get_string('roles');
5373 if (!empty($data->reset_roles_overrides)) {
5374 $children = $context->get_child_contexts();
5375 foreach ($children as $child) {
5376 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5378 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5379 // Force refresh for logged in users.
5380 $context->mark_dirty();
5381 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5384 if (!empty($data->reset_roles_local)) {
5385 $children = $context->get_child_contexts();
5386 foreach ($children as $child) {
5387 role_unassign_all(array('contextid' => $child->id));
5389 // Force refresh for logged in users.
5390 $context->mark_dirty();
5391 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5394 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5395 $data->unenrolled = array();
5396 if (!empty($data->unenrol_users)) {
5397 $plugins = enrol_get_plugins(true);
5398 $instances = enrol_get_instances($data->courseid, true);
5399 foreach ($instances as $key => $instance) {
5400 if (!isset($plugins[$instance->enrol])) {
5401 unset($instances[$key]);
5402 continue;
5406 foreach ($data->unenrol_users as $withroleid) {
5407 if ($withroleid) {
5408 $sql = "SELECT ue.*
5409 FROM {user_enrolments} ue
5410 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5411 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5412 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5413 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5415 } else {
5416 // Without any role assigned at course context.
5417 $sql = "SELECT ue.*
5418 FROM {user_enrolments} ue
5419 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5420 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5421 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5422 WHERE ra.id IS null";
5423 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5426 $rs = $DB->get_recordset_sql($sql, $params);
5427 foreach ($rs as $ue) {
5428 if (!isset($instances[$ue->enrolid])) {
5429 continue;
5431 $instance = $instances[$ue->enrolid];
5432 $plugin = $plugins[$instance->enrol];
5433 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5434 continue;
5437 $plugin->unenrol_user($instance, $ue->userid);
5438 $data->unenrolled[$ue->userid] = $ue->userid;
5440 $rs->close();
5443 if (!empty($data->unenrolled)) {
5444 $status[] = array(
5445 'component' => $componentstr,
5446 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5447 'error' => false
5451 $componentstr = get_string('groups');
5453 // Remove all group members.
5454 if (!empty($data->reset_groups_members)) {
5455 groups_delete_group_members($data->courseid);
5456 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5459 // Remove all groups.
5460 if (!empty($data->reset_groups_remove)) {
5461 groups_delete_groups($data->courseid, false);
5462 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5465 // Remove all grouping members.
5466 if (!empty($data->reset_groupings_members)) {
5467 groups_delete_groupings_groups($data->courseid, false);
5468 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5471 // Remove all groupings.
5472 if (!empty($data->reset_groupings_remove)) {
5473 groups_delete_groupings($data->courseid, false);
5474 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5477 // Look in every instance of every module for data to delete.
5478 $unsupportedmods = array();
5479 if ($allmods = $DB->get_records('modules') ) {
5480 foreach ($allmods as $mod) {
5481 $modname = $mod->name;
5482 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5483 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5484 if (file_exists($modfile)) {
5485 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5486 continue; // Skip mods with no instances.
5488 include_once($modfile);
5489 if (function_exists($moddeleteuserdata)) {
5490 $modstatus = $moddeleteuserdata($data);
5491 if (is_array($modstatus)) {
5492 $status = array_merge($status, $modstatus);
5493 } else {
5494 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5496 } else {
5497 $unsupportedmods[] = $mod;
5499 } else {
5500 debugging('Missing lib.php in '.$modname.' module!');
5505 // Mention unsupported mods.
5506 if (!empty($unsupportedmods)) {
5507 foreach ($unsupportedmods as $mod) {
5508 $status[] = array(
5509 'component' => get_string('modulenameplural', $mod->name),
5510 'item' => '',
5511 'error' => get_string('resetnotimplemented')
5516 $componentstr = get_string('gradebook', 'grades');
5517 // Reset gradebook,.
5518 if (!empty($data->reset_gradebook_items)) {
5519 remove_course_grades($data->courseid, false);
5520 grade_grab_course_grades($data->courseid);
5521 grade_regrade_final_grades($data->courseid);
5522 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5524 } else if (!empty($data->reset_gradebook_grades)) {
5525 grade_course_reset($data->courseid);
5526 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5528 // Reset comments.
5529 if (!empty($data->reset_comments)) {
5530 require_once($CFG->dirroot.'/comment/lib.php');
5531 comment::reset_course_page_comments($context);
5534 $event = \core\event\course_reset_ended::create($eventparams);
5535 $event->trigger();
5537 return $status;
5541 * Generate an email processing address.
5543 * @param int $modid
5544 * @param string $modargs
5545 * @return string Returns email processing address
5547 function generate_email_processing_address($modid, $modargs) {
5548 global $CFG;
5550 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5551 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5557 * @todo Finish documenting this function
5559 * @param string $modargs
5560 * @param string $body Currently unused
5562 function moodle_process_email($modargs, $body) {
5563 global $DB;
5565 // The first char should be an unencoded letter. We'll take this as an action.
5566 switch ($modargs{0}) {
5567 case 'B': { // Bounce.
5568 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5569 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5570 // Check the half md5 of their email.
5571 $md5check = substr(md5($user->email), 0, 16);
5572 if ($md5check == substr($modargs, -16)) {
5573 set_bounce_count($user);
5575 // Else maybe they've already changed it?
5578 break;
5579 // Maybe more later?
5583 // CORRESPONDENCE.
5586 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5588 * @param string $action 'get', 'buffer', 'close' or 'flush'
5589 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5591 function get_mailer($action='get') {
5592 global $CFG;
5594 /** @var moodle_phpmailer $mailer */
5595 static $mailer = null;
5596 static $counter = 0;
5598 if (!isset($CFG->smtpmaxbulk)) {
5599 $CFG->smtpmaxbulk = 1;
5602 if ($action == 'get') {
5603 $prevkeepalive = false;
5605 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5606 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5607 $counter++;
5608 // Reset the mailer.
5609 $mailer->Priority = 3;
5610 $mailer->CharSet = 'UTF-8'; // Our default.
5611 $mailer->ContentType = "text/plain";
5612 $mailer->Encoding = "8bit";
5613 $mailer->From = "root@localhost";
5614 $mailer->FromName = "Root User";
5615 $mailer->Sender = "";
5616 $mailer->Subject = "";
5617 $mailer->Body = "";
5618 $mailer->AltBody = "";
5619 $mailer->ConfirmReadingTo = "";
5621 $mailer->clearAllRecipients();
5622 $mailer->clearReplyTos();
5623 $mailer->clearAttachments();
5624 $mailer->clearCustomHeaders();
5625 return $mailer;
5628 $prevkeepalive = $mailer->SMTPKeepAlive;
5629 get_mailer('flush');
5632 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5633 $mailer = new moodle_phpmailer();
5635 $counter = 1;
5637 if ($CFG->smtphosts == 'qmail') {
5638 // Use Qmail system.
5639 $mailer->isQmail();
5641 } else if (empty($CFG->smtphosts)) {
5642 // Use PHP mail() = sendmail.
5643 $mailer->isMail();
5645 } else {
5646 // Use SMTP directly.
5647 $mailer->isSMTP();
5648 if (!empty($CFG->debugsmtp)) {
5649 $mailer->SMTPDebug = true;
5651 // Specify main and backup servers.
5652 $mailer->Host = $CFG->smtphosts;
5653 // Specify secure connection protocol.
5654 $mailer->SMTPSecure = $CFG->smtpsecure;
5655 // Use previous keepalive.
5656 $mailer->SMTPKeepAlive = $prevkeepalive;
5658 if ($CFG->smtpuser) {
5659 // Use SMTP authentication.
5660 $mailer->SMTPAuth = true;
5661 $mailer->Username = $CFG->smtpuser;
5662 $mailer->Password = $CFG->smtppass;
5666 return $mailer;
5669 $nothing = null;
5671 // Keep smtp session open after sending.
5672 if ($action == 'buffer') {
5673 if (!empty($CFG->smtpmaxbulk)) {
5674 get_mailer('flush');
5675 $m = get_mailer();
5676 if ($m->Mailer == 'smtp') {
5677 $m->SMTPKeepAlive = true;
5680 return $nothing;
5683 // Close smtp session, but continue buffering.
5684 if ($action == 'flush') {
5685 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5686 if (!empty($mailer->SMTPDebug)) {
5687 echo '<pre>'."\n";
5689 $mailer->SmtpClose();
5690 if (!empty($mailer->SMTPDebug)) {
5691 echo '</pre>';
5694 return $nothing;
5697 // Close smtp session, do not buffer anymore.
5698 if ($action == 'close') {
5699 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5700 get_mailer('flush');
5701 $mailer->SMTPKeepAlive = false;
5703 $mailer = null; // Better force new instance.
5704 return $nothing;
5709 * Send an email to a specified user
5711 * @param stdClass $user A {@link $USER} object
5712 * @param stdClass $from A {@link $USER} object
5713 * @param string $subject plain text subject line of the email
5714 * @param string $messagetext plain text version of the message
5715 * @param string $messagehtml complete html version of the message (optional)
5716 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5717 * @param string $attachname the name of the file (extension indicates MIME)
5718 * @param bool $usetrueaddress determines whether $from email address should
5719 * be sent out. Will be overruled by user profile setting for maildisplay
5720 * @param string $replyto Email address to reply to
5721 * @param string $replytoname Name of reply to recipient
5722 * @param int $wordwrapwidth custom word wrap width, default 79
5723 * @return bool Returns true if mail was sent OK and false if there was an error.
5725 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5726 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5728 global $CFG;
5730 if (empty($user) or empty($user->id)) {
5731 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5732 return false;
5735 if (empty($user->email)) {
5736 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5737 return false;
5740 if (!empty($user->deleted)) {
5741 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5742 return false;
5745 if (defined('BEHAT_SITE_RUNNING')) {
5746 // Fake email sending in behat.
5747 return true;
5750 if (!empty($CFG->noemailever)) {
5751 // Hidden setting for development sites, set in config.php if needed.
5752 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5753 return true;
5756 if (!empty($CFG->divertallemailsto)) {
5757 $subject = "[DIVERTED {$user->email}] $subject";
5758 $user = clone($user);
5759 $user->email = $CFG->divertallemailsto;
5762 // Skip mail to suspended users.
5763 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5764 return true;
5767 if (!validate_email($user->email)) {
5768 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5769 $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
5770 error_log($invalidemail);
5771 if (CLI_SCRIPT) {
5772 mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
5774 return false;
5777 if (over_bounce_threshold($user)) {
5778 $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
5779 error_log($bouncemsg);
5780 if (CLI_SCRIPT) {
5781 mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
5783 return false;
5786 // If the user is a remote mnet user, parse the email text for URL to the
5787 // wwwroot and modify the url to direct the user's browser to login at their
5788 // home site (identity provider - idp) before hitting the link itself.
5789 if (is_mnet_remote_user($user)) {
5790 require_once($CFG->dirroot.'/mnet/lib.php');
5792 $jumpurl = mnet_get_idp_jump_url($user);
5793 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5795 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5796 $callback,
5797 $messagetext);
5798 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5799 $callback,
5800 $messagehtml);
5802 $mail = get_mailer();
5804 if (!empty($mail->SMTPDebug)) {
5805 echo '<pre>' . "\n";
5808 $temprecipients = array();
5809 $tempreplyto = array();
5811 $supportuser = core_user::get_support_user();
5813 // Make up an email address for handling bounces.
5814 if (!empty($CFG->handlebounces)) {
5815 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5816 $mail->Sender = generate_email_processing_address(0, $modargs);
5817 } else {
5818 $mail->Sender = $supportuser->email;
5821 if (!empty($CFG->emailonlyfromnoreplyaddress)) {
5822 $usetrueaddress = false;
5823 if (empty($replyto) && $from->maildisplay) {
5824 $replyto = $from->email;
5825 $replytoname = fullname($from);
5829 if (is_string($from)) { // So we can pass whatever we want if there is need.
5830 $mail->From = $CFG->noreplyaddress;
5831 $mail->FromName = $from;
5832 } else if ($usetrueaddress and $from->maildisplay) {
5833 $mail->From = $from->email;
5834 $mail->FromName = fullname($from);
5835 } else {
5836 $mail->From = $CFG->noreplyaddress;
5837 $mail->FromName = fullname($from);
5838 if (empty($replyto)) {
5839 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5843 if (!empty($replyto)) {
5844 $tempreplyto[] = array($replyto, $replytoname);
5847 $mail->Subject = substr($subject, 0, 900);
5849 $temprecipients[] = array($user->email, fullname($user));
5851 // Set word wrap.
5852 $mail->WordWrap = $wordwrapwidth;
5854 if (!empty($from->customheaders)) {
5855 // Add custom headers.
5856 if (is_array($from->customheaders)) {
5857 foreach ($from->customheaders as $customheader) {
5858 $mail->addCustomHeader($customheader);
5860 } else {
5861 $mail->addCustomHeader($from->customheaders);
5865 if (!empty($from->priority)) {
5866 $mail->Priority = $from->priority;
5869 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5870 // Don't ever send HTML to users who don't want it.
5871 $mail->isHTML(true);
5872 $mail->Encoding = 'quoted-printable';
5873 $mail->Body = $messagehtml;
5874 $mail->AltBody = "\n$messagetext\n";
5875 } else {
5876 $mail->IsHTML(false);
5877 $mail->Body = "\n$messagetext\n";
5880 if ($attachment && $attachname) {
5881 if (preg_match( "~\\.\\.~" , $attachment )) {
5882 // Security check for ".." in dir path.
5883 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5884 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5885 } else {
5886 require_once($CFG->libdir.'/filelib.php');
5887 $mimetype = mimeinfo('type', $attachname);
5889 $attachmentpath = $attachment;
5891 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5892 $attachpath = str_replace('\\', '/', $attachmentpath);
5893 // Make sure both variables are normalised before comparing.
5894 $temppath = str_replace('\\', '/', $CFG->tempdir);
5896 // If the attachment is a full path to a file in the tempdir, use it as is,
5897 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5898 if (strpos($attachpath, $temppath) !== 0) {
5899 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5902 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5906 // Check if the email should be sent in an other charset then the default UTF-8.
5907 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5909 // Use the defined site mail charset or eventually the one preferred by the recipient.
5910 $charset = $CFG->sitemailcharset;
5911 if (!empty($CFG->allowusermailcharset)) {
5912 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5913 $charset = $useremailcharset;
5917 // Convert all the necessary strings if the charset is supported.
5918 $charsets = get_list_of_charsets();
5919 unset($charsets['UTF-8']);
5920 if (in_array($charset, $charsets)) {
5921 $mail->CharSet = $charset;
5922 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5923 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5924 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5925 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5927 foreach ($temprecipients as $key => $values) {
5928 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5930 foreach ($tempreplyto as $key => $values) {
5931 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5936 foreach ($temprecipients as $values) {
5937 $mail->addAddress($values[0], $values[1]);
5939 foreach ($tempreplyto as $values) {
5940 $mail->addReplyTo($values[0], $values[1]);
5943 if ($mail->send()) {
5944 set_send_count($user);
5945 if (!empty($mail->SMTPDebug)) {
5946 echo '</pre>';
5948 return true;
5949 } else {
5950 // Trigger event for failing to send email.
5951 $event = \core\event\email_failed::create(array(
5952 'context' => context_system::instance(),
5953 'userid' => $from->id,
5954 'relateduserid' => $user->id,
5955 'other' => array(
5956 'subject' => $subject,
5957 'message' => $messagetext,
5958 'errorinfo' => $mail->ErrorInfo
5961 $event->trigger();
5962 if (CLI_SCRIPT) {
5963 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5965 if (!empty($mail->SMTPDebug)) {
5966 echo '</pre>';
5968 return false;
5973 * Generate a signoff for emails based on support settings
5975 * @return string
5977 function generate_email_signoff() {
5978 global $CFG;
5980 $signoff = "\n";
5981 if (!empty($CFG->supportname)) {
5982 $signoff .= $CFG->supportname."\n";
5984 if (!empty($CFG->supportemail)) {
5985 $signoff .= $CFG->supportemail."\n";
5987 if (!empty($CFG->supportpage)) {
5988 $signoff .= $CFG->supportpage."\n";
5990 return $signoff;
5994 * Sets specified user's password and send the new password to the user via email.
5996 * @param stdClass $user A {@link $USER} object
5997 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
5998 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6000 function setnew_password_and_mail($user, $fasthash = false) {
6001 global $CFG, $DB;
6003 // We try to send the mail in language the user understands,
6004 // unfortunately the filter_string() does not support alternative langs yet
6005 // so multilang will not work properly for site->fullname.
6006 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6008 $site = get_site();
6010 $supportuser = core_user::get_support_user();
6012 $newpassword = generate_password();
6014 update_internal_user_password($user, $newpassword, $fasthash);
6016 $a = new stdClass();
6017 $a->firstname = fullname($user, true);
6018 $a->sitename = format_string($site->fullname);
6019 $a->username = $user->username;
6020 $a->newpassword = $newpassword;
6021 $a->link = $CFG->wwwroot .'/login/';
6022 $a->signoff = generate_email_signoff();
6024 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6026 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6028 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6029 return email_to_user($user, $supportuser, $subject, $message);
6034 * Resets specified user's password and send the new password to the user via email.
6036 * @param stdClass $user A {@link $USER} object
6037 * @return bool Returns true if mail was sent OK and false if there was an error.
6039 function reset_password_and_mail($user) {
6040 global $CFG;
6042 $site = get_site();
6043 $supportuser = core_user::get_support_user();
6045 $userauth = get_auth_plugin($user->auth);
6046 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6047 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6048 return false;
6051 $newpassword = generate_password();
6053 if (!$userauth->user_update_password($user, $newpassword)) {
6054 print_error("cannotsetpassword");
6057 $a = new stdClass();
6058 $a->firstname = $user->firstname;
6059 $a->lastname = $user->lastname;
6060 $a->sitename = format_string($site->fullname);
6061 $a->username = $user->username;
6062 $a->newpassword = $newpassword;
6063 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
6064 $a->signoff = generate_email_signoff();
6066 $message = get_string('newpasswordtext', '', $a);
6068 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6070 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6072 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6073 return email_to_user($user, $supportuser, $subject, $message);
6077 * Send email to specified user with confirmation text and activation link.
6079 * @param stdClass $user A {@link $USER} object
6080 * @return bool Returns true if mail was sent OK and false if there was an error.
6082 function send_confirmation_email($user) {
6083 global $CFG;
6085 $site = get_site();
6086 $supportuser = core_user::get_support_user();
6088 $data = new stdClass();
6089 $data->firstname = fullname($user);
6090 $data->sitename = format_string($site->fullname);
6091 $data->admin = generate_email_signoff();
6093 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6095 $username = urlencode($user->username);
6096 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
6097 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
6098 $message = get_string('emailconfirmation', '', $data);
6099 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6101 $user->mailformat = 1; // Always send HTML version as well.
6103 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6104 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6108 * Sends a password change confirmation email.
6110 * @param stdClass $user A {@link $USER} object
6111 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6112 * @return bool Returns true if mail was sent OK and false if there was an error.
6114 function send_password_change_confirmation_email($user, $resetrecord) {
6115 global $CFG;
6117 $site = get_site();
6118 $supportuser = core_user::get_support_user();
6119 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6121 $data = new stdClass();
6122 $data->firstname = $user->firstname;
6123 $data->lastname = $user->lastname;
6124 $data->username = $user->username;
6125 $data->sitename = format_string($site->fullname);
6126 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6127 $data->admin = generate_email_signoff();
6128 $data->resetminutes = $pwresetmins;
6130 $message = get_string('emailresetconfirmation', '', $data);
6131 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6133 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6134 return email_to_user($user, $supportuser, $subject, $message);
6139 * Sends an email containinginformation on how to change your password.
6141 * @param stdClass $user A {@link $USER} object
6142 * @return bool Returns true if mail was sent OK and false if there was an error.
6144 function send_password_change_info($user) {
6145 global $CFG;
6147 $site = get_site();
6148 $supportuser = core_user::get_support_user();
6149 $systemcontext = context_system::instance();
6151 $data = new stdClass();
6152 $data->firstname = $user->firstname;
6153 $data->lastname = $user->lastname;
6154 $data->sitename = format_string($site->fullname);
6155 $data->admin = generate_email_signoff();
6157 $userauth = get_auth_plugin($user->auth);
6159 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6160 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6161 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6162 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6163 return email_to_user($user, $supportuser, $subject, $message);
6166 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6167 // We have some external url for password changing.
6168 $data->link .= $userauth->change_password_url();
6170 } else {
6171 // No way to change password, sorry.
6172 $data->link = '';
6175 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6176 $message = get_string('emailpasswordchangeinfo', '', $data);
6177 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6178 } else {
6179 $message = get_string('emailpasswordchangeinfofail', '', $data);
6180 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6183 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6184 return email_to_user($user, $supportuser, $subject, $message);
6189 * Check that an email is allowed. It returns an error message if there was a problem.
6191 * @param string $email Content of email
6192 * @return string|false
6194 function email_is_not_allowed($email) {
6195 global $CFG;
6197 if (!empty($CFG->allowemailaddresses)) {
6198 $allowed = explode(' ', $CFG->allowemailaddresses);
6199 foreach ($allowed as $allowedpattern) {
6200 $allowedpattern = trim($allowedpattern);
6201 if (!$allowedpattern) {
6202 continue;
6204 if (strpos($allowedpattern, '.') === 0) {
6205 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6206 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6207 return false;
6210 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6211 return false;
6214 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6216 } else if (!empty($CFG->denyemailaddresses)) {
6217 $denied = explode(' ', $CFG->denyemailaddresses);
6218 foreach ($denied as $deniedpattern) {
6219 $deniedpattern = trim($deniedpattern);
6220 if (!$deniedpattern) {
6221 continue;
6223 if (strpos($deniedpattern, '.') === 0) {
6224 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6225 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6226 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6229 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6230 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6235 return false;
6238 // FILE HANDLING.
6241 * Returns local file storage instance
6243 * @return file_storage
6245 function get_file_storage() {
6246 global $CFG;
6248 static $fs = null;
6250 if ($fs) {
6251 return $fs;
6254 require_once("$CFG->libdir/filelib.php");
6256 if (isset($CFG->filedir)) {
6257 $filedir = $CFG->filedir;
6258 } else {
6259 $filedir = $CFG->dataroot.'/filedir';
6262 if (isset($CFG->trashdir)) {
6263 $trashdirdir = $CFG->trashdir;
6264 } else {
6265 $trashdirdir = $CFG->dataroot.'/trashdir';
6268 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6270 return $fs;
6274 * Returns local file storage instance
6276 * @return file_browser
6278 function get_file_browser() {
6279 global $CFG;
6281 static $fb = null;
6283 if ($fb) {
6284 return $fb;
6287 require_once("$CFG->libdir/filelib.php");
6289 $fb = new file_browser();
6291 return $fb;
6295 * Returns file packer
6297 * @param string $mimetype default application/zip
6298 * @return file_packer
6300 function get_file_packer($mimetype='application/zip') {
6301 global $CFG;
6303 static $fp = array();
6305 if (isset($fp[$mimetype])) {
6306 return $fp[$mimetype];
6309 switch ($mimetype) {
6310 case 'application/zip':
6311 case 'application/vnd.moodle.profiling':
6312 $classname = 'zip_packer';
6313 break;
6315 case 'application/x-gzip' :
6316 $classname = 'tgz_packer';
6317 break;
6319 case 'application/vnd.moodle.backup':
6320 $classname = 'mbz_packer';
6321 break;
6323 default:
6324 return false;
6327 require_once("$CFG->libdir/filestorage/$classname.php");
6328 $fp[$mimetype] = new $classname();
6330 return $fp[$mimetype];
6334 * Returns current name of file on disk if it exists.
6336 * @param string $newfile File to be verified
6337 * @return string Current name of file on disk if true
6339 function valid_uploaded_file($newfile) {
6340 if (empty($newfile)) {
6341 return '';
6343 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6344 return $newfile['tmp_name'];
6345 } else {
6346 return '';
6351 * Returns the maximum size for uploading files.
6353 * There are seven possible upload limits:
6354 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6355 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6356 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6357 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6358 * 5. by the Moodle admin in $CFG->maxbytes
6359 * 6. by the teacher in the current course $course->maxbytes
6360 * 7. by the teacher for the current module, eg $assignment->maxbytes
6362 * These last two are passed to this function as arguments (in bytes).
6363 * Anything defined as 0 is ignored.
6364 * The smallest of all the non-zero numbers is returned.
6366 * @todo Finish documenting this function
6368 * @param int $sitebytes Set maximum size
6369 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6370 * @param int $modulebytes Current module ->maxbytes (in bytes)
6371 * @return int The maximum size for uploading files.
6373 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6375 if (! $filesize = ini_get('upload_max_filesize')) {
6376 $filesize = '5M';
6378 $minimumsize = get_real_size($filesize);
6380 if ($postsize = ini_get('post_max_size')) {
6381 $postsize = get_real_size($postsize);
6382 if ($postsize < $minimumsize) {
6383 $minimumsize = $postsize;
6387 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6388 $minimumsize = $sitebytes;
6391 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6392 $minimumsize = $coursebytes;
6395 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6396 $minimumsize = $modulebytes;
6399 return $minimumsize;
6403 * Returns the maximum size for uploading files for the current user
6405 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6407 * @param context $context The context in which to check user capabilities
6408 * @param int $sitebytes Set maximum size
6409 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6410 * @param int $modulebytes Current module ->maxbytes (in bytes)
6411 * @param stdClass $user The user
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 global $USER;
6417 if (empty($user)) {
6418 $user = $USER;
6421 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6422 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6425 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6429 * Returns an array of possible sizes in local language
6431 * Related to {@link get_max_upload_file_size()} - this function returns an
6432 * array of possible sizes in an array, translated to the
6433 * local language.
6435 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6437 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6438 * with the value set to 0. This option will be the first in the list.
6440 * @uses SORT_NUMERIC
6441 * @param int $sitebytes Set maximum size
6442 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6443 * @param int $modulebytes Current module ->maxbytes (in bytes)
6444 * @param int|array $custombytes custom upload size/s which will be added to list,
6445 * Only value/s smaller then maxsize will be added to list.
6446 * @return array
6448 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6449 global $CFG;
6451 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6452 return array();
6455 if ($sitebytes == 0) {
6456 // Will get the minimum of upload_max_filesize or post_max_size.
6457 $sitebytes = get_max_upload_file_size();
6460 $filesize = array();
6461 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6462 5242880, 10485760, 20971520, 52428800, 104857600);
6464 // If custombytes is given and is valid then add it to the list.
6465 if (is_number($custombytes) and $custombytes > 0) {
6466 $custombytes = (int)$custombytes;
6467 if (!in_array($custombytes, $sizelist)) {
6468 $sizelist[] = $custombytes;
6470 } else if (is_array($custombytes)) {
6471 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6474 // Allow maxbytes to be selected if it falls outside the above boundaries.
6475 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6476 // Note: get_real_size() is used in order to prevent problems with invalid values.
6477 $sizelist[] = get_real_size($CFG->maxbytes);
6480 foreach ($sizelist as $sizebytes) {
6481 if ($sizebytes < $maxsize && $sizebytes > 0) {
6482 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6486 $limitlevel = '';
6487 $displaysize = '';
6488 if ($modulebytes &&
6489 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6490 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6491 $limitlevel = get_string('activity', 'core');
6492 $displaysize = display_size($modulebytes);
6493 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6495 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6496 $limitlevel = get_string('course', 'core');
6497 $displaysize = display_size($coursebytes);
6498 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6500 } else if ($sitebytes) {
6501 $limitlevel = get_string('site', 'core');
6502 $displaysize = display_size($sitebytes);
6503 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6506 krsort($filesize, SORT_NUMERIC);
6507 if ($limitlevel) {
6508 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6509 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6512 return $filesize;
6516 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6518 * If excludefiles is defined, then that file/directory is ignored
6519 * If getdirs is true, then (sub)directories are included in the output
6520 * If getfiles is true, then files are included in the output
6521 * (at least one of these must be true!)
6523 * @todo Finish documenting this function. Add examples of $excludefile usage.
6525 * @param string $rootdir A given root directory to start from
6526 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6527 * @param bool $descend If true then subdirectories are recursed as well
6528 * @param bool $getdirs If true then (sub)directories are included in the output
6529 * @param bool $getfiles If true then files are included in the output
6530 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6532 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6534 $dirs = array();
6536 if (!$getdirs and !$getfiles) { // Nothing to show.
6537 return $dirs;
6540 if (!is_dir($rootdir)) { // Must be a directory.
6541 return $dirs;
6544 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6545 return $dirs;
6548 if (!is_array($excludefiles)) {
6549 $excludefiles = array($excludefiles);
6552 while (false !== ($file = readdir($dir))) {
6553 $firstchar = substr($file, 0, 1);
6554 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6555 continue;
6557 $fullfile = $rootdir .'/'. $file;
6558 if (filetype($fullfile) == 'dir') {
6559 if ($getdirs) {
6560 $dirs[] = $file;
6562 if ($descend) {
6563 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6564 foreach ($subdirs as $subdir) {
6565 $dirs[] = $file .'/'. $subdir;
6568 } else if ($getfiles) {
6569 $dirs[] = $file;
6572 closedir($dir);
6574 asort($dirs);
6576 return $dirs;
6581 * Adds up all the files in a directory and works out the size.
6583 * @param string $rootdir The directory to start from
6584 * @param string $excludefile A file to exclude when summing directory size
6585 * @return int The summed size of all files and subfiles within the root directory
6587 function get_directory_size($rootdir, $excludefile='') {
6588 global $CFG;
6590 // Do it this way if we can, it's much faster.
6591 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6592 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6593 $output = null;
6594 $return = null;
6595 exec($command, $output, $return);
6596 if (is_array($output)) {
6597 // We told it to return k.
6598 return get_real_size(intval($output[0]).'k');
6602 if (!is_dir($rootdir)) {
6603 // Must be a directory.
6604 return 0;
6607 if (!$dir = @opendir($rootdir)) {
6608 // Can't open it for some reason.
6609 return 0;
6612 $size = 0;
6614 while (false !== ($file = readdir($dir))) {
6615 $firstchar = substr($file, 0, 1);
6616 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6617 continue;
6619 $fullfile = $rootdir .'/'. $file;
6620 if (filetype($fullfile) == 'dir') {
6621 $size += get_directory_size($fullfile, $excludefile);
6622 } else {
6623 $size += filesize($fullfile);
6626 closedir($dir);
6628 return $size;
6632 * Converts bytes into display form
6634 * @static string $gb Localized string for size in gigabytes
6635 * @static string $mb Localized string for size in megabytes
6636 * @static string $kb Localized string for size in kilobytes
6637 * @static string $b Localized string for size in bytes
6638 * @param int $size The size to convert to human readable form
6639 * @return string
6641 function display_size($size) {
6643 static $gb, $mb, $kb, $b;
6645 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6646 return get_string('unlimited');
6649 if (empty($gb)) {
6650 $gb = get_string('sizegb');
6651 $mb = get_string('sizemb');
6652 $kb = get_string('sizekb');
6653 $b = get_string('sizeb');
6656 if ($size >= 1073741824) {
6657 $size = round($size / 1073741824 * 10) / 10 . $gb;
6658 } else if ($size >= 1048576) {
6659 $size = round($size / 1048576 * 10) / 10 . $mb;
6660 } else if ($size >= 1024) {
6661 $size = round($size / 1024 * 10) / 10 . $kb;
6662 } else {
6663 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6665 return $size;
6669 * Cleans a given filename by removing suspicious or troublesome characters
6671 * @see clean_param()
6672 * @param string $string file name
6673 * @return string cleaned file name
6675 function clean_filename($string) {
6676 return clean_param($string, PARAM_FILE);
6680 // STRING TRANSLATION.
6683 * Returns the code for the current language
6685 * @category string
6686 * @return string
6688 function current_language() {
6689 global $CFG, $USER, $SESSION, $COURSE;
6691 if (!empty($SESSION->forcelang)) {
6692 // Allows overriding course-forced language (useful for admins to check
6693 // issues in courses whose language they don't understand).
6694 // Also used by some code to temporarily get language-related information in a
6695 // specific language (see force_current_language()).
6696 $return = $SESSION->forcelang;
6698 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6699 // Course language can override all other settings for this page.
6700 $return = $COURSE->lang;
6702 } else if (!empty($SESSION->lang)) {
6703 // Session language can override other settings.
6704 $return = $SESSION->lang;
6706 } else if (!empty($USER->lang)) {
6707 $return = $USER->lang;
6709 } else if (isset($CFG->lang)) {
6710 $return = $CFG->lang;
6712 } else {
6713 $return = 'en';
6716 // Just in case this slipped in from somewhere by accident.
6717 $return = str_replace('_utf8', '', $return);
6719 return $return;
6723 * Returns parent language of current active language if defined
6725 * @category string
6726 * @param string $lang null means current language
6727 * @return string
6729 function get_parent_language($lang=null) {
6731 // Let's hack around the current language.
6732 if (!empty($lang)) {
6733 $oldforcelang = force_current_language($lang);
6736 $parentlang = get_string('parentlanguage', 'langconfig');
6737 if ($parentlang === 'en') {
6738 $parentlang = '';
6741 // Let's hack around the current language.
6742 if (!empty($lang)) {
6743 force_current_language($oldforcelang);
6746 return $parentlang;
6750 * Force the current language to get strings and dates localised in the given language.
6752 * After calling this function, all strings will be provided in the given language
6753 * until this function is called again, or equivalent code is run.
6755 * @param string $language
6756 * @return string previous $SESSION->forcelang value
6758 function force_current_language($language) {
6759 global $SESSION;
6760 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6761 if ($language !== $sessionforcelang) {
6762 // Seting forcelang to null or an empty string disables it's effect.
6763 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6764 $SESSION->forcelang = $language;
6765 moodle_setlocale();
6768 return $sessionforcelang;
6772 * Returns current string_manager instance.
6774 * The param $forcereload is needed for CLI installer only where the string_manager instance
6775 * must be replaced during the install.php script life time.
6777 * @category string
6778 * @param bool $forcereload shall the singleton be released and new instance created instead?
6779 * @return core_string_manager
6781 function get_string_manager($forcereload=false) {
6782 global $CFG;
6784 static $singleton = null;
6786 if ($forcereload) {
6787 $singleton = null;
6789 if ($singleton === null) {
6790 if (empty($CFG->early_install_lang)) {
6792 if (empty($CFG->langlist)) {
6793 $translist = array();
6794 } else {
6795 $translist = explode(',', $CFG->langlist);
6798 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6800 } else {
6801 $singleton = new core_string_manager_install();
6805 return $singleton;
6809 * Returns a localized string.
6811 * Returns the translated string specified by $identifier as
6812 * for $module. Uses the same format files as STphp.
6813 * $a is an object, string or number that can be used
6814 * within translation strings
6816 * eg 'hello {$a->firstname} {$a->lastname}'
6817 * or 'hello {$a}'
6819 * If you would like to directly echo the localized string use
6820 * the function {@link print_string()}
6822 * Example usage of this function involves finding the string you would
6823 * like a local equivalent of and using its identifier and module information
6824 * to retrieve it.<br/>
6825 * If you open moodle/lang/en/moodle.php and look near line 278
6826 * you will find a string to prompt a user for their word for 'course'
6827 * <code>
6828 * $string['course'] = 'Course';
6829 * </code>
6830 * So if you want to display the string 'Course'
6831 * in any language that supports it on your site
6832 * you just need to use the identifier 'course'
6833 * <code>
6834 * $mystring = '<strong>'. get_string('course') .'</strong>';
6835 * or
6836 * </code>
6837 * If the string you want is in another file you'd take a slightly
6838 * different approach. Looking in moodle/lang/en/calendar.php you find
6839 * around line 75:
6840 * <code>
6841 * $string['typecourse'] = 'Course event';
6842 * </code>
6843 * If you want to display the string "Course event" in any language
6844 * supported you would use the identifier 'typecourse' and the module 'calendar'
6845 * (because it is in the file calendar.php):
6846 * <code>
6847 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6848 * </code>
6850 * As a last resort, should the identifier fail to map to a string
6851 * the returned string will be [[ $identifier ]]
6853 * In Moodle 2.3 there is a new argument to this function $lazyload.
6854 * Setting $lazyload to true causes get_string to return a lang_string object
6855 * rather than the string itself. The fetching of the string is then put off until
6856 * the string object is first used. The object can be used by calling it's out
6857 * method or by casting the object to a string, either directly e.g.
6858 * (string)$stringobject
6859 * or indirectly by using the string within another string or echoing it out e.g.
6860 * echo $stringobject
6861 * return "<p>{$stringobject}</p>";
6862 * It is worth noting that using $lazyload and attempting to use the string as an
6863 * array key will cause a fatal error as objects cannot be used as array keys.
6864 * But you should never do that anyway!
6865 * For more information {@link lang_string}
6867 * @category string
6868 * @param string $identifier The key identifier for the localized string
6869 * @param string $component The module where the key identifier is stored,
6870 * usually expressed as the filename in the language pack without the
6871 * .php on the end but can also be written as mod/forum or grade/export/xls.
6872 * If none is specified then moodle.php is used.
6873 * @param string|object|array $a An object, string or number that can be used
6874 * within translation strings
6875 * @param bool $lazyload If set to true a string object is returned instead of
6876 * the string itself. The string then isn't calculated until it is first used.
6877 * @return string The localized string.
6878 * @throws coding_exception
6880 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6881 global $CFG;
6883 // If the lazy load argument has been supplied return a lang_string object
6884 // instead.
6885 // We need to make sure it is true (and a bool) as you will see below there
6886 // used to be a forth argument at one point.
6887 if ($lazyload === true) {
6888 return new lang_string($identifier, $component, $a);
6891 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6892 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6895 // There is now a forth argument again, this time it is a boolean however so
6896 // we can still check for the old extralocations parameter.
6897 if (!is_bool($lazyload) && !empty($lazyload)) {
6898 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6901 if (strpos($component, '/') !== false) {
6902 debugging('The module name you passed to get_string is the deprecated format ' .
6903 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6904 $componentpath = explode('/', $component);
6906 switch ($componentpath[0]) {
6907 case 'mod':
6908 $component = $componentpath[1];
6909 break;
6910 case 'blocks':
6911 case 'block':
6912 $component = 'block_'.$componentpath[1];
6913 break;
6914 case 'enrol':
6915 $component = 'enrol_'.$componentpath[1];
6916 break;
6917 case 'format':
6918 $component = 'format_'.$componentpath[1];
6919 break;
6920 case 'grade':
6921 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6922 break;
6926 $result = get_string_manager()->get_string($identifier, $component, $a);
6928 // Debugging feature lets you display string identifier and component.
6929 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6930 $result .= ' {' . $identifier . '/' . $component . '}';
6932 return $result;
6936 * Converts an array of strings to their localized value.
6938 * @param array $array An array of strings
6939 * @param string $component The language module that these strings can be found in.
6940 * @return stdClass translated strings.
6942 function get_strings($array, $component = '') {
6943 $string = new stdClass;
6944 foreach ($array as $item) {
6945 $string->$item = get_string($item, $component);
6947 return $string;
6951 * Prints out a translated string.
6953 * Prints out a translated string using the return value from the {@link get_string()} function.
6955 * Example usage of this function when the string is in the moodle.php file:<br/>
6956 * <code>
6957 * echo '<strong>';
6958 * print_string('course');
6959 * echo '</strong>';
6960 * </code>
6962 * Example usage of this function when the string is not in the moodle.php file:<br/>
6963 * <code>
6964 * echo '<h1>';
6965 * print_string('typecourse', 'calendar');
6966 * echo '</h1>';
6967 * </code>
6969 * @category string
6970 * @param string $identifier The key identifier for the localized string
6971 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6972 * @param string|object|array $a An object, string or number that can be used within translation strings
6974 function print_string($identifier, $component = '', $a = null) {
6975 echo get_string($identifier, $component, $a);
6979 * Returns a list of charset codes
6981 * Returns a list of charset codes. It's hardcoded, so they should be added manually
6982 * (checking that such charset is supported by the texlib library!)
6984 * @return array And associative array with contents in the form of charset => charset
6986 function get_list_of_charsets() {
6988 $charsets = array(
6989 'EUC-JP' => 'EUC-JP',
6990 'ISO-2022-JP'=> 'ISO-2022-JP',
6991 'ISO-8859-1' => 'ISO-8859-1',
6992 'SHIFT-JIS' => 'SHIFT-JIS',
6993 'GB2312' => 'GB2312',
6994 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
6995 'UTF-8' => 'UTF-8');
6997 asort($charsets);
6999 return $charsets;
7003 * Returns a list of valid and compatible themes
7005 * @return array
7007 function get_list_of_themes() {
7008 global $CFG;
7010 $themes = array();
7012 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7013 $themelist = explode(',', $CFG->themelist);
7014 } else {
7015 $themelist = array_keys(core_component::get_plugin_list("theme"));
7018 foreach ($themelist as $key => $themename) {
7019 $theme = theme_config::load($themename);
7020 $themes[$themename] = $theme;
7023 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7025 return $themes;
7029 * Returns a list of timezones in the current language
7031 * @return array
7033 function get_list_of_timezones() {
7034 global $DB;
7036 static $timezones;
7038 if (!empty($timezones)) { // This function has been called recently.
7039 return $timezones;
7042 $timezones = array();
7044 if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
7045 foreach ($rawtimezones as $timezone) {
7046 if (!empty($timezone->name)) {
7047 if (get_string_manager()->string_exists(strtolower($timezone->name), 'timezones')) {
7048 $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
7049 } else {
7050 $timezones[$timezone->name] = $timezone->name;
7052 if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found.
7053 $timezones[$timezone->name] = $timezone->name;
7059 asort($timezones);
7061 for ($i = -13; $i <= 13; $i += .5) {
7062 $tzstring = 'UTC';
7063 if ($i < 0) {
7064 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
7065 } else if ($i > 0) {
7066 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
7067 } else {
7068 $timezones[sprintf("%.1f", $i)] = $tzstring;
7072 return $timezones;
7076 * Factory function for emoticon_manager
7078 * @return emoticon_manager singleton
7080 function get_emoticon_manager() {
7081 static $singleton = null;
7083 if (is_null($singleton)) {
7084 $singleton = new emoticon_manager();
7087 return $singleton;
7091 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7093 * Whenever this manager mentiones 'emoticon object', the following data
7094 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7095 * altidentifier and altcomponent
7097 * @see admin_setting_emoticons
7099 * @copyright 2010 David Mudrak
7100 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7102 class emoticon_manager {
7105 * Returns the currently enabled emoticons
7107 * @return array of emoticon objects
7109 public function get_emoticons() {
7110 global $CFG;
7112 if (empty($CFG->emoticons)) {
7113 return array();
7116 $emoticons = $this->decode_stored_config($CFG->emoticons);
7118 if (!is_array($emoticons)) {
7119 // Something is wrong with the format of stored setting.
7120 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7121 return array();
7124 return $emoticons;
7128 * Converts emoticon object into renderable pix_emoticon object
7130 * @param stdClass $emoticon emoticon object
7131 * @param array $attributes explicit HTML attributes to set
7132 * @return pix_emoticon
7134 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7135 $stringmanager = get_string_manager();
7136 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7137 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7138 } else {
7139 $alt = s($emoticon->text);
7141 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7145 * Encodes the array of emoticon objects into a string storable in config table
7147 * @see self::decode_stored_config()
7148 * @param array $emoticons array of emtocion objects
7149 * @return string
7151 public function encode_stored_config(array $emoticons) {
7152 return json_encode($emoticons);
7156 * Decodes the string into an array of emoticon objects
7158 * @see self::encode_stored_config()
7159 * @param string $encoded
7160 * @return string|null
7162 public function decode_stored_config($encoded) {
7163 $decoded = json_decode($encoded);
7164 if (!is_array($decoded)) {
7165 return null;
7167 return $decoded;
7171 * Returns default set of emoticons supported by Moodle
7173 * @return array of sdtClasses
7175 public function default_emoticons() {
7176 return array(
7177 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7178 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7179 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7180 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7181 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7182 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7183 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7184 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7185 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7186 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7187 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7188 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7189 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7190 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7191 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7192 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7193 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7194 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7195 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7196 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7197 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7198 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7199 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7200 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7201 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7202 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7203 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7204 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7205 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7206 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7211 * Helper method preparing the stdClass with the emoticon properties
7213 * @param string|array $text or array of strings
7214 * @param string $imagename to be used by {@link pix_emoticon}
7215 * @param string $altidentifier alternative string identifier, null for no alt
7216 * @param string $altcomponent where the alternative string is defined
7217 * @param string $imagecomponent to be used by {@link pix_emoticon}
7218 * @return stdClass
7220 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7221 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7222 return (object)array(
7223 'text' => $text,
7224 'imagename' => $imagename,
7225 'imagecomponent' => $imagecomponent,
7226 'altidentifier' => $altidentifier,
7227 'altcomponent' => $altcomponent,
7232 // ENCRYPTION.
7235 * rc4encrypt
7237 * @param string $data Data to encrypt.
7238 * @return string The now encrypted data.
7240 function rc4encrypt($data) {
7241 return endecrypt(get_site_identifier(), $data, '');
7245 * rc4decrypt
7247 * @param string $data Data to decrypt.
7248 * @return string The now decrypted data.
7250 function rc4decrypt($data) {
7251 return endecrypt(get_site_identifier(), $data, 'de');
7255 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7257 * @todo Finish documenting this function
7259 * @param string $pwd The password to use when encrypting or decrypting
7260 * @param string $data The data to be decrypted/encrypted
7261 * @param string $case Either 'de' for decrypt or '' for encrypt
7262 * @return string
7264 function endecrypt ($pwd, $data, $case) {
7266 if ($case == 'de') {
7267 $data = urldecode($data);
7270 $key[] = '';
7271 $box[] = '';
7272 $pwdlength = strlen($pwd);
7274 for ($i = 0; $i <= 255; $i++) {
7275 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7276 $box[$i] = $i;
7279 $x = 0;
7281 for ($i = 0; $i <= 255; $i++) {
7282 $x = ($x + $box[$i] + $key[$i]) % 256;
7283 $tempswap = $box[$i];
7284 $box[$i] = $box[$x];
7285 $box[$x] = $tempswap;
7288 $cipher = '';
7290 $a = 0;
7291 $j = 0;
7293 for ($i = 0; $i < strlen($data); $i++) {
7294 $a = ($a + 1) % 256;
7295 $j = ($j + $box[$a]) % 256;
7296 $temp = $box[$a];
7297 $box[$a] = $box[$j];
7298 $box[$j] = $temp;
7299 $k = $box[(($box[$a] + $box[$j]) % 256)];
7300 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7301 $cipher .= chr($cipherby);
7304 if ($case == 'de') {
7305 $cipher = urldecode(urlencode($cipher));
7306 } else {
7307 $cipher = urlencode($cipher);
7310 return $cipher;
7313 // ENVIRONMENT CHECKING.
7316 * This method validates a plug name. It is much faster than calling clean_param.
7318 * @param string $name a string that might be a plugin name.
7319 * @return bool if this string is a valid plugin name.
7321 function is_valid_plugin_name($name) {
7322 // This does not work for 'mod', bad luck, use any other type.
7323 return core_component::is_valid_plugin_name('tool', $name);
7327 * Get a list of all the plugins of a given type that define a certain API function
7328 * in a certain file. The plugin component names and function names are returned.
7330 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7331 * @param string $function the part of the name of the function after the
7332 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7333 * names like report_courselist_hook.
7334 * @param string $file the name of file within the plugin that defines the
7335 * function. Defaults to lib.php.
7336 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7337 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7339 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7340 $pluginfunctions = array();
7341 $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, $file, true);
7342 foreach ($pluginswithfile as $plugin => $notused) {
7343 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7345 if (function_exists($fullfunction)) {
7346 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7347 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
7349 } else if ($plugintype === 'mod') {
7350 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7351 $shortfunction = $plugin . '_' . $function;
7352 if (function_exists($shortfunction)) {
7353 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
7357 return $pluginfunctions;
7361 * Lists plugin-like directories within specified directory
7363 * This function was originally used for standard Moodle plugins, please use
7364 * new core_component::get_plugin_list() now.
7366 * This function is used for general directory listing and backwards compatility.
7368 * @param string $directory relative directory from root
7369 * @param string $exclude dir name to exclude from the list (defaults to none)
7370 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7371 * @return array Sorted array of directory names found under the requested parameters
7373 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7374 global $CFG;
7376 $plugins = array();
7378 if (empty($basedir)) {
7379 $basedir = $CFG->dirroot .'/'. $directory;
7381 } else {
7382 $basedir = $basedir .'/'. $directory;
7385 if ($CFG->debugdeveloper and empty($exclude)) {
7386 // Make sure devs do not use this to list normal plugins,
7387 // this is intended for general directories that are not plugins!
7389 $subtypes = core_component::get_plugin_types();
7390 if (in_array($basedir, $subtypes)) {
7391 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7393 unset($subtypes);
7396 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7397 if (!$dirhandle = opendir($basedir)) {
7398 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7399 return array();
7401 while (false !== ($dir = readdir($dirhandle))) {
7402 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7403 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7404 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7405 continue;
7407 if (filetype($basedir .'/'. $dir) != 'dir') {
7408 continue;
7410 $plugins[] = $dir;
7412 closedir($dirhandle);
7414 if ($plugins) {
7415 asort($plugins);
7417 return $plugins;
7421 * Invoke plugin's callback functions
7423 * @param string $type plugin type e.g. 'mod'
7424 * @param string $name plugin name
7425 * @param string $feature feature name
7426 * @param string $action feature's action
7427 * @param array $params parameters of callback function, should be an array
7428 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7429 * @return mixed
7431 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7433 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7434 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7438 * Invoke component's callback functions
7440 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7441 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7442 * @param array $params parameters of callback function
7443 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7444 * @return mixed
7446 function component_callback($component, $function, array $params = array(), $default = null) {
7448 $functionname = component_callback_exists($component, $function);
7450 if ($functionname) {
7451 // Function exists, so just return function result.
7452 $ret = call_user_func_array($functionname, $params);
7453 if (is_null($ret)) {
7454 return $default;
7455 } else {
7456 return $ret;
7459 return $default;
7463 * Determine if a component callback exists and return the function name to call. Note that this
7464 * function will include the required library files so that the functioname returned can be
7465 * called directly.
7467 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7468 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7469 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7470 * @throws coding_exception if invalid component specfied
7472 function component_callback_exists($component, $function) {
7473 global $CFG; // This is needed for the inclusions.
7475 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7476 if (empty($cleancomponent)) {
7477 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7479 $component = $cleancomponent;
7481 list($type, $name) = core_component::normalize_component($component);
7482 $component = $type . '_' . $name;
7484 $oldfunction = $name.'_'.$function;
7485 $function = $component.'_'.$function;
7487 $dir = core_component::get_component_directory($component);
7488 if (empty($dir)) {
7489 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7492 // Load library and look for function.
7493 if (file_exists($dir.'/lib.php')) {
7494 require_once($dir.'/lib.php');
7497 if (!function_exists($function) and function_exists($oldfunction)) {
7498 if ($type !== 'mod' and $type !== 'core') {
7499 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7501 $function = $oldfunction;
7504 if (function_exists($function)) {
7505 return $function;
7507 return false;
7511 * Checks whether a plugin supports a specified feature.
7513 * @param string $type Plugin type e.g. 'mod'
7514 * @param string $name Plugin name e.g. 'forum'
7515 * @param string $feature Feature code (FEATURE_xx constant)
7516 * @param mixed $default default value if feature support unknown
7517 * @return mixed Feature result (false if not supported, null if feature is unknown,
7518 * otherwise usually true but may have other feature-specific value such as array)
7519 * @throws coding_exception
7521 function plugin_supports($type, $name, $feature, $default = null) {
7522 global $CFG;
7524 if ($type === 'mod' and $name === 'NEWMODULE') {
7525 // Somebody forgot to rename the module template.
7526 return false;
7529 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7530 if (empty($component)) {
7531 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7534 $function = null;
7536 if ($type === 'mod') {
7537 // We need this special case because we support subplugins in modules,
7538 // otherwise it would end up in infinite loop.
7539 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7540 include_once("$CFG->dirroot/mod/$name/lib.php");
7541 $function = $component.'_supports';
7542 if (!function_exists($function)) {
7543 // Legacy non-frankenstyle function name.
7544 $function = $name.'_supports';
7548 } else {
7549 if (!$path = core_component::get_plugin_directory($type, $name)) {
7550 // Non existent plugin type.
7551 return false;
7553 if (file_exists("$path/lib.php")) {
7554 include_once("$path/lib.php");
7555 $function = $component.'_supports';
7559 if ($function and function_exists($function)) {
7560 $supports = $function($feature);
7561 if (is_null($supports)) {
7562 // Plugin does not know - use default.
7563 return $default;
7564 } else {
7565 return $supports;
7569 // Plugin does not care, so use default.
7570 return $default;
7574 * Returns true if the current version of PHP is greater that the specified one.
7576 * @todo Check PHP version being required here is it too low?
7578 * @param string $version The version of php being tested.
7579 * @return bool
7581 function check_php_version($version='5.2.4') {
7582 return (version_compare(phpversion(), $version) >= 0);
7586 * Determine if moodle installation requires update.
7588 * Checks version numbers of main code and all plugins to see
7589 * if there are any mismatches.
7591 * @return bool
7593 function moodle_needs_upgrading() {
7594 global $CFG;
7596 if (empty($CFG->version)) {
7597 return true;
7600 // There is no need to purge plugininfo caches here because
7601 // these caches are not used during upgrade and they are purged after
7602 // every upgrade.
7604 if (empty($CFG->allversionshash)) {
7605 return true;
7608 $hash = core_component::get_all_versions_hash();
7610 return ($hash !== $CFG->allversionshash);
7614 * Returns the major version of this site
7616 * Moodle version numbers consist of three numbers separated by a dot, for
7617 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7618 * called major version. This function extracts the major version from either
7619 * $CFG->release (default) or eventually from the $release variable defined in
7620 * the main version.php.
7622 * @param bool $fromdisk should the version if source code files be used
7623 * @return string|false the major version like '2.3', false if could not be determined
7625 function moodle_major_version($fromdisk = false) {
7626 global $CFG;
7628 if ($fromdisk) {
7629 $release = null;
7630 require($CFG->dirroot.'/version.php');
7631 if (empty($release)) {
7632 return false;
7635 } else {
7636 if (empty($CFG->release)) {
7637 return false;
7639 $release = $CFG->release;
7642 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7643 return $matches[0];
7644 } else {
7645 return false;
7649 // MISCELLANEOUS.
7652 * Sets the system locale
7654 * @category string
7655 * @param string $locale Can be used to force a locale
7657 function moodle_setlocale($locale='') {
7658 global $CFG;
7660 static $currentlocale = ''; // Last locale caching.
7662 $oldlocale = $currentlocale;
7664 // Fetch the correct locale based on ostype.
7665 if ($CFG->ostype == 'WINDOWS') {
7666 $stringtofetch = 'localewin';
7667 } else {
7668 $stringtofetch = 'locale';
7671 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7672 if (!empty($locale)) {
7673 $currentlocale = $locale;
7674 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7675 $currentlocale = $CFG->locale;
7676 } else {
7677 $currentlocale = get_string($stringtofetch, 'langconfig');
7680 // Do nothing if locale already set up.
7681 if ($oldlocale == $currentlocale) {
7682 return;
7685 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7686 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7687 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7689 // Get current values.
7690 $monetary= setlocale (LC_MONETARY, 0);
7691 $numeric = setlocale (LC_NUMERIC, 0);
7692 $ctype = setlocale (LC_CTYPE, 0);
7693 if ($CFG->ostype != 'WINDOWS') {
7694 $messages= setlocale (LC_MESSAGES, 0);
7696 // Set locale to all.
7697 $result = setlocale (LC_ALL, $currentlocale);
7698 // If setting of locale fails try the other utf8 or utf-8 variant,
7699 // some operating systems support both (Debian), others just one (OSX).
7700 if ($result === false) {
7701 if (stripos($currentlocale, '.UTF-8') !== false) {
7702 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7703 setlocale (LC_ALL, $newlocale);
7704 } else if (stripos($currentlocale, '.UTF8') !== false) {
7705 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7706 setlocale (LC_ALL, $newlocale);
7709 // Set old values.
7710 setlocale (LC_MONETARY, $monetary);
7711 setlocale (LC_NUMERIC, $numeric);
7712 if ($CFG->ostype != 'WINDOWS') {
7713 setlocale (LC_MESSAGES, $messages);
7715 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7716 // To workaround a well-known PHP problem with Turkish letter Ii.
7717 setlocale (LC_CTYPE, $ctype);
7722 * Count words in a string.
7724 * Words are defined as things between whitespace.
7726 * @category string
7727 * @param string $string The text to be searched for words.
7728 * @return int The count of words in the specified string
7730 function count_words($string) {
7731 $string = strip_tags($string);
7732 // Decode HTML entities.
7733 $string = html_entity_decode($string);
7734 // Replace underscores (which are classed as word characters) with spaces.
7735 $string = preg_replace('/_/u', ' ', $string);
7736 // Remove any characters that shouldn't be treated as word boundaries.
7737 $string = preg_replace('/[\'’-]/u', '', $string);
7738 // Remove dots and commas from within numbers only.
7739 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7741 return count(preg_split('/\w\b/u', $string)) - 1;
7745 * Count letters in a string.
7747 * Letters are defined as chars not in tags and different from whitespace.
7749 * @category string
7750 * @param string $string The text to be searched for letters.
7751 * @return int The count of letters in the specified text.
7753 function count_letters($string) {
7754 $string = strip_tags($string); // Tags are out now.
7755 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7757 return core_text::strlen($string);
7761 * Generate and return a random string of the specified length.
7763 * @param int $length The length of the string to be created.
7764 * @return string
7766 function random_string ($length=15) {
7767 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7768 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7769 $pool .= '0123456789';
7770 $poollen = strlen($pool);
7771 $string = '';
7772 for ($i = 0; $i < $length; $i++) {
7773 $string .= substr($pool, (mt_rand()%($poollen)), 1);
7775 return $string;
7779 * Generate a complex random string (useful for md5 salts)
7781 * This function is based on the above {@link random_string()} however it uses a
7782 * larger pool of characters and generates a string between 24 and 32 characters
7784 * @param int $length Optional if set generates a string to exactly this length
7785 * @return string
7787 function complex_random_string($length=null) {
7788 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7789 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7790 $poollen = strlen($pool);
7791 if ($length===null) {
7792 $length = floor(rand(24, 32));
7794 $string = '';
7795 for ($i = 0; $i < $length; $i++) {
7796 $string .= $pool[(mt_rand()%$poollen)];
7798 return $string;
7802 * Given some text (which may contain HTML) and an ideal length,
7803 * this function truncates the text neatly on a word boundary if possible
7805 * @category string
7806 * @param string $text text to be shortened
7807 * @param int $ideal ideal string length
7808 * @param boolean $exact if false, $text will not be cut mid-word
7809 * @param string $ending The string to append if the passed string is truncated
7810 * @return string $truncate shortened string
7812 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7813 // If the plain text is shorter than the maximum length, return the whole text.
7814 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7815 return $text;
7818 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7819 // and only tag in its 'line'.
7820 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7822 $totallength = core_text::strlen($ending);
7823 $truncate = '';
7825 // This array stores information about open and close tags and their position
7826 // in the truncated string. Each item in the array is an object with fields
7827 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7828 // (byte position in truncated text).
7829 $tagdetails = array();
7831 foreach ($lines as $linematchings) {
7832 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7833 if (!empty($linematchings[1])) {
7834 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7835 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7836 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7837 // Record closing tag.
7838 $tagdetails[] = (object) array(
7839 'open' => false,
7840 'tag' => core_text::strtolower($tagmatchings[1]),
7841 'pos' => core_text::strlen($truncate),
7844 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7845 // Record opening tag.
7846 $tagdetails[] = (object) array(
7847 'open' => true,
7848 'tag' => core_text::strtolower($tagmatchings[1]),
7849 'pos' => core_text::strlen($truncate),
7853 // Add html-tag to $truncate'd text.
7854 $truncate .= $linematchings[1];
7857 // Calculate the length of the plain text part of the line; handle entities as one character.
7858 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7859 if ($totallength + $contentlength > $ideal) {
7860 // The number of characters which are left.
7861 $left = $ideal - $totallength;
7862 $entitieslength = 0;
7863 // Search for html entities.
7864 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)) {
7865 // Calculate the real length of all entities in the legal range.
7866 foreach ($entities[0] as $entity) {
7867 if ($entity[1]+1-$entitieslength <= $left) {
7868 $left--;
7869 $entitieslength += core_text::strlen($entity[0]);
7870 } else {
7871 // No more characters left.
7872 break;
7876 $breakpos = $left + $entitieslength;
7878 // If the words shouldn't be cut in the middle...
7879 if (!$exact) {
7880 // Search the last occurence of a space.
7881 for (; $breakpos > 0; $breakpos--) {
7882 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
7883 if ($char === '.' or $char === ' ') {
7884 $breakpos += 1;
7885 break;
7886 } else if (strlen($char) > 2) {
7887 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7888 $breakpos += 1;
7889 break;
7894 if ($breakpos == 0) {
7895 // This deals with the test_shorten_text_no_spaces case.
7896 $breakpos = $left + $entitieslength;
7897 } else if ($breakpos > $left + $entitieslength) {
7898 // This deals with the previous for loop breaking on the first char.
7899 $breakpos = $left + $entitieslength;
7902 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
7903 // Maximum length is reached, so get off the loop.
7904 break;
7905 } else {
7906 $truncate .= $linematchings[2];
7907 $totallength += $contentlength;
7910 // If the maximum length is reached, get off the loop.
7911 if ($totallength >= $ideal) {
7912 break;
7916 // Add the defined ending to the text.
7917 $truncate .= $ending;
7919 // Now calculate the list of open html tags based on the truncate position.
7920 $opentags = array();
7921 foreach ($tagdetails as $taginfo) {
7922 if ($taginfo->open) {
7923 // Add tag to the beginning of $opentags list.
7924 array_unshift($opentags, $taginfo->tag);
7925 } else {
7926 // Can have multiple exact same open tags, close the last one.
7927 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
7928 if ($pos !== false) {
7929 unset($opentags[$pos]);
7934 // Close all unclosed html-tags.
7935 foreach ($opentags as $tag) {
7936 $truncate .= '</' . $tag . '>';
7939 return $truncate;
7944 * Given dates in seconds, how many weeks is the date from startdate
7945 * The first week is 1, the second 2 etc ...
7947 * @param int $startdate Timestamp for the start date
7948 * @param int $thedate Timestamp for the end date
7949 * @return string
7951 function getweek ($startdate, $thedate) {
7952 if ($thedate < $startdate) {
7953 return 0;
7956 return floor(($thedate - $startdate) / WEEKSECS) + 1;
7960 * Returns a randomly generated password of length $maxlen. inspired by
7962 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
7963 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
7965 * @param int $maxlen The maximum size of the password being generated.
7966 * @return string
7968 function generate_password($maxlen=10) {
7969 global $CFG;
7971 if (empty($CFG->passwordpolicy)) {
7972 $fillers = PASSWORD_DIGITS;
7973 $wordlist = file($CFG->wordlist);
7974 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7975 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7976 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
7977 $password = $word1 . $filler1 . $word2;
7978 } else {
7979 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
7980 $digits = $CFG->minpassworddigits;
7981 $lower = $CFG->minpasswordlower;
7982 $upper = $CFG->minpasswordupper;
7983 $nonalphanum = $CFG->minpasswordnonalphanum;
7984 $total = $lower + $upper + $digits + $nonalphanum;
7985 // Var minlength should be the greater one of the two ( $minlen and $total ).
7986 $minlen = $minlen < $total ? $total : $minlen;
7987 // Var maxlen can never be smaller than minlen.
7988 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
7989 $additional = $maxlen - $total;
7991 // Make sure we have enough characters to fulfill
7992 // complexity requirements.
7993 $passworddigits = PASSWORD_DIGITS;
7994 while ($digits > strlen($passworddigits)) {
7995 $passworddigits .= PASSWORD_DIGITS;
7997 $passwordlower = PASSWORD_LOWER;
7998 while ($lower > strlen($passwordlower)) {
7999 $passwordlower .= PASSWORD_LOWER;
8001 $passwordupper = PASSWORD_UPPER;
8002 while ($upper > strlen($passwordupper)) {
8003 $passwordupper .= PASSWORD_UPPER;
8005 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8006 while ($nonalphanum > strlen($passwordnonalphanum)) {
8007 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8010 // Now mix and shuffle it all.
8011 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8012 substr(str_shuffle ($passwordupper), 0, $upper) .
8013 substr(str_shuffle ($passworddigits), 0, $digits) .
8014 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8015 substr(str_shuffle ($passwordlower .
8016 $passwordupper .
8017 $passworddigits .
8018 $passwordnonalphanum), 0 , $additional));
8021 return substr ($password, 0, $maxlen);
8025 * Given a float, prints it nicely.
8026 * Localized floats must not be used in calculations!
8028 * The stripzeros feature is intended for making numbers look nicer in small
8029 * areas where it is not necessary to indicate the degree of accuracy by showing
8030 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8031 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8033 * @param float $float The float to print
8034 * @param int $decimalpoints The number of decimal places to print.
8035 * @param bool $localized use localized decimal separator
8036 * @param bool $stripzeros If true, removes final zeros after decimal point
8037 * @return string locale float
8039 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8040 if (is_null($float)) {
8041 return '';
8043 if ($localized) {
8044 $separator = get_string('decsep', 'langconfig');
8045 } else {
8046 $separator = '.';
8048 $result = number_format($float, $decimalpoints, $separator, '');
8049 if ($stripzeros) {
8050 // Remove zeros and final dot if not needed.
8051 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8053 return $result;
8057 * Converts locale specific floating point/comma number back to standard PHP float value
8058 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8060 * @param string $localefloat locale aware float representation
8061 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8062 * @return mixed float|bool - false or the parsed float.
8064 function unformat_float($localefloat, $strict = false) {
8065 $localefloat = trim($localefloat);
8067 if ($localefloat == '') {
8068 return null;
8071 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8072 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8074 if ($strict && !is_numeric($localefloat)) {
8075 return false;
8078 return (float)$localefloat;
8082 * Given a simple array, this shuffles it up just like shuffle()
8083 * Unlike PHP's shuffle() this function works on any machine.
8085 * @param array $array The array to be rearranged
8086 * @return array
8088 function swapshuffle($array) {
8090 $last = count($array) - 1;
8091 for ($i = 0; $i <= $last; $i++) {
8092 $from = rand(0, $last);
8093 $curr = $array[$i];
8094 $array[$i] = $array[$from];
8095 $array[$from] = $curr;
8097 return $array;
8101 * Like {@link swapshuffle()}, but works on associative arrays
8103 * @param array $array The associative array to be rearranged
8104 * @return array
8106 function swapshuffle_assoc($array) {
8108 $newarray = array();
8109 $newkeys = swapshuffle(array_keys($array));
8111 foreach ($newkeys as $newkey) {
8112 $newarray[$newkey] = $array[$newkey];
8114 return $newarray;
8118 * Given an arbitrary array, and a number of draws,
8119 * this function returns an array with that amount
8120 * of items. The indexes are retained.
8122 * @todo Finish documenting this function
8124 * @param array $array
8125 * @param int $draws
8126 * @return array
8128 function draw_rand_array($array, $draws) {
8130 $return = array();
8132 $last = count($array);
8134 if ($draws > $last) {
8135 $draws = $last;
8138 while ($draws > 0) {
8139 $last--;
8141 $keys = array_keys($array);
8142 $rand = rand(0, $last);
8144 $return[$keys[$rand]] = $array[$keys[$rand]];
8145 unset($array[$keys[$rand]]);
8147 $draws--;
8150 return $return;
8154 * Calculate the difference between two microtimes
8156 * @param string $a The first Microtime
8157 * @param string $b The second Microtime
8158 * @return string
8160 function microtime_diff($a, $b) {
8161 list($adec, $asec) = explode(' ', $a);
8162 list($bdec, $bsec) = explode(' ', $b);
8163 return $bsec - $asec + $bdec - $adec;
8167 * Given a list (eg a,b,c,d,e) this function returns
8168 * an array of 1->a, 2->b, 3->c etc
8170 * @param string $list The string to explode into array bits
8171 * @param string $separator The separator used within the list string
8172 * @return array The now assembled array
8174 function make_menu_from_list($list, $separator=',') {
8176 $array = array_reverse(explode($separator, $list), true);
8177 foreach ($array as $key => $item) {
8178 $outarray[$key+1] = trim($item);
8180 return $outarray;
8184 * Creates an array that represents all the current grades that
8185 * can be chosen using the given grading type.
8187 * Negative numbers
8188 * are scales, zero is no grade, and positive numbers are maximum
8189 * grades.
8191 * @todo Finish documenting this function or better deprecated this completely!
8193 * @param int $gradingtype
8194 * @return array
8196 function make_grades_menu($gradingtype) {
8197 global $DB;
8199 $grades = array();
8200 if ($gradingtype < 0) {
8201 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8202 return make_menu_from_list($scale->scale);
8204 } else if ($gradingtype > 0) {
8205 for ($i=$gradingtype; $i>=0; $i--) {
8206 $grades[$i] = $i .' / '. $gradingtype;
8208 return $grades;
8210 return $grades;
8214 * This function returns the number of activities using the given scale in the given course.
8216 * @param int $courseid The course ID to check.
8217 * @param int $scaleid The scale ID to check
8218 * @return int
8220 function course_scale_used($courseid, $scaleid) {
8221 global $CFG, $DB;
8223 $return = 0;
8225 if (!empty($scaleid)) {
8226 if ($cms = get_course_mods($courseid)) {
8227 foreach ($cms as $cm) {
8228 // Check cm->name/lib.php exists.
8229 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
8230 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
8231 $functionname = $cm->modname.'_scale_used';
8232 if (function_exists($functionname)) {
8233 if ($functionname($cm->instance, $scaleid)) {
8234 $return++;
8241 // Check if any course grade item makes use of the scale.
8242 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8244 // Check if any outcome in the course makes use of the scale.
8245 $return += $DB->count_records_sql("SELECT COUNT('x')
8246 FROM {grade_outcomes_courses} goc,
8247 {grade_outcomes} go
8248 WHERE go.id = goc.outcomeid
8249 AND go.scaleid = ? AND goc.courseid = ?",
8250 array($scaleid, $courseid));
8252 return $return;
8256 * This function returns the number of activities using scaleid in the entire site
8258 * @param int $scaleid
8259 * @param array $courses
8260 * @return int
8262 function site_scale_used($scaleid, &$courses) {
8263 $return = 0;
8265 if (!is_array($courses) || count($courses) == 0) {
8266 $courses = get_courses("all", false, "c.id, c.shortname");
8269 if (!empty($scaleid)) {
8270 if (is_array($courses) && count($courses) > 0) {
8271 foreach ($courses as $course) {
8272 $return += course_scale_used($course->id, $scaleid);
8276 return $return;
8280 * make_unique_id_code
8282 * @todo Finish documenting this function
8284 * @uses $_SERVER
8285 * @param string $extra Extra string to append to the end of the code
8286 * @return string
8288 function make_unique_id_code($extra = '') {
8290 $hostname = 'unknownhost';
8291 if (!empty($_SERVER['HTTP_HOST'])) {
8292 $hostname = $_SERVER['HTTP_HOST'];
8293 } else if (!empty($_ENV['HTTP_HOST'])) {
8294 $hostname = $_ENV['HTTP_HOST'];
8295 } else if (!empty($_SERVER['SERVER_NAME'])) {
8296 $hostname = $_SERVER['SERVER_NAME'];
8297 } else if (!empty($_ENV['SERVER_NAME'])) {
8298 $hostname = $_ENV['SERVER_NAME'];
8301 $date = gmdate("ymdHis");
8303 $random = random_string(6);
8305 if ($extra) {
8306 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8307 } else {
8308 return $hostname .'+'. $date .'+'. $random;
8314 * Function to check the passed address is within the passed subnet
8316 * The parameter is a comma separated string of subnet definitions.
8317 * Subnet strings can be in one of three formats:
8318 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8319 * 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)
8320 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8321 * Code for type 1 modified from user posted comments by mediator at
8322 * {@link http://au.php.net/manual/en/function.ip2long.php}
8324 * @param string $addr The address you are checking
8325 * @param string $subnetstr The string of subnet addresses
8326 * @return bool
8328 function address_in_subnet($addr, $subnetstr) {
8330 if ($addr == '0.0.0.0') {
8331 return false;
8333 $subnets = explode(',', $subnetstr);
8334 $found = false;
8335 $addr = trim($addr);
8336 $addr = cleanremoteaddr($addr, false); // Normalise.
8337 if ($addr === null) {
8338 return false;
8340 $addrparts = explode(':', $addr);
8342 $ipv6 = strpos($addr, ':');
8344 foreach ($subnets as $subnet) {
8345 $subnet = trim($subnet);
8346 if ($subnet === '') {
8347 continue;
8350 if (strpos($subnet, '/') !== false) {
8351 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8352 list($ip, $mask) = explode('/', $subnet);
8353 $mask = trim($mask);
8354 if (!is_number($mask)) {
8355 continue; // Incorect mask number, eh?
8357 $ip = cleanremoteaddr($ip, false); // Normalise.
8358 if ($ip === null) {
8359 continue;
8361 if (strpos($ip, ':') !== false) {
8362 // IPv6.
8363 if (!$ipv6) {
8364 continue;
8366 if ($mask > 128 or $mask < 0) {
8367 continue; // Nonsense.
8369 if ($mask == 0) {
8370 return true; // Any address.
8372 if ($mask == 128) {
8373 if ($ip === $addr) {
8374 return true;
8376 continue;
8378 $ipparts = explode(':', $ip);
8379 $modulo = $mask % 16;
8380 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8381 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8382 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8383 if ($modulo == 0) {
8384 return true;
8386 $pos = ($mask-$modulo)/16;
8387 $ipnet = hexdec($ipparts[$pos]);
8388 $addrnet = hexdec($addrparts[$pos]);
8389 $mask = 0xffff << (16 - $modulo);
8390 if (($addrnet & $mask) == ($ipnet & $mask)) {
8391 return true;
8395 } else {
8396 // IPv4.
8397 if ($ipv6) {
8398 continue;
8400 if ($mask > 32 or $mask < 0) {
8401 continue; // Nonsense.
8403 if ($mask == 0) {
8404 return true;
8406 if ($mask == 32) {
8407 if ($ip === $addr) {
8408 return true;
8410 continue;
8412 $mask = 0xffffffff << (32 - $mask);
8413 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8414 return true;
8418 } else if (strpos($subnet, '-') !== false) {
8419 // 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.
8420 $parts = explode('-', $subnet);
8421 if (count($parts) != 2) {
8422 continue;
8425 if (strpos($subnet, ':') !== false) {
8426 // IPv6.
8427 if (!$ipv6) {
8428 continue;
8430 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8431 if ($ipstart === null) {
8432 continue;
8434 $ipparts = explode(':', $ipstart);
8435 $start = hexdec(array_pop($ipparts));
8436 $ipparts[] = trim($parts[1]);
8437 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8438 if ($ipend === null) {
8439 continue;
8441 $ipparts[7] = '';
8442 $ipnet = implode(':', $ipparts);
8443 if (strpos($addr, $ipnet) !== 0) {
8444 continue;
8446 $ipparts = explode(':', $ipend);
8447 $end = hexdec($ipparts[7]);
8449 $addrend = hexdec($addrparts[7]);
8451 if (($addrend >= $start) and ($addrend <= $end)) {
8452 return true;
8455 } else {
8456 // IPv4.
8457 if ($ipv6) {
8458 continue;
8460 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8461 if ($ipstart === null) {
8462 continue;
8464 $ipparts = explode('.', $ipstart);
8465 $ipparts[3] = trim($parts[1]);
8466 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8467 if ($ipend === null) {
8468 continue;
8471 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8472 return true;
8476 } else {
8477 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8478 if (strpos($subnet, ':') !== false) {
8479 // IPv6.
8480 if (!$ipv6) {
8481 continue;
8483 $parts = explode(':', $subnet);
8484 $count = count($parts);
8485 if ($parts[$count-1] === '') {
8486 unset($parts[$count-1]); // Trim trailing :'s.
8487 $count--;
8488 $subnet = implode('.', $parts);
8490 $isip = cleanremoteaddr($subnet, false); // Normalise.
8491 if ($isip !== null) {
8492 if ($isip === $addr) {
8493 return true;
8495 continue;
8496 } else if ($count > 8) {
8497 continue;
8499 $zeros = array_fill(0, 8-$count, '0');
8500 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8501 if (address_in_subnet($addr, $subnet)) {
8502 return true;
8505 } else {
8506 // IPv4.
8507 if ($ipv6) {
8508 continue;
8510 $parts = explode('.', $subnet);
8511 $count = count($parts);
8512 if ($parts[$count-1] === '') {
8513 unset($parts[$count-1]); // Trim trailing .
8514 $count--;
8515 $subnet = implode('.', $parts);
8517 if ($count == 4) {
8518 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8519 if ($subnet === $addr) {
8520 return true;
8522 continue;
8523 } else if ($count > 4) {
8524 continue;
8526 $zeros = array_fill(0, 4-$count, '0');
8527 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8528 if (address_in_subnet($addr, $subnet)) {
8529 return true;
8535 return false;
8539 * For outputting debugging info
8541 * @param string $string The string to write
8542 * @param string $eol The end of line char(s) to use
8543 * @param string $sleep Period to make the application sleep
8544 * This ensures any messages have time to display before redirect
8546 function mtrace($string, $eol="\n", $sleep=0) {
8548 if (defined('STDOUT') and !PHPUNIT_TEST) {
8549 fwrite(STDOUT, $string.$eol);
8550 } else {
8551 echo $string . $eol;
8554 flush();
8556 // Delay to keep message on user's screen in case of subsequent redirect.
8557 if ($sleep) {
8558 sleep($sleep);
8563 * Replace 1 or more slashes or backslashes to 1 slash
8565 * @param string $path The path to strip
8566 * @return string the path with double slashes removed
8568 function cleardoubleslashes ($path) {
8569 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8573 * Is current ip in give list?
8575 * @param string $list
8576 * @return bool
8578 function remoteip_in_list($list) {
8579 $inlist = false;
8580 $clientip = getremoteaddr(null);
8582 if (!$clientip) {
8583 // Ensure access on cli.
8584 return true;
8587 $list = explode("\n", $list);
8588 foreach ($list as $subnet) {
8589 $subnet = trim($subnet);
8590 if (address_in_subnet($clientip, $subnet)) {
8591 $inlist = true;
8592 break;
8595 return $inlist;
8599 * Returns most reliable client address
8601 * @param string $default If an address can't be determined, then return this
8602 * @return string The remote IP address
8604 function getremoteaddr($default='0.0.0.0') {
8605 global $CFG;
8607 if (empty($CFG->getremoteaddrconf)) {
8608 // This will happen, for example, before just after the upgrade, as the
8609 // user is redirected to the admin screen.
8610 $variablestoskip = 0;
8611 } else {
8612 $variablestoskip = $CFG->getremoteaddrconf;
8614 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8615 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8616 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8617 return $address ? $address : $default;
8620 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8621 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8622 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8623 $address = $forwardedaddresses[0];
8625 if (substr_count($address, ":") > 1) {
8626 // Remove port and brackets from IPv6.
8627 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8628 $address = $matches[1];
8630 } else {
8631 // Remove port from IPv4.
8632 if (substr_count($address, ":") == 1) {
8633 $address = explode(":", $address)[0];
8637 $address = cleanremoteaddr($address);
8638 return $address ? $address : $default;
8641 if (!empty($_SERVER['REMOTE_ADDR'])) {
8642 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8643 return $address ? $address : $default;
8644 } else {
8645 return $default;
8650 * Cleans an ip address. Internal addresses are now allowed.
8651 * (Originally local addresses were not allowed.)
8653 * @param string $addr IPv4 or IPv6 address
8654 * @param bool $compress use IPv6 address compression
8655 * @return string normalised ip address string, null if error
8657 function cleanremoteaddr($addr, $compress=false) {
8658 $addr = trim($addr);
8660 // TODO: maybe add a separate function is_addr_public() or something like this.
8662 if (strpos($addr, ':') !== false) {
8663 // Can be only IPv6.
8664 $parts = explode(':', $addr);
8665 $count = count($parts);
8667 if (strpos($parts[$count-1], '.') !== false) {
8668 // Legacy ipv4 notation.
8669 $last = array_pop($parts);
8670 $ipv4 = cleanremoteaddr($last, true);
8671 if ($ipv4 === null) {
8672 return null;
8674 $bits = explode('.', $ipv4);
8675 $parts[] = dechex($bits[0]).dechex($bits[1]);
8676 $parts[] = dechex($bits[2]).dechex($bits[3]);
8677 $count = count($parts);
8678 $addr = implode(':', $parts);
8681 if ($count < 3 or $count > 8) {
8682 return null; // Severly malformed.
8685 if ($count != 8) {
8686 if (strpos($addr, '::') === false) {
8687 return null; // Malformed.
8689 // Uncompress.
8690 $insertat = array_search('', $parts, true);
8691 $missing = array_fill(0, 1 + 8 - $count, '0');
8692 array_splice($parts, $insertat, 1, $missing);
8693 foreach ($parts as $key => $part) {
8694 if ($part === '') {
8695 $parts[$key] = '0';
8700 $adr = implode(':', $parts);
8701 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8702 return null; // Incorrect format - sorry.
8705 // Normalise 0s and case.
8706 $parts = array_map('hexdec', $parts);
8707 $parts = array_map('dechex', $parts);
8709 $result = implode(':', $parts);
8711 if (!$compress) {
8712 return $result;
8715 if ($result === '0:0:0:0:0:0:0:0') {
8716 return '::'; // All addresses.
8719 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8720 if ($compressed !== $result) {
8721 return $compressed;
8724 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8725 if ($compressed !== $result) {
8726 return $compressed;
8729 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8730 if ($compressed !== $result) {
8731 return $compressed;
8734 return $result;
8737 // First get all things that look like IPv4 addresses.
8738 $parts = array();
8739 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8740 return null;
8742 unset($parts[0]);
8744 foreach ($parts as $key => $match) {
8745 if ($match > 255) {
8746 return null;
8748 $parts[$key] = (int)$match; // Normalise 0s.
8751 return implode('.', $parts);
8755 * This function will make a complete copy of anything it's given,
8756 * regardless of whether it's an object or not.
8758 * @param mixed $thing Something you want cloned
8759 * @return mixed What ever it is you passed it
8761 function fullclone($thing) {
8762 return unserialize(serialize($thing));
8766 * If new messages are waiting for the current user, then insert
8767 * JavaScript to pop up the messaging window into the page
8769 * @return void
8771 function message_popup_window() {
8772 global $USER, $DB, $PAGE, $CFG;
8774 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
8775 return;
8778 if (!isloggedin() || isguestuser()) {
8779 return;
8782 if (!isset($USER->message_lastpopup)) {
8783 $USER->message_lastpopup = 0;
8784 } else if ($USER->message_lastpopup > (time()-120)) {
8785 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8786 return;
8789 // A quick query to check whether the user has new messages.
8790 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
8791 if ($messagecount < 1) {
8792 return;
8795 // There are unread messages so now do a more complex but slower query.
8796 $messagesql = "SELECT m.id, c.blocked
8797 FROM {message} m
8798 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8799 JOIN {message_processors} p ON mw.processorid=p.id
8800 JOIN {user} u ON m.useridfrom=u.id
8801 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8802 AND c.userid = m.useridto
8803 WHERE m.useridto = :userid
8804 AND p.name='popup'";
8806 // If the user was last notified over an hour ago we can re-notify them of old messages
8807 // so don't worry about when the new message was sent.
8808 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
8809 if (!$lastnotifiedlongago) {
8810 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8813 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
8815 $validmessages = 0;
8816 foreach ($waitingmessages as $messageinfo) {
8817 if ($messageinfo->blocked) {
8818 // Message is from a user who has since been blocked so just mark it read.
8819 // Get the full message to mark as read.
8820 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id));
8821 message_mark_message_read($messageobject, time());
8822 } else {
8823 $validmessages++;
8827 if ($validmessages > 0) {
8828 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8829 $strgomessage = get_string('gotomessages', 'message');
8830 $strstaymessage = get_string('ignore', 'admin');
8832 $notificationsound = null;
8833 $beep = get_user_preferences('message_beepnewmessage', '');
8834 if (!empty($beep)) {
8835 // Browsers will work down this list until they find something they support.
8836 $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
8837 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
8838 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8839 $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8841 $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8844 $url = $CFG->wwwroot.'/message/index.php';
8845 $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8846 html_writer::start_tag('div', array('id' => 'newmessagetext')).
8847 $strmessages.
8848 html_writer::end_tag('div').
8850 $notificationsound.
8851 html_writer::start_tag('div', array('id' => 'newmessagelinks')).
8852 html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
8853 html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
8854 html_writer::end_tag('div');
8855 html_writer::end_tag('div');
8857 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
8859 $USER->message_lastpopup = time();
8864 * Used to make sure that $min <= $value <= $max
8866 * Make sure that value is between min, and max
8868 * @param int $min The minimum value
8869 * @param int $value The value to check
8870 * @param int $max The maximum value
8871 * @return int
8873 function bounded_number($min, $value, $max) {
8874 if ($value < $min) {
8875 return $min;
8877 if ($value > $max) {
8878 return $max;
8880 return $value;
8884 * Check if there is a nested array within the passed array
8886 * @param array $array
8887 * @return bool true if there is a nested array false otherwise
8889 function array_is_nested($array) {
8890 foreach ($array as $value) {
8891 if (is_array($value)) {
8892 return true;
8895 return false;
8899 * get_performance_info() pairs up with init_performance_info()
8900 * loaded in setup.php. Returns an array with 'html' and 'txt'
8901 * values ready for use, and each of the individual stats provided
8902 * separately as well.
8904 * @return array
8906 function get_performance_info() {
8907 global $CFG, $PERF, $DB, $PAGE;
8909 $info = array();
8910 $info['html'] = ''; // Holds userfriendly HTML representation.
8911 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8913 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8915 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8916 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8918 if (function_exists('memory_get_usage')) {
8919 $info['memory_total'] = memory_get_usage();
8920 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8921 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8922 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8923 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8926 if (function_exists('memory_get_peak_usage')) {
8927 $info['memory_peak'] = memory_get_peak_usage();
8928 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8929 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8932 $inc = get_included_files();
8933 $info['includecount'] = count($inc);
8934 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8935 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8937 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8938 // We can not track more performance before installation or before PAGE init, sorry.
8939 return $info;
8942 $filtermanager = filter_manager::instance();
8943 if (method_exists($filtermanager, 'get_performance_summary')) {
8944 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8945 $info = array_merge($filterinfo, $info);
8946 foreach ($filterinfo as $key => $value) {
8947 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8948 $info['txt'] .= "$key: $value ";
8952 $stringmanager = get_string_manager();
8953 if (method_exists($stringmanager, 'get_performance_summary')) {
8954 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8955 $info = array_merge($filterinfo, $info);
8956 foreach ($filterinfo as $key => $value) {
8957 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8958 $info['txt'] .= "$key: $value ";
8962 if (!empty($PERF->logwrites)) {
8963 $info['logwrites'] = $PERF->logwrites;
8964 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8965 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8968 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
8969 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
8970 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8972 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
8973 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
8974 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
8976 if (function_exists('posix_times')) {
8977 $ptimes = posix_times();
8978 if (is_array($ptimes)) {
8979 foreach ($ptimes as $key => $val) {
8980 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
8982 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
8983 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8987 // Grab the load average for the last minute.
8988 // /proc will only work under some linux configurations
8989 // while uptime is there under MacOSX/Darwin and other unices.
8990 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
8991 list($serverload) = explode(' ', $loadavg[0]);
8992 unset($loadavg);
8993 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
8994 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
8995 $serverload = $matches[1];
8996 } else {
8997 trigger_error('Could not parse uptime output!');
9000 if (!empty($serverload)) {
9001 $info['serverload'] = $serverload;
9002 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
9003 $info['txt'] .= "serverload: {$info['serverload']} ";
9006 // Display size of session if session started.
9007 if ($si = \core\session\manager::get_performance_info()) {
9008 $info['sessionsize'] = $si['size'];
9009 $info['html'] .= $si['html'];
9010 $info['txt'] .= $si['txt'];
9013 if ($stats = cache_helper::get_stats()) {
9014 $html = '<span class="cachesused">';
9015 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
9016 $text = 'Caches used (hits/misses/sets): ';
9017 $hits = 0;
9018 $misses = 0;
9019 $sets = 0;
9020 foreach ($stats as $definition => $stores) {
9021 $html .= '<span class="cache-definition-stats">';
9022 $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
9023 $text .= "$definition {";
9024 foreach ($stores as $store => $data) {
9025 $hits += $data['hits'];
9026 $misses += $data['misses'];
9027 $sets += $data['sets'];
9028 if ($data['hits'] == 0 and $data['misses'] > 0) {
9029 $cachestoreclass = 'nohits';
9030 } else if ($data['hits'] < $data['misses']) {
9031 $cachestoreclass = 'lowhits';
9032 } else {
9033 $cachestoreclass = 'hihits';
9035 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9036 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
9038 $html .= '</span>';
9039 $text .= '} ';
9041 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
9042 $html .= '</span> ';
9043 $info['cachesused'] = "$hits / $misses / $sets";
9044 $info['html'] .= $html;
9045 $info['txt'] .= $text.'. ';
9046 } else {
9047 $info['cachesused'] = '0 / 0 / 0';
9048 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
9049 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9052 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
9053 return $info;
9057 * Legacy function.
9059 * @todo Document this function linux people
9061 function apd_get_profiling() {
9062 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
9066 * Delete directory or only its content
9068 * @param string $dir directory path
9069 * @param bool $contentonly
9070 * @return bool success, true also if dir does not exist
9072 function remove_dir($dir, $contentonly=false) {
9073 if (!file_exists($dir)) {
9074 // Nothing to do.
9075 return true;
9077 if (!$handle = opendir($dir)) {
9078 return false;
9080 $result = true;
9081 while (false!==($item = readdir($handle))) {
9082 if ($item != '.' && $item != '..') {
9083 if (is_dir($dir.'/'.$item)) {
9084 $result = remove_dir($dir.'/'.$item) && $result;
9085 } else {
9086 $result = unlink($dir.'/'.$item) && $result;
9090 closedir($handle);
9091 if ($contentonly) {
9092 clearstatcache(); // Make sure file stat cache is properly invalidated.
9093 return $result;
9095 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9096 clearstatcache(); // Make sure file stat cache is properly invalidated.
9097 return $result;
9101 * Detect if an object or a class contains a given property
9102 * will take an actual object or the name of a class
9104 * @param mix $obj Name of class or real object to test
9105 * @param string $property name of property to find
9106 * @return bool true if property exists
9108 function object_property_exists( $obj, $property ) {
9109 if (is_string( $obj )) {
9110 $properties = get_class_vars( $obj );
9111 } else {
9112 $properties = get_object_vars( $obj );
9114 return array_key_exists( $property, $properties );
9118 * Converts an object into an associative array
9120 * This function converts an object into an associative array by iterating
9121 * over its public properties. Because this function uses the foreach
9122 * construct, Iterators are respected. It works recursively on arrays of objects.
9123 * Arrays and simple values are returned as is.
9125 * If class has magic properties, it can implement IteratorAggregate
9126 * and return all available properties in getIterator()
9128 * @param mixed $var
9129 * @return array
9131 function convert_to_array($var) {
9132 $result = array();
9134 // Loop over elements/properties.
9135 foreach ($var as $key => $value) {
9136 // Recursively convert objects.
9137 if (is_object($value) || is_array($value)) {
9138 $result[$key] = convert_to_array($value);
9139 } else {
9140 // Simple values are untouched.
9141 $result[$key] = $value;
9144 return $result;
9148 * Detect a custom script replacement in the data directory that will
9149 * replace an existing moodle script
9151 * @return string|bool full path name if a custom script exists, false if no custom script exists
9153 function custom_script_path() {
9154 global $CFG, $SCRIPT;
9156 if ($SCRIPT === null) {
9157 // Probably some weird external script.
9158 return false;
9161 $scriptpath = $CFG->customscripts . $SCRIPT;
9163 // Check the custom script exists.
9164 if (file_exists($scriptpath) and is_file($scriptpath)) {
9165 return $scriptpath;
9166 } else {
9167 return false;
9172 * Returns whether or not the user object is a remote MNET user. This function
9173 * is in moodlelib because it does not rely on loading any of the MNET code.
9175 * @param object $user A valid user object
9176 * @return bool True if the user is from a remote Moodle.
9178 function is_mnet_remote_user($user) {
9179 global $CFG;
9181 if (!isset($CFG->mnet_localhost_id)) {
9182 include_once($CFG->dirroot . '/mnet/lib.php');
9183 $env = new mnet_environment();
9184 $env->init();
9185 unset($env);
9188 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9192 * This function will search for browser prefereed languages, setting Moodle
9193 * to use the best one available if $SESSION->lang is undefined
9195 function setup_lang_from_browser() {
9196 global $CFG, $SESSION, $USER;
9198 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9199 // Lang is defined in session or user profile, nothing to do.
9200 return;
9203 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9204 return;
9207 // Extract and clean langs from headers.
9208 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9209 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9210 $rawlangs = explode(',', $rawlangs); // Convert to array.
9211 $langs = array();
9213 $order = 1.0;
9214 foreach ($rawlangs as $lang) {
9215 if (strpos($lang, ';') === false) {
9216 $langs[(string)$order] = $lang;
9217 $order = $order-0.01;
9218 } else {
9219 $parts = explode(';', $lang);
9220 $pos = strpos($parts[1], '=');
9221 $langs[substr($parts[1], $pos+1)] = $parts[0];
9224 krsort($langs, SORT_NUMERIC);
9226 // Look for such langs under standard locations.
9227 foreach ($langs as $lang) {
9228 // Clean it properly for include.
9229 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9230 if (get_string_manager()->translation_exists($lang, false)) {
9231 // Lang exists, set it in session.
9232 $SESSION->lang = $lang;
9233 // We have finished. Go out.
9234 break;
9237 return;
9241 * Check if $url matches anything in proxybypass list
9243 * Any errors just result in the proxy being used (least bad)
9245 * @param string $url url to check
9246 * @return boolean true if we should bypass the proxy
9248 function is_proxybypass( $url ) {
9249 global $CFG;
9251 // Sanity check.
9252 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9253 return false;
9256 // Get the host part out of the url.
9257 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9258 return false;
9261 // Get the possible bypass hosts into an array.
9262 $matches = explode( ',', $CFG->proxybypass );
9264 // Check for a match.
9265 // (IPs need to match the left hand side and hosts the right of the url,
9266 // but we can recklessly check both as there can't be a false +ve).
9267 foreach ($matches as $match) {
9268 $match = trim($match);
9270 // Try for IP match (Left side).
9271 $lhs = substr($host, 0, strlen($match));
9272 if (strcasecmp($match, $lhs)==0) {
9273 return true;
9276 // Try for host match (Right side).
9277 $rhs = substr($host, -strlen($match));
9278 if (strcasecmp($match, $rhs)==0) {
9279 return true;
9283 // Nothing matched.
9284 return false;
9288 * Check if the passed navigation is of the new style
9290 * @param mixed $navigation
9291 * @return bool true for yes false for no
9293 function is_newnav($navigation) {
9294 if (is_array($navigation) && !empty($navigation['newnav'])) {
9295 return true;
9296 } else {
9297 return false;
9302 * Checks whether the given variable name is defined as a variable within the given object.
9304 * This will NOT work with stdClass objects, which have no class variables.
9306 * @param string $var The variable name
9307 * @param object $object The object to check
9308 * @return boolean
9310 function in_object_vars($var, $object) {
9311 $classvars = get_class_vars(get_class($object));
9312 $classvars = array_keys($classvars);
9313 return in_array($var, $classvars);
9317 * Returns an array without repeated objects.
9318 * This function is similar to array_unique, but for arrays that have objects as values
9320 * @param array $array
9321 * @param bool $keepkeyassoc
9322 * @return array
9324 function object_array_unique($array, $keepkeyassoc = true) {
9325 $duplicatekeys = array();
9326 $tmp = array();
9328 foreach ($array as $key => $val) {
9329 // Convert objects to arrays, in_array() does not support objects.
9330 if (is_object($val)) {
9331 $val = (array)$val;
9334 if (!in_array($val, $tmp)) {
9335 $tmp[] = $val;
9336 } else {
9337 $duplicatekeys[] = $key;
9341 foreach ($duplicatekeys as $key) {
9342 unset($array[$key]);
9345 return $keepkeyassoc ? $array : array_values($array);
9349 * Is a userid the primary administrator?
9351 * @param int $userid int id of user to check
9352 * @return boolean
9354 function is_primary_admin($userid) {
9355 $primaryadmin = get_admin();
9357 if ($userid == $primaryadmin->id) {
9358 return true;
9359 } else {
9360 return false;
9365 * Returns the site identifier
9367 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9369 function get_site_identifier() {
9370 global $CFG;
9371 // Check to see if it is missing. If so, initialise it.
9372 if (empty($CFG->siteidentifier)) {
9373 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9375 // Return it.
9376 return $CFG->siteidentifier;
9380 * Check whether the given password has no more than the specified
9381 * number of consecutive identical characters.
9383 * @param string $password password to be checked against the password policy
9384 * @param integer $maxchars maximum number of consecutive identical characters
9385 * @return bool
9387 function check_consecutive_identical_characters($password, $maxchars) {
9389 if ($maxchars < 1) {
9390 return true; // Zero 0 is to disable this check.
9392 if (strlen($password) <= $maxchars) {
9393 return true; // Too short to fail this test.
9396 $previouschar = '';
9397 $consecutivecount = 1;
9398 foreach (str_split($password) as $char) {
9399 if ($char != $previouschar) {
9400 $consecutivecount = 1;
9401 } else {
9402 $consecutivecount++;
9403 if ($consecutivecount > $maxchars) {
9404 return false; // Check failed already.
9408 $previouschar = $char;
9411 return true;
9415 * Helper function to do partial function binding.
9416 * so we can use it for preg_replace_callback, for example
9417 * this works with php functions, user functions, static methods and class methods
9418 * it returns you a callback that you can pass on like so:
9420 * $callback = partial('somefunction', $arg1, $arg2);
9421 * or
9422 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9423 * or even
9424 * $obj = new someclass();
9425 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9427 * and then the arguments that are passed through at calltime are appended to the argument list.
9429 * @param mixed $function a php callback
9430 * @param mixed $arg1,... $argv arguments to partially bind with
9431 * @return array Array callback
9433 function partial() {
9434 if (!class_exists('partial')) {
9436 * Used to manage function binding.
9437 * @copyright 2009 Penny Leach
9438 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9440 class partial{
9441 /** @var array */
9442 public $values = array();
9443 /** @var string The function to call as a callback. */
9444 public $func;
9446 * Constructor
9447 * @param string $func
9448 * @param array $args
9450 public function __construct($func, $args) {
9451 $this->values = $args;
9452 $this->func = $func;
9455 * Calls the callback function.
9456 * @return mixed
9458 public function method() {
9459 $args = func_get_args();
9460 return call_user_func_array($this->func, array_merge($this->values, $args));
9464 $args = func_get_args();
9465 $func = array_shift($args);
9466 $p = new partial($func, $args);
9467 return array($p, 'method');
9471 * helper function to load up and initialise the mnet environment
9472 * this must be called before you use mnet functions.
9474 * @return mnet_environment the equivalent of old $MNET global
9476 function get_mnet_environment() {
9477 global $CFG;
9478 require_once($CFG->dirroot . '/mnet/lib.php');
9479 static $instance = null;
9480 if (empty($instance)) {
9481 $instance = new mnet_environment();
9482 $instance->init();
9484 return $instance;
9488 * during xmlrpc server code execution, any code wishing to access
9489 * information about the remote peer must use this to get it.
9491 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9493 function get_mnet_remote_client() {
9494 if (!defined('MNET_SERVER')) {
9495 debugging(get_string('notinxmlrpcserver', 'mnet'));
9496 return false;
9498 global $MNET_REMOTE_CLIENT;
9499 if (isset($MNET_REMOTE_CLIENT)) {
9500 return $MNET_REMOTE_CLIENT;
9502 return false;
9506 * during the xmlrpc server code execution, this will be called
9507 * to setup the object returned by {@link get_mnet_remote_client}
9509 * @param mnet_remote_client $client the client to set up
9510 * @throws moodle_exception
9512 function set_mnet_remote_client($client) {
9513 if (!defined('MNET_SERVER')) {
9514 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9516 global $MNET_REMOTE_CLIENT;
9517 $MNET_REMOTE_CLIENT = $client;
9521 * return the jump url for a given remote user
9522 * this is used for rewriting forum post links in emails, etc
9524 * @param stdclass $user the user to get the idp url for
9526 function mnet_get_idp_jump_url($user) {
9527 global $CFG;
9529 static $mnetjumps = array();
9530 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9531 $idp = mnet_get_peer_host($user->mnethostid);
9532 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9533 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9535 return $mnetjumps[$user->mnethostid];
9539 * Gets the homepage to use for the current user
9541 * @return int One of HOMEPAGE_*
9543 function get_home_page() {
9544 global $CFG;
9546 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9547 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9548 return HOMEPAGE_MY;
9549 } else {
9550 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9553 return HOMEPAGE_SITE;
9557 * Gets the name of a course to be displayed when showing a list of courses.
9558 * By default this is just $course->fullname but user can configure it. The
9559 * result of this function should be passed through print_string.
9560 * @param stdClass|course_in_list $course Moodle course object
9561 * @return string Display name of course (either fullname or short + fullname)
9563 function get_course_display_name_for_list($course) {
9564 global $CFG;
9565 if (!empty($CFG->courselistshortnames)) {
9566 if (!($course instanceof stdClass)) {
9567 $course = (object)convert_to_array($course);
9569 return get_string('courseextendednamedisplay', '', $course);
9570 } else {
9571 return $course->fullname;
9576 * The lang_string class
9578 * This special class is used to create an object representation of a string request.
9579 * It is special because processing doesn't occur until the object is first used.
9580 * The class was created especially to aid performance in areas where strings were
9581 * required to be generated but were not necessarily used.
9582 * As an example the admin tree when generated uses over 1500 strings, of which
9583 * normally only 1/3 are ever actually printed at any time.
9584 * The performance advantage is achieved by not actually processing strings that
9585 * arn't being used, as such reducing the processing required for the page.
9587 * How to use the lang_string class?
9588 * There are two methods of using the lang_string class, first through the
9589 * forth argument of the get_string function, and secondly directly.
9590 * The following are examples of both.
9591 * 1. Through get_string calls e.g.
9592 * $string = get_string($identifier, $component, $a, true);
9593 * $string = get_string('yes', 'moodle', null, true);
9594 * 2. Direct instantiation
9595 * $string = new lang_string($identifier, $component, $a, $lang);
9596 * $string = new lang_string('yes');
9598 * How do I use a lang_string object?
9599 * The lang_string object makes use of a magic __toString method so that you
9600 * are able to use the object exactly as you would use a string in most cases.
9601 * This means you are able to collect it into a variable and then directly
9602 * echo it, or concatenate it into another string, or similar.
9603 * The other thing you can do is manually get the string by calling the
9604 * lang_strings out method e.g.
9605 * $string = new lang_string('yes');
9606 * $string->out();
9607 * Also worth noting is that the out method can take one argument, $lang which
9608 * allows the developer to change the language on the fly.
9610 * When should I use a lang_string object?
9611 * The lang_string object is designed to be used in any situation where a
9612 * string may not be needed, but needs to be generated.
9613 * The admin tree is a good example of where lang_string objects should be
9614 * used.
9615 * A more practical example would be any class that requries strings that may
9616 * not be printed (after all classes get renderer by renderers and who knows
9617 * what they will do ;))
9619 * When should I not use a lang_string object?
9620 * Don't use lang_strings when you are going to use a string immediately.
9621 * There is no need as it will be processed immediately and there will be no
9622 * advantage, and in fact perhaps a negative hit as a class has to be
9623 * instantiated for a lang_string object, however get_string won't require
9624 * that.
9626 * Limitations:
9627 * 1. You cannot use a lang_string object as an array offset. Doing so will
9628 * result in PHP throwing an error. (You can use it as an object property!)
9630 * @package core
9631 * @category string
9632 * @copyright 2011 Sam Hemelryk
9633 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9635 class lang_string {
9637 /** @var string The strings identifier */
9638 protected $identifier;
9639 /** @var string The strings component. Default '' */
9640 protected $component = '';
9641 /** @var array|stdClass Any arguments required for the string. Default null */
9642 protected $a = null;
9643 /** @var string The language to use when processing the string. Default null */
9644 protected $lang = null;
9646 /** @var string The processed string (once processed) */
9647 protected $string = null;
9650 * A special boolean. If set to true then the object has been woken up and
9651 * cannot be regenerated. If this is set then $this->string MUST be used.
9652 * @var bool
9654 protected $forcedstring = false;
9657 * Constructs a lang_string object
9659 * This function should do as little processing as possible to ensure the best
9660 * performance for strings that won't be used.
9662 * @param string $identifier The strings identifier
9663 * @param string $component The strings component
9664 * @param stdClass|array $a Any arguments the string requires
9665 * @param string $lang The language to use when processing the string.
9666 * @throws coding_exception
9668 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9669 if (empty($component)) {
9670 $component = 'moodle';
9673 $this->identifier = $identifier;
9674 $this->component = $component;
9675 $this->lang = $lang;
9677 // We MUST duplicate $a to ensure that it if it changes by reference those
9678 // changes are not carried across.
9679 // To do this we always ensure $a or its properties/values are strings
9680 // and that any properties/values that arn't convertable are forgotten.
9681 if (!empty($a)) {
9682 if (is_scalar($a)) {
9683 $this->a = $a;
9684 } else if ($a instanceof lang_string) {
9685 $this->a = $a->out();
9686 } else if (is_object($a) or is_array($a)) {
9687 $a = (array)$a;
9688 $this->a = array();
9689 foreach ($a as $key => $value) {
9690 // Make sure conversion errors don't get displayed (results in '').
9691 if (is_array($value)) {
9692 $this->a[$key] = '';
9693 } else if (is_object($value)) {
9694 if (method_exists($value, '__toString')) {
9695 $this->a[$key] = $value->__toString();
9696 } else {
9697 $this->a[$key] = '';
9699 } else {
9700 $this->a[$key] = (string)$value;
9706 if (debugging(false, DEBUG_DEVELOPER)) {
9707 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9708 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9710 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9711 throw new coding_exception('Invalid string compontent. Please check your string definition');
9713 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9714 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9720 * Processes the string.
9722 * This function actually processes the string, stores it in the string property
9723 * and then returns it.
9724 * You will notice that this function is VERY similar to the get_string method.
9725 * That is because it is pretty much doing the same thing.
9726 * However as this function is an upgrade it isn't as tolerant to backwards
9727 * compatibility.
9729 * @return string
9730 * @throws coding_exception
9732 protected function get_string() {
9733 global $CFG;
9735 // Check if we need to process the string.
9736 if ($this->string === null) {
9737 // Check the quality of the identifier.
9738 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9739 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);
9742 // Process the string.
9743 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9744 // Debugging feature lets you display string identifier and component.
9745 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9746 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9749 // Return the string.
9750 return $this->string;
9754 * Returns the string
9756 * @param string $lang The langauge to use when processing the string
9757 * @return string
9759 public function out($lang = null) {
9760 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9761 if ($this->forcedstring) {
9762 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9763 return $this->get_string();
9765 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9766 return $translatedstring->out();
9768 return $this->get_string();
9772 * Magic __toString method for printing a string
9774 * @return string
9776 public function __toString() {
9777 return $this->get_string();
9781 * Magic __set_state method used for var_export
9783 * @return string
9785 public function __set_state() {
9786 return $this->get_string();
9790 * Prepares the lang_string for sleep and stores only the forcedstring and
9791 * string properties... the string cannot be regenerated so we need to ensure
9792 * it is generated for this.
9794 * @return string
9796 public function __sleep() {
9797 $this->get_string();
9798 $this->forcedstring = true;
9799 return array('forcedstring', 'string', 'lang');