MDL-45445 events: trivial changes
[moodle.git] / lib / moodlelib.php
blob3b76dd9725550320777016ff2961e816812a0a21
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 = str_replace(" " , "", $param);
1172 // Convert uppercase to lowercase MDL-16919.
1173 $param = core_text::strtolower($param);
1174 if (empty($CFG->extendedusernamechars)) {
1175 // Regular expression, eliminate all chars EXCEPT:
1176 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1177 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1179 return $param;
1181 case PARAM_EMAIL:
1182 $param = fix_utf8($param);
1183 if (validate_email($param)) {
1184 return $param;
1185 } else {
1186 return '';
1189 case PARAM_STRINGID:
1190 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1191 return $param;
1192 } else {
1193 return '';
1196 case PARAM_TIMEZONE:
1197 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1198 $param = fix_utf8($param);
1199 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1200 if (preg_match($timezonepattern, $param)) {
1201 return $param;
1202 } else {
1203 return '';
1206 default:
1207 // Doh! throw error, switched parameters in optional_param or another serious problem.
1208 print_error("unknownparamtype", '', '', $type);
1213 * Makes sure the data is using valid utf8, invalid characters are discarded.
1215 * Note: this function is not intended for full objects with methods and private properties.
1217 * @param mixed $value
1218 * @return mixed with proper utf-8 encoding
1220 function fix_utf8($value) {
1221 if (is_null($value) or $value === '') {
1222 return $value;
1224 } else if (is_string($value)) {
1225 if ((string)(int)$value === $value) {
1226 // Shortcut.
1227 return $value;
1229 // No null bytes expected in our data, so let's remove it.
1230 $value = str_replace("\0", '', $value);
1232 // Note: this duplicates min_fix_utf8() intentionally.
1233 static $buggyiconv = null;
1234 if ($buggyiconv === null) {
1235 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1238 if ($buggyiconv) {
1239 if (function_exists('mb_convert_encoding')) {
1240 $subst = mb_substitute_character();
1241 mb_substitute_character('');
1242 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1243 mb_substitute_character($subst);
1245 } else {
1246 // Warn admins on admin/index.php page.
1247 $result = $value;
1250 } else {
1251 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1254 return $result;
1256 } else if (is_array($value)) {
1257 foreach ($value as $k => $v) {
1258 $value[$k] = fix_utf8($v);
1260 return $value;
1262 } else if (is_object($value)) {
1263 // Do not modify original.
1264 $value = clone($value);
1265 foreach ($value as $k => $v) {
1266 $value->$k = fix_utf8($v);
1268 return $value;
1270 } else {
1271 // This is some other type, no utf-8 here.
1272 return $value;
1277 * Return true if given value is integer or string with integer value
1279 * @param mixed $value String or Int
1280 * @return bool true if number, false if not
1282 function is_number($value) {
1283 if (is_int($value)) {
1284 return true;
1285 } else if (is_string($value)) {
1286 return ((string)(int)$value) === $value;
1287 } else {
1288 return false;
1293 * Returns host part from url.
1295 * @param string $url full url
1296 * @return string host, null if not found
1298 function get_host_from_url($url) {
1299 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1300 if ($matches) {
1301 return $matches[1];
1303 return null;
1307 * Tests whether anything was returned by text editor
1309 * This function is useful for testing whether something you got back from
1310 * the HTML editor actually contains anything. Sometimes the HTML editor
1311 * appear to be empty, but actually you get back a <br> tag or something.
1313 * @param string $string a string containing HTML.
1314 * @return boolean does the string contain any actual content - that is text,
1315 * images, objects, etc.
1317 function html_is_blank($string) {
1318 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1322 * Set a key in global configuration
1324 * Set a key/value pair in both this session's {@link $CFG} global variable
1325 * and in the 'config' database table for future sessions.
1327 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1328 * In that case it doesn't affect $CFG.
1330 * A NULL value will delete the entry.
1332 * @param string $name the key to set
1333 * @param string $value the value to set (without magic quotes)
1334 * @param string $plugin (optional) the plugin scope, default null
1335 * @return bool true or exception
1337 function set_config($name, $value, $plugin=null) {
1338 global $CFG, $DB;
1340 if (empty($plugin)) {
1341 if (!array_key_exists($name, $CFG->config_php_settings)) {
1342 // So it's defined for this invocation at least.
1343 if (is_null($value)) {
1344 unset($CFG->$name);
1345 } else {
1346 // Settings from db are always strings.
1347 $CFG->$name = (string)$value;
1351 if ($DB->get_field('config', 'name', array('name' => $name))) {
1352 if ($value === null) {
1353 $DB->delete_records('config', array('name' => $name));
1354 } else {
1355 $DB->set_field('config', 'value', $value, array('name' => $name));
1357 } else {
1358 if ($value !== null) {
1359 $config = new stdClass();
1360 $config->name = $name;
1361 $config->value = $value;
1362 $DB->insert_record('config', $config, false);
1365 if ($name === 'siteidentifier') {
1366 cache_helper::update_site_identifier($value);
1368 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1369 } else {
1370 // Plugin scope.
1371 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1372 if ($value===null) {
1373 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1374 } else {
1375 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1377 } else {
1378 if ($value !== null) {
1379 $config = new stdClass();
1380 $config->plugin = $plugin;
1381 $config->name = $name;
1382 $config->value = $value;
1383 $DB->insert_record('config_plugins', $config, false);
1386 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1389 return true;
1393 * Get configuration values from the global config table
1394 * or the config_plugins table.
1396 * If called with one parameter, it will load all the config
1397 * variables for one plugin, and return them as an object.
1399 * If called with 2 parameters it will return a string single
1400 * value or false if the value is not found.
1402 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1403 * that we need only fetch it once per request.
1404 * @param string $plugin full component name
1405 * @param string $name default null
1406 * @return mixed hash-like object or single value, return false no config found
1407 * @throws dml_exception
1409 function get_config($plugin, $name = null) {
1410 global $CFG, $DB;
1412 static $siteidentifier = null;
1414 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1415 $forced =& $CFG->config_php_settings;
1416 $iscore = true;
1417 $plugin = 'core';
1418 } else {
1419 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1420 $forced =& $CFG->forced_plugin_settings[$plugin];
1421 } else {
1422 $forced = array();
1424 $iscore = false;
1427 if ($siteidentifier === null) {
1428 try {
1429 // This may fail during installation.
1430 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1431 // install the database.
1432 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1433 } catch (dml_exception $ex) {
1434 // Set siteidentifier to false. We don't want to trip this continually.
1435 $siteidentifier = false;
1436 throw $ex;
1440 if (!empty($name)) {
1441 if (array_key_exists($name, $forced)) {
1442 return (string)$forced[$name];
1443 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1444 return $siteidentifier;
1448 $cache = cache::make('core', 'config');
1449 $result = $cache->get($plugin);
1450 if ($result === false) {
1451 // The user is after a recordset.
1452 if (!$iscore) {
1453 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1454 } else {
1455 // This part is not really used any more, but anyway...
1456 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1458 $cache->set($plugin, $result);
1461 if (!empty($name)) {
1462 if (array_key_exists($name, $result)) {
1463 return $result[$name];
1465 return false;
1468 if ($plugin === 'core') {
1469 $result['siteidentifier'] = $siteidentifier;
1472 foreach ($forced as $key => $value) {
1473 if (is_null($value) or is_array($value) or is_object($value)) {
1474 // We do not want any extra mess here, just real settings that could be saved in db.
1475 unset($result[$key]);
1476 } else {
1477 // Convert to string as if it went through the DB.
1478 $result[$key] = (string)$value;
1482 return (object)$result;
1486 * Removes a key from global configuration.
1488 * @param string $name the key to set
1489 * @param string $plugin (optional) the plugin scope
1490 * @return boolean whether the operation succeeded.
1492 function unset_config($name, $plugin=null) {
1493 global $CFG, $DB;
1495 if (empty($plugin)) {
1496 unset($CFG->$name);
1497 $DB->delete_records('config', array('name' => $name));
1498 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1499 } else {
1500 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1501 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1504 return true;
1508 * Remove all the config variables for a given plugin.
1510 * NOTE: this function is called from lib/db/upgrade.php
1512 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1513 * @return boolean whether the operation succeeded.
1515 function unset_all_config_for_plugin($plugin) {
1516 global $DB;
1517 // Delete from the obvious config_plugins first.
1518 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1519 // Next delete any suspect settings from config.
1520 $like = $DB->sql_like('name', '?', true, true, false, '|');
1521 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1522 $DB->delete_records_select('config', $like, $params);
1523 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1524 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1526 return true;
1530 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1532 * All users are verified if they still have the necessary capability.
1534 * @param string $value the value of the config setting.
1535 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1536 * @param bool $includeadmins include administrators.
1537 * @return array of user objects.
1539 function get_users_from_config($value, $capability, $includeadmins = true) {
1540 if (empty($value) or $value === '$@NONE@$') {
1541 return array();
1544 // We have to make sure that users still have the necessary capability,
1545 // it should be faster to fetch them all first and then test if they are present
1546 // instead of validating them one-by-one.
1547 $users = get_users_by_capability(context_system::instance(), $capability);
1548 if ($includeadmins) {
1549 $admins = get_admins();
1550 foreach ($admins as $admin) {
1551 $users[$admin->id] = $admin;
1555 if ($value === '$@ALL@$') {
1556 return $users;
1559 $result = array(); // Result in correct order.
1560 $allowed = explode(',', $value);
1561 foreach ($allowed as $uid) {
1562 if (isset($users[$uid])) {
1563 $user = $users[$uid];
1564 $result[$user->id] = $user;
1568 return $result;
1573 * Invalidates browser caches and cached data in temp.
1575 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1576 * {@link phpunit_util::reset_dataroot()}
1578 * @return void
1580 function purge_all_caches() {
1581 global $CFG, $DB;
1583 reset_text_filters_cache();
1584 js_reset_all_caches();
1585 theme_reset_all_caches();
1586 get_string_manager()->reset_caches();
1587 core_text::reset_caches();
1588 if (class_exists('core_plugin_manager')) {
1589 core_plugin_manager::reset_caches();
1592 // Bump up cacherev field for all courses.
1593 try {
1594 increment_revision_number('course', 'cacherev', '');
1595 } catch (moodle_exception $e) {
1596 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1599 $DB->reset_caches();
1600 cache_helper::purge_all();
1602 // Purge all other caches: rss, simplepie, etc.
1603 remove_dir($CFG->cachedir.'', true);
1605 // Make sure cache dir is writable, throws exception if not.
1606 make_cache_directory('');
1608 // This is the only place where we purge local caches, we are only adding files there.
1609 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1610 remove_dir($CFG->localcachedir, true);
1611 set_config('localcachedirpurged', time());
1612 make_localcache_directory('', true);
1613 \core\task\manager::clear_static_caches();
1617 * Get volatile flags
1619 * @param string $type
1620 * @param int $changedsince default null
1621 * @return array records array
1623 function get_cache_flags($type, $changedsince = null) {
1624 global $DB;
1626 $params = array('type' => $type, 'expiry' => time());
1627 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1628 if ($changedsince !== null) {
1629 $params['changedsince'] = $changedsince;
1630 $sqlwhere .= " AND timemodified > :changedsince";
1632 $cf = array();
1633 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1634 foreach ($flags as $flag) {
1635 $cf[$flag->name] = $flag->value;
1638 return $cf;
1642 * Get volatile flags
1644 * @param string $type
1645 * @param string $name
1646 * @param int $changedsince default null
1647 * @return string|false The cache flag value or false
1649 function get_cache_flag($type, $name, $changedsince=null) {
1650 global $DB;
1652 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1654 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1655 if ($changedsince !== null) {
1656 $params['changedsince'] = $changedsince;
1657 $sqlwhere .= " AND timemodified > :changedsince";
1660 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1664 * Set a volatile flag
1666 * @param string $type the "type" namespace for the key
1667 * @param string $name the key to set
1668 * @param string $value the value to set (without magic quotes) - null will remove the flag
1669 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1670 * @return bool Always returns true
1672 function set_cache_flag($type, $name, $value, $expiry = null) {
1673 global $DB;
1675 $timemodified = time();
1676 if ($expiry === null || $expiry < $timemodified) {
1677 $expiry = $timemodified + 24 * 60 * 60;
1678 } else {
1679 $expiry = (int)$expiry;
1682 if ($value === null) {
1683 unset_cache_flag($type, $name);
1684 return true;
1687 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1688 // This is a potential problem in DEBUG_DEVELOPER.
1689 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1690 return true; // No need to update.
1692 $f->value = $value;
1693 $f->expiry = $expiry;
1694 $f->timemodified = $timemodified;
1695 $DB->update_record('cache_flags', $f);
1696 } else {
1697 $f = new stdClass();
1698 $f->flagtype = $type;
1699 $f->name = $name;
1700 $f->value = $value;
1701 $f->expiry = $expiry;
1702 $f->timemodified = $timemodified;
1703 $DB->insert_record('cache_flags', $f);
1705 return true;
1709 * Removes a single volatile flag
1711 * @param string $type the "type" namespace for the key
1712 * @param string $name the key to set
1713 * @return bool
1715 function unset_cache_flag($type, $name) {
1716 global $DB;
1717 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1718 return true;
1722 * Garbage-collect volatile flags
1724 * @return bool Always returns true
1726 function gc_cache_flags() {
1727 global $DB;
1728 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1729 return true;
1732 // USER PREFERENCE API.
1735 * Refresh user preference cache. This is used most often for $USER
1736 * object that is stored in session, but it also helps with performance in cron script.
1738 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1740 * @package core
1741 * @category preference
1742 * @access public
1743 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1744 * @param int $cachelifetime Cache life time on the current page (in seconds)
1745 * @throws coding_exception
1746 * @return null
1748 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1749 global $DB;
1750 // Static cache, we need to check on each page load, not only every 2 minutes.
1751 static $loadedusers = array();
1753 if (!isset($user->id)) {
1754 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1757 if (empty($user->id) or isguestuser($user->id)) {
1758 // No permanent storage for not-logged-in users and guest.
1759 if (!isset($user->preference)) {
1760 $user->preference = array();
1762 return;
1765 $timenow = time();
1767 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1768 // Already loaded at least once on this page. Are we up to date?
1769 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1770 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1771 return;
1773 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1774 // No change since the lastcheck on this page.
1775 $user->preference['_lastloaded'] = $timenow;
1776 return;
1780 // OK, so we have to reload all preferences.
1781 $loadedusers[$user->id] = true;
1782 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1783 $user->preference['_lastloaded'] = $timenow;
1787 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1789 * NOTE: internal function, do not call from other code.
1791 * @package core
1792 * @access private
1793 * @param integer $userid the user whose prefs were changed.
1795 function mark_user_preferences_changed($userid) {
1796 global $CFG;
1798 if (empty($userid) or isguestuser($userid)) {
1799 // No cache flags for guest and not-logged-in users.
1800 return;
1803 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1807 * Sets a preference for the specified user.
1809 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1811 * @package core
1812 * @category preference
1813 * @access public
1814 * @param string $name The key to set as preference for the specified user
1815 * @param string $value The value to set for the $name key in the specified user's
1816 * record, null means delete current value.
1817 * @param stdClass|int|null $user A moodle user object or id, null means current user
1818 * @throws coding_exception
1819 * @return bool Always true or exception
1821 function set_user_preference($name, $value, $user = null) {
1822 global $USER, $DB;
1824 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1825 throw new coding_exception('Invalid preference name in set_user_preference() call');
1828 if (is_null($value)) {
1829 // Null means delete current.
1830 return unset_user_preference($name, $user);
1831 } else if (is_object($value)) {
1832 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1833 } else if (is_array($value)) {
1834 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1836 // Value column maximum length is 1333 characters.
1837 $value = (string)$value;
1838 if (core_text::strlen($value) > 1333) {
1839 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1842 if (is_null($user)) {
1843 $user = $USER;
1844 } else if (isset($user->id)) {
1845 // It is a valid object.
1846 } else if (is_numeric($user)) {
1847 $user = (object)array('id' => (int)$user);
1848 } else {
1849 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1852 check_user_preferences_loaded($user);
1854 if (empty($user->id) or isguestuser($user->id)) {
1855 // No permanent storage for not-logged-in users and guest.
1856 $user->preference[$name] = $value;
1857 return true;
1860 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1861 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1862 // Preference already set to this value.
1863 return true;
1865 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1867 } else {
1868 $preference = new stdClass();
1869 $preference->userid = $user->id;
1870 $preference->name = $name;
1871 $preference->value = $value;
1872 $DB->insert_record('user_preferences', $preference);
1875 // Update value in cache.
1876 $user->preference[$name] = $value;
1878 // Set reload flag for other sessions.
1879 mark_user_preferences_changed($user->id);
1881 return true;
1885 * Sets a whole array of preferences for the current user
1887 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1889 * @package core
1890 * @category preference
1891 * @access public
1892 * @param array $prefarray An array of key/value pairs to be set
1893 * @param stdClass|int|null $user A moodle user object or id, null means current user
1894 * @return bool Always true or exception
1896 function set_user_preferences(array $prefarray, $user = null) {
1897 foreach ($prefarray as $name => $value) {
1898 set_user_preference($name, $value, $user);
1900 return true;
1904 * Unsets a preference completely by deleting it from the database
1906 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1908 * @package core
1909 * @category preference
1910 * @access public
1911 * @param string $name The key to unset as preference for the specified user
1912 * @param stdClass|int|null $user A moodle user object or id, null means current user
1913 * @throws coding_exception
1914 * @return bool Always true or exception
1916 function unset_user_preference($name, $user = null) {
1917 global $USER, $DB;
1919 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1920 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1923 if (is_null($user)) {
1924 $user = $USER;
1925 } else if (isset($user->id)) {
1926 // It is a valid object.
1927 } else if (is_numeric($user)) {
1928 $user = (object)array('id' => (int)$user);
1929 } else {
1930 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1933 check_user_preferences_loaded($user);
1935 if (empty($user->id) or isguestuser($user->id)) {
1936 // No permanent storage for not-logged-in user and guest.
1937 unset($user->preference[$name]);
1938 return true;
1941 // Delete from DB.
1942 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1944 // Delete the preference from cache.
1945 unset($user->preference[$name]);
1947 // Set reload flag for other sessions.
1948 mark_user_preferences_changed($user->id);
1950 return true;
1954 * Used to fetch user preference(s)
1956 * If no arguments are supplied this function will return
1957 * all of the current user preferences as an array.
1959 * If a name is specified then this function
1960 * attempts to return that particular preference value. If
1961 * none is found, then the optional value $default is returned,
1962 * otherwise null.
1964 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1966 * @package core
1967 * @category preference
1968 * @access public
1969 * @param string $name Name of the key to use in finding a preference value
1970 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1971 * @param stdClass|int|null $user A moodle user object or id, null means current user
1972 * @throws coding_exception
1973 * @return string|mixed|null A string containing the value of a single preference. An
1974 * array with all of the preferences or null
1976 function get_user_preferences($name = null, $default = null, $user = null) {
1977 global $USER;
1979 if (is_null($name)) {
1980 // All prefs.
1981 } else if (is_numeric($name) or $name === '_lastloaded') {
1982 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1985 if (is_null($user)) {
1986 $user = $USER;
1987 } else if (isset($user->id)) {
1988 // Is a valid object.
1989 } else if (is_numeric($user)) {
1990 $user = (object)array('id' => (int)$user);
1991 } else {
1992 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1995 check_user_preferences_loaded($user);
1997 if (empty($name)) {
1998 // All values.
1999 return $user->preference;
2000 } else if (isset($user->preference[$name])) {
2001 // The single string value.
2002 return $user->preference[$name];
2003 } else {
2004 // Default value (null if not specified).
2005 return $default;
2009 // FUNCTIONS FOR HANDLING TIME.
2012 * Given date parts in user time produce a GMT timestamp.
2014 * @package core
2015 * @category time
2016 * @param int $year The year part to create timestamp of
2017 * @param int $month The month part to create timestamp of
2018 * @param int $day The day part to create timestamp of
2019 * @param int $hour The hour part to create timestamp of
2020 * @param int $minute The minute part to create timestamp of
2021 * @param int $second The second part to create timestamp of
2022 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2023 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2024 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2025 * applied only if timezone is 99 or string.
2026 * @return int GMT timestamp
2028 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2030 // Save input timezone, required for dst offset check.
2031 $passedtimezone = $timezone;
2033 $timezone = get_user_timezone_offset($timezone);
2035 if (abs($timezone) > 13) {
2036 // Server time.
2037 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2038 } else {
2039 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2040 $time = usertime($time, $timezone);
2042 // Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
2043 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
2044 $time -= dst_offset_on($time, $passedtimezone);
2048 return $time;
2053 * Format a date/time (seconds) as weeks, days, hours etc as needed
2055 * Given an amount of time in seconds, returns string
2056 * formatted nicely as weeks, days, hours etc as needed
2058 * @package core
2059 * @category time
2060 * @uses MINSECS
2061 * @uses HOURSECS
2062 * @uses DAYSECS
2063 * @uses YEARSECS
2064 * @param int $totalsecs Time in seconds
2065 * @param stdClass $str Should be a time object
2066 * @return string A nicely formatted date/time string
2068 function format_time($totalsecs, $str = null) {
2070 $totalsecs = abs($totalsecs);
2072 if (!$str) {
2073 // Create the str structure the slow way.
2074 $str = new stdClass();
2075 $str->day = get_string('day');
2076 $str->days = get_string('days');
2077 $str->hour = get_string('hour');
2078 $str->hours = get_string('hours');
2079 $str->min = get_string('min');
2080 $str->mins = get_string('mins');
2081 $str->sec = get_string('sec');
2082 $str->secs = get_string('secs');
2083 $str->year = get_string('year');
2084 $str->years = get_string('years');
2087 $years = floor($totalsecs/YEARSECS);
2088 $remainder = $totalsecs - ($years*YEARSECS);
2089 $days = floor($remainder/DAYSECS);
2090 $remainder = $totalsecs - ($days*DAYSECS);
2091 $hours = floor($remainder/HOURSECS);
2092 $remainder = $remainder - ($hours*HOURSECS);
2093 $mins = floor($remainder/MINSECS);
2094 $secs = $remainder - ($mins*MINSECS);
2096 $ss = ($secs == 1) ? $str->sec : $str->secs;
2097 $sm = ($mins == 1) ? $str->min : $str->mins;
2098 $sh = ($hours == 1) ? $str->hour : $str->hours;
2099 $sd = ($days == 1) ? $str->day : $str->days;
2100 $sy = ($years == 1) ? $str->year : $str->years;
2102 $oyears = '';
2103 $odays = '';
2104 $ohours = '';
2105 $omins = '';
2106 $osecs = '';
2108 if ($years) {
2109 $oyears = $years .' '. $sy;
2111 if ($days) {
2112 $odays = $days .' '. $sd;
2114 if ($hours) {
2115 $ohours = $hours .' '. $sh;
2117 if ($mins) {
2118 $omins = $mins .' '. $sm;
2120 if ($secs) {
2121 $osecs = $secs .' '. $ss;
2124 if ($years) {
2125 return trim($oyears .' '. $odays);
2127 if ($days) {
2128 return trim($odays .' '. $ohours);
2130 if ($hours) {
2131 return trim($ohours .' '. $omins);
2133 if ($mins) {
2134 return trim($omins .' '. $osecs);
2136 if ($secs) {
2137 return $osecs;
2139 return get_string('now');
2143 * Returns a formatted string that represents a date in user time.
2145 * @package core
2146 * @category time
2147 * @param int $date the timestamp in UTC, as obtained from the database.
2148 * @param string $format strftime format. You should probably get this using
2149 * get_string('strftime...', 'langconfig');
2150 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2151 * not 99 then daylight saving will not be added.
2152 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2153 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2154 * If false then the leading zero is maintained.
2155 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2156 * @return string the formatted date/time.
2158 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2159 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2160 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2164 * Returns a formatted date ensuring it is UTF-8.
2166 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2167 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2169 * This function does not do any calculation regarding the user preferences and should
2170 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2171 * to differentiate the use of server time or not (strftime() against gmstrftime()).
2173 * @param int $date the timestamp.
2174 * @param string $format strftime format.
2175 * @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2176 * @return string the formatted date/time.
2177 * @since Moodle 2.3.3
2179 function date_format_string($date, $format, $tz = 99) {
2180 global $CFG;
2182 $localewincharset = null;
2183 // Get the calendar type user is using.
2184 if ($CFG->ostype == 'WINDOWS') {
2185 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2186 $localewincharset = $calendartype->locale_win_charset();
2189 if (abs($tz) > 13) {
2190 if ($localewincharset) {
2191 $format = core_text::convert($format, 'utf-8', $localewincharset);
2192 $datestring = strftime($format, $date);
2193 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2194 } else {
2195 $datestring = strftime($format, $date);
2197 } else {
2198 if ($localewincharset) {
2199 $format = core_text::convert($format, 'utf-8', $localewincharset);
2200 $datestring = gmstrftime($format, $date);
2201 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2202 } else {
2203 $datestring = gmstrftime($format, $date);
2206 return $datestring;
2210 * Given a $time timestamp in GMT (seconds since epoch),
2211 * returns an array that represents the date in user time
2213 * @package core
2214 * @category time
2215 * @uses HOURSECS
2216 * @param int $time Timestamp in GMT
2217 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2218 * dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
2219 * @return array An array that represents the date in user time
2221 function usergetdate($time, $timezone=99) {
2223 // Save input timezone, required for dst offset check.
2224 $passedtimezone = $timezone;
2226 $timezone = get_user_timezone_offset($timezone);
2228 if (abs($timezone) > 13) {
2229 // Server time.
2230 return getdate($time);
2233 // Add daylight saving offset for string timezones only, as we can't get dst for
2234 // float values. if timezone is 99 (user default timezone), then try update dst.
2235 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2236 $time += dst_offset_on($time, $passedtimezone);
2239 $time += intval((float)$timezone * HOURSECS);
2241 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2243 // Be careful to ensure the returned array matches that produced by getdate() above.
2244 list(
2245 $getdate['month'],
2246 $getdate['weekday'],
2247 $getdate['yday'],
2248 $getdate['year'],
2249 $getdate['mon'],
2250 $getdate['wday'],
2251 $getdate['mday'],
2252 $getdate['hours'],
2253 $getdate['minutes'],
2254 $getdate['seconds']
2255 ) = explode('_', $datestring);
2257 // Set correct datatype to match with getdate().
2258 $getdate['seconds'] = (int)$getdate['seconds'];
2259 $getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
2260 $getdate['year'] = (int)$getdate['year'];
2261 $getdate['mon'] = (int)$getdate['mon'];
2262 $getdate['wday'] = (int)$getdate['wday'];
2263 $getdate['mday'] = (int)$getdate['mday'];
2264 $getdate['hours'] = (int)$getdate['hours'];
2265 $getdate['minutes'] = (int)$getdate['minutes'];
2266 return $getdate;
2270 * Given a GMT timestamp (seconds since epoch), offsets it by
2271 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2273 * @package core
2274 * @category time
2275 * @uses HOURSECS
2276 * @param int $date Timestamp in GMT
2277 * @param float|int|string $timezone timezone to calculate GMT time offset before
2278 * calculating user time, 99 is default user timezone
2279 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2280 * @return int
2282 function usertime($date, $timezone=99) {
2284 $timezone = get_user_timezone_offset($timezone);
2286 if (abs($timezone) > 13) {
2287 return $date;
2289 return $date - (int)($timezone * HOURSECS);
2293 * Given a time, return the GMT timestamp of the most recent midnight
2294 * for the current user.
2296 * @package core
2297 * @category time
2298 * @param int $date Timestamp in GMT
2299 * @param float|int|string $timezone timezone to calculate GMT time offset before
2300 * calculating user midnight time, 99 is default user timezone
2301 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2302 * @return int Returns a GMT timestamp
2304 function usergetmidnight($date, $timezone=99) {
2306 $userdate = usergetdate($date, $timezone);
2308 // Time of midnight of this user's day, in GMT.
2309 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2314 * Returns a string that prints the user's timezone
2316 * @package core
2317 * @category time
2318 * @param float|int|string $timezone timezone to calculate GMT time offset before
2319 * calculating user timezone, 99 is default user timezone
2320 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2321 * @return string
2323 function usertimezone($timezone=99) {
2325 $tz = get_user_timezone($timezone);
2327 if (!is_float($tz)) {
2328 return $tz;
2331 if (abs($tz) > 13) {
2332 // Server time.
2333 return get_string('serverlocaltime');
2336 if ($tz == intval($tz)) {
2337 // Don't show .0 for whole hours.
2338 $tz = intval($tz);
2341 if ($tz == 0) {
2342 return 'UTC';
2343 } else if ($tz > 0) {
2344 return 'UTC+'.$tz;
2345 } else {
2346 return 'UTC'.$tz;
2352 * Returns a float which represents the user's timezone difference from GMT in hours
2353 * Checks various settings and picks the most dominant of those which have a value
2355 * @package core
2356 * @category time
2357 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2358 * 99 is default user timezone
2359 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2360 * @return float
2362 function get_user_timezone_offset($tz = 99) {
2363 $tz = get_user_timezone($tz);
2365 if (is_float($tz)) {
2366 return $tz;
2367 } else {
2368 $tzrecord = get_timezone_record($tz);
2369 if (empty($tzrecord)) {
2370 return 99.0;
2372 return (float)$tzrecord->gmtoff / HOURMINS;
2377 * Returns an int which represents the systems's timezone difference from GMT in seconds
2379 * @package core
2380 * @category time
2381 * @param float|int|string $tz timezone for which offset is required.
2382 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2383 * @return int|bool if found, false is timezone 99 or error
2385 function get_timezone_offset($tz) {
2386 if ($tz == 99) {
2387 return false;
2390 if (is_numeric($tz)) {
2391 return intval($tz * 60*60);
2394 if (!$tzrecord = get_timezone_record($tz)) {
2395 return false;
2397 return intval($tzrecord->gmtoff * 60);
2401 * Returns a float or a string which denotes the user's timezone
2402 * 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)
2403 * means that for this timezone there are also DST rules to be taken into account
2404 * Checks various settings and picks the most dominant of those which have a value
2406 * @package core
2407 * @category time
2408 * @param float|int|string $tz timezone to calculate GMT time offset before
2409 * calculating user timezone, 99 is default user timezone
2410 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2411 * @return float|string
2413 function get_user_timezone($tz = 99) {
2414 global $USER, $CFG;
2416 $timezones = array(
2417 $tz,
2418 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2419 isset($USER->timezone) ? $USER->timezone : 99,
2420 isset($CFG->timezone) ? $CFG->timezone : 99,
2423 $tz = 99;
2425 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2426 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2427 $tz = $next['value'];
2429 return is_numeric($tz) ? (float) $tz : $tz;
2433 * Returns cached timezone record for given $timezonename
2435 * @package core
2436 * @param string $timezonename name of the timezone
2437 * @return stdClass|bool timezonerecord or false
2439 function get_timezone_record($timezonename) {
2440 global $DB;
2441 static $cache = null;
2443 if ($cache === null) {
2444 $cache = array();
2447 if (isset($cache[$timezonename])) {
2448 return $cache[$timezonename];
2451 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2452 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2456 * Build and store the users Daylight Saving Time (DST) table
2458 * @package core
2459 * @param int $fromyear Start year for the table, defaults to 1971
2460 * @param int $toyear End year for the table, defaults to 2035
2461 * @param int|float|string $strtimezone timezone to check if dst should be applied.
2462 * @return bool
2464 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2465 global $SESSION, $DB;
2467 $usertz = get_user_timezone($strtimezone);
2469 if (is_float($usertz)) {
2470 // Trivial timezone, no DST.
2471 return false;
2474 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2475 // We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
2476 unset($SESSION->dst_offsets);
2477 unset($SESSION->dst_range);
2480 if (!empty($SESSION->dst_offsets) && empty($fromyear) && empty($toyear)) {
2481 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
2482 // This will be the return path most of the time, pretty light computationally.
2483 return true;
2486 // Reaching here means we either need to extend our table or create it from scratch.
2488 // Remember which TZ we calculated these changes for.
2489 $SESSION->dst_offsettz = $usertz;
2491 if (empty($SESSION->dst_offsets)) {
2492 // If we 're creating from scratch, put the two guard elements in there.
2493 $SESSION->dst_offsets = array(1 => null, 0 => null);
2495 if (empty($SESSION->dst_range)) {
2496 // If creating from scratch.
2497 $from = max((empty($fromyear) ? intval(date('Y')) - 3 : $fromyear), 1971);
2498 $to = min((empty($toyear) ? intval(date('Y')) + 3 : $toyear), 2035);
2500 // Fill in the array with the extra years we need to process.
2501 $yearstoprocess = array();
2502 for ($i = $from; $i <= $to; ++$i) {
2503 $yearstoprocess[] = $i;
2506 // Take note of which years we have processed for future calls.
2507 $SESSION->dst_range = array($from, $to);
2508 } else {
2509 // If needing to extend the table, do the same.
2510 $yearstoprocess = array();
2512 $from = max((empty($fromyear) ? $SESSION->dst_range[0] : $fromyear), 1971);
2513 $to = min((empty($toyear) ? $SESSION->dst_range[1] : $toyear), 2035);
2515 if ($from < $SESSION->dst_range[0]) {
2516 // Take note of which years we need to process and then note that we have processed them for future calls.
2517 for ($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2518 $yearstoprocess[] = $i;
2520 $SESSION->dst_range[0] = $from;
2522 if ($to > $SESSION->dst_range[1]) {
2523 // Take note of which years we need to process and then note that we have processed them for future calls.
2524 for ($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2525 $yearstoprocess[] = $i;
2527 $SESSION->dst_range[1] = $to;
2531 if (empty($yearstoprocess)) {
2532 // This means that there was a call requesting a SMALLER range than we have already calculated.
2533 return true;
2536 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2537 // Also, the array is sorted in descending timestamp order!
2539 // Get DB data.
2541 static $presetscache = array();
2542 if (!isset($presetscache[$usertz])) {
2543 $presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
2544 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
2545 'std_startday, std_weekday, std_skipweeks, std_time');
2547 if (empty($presetscache[$usertz])) {
2548 return false;
2551 // Remove ending guard (first element of the array).
2552 reset($SESSION->dst_offsets);
2553 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2555 // Add all required change timestamps.
2556 foreach ($yearstoprocess as $y) {
2557 // Find the record which is in effect for the year $y.
2558 foreach ($presetscache[$usertz] as $year => $preset) {
2559 if ($year <= $y) {
2560 break;
2564 $changes = dst_changes_for_year($y, $preset);
2566 if ($changes === null) {
2567 continue;
2569 if ($changes['dst'] != 0) {
2570 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2572 if ($changes['std'] != 0) {
2573 $SESSION->dst_offsets[$changes['std']] = 0;
2577 // Put in a guard element at the top.
2578 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2579 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = null; // DAYSECS is arbitrary, any "small" number will do.
2581 // Sort again.
2582 krsort($SESSION->dst_offsets);
2584 return true;
2588 * Calculates the required DST change and returns a Timestamp Array
2590 * @package core
2591 * @category time
2592 * @uses HOURSECS
2593 * @uses MINSECS
2594 * @param int|string $year Int or String Year to focus on
2595 * @param object $timezone Instatiated Timezone object
2596 * @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
2598 function dst_changes_for_year($year, $timezone) {
2600 if ($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 &&
2601 $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2602 return null;
2605 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2606 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2608 list($dsthour, $dstmin) = explode(':', $timezone->dst_time);
2609 list($stdhour, $stdmin) = explode(':', $timezone->std_time);
2611 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2612 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2614 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2615 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2616 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2618 $timedst += $dsthour * HOURSECS + $dstmin * MINSECS;
2619 $timestd += $stdhour * HOURSECS + $stdmin * MINSECS;
2621 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2625 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2626 * - Note: Daylight saving only works for string timezones and not for float.
2628 * @package core
2629 * @category time
2630 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2631 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2632 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2633 * @return int
2635 function dst_offset_on($time, $strtimezone = null) {
2636 global $SESSION;
2638 if (!calculate_user_dst_table(null, null, $strtimezone) || empty($SESSION->dst_offsets)) {
2639 return 0;
2642 reset($SESSION->dst_offsets);
2643 while (list($from, $offset) = each($SESSION->dst_offsets)) {
2644 if ($from <= $time) {
2645 break;
2649 // This is the normal return path.
2650 if ($offset !== null) {
2651 return $offset;
2654 // Reaching this point means we haven't calculated far enough, do it now:
2655 // Calculate extra DST changes if needed and recurse. The recursion always
2656 // moves toward the stopping condition, so will always end.
2658 if ($from == 0) {
2659 // We need a year smaller than $SESSION->dst_range[0].
2660 if ($SESSION->dst_range[0] == 1971) {
2661 return 0;
2663 calculate_user_dst_table($SESSION->dst_range[0] - 5, null, $strtimezone);
2664 return dst_offset_on($time, $strtimezone);
2665 } else {
2666 // We need a year larger than $SESSION->dst_range[1].
2667 if ($SESSION->dst_range[1] == 2035) {
2668 return 0;
2670 calculate_user_dst_table(null, $SESSION->dst_range[1] + 5, $strtimezone);
2671 return dst_offset_on($time, $strtimezone);
2676 * Calculates when the day appears in specific month
2678 * @package core
2679 * @category time
2680 * @param int $startday starting day of the month
2681 * @param int $weekday The day when week starts (normally taken from user preferences)
2682 * @param int $month The month whose day is sought
2683 * @param int $year The year of the month whose day is sought
2684 * @return int
2686 function find_day_in_month($startday, $weekday, $month, $year) {
2687 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2689 $daysinmonth = days_in_month($month, $year);
2690 $daysinweek = count($calendartype->get_weekdays());
2692 if ($weekday == -1) {
2693 // Don't care about weekday, so return:
2694 // abs($startday) if $startday != -1
2695 // $daysinmonth otherwise.
2696 return ($startday == -1) ? $daysinmonth : abs($startday);
2699 // From now on we 're looking for a specific weekday.
2700 // Give "end of month" its actual value, since we know it.
2701 if ($startday == -1) {
2702 $startday = -1 * $daysinmonth;
2705 // Starting from day $startday, the sign is the direction.
2706 if ($startday < 1) {
2707 $startday = abs($startday);
2708 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2710 // This is the last such weekday of the month.
2711 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2712 if ($lastinmonth > $daysinmonth) {
2713 $lastinmonth -= $daysinweek;
2716 // Find the first such weekday <= $startday.
2717 while ($lastinmonth > $startday) {
2718 $lastinmonth -= $daysinweek;
2721 return $lastinmonth;
2722 } else {
2723 $indexweekday = dayofweek($startday, $month, $year);
2725 $diff = $weekday - $indexweekday;
2726 if ($diff < 0) {
2727 $diff += $daysinweek;
2730 // This is the first such weekday of the month equal to or after $startday.
2731 $firstfromindex = $startday + $diff;
2733 return $firstfromindex;
2738 * Calculate the number of days in a given month
2740 * @package core
2741 * @category time
2742 * @param int $month The month whose day count is sought
2743 * @param int $year The year of the month whose day count is sought
2744 * @return int
2746 function days_in_month($month, $year) {
2747 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2748 return $calendartype->get_num_days_in_month($year, $month);
2752 * Calculate the position in the week of a specific calendar day
2754 * @package core
2755 * @category time
2756 * @param int $day The day of the date whose position in the week is sought
2757 * @param int $month The month of the date whose position in the week is sought
2758 * @param int $year The year of the date whose position in the week is sought
2759 * @return int
2761 function dayofweek($day, $month, $year) {
2762 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2763 return $calendartype->get_weekday($year, $month, $day);
2766 // USER AUTHENTICATION AND LOGIN.
2769 * Returns full login url.
2771 * @return string login url
2773 function get_login_url() {
2774 global $CFG;
2776 $url = "$CFG->wwwroot/login/index.php";
2778 if (!empty($CFG->loginhttps)) {
2779 $url = str_replace('http:', 'https:', $url);
2782 return $url;
2786 * This function checks that the current user is logged in and has the
2787 * required privileges
2789 * This function checks that the current user is logged in, and optionally
2790 * whether they are allowed to be in a particular course and view a particular
2791 * course module.
2792 * If they are not logged in, then it redirects them to the site login unless
2793 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2794 * case they are automatically logged in as guests.
2795 * If $courseid is given and the user is not enrolled in that course then the
2796 * user is redirected to the course enrolment page.
2797 * If $cm is given and the course module is hidden and the user is not a teacher
2798 * in the course then the user is redirected to the course home page.
2800 * When $cm parameter specified, this function sets page layout to 'module'.
2801 * You need to change it manually later if some other layout needed.
2803 * @package core_access
2804 * @category access
2806 * @param mixed $courseorid id of the course or course object
2807 * @param bool $autologinguest default true
2808 * @param object $cm course module object
2809 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2810 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2811 * in order to keep redirects working properly. MDL-14495
2812 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2813 * @return mixed Void, exit, and die depending on path
2814 * @throws coding_exception
2815 * @throws require_login_exception
2817 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2818 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2820 // Must not redirect when byteserving already started.
2821 if (!empty($_SERVER['HTTP_RANGE'])) {
2822 $preventredirect = true;
2825 // Setup global $COURSE, themes, language and locale.
2826 if (!empty($courseorid)) {
2827 if (is_object($courseorid)) {
2828 $course = $courseorid;
2829 } else if ($courseorid == SITEID) {
2830 $course = clone($SITE);
2831 } else {
2832 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2834 if ($cm) {
2835 if ($cm->course != $course->id) {
2836 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2838 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2839 if (!($cm instanceof cm_info)) {
2840 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2841 // db queries so this is not really a performance concern, however it is obviously
2842 // better if you use get_fast_modinfo to get the cm before calling this.
2843 $modinfo = get_fast_modinfo($course);
2844 $cm = $modinfo->get_cm($cm->id);
2846 $PAGE->set_cm($cm, $course); // Set's up global $COURSE.
2847 $PAGE->set_pagelayout('incourse');
2848 } else {
2849 $PAGE->set_course($course); // Set's up global $COURSE.
2851 } else {
2852 // Do not touch global $COURSE via $PAGE->set_course(),
2853 // the reasons is we need to be able to call require_login() at any time!!
2854 $course = $SITE;
2855 if ($cm) {
2856 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2860 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2861 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2862 // risk leading the user back to the AJAX request URL.
2863 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2864 $setwantsurltome = false;
2867 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2868 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
2869 if ($setwantsurltome) {
2870 $SESSION->wantsurl = qualified_me();
2872 redirect(get_login_url());
2875 // If the user is not even logged in yet then make sure they are.
2876 if (!isloggedin()) {
2877 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2878 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2879 // Misconfigured site guest, just redirect to login page.
2880 redirect(get_login_url());
2881 exit; // Never reached.
2883 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2884 complete_user_login($guest);
2885 $USER->autologinguest = true;
2886 $SESSION->lang = $lang;
2887 } else {
2888 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2889 if ($preventredirect) {
2890 throw new require_login_exception('You are not logged in');
2893 if ($setwantsurltome) {
2894 $SESSION->wantsurl = qualified_me();
2896 if (!empty($_SERVER['HTTP_REFERER'])) {
2897 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2899 redirect(get_login_url());
2900 exit; // Never reached.
2904 // Loginas as redirection if needed.
2905 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2906 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2907 if ($USER->loginascontext->instanceid != $course->id) {
2908 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2913 // Check whether the user should be changing password (but only if it is REALLY them).
2914 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2915 $userauth = get_auth_plugin($USER->auth);
2916 if ($userauth->can_change_password() and !$preventredirect) {
2917 if ($setwantsurltome) {
2918 $SESSION->wantsurl = qualified_me();
2920 if ($changeurl = $userauth->change_password_url()) {
2921 // Use plugin custom url.
2922 redirect($changeurl);
2923 } else {
2924 // Use moodle internal method.
2925 if (empty($CFG->loginhttps)) {
2926 redirect($CFG->wwwroot .'/login/change_password.php');
2927 } else {
2928 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2929 redirect($wwwroot .'/login/change_password.php');
2932 } else {
2933 print_error('nopasswordchangeforced', 'auth');
2937 // Check that the user account is properly set up.
2938 if (user_not_fully_set_up($USER)) {
2939 if ($preventredirect) {
2940 throw new require_login_exception('User not fully set-up');
2942 if ($setwantsurltome) {
2943 $SESSION->wantsurl = qualified_me();
2945 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2948 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2949 sesskey();
2951 // Do not bother admins with any formalities.
2952 if (is_siteadmin()) {
2953 // Set accesstime or the user will appear offline which messes up messaging.
2954 user_accesstime_log($course->id);
2955 return;
2958 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2959 if (!$USER->policyagreed and !is_siteadmin()) {
2960 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2961 if ($preventredirect) {
2962 throw new require_login_exception('Policy not agreed');
2964 if ($setwantsurltome) {
2965 $SESSION->wantsurl = qualified_me();
2967 redirect($CFG->wwwroot .'/user/policy.php');
2968 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2969 if ($preventredirect) {
2970 throw new require_login_exception('Policy not agreed');
2972 if ($setwantsurltome) {
2973 $SESSION->wantsurl = qualified_me();
2975 redirect($CFG->wwwroot .'/user/policy.php');
2979 // Fetch the system context, the course context, and prefetch its child contexts.
2980 $sysctx = context_system::instance();
2981 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2982 if ($cm) {
2983 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2984 } else {
2985 $cmcontext = null;
2988 // If the site is currently under maintenance, then print a message.
2989 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2990 if ($preventredirect) {
2991 throw new require_login_exception('Maintenance in progress');
2994 print_maintenance_message();
2997 // Make sure the course itself is not hidden.
2998 if ($course->id == SITEID) {
2999 // Frontpage can not be hidden.
3000 } else {
3001 if (is_role_switched($course->id)) {
3002 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
3003 } else {
3004 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3005 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
3006 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
3007 if ($preventredirect) {
3008 throw new require_login_exception('Course is hidden');
3010 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3011 // the navigation will mess up when trying to find it.
3012 navigation_node::override_active_url(new moodle_url('/'));
3013 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3018 // Is the user enrolled?
3019 if ($course->id == SITEID) {
3020 // Everybody is enrolled on the frontpage.
3021 } else {
3022 if (\core\session\manager::is_loggedinas()) {
3023 // Make sure the REAL person can access this course first.
3024 $realuser = \core\session\manager::get_realuser();
3025 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
3026 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
3027 if ($preventredirect) {
3028 throw new require_login_exception('Invalid course login-as access');
3030 echo $OUTPUT->header();
3031 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
3035 $access = false;
3037 if (is_role_switched($course->id)) {
3038 // Ok, user had to be inside this course before the switch.
3039 $access = true;
3041 } else if (is_viewing($coursecontext, $USER)) {
3042 // Ok, no need to mess with enrol.
3043 $access = true;
3045 } else {
3046 if (isset($USER->enrol['enrolled'][$course->id])) {
3047 if ($USER->enrol['enrolled'][$course->id] > time()) {
3048 $access = true;
3049 if (isset($USER->enrol['tempguest'][$course->id])) {
3050 unset($USER->enrol['tempguest'][$course->id]);
3051 remove_temp_course_roles($coursecontext);
3053 } else {
3054 // Expired.
3055 unset($USER->enrol['enrolled'][$course->id]);
3058 if (isset($USER->enrol['tempguest'][$course->id])) {
3059 if ($USER->enrol['tempguest'][$course->id] == 0) {
3060 $access = true;
3061 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3062 $access = true;
3063 } else {
3064 // Expired.
3065 unset($USER->enrol['tempguest'][$course->id]);
3066 remove_temp_course_roles($coursecontext);
3070 if (!$access) {
3071 // Cache not ok.
3072 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3073 if ($until !== false) {
3074 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3075 if ($until == 0) {
3076 $until = ENROL_MAX_TIMESTAMP;
3078 $USER->enrol['enrolled'][$course->id] = $until;
3079 $access = true;
3081 } else {
3082 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3083 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3084 $enrols = enrol_get_plugins(true);
3085 // First ask all enabled enrol instances in course if they want to auto enrol user.
3086 foreach ($instances as $instance) {
3087 if (!isset($enrols[$instance->enrol])) {
3088 continue;
3090 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3091 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3092 if ($until !== false) {
3093 if ($until == 0) {
3094 $until = ENROL_MAX_TIMESTAMP;
3096 $USER->enrol['enrolled'][$course->id] = $until;
3097 $access = true;
3098 break;
3101 // If not enrolled yet try to gain temporary guest access.
3102 if (!$access) {
3103 foreach ($instances as $instance) {
3104 if (!isset($enrols[$instance->enrol])) {
3105 continue;
3107 // Get a duration for the guest access, a timestamp in the future or false.
3108 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3109 if ($until !== false and $until > time()) {
3110 $USER->enrol['tempguest'][$course->id] = $until;
3111 $access = true;
3112 break;
3120 if (!$access) {
3121 if ($preventredirect) {
3122 throw new require_login_exception('Not enrolled');
3124 if ($setwantsurltome) {
3125 $SESSION->wantsurl = qualified_me();
3127 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3131 // Check visibility of activity to current user; includes visible flag, groupmembersonly, conditional availability, etc.
3132 if ($cm && !$cm->uservisible) {
3133 if ($preventredirect) {
3134 throw new require_login_exception('Activity is hidden');
3136 if ($course->id != SITEID) {
3137 $url = new moodle_url('/course/view.php', array('id' => $course->id));
3138 } else {
3139 $url = new moodle_url('/');
3141 redirect($url, get_string('activityiscurrentlyhidden'));
3144 // Finally access granted, update lastaccess times.
3145 user_accesstime_log($course->id);
3150 * This function just makes sure a user is logged out.
3152 * @package core_access
3153 * @category access
3155 function require_logout() {
3156 global $USER, $DB;
3158 if (!isloggedin()) {
3159 // This should not happen often, no need for hooks or events here.
3160 \core\session\manager::terminate_current();
3161 return;
3164 // Execute hooks before action.
3165 $authsequence = get_enabled_auth_plugins();
3166 foreach ($authsequence as $authname) {
3167 $authplugin = get_auth_plugin($authname);
3168 $authplugin->prelogout_hook();
3171 // Store info that gets removed during logout.
3172 $sid = session_id();
3173 $event = \core\event\user_loggedout::create(
3174 array(
3175 'userid' => $USER->id,
3176 'objectid' => $USER->id,
3177 'other' => array('sessionid' => $sid),
3180 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3181 $event->add_record_snapshot('sessions', $session);
3184 // Delete session record and drop $_SESSION content.
3185 \core\session\manager::terminate_current();
3187 // Trigger event AFTER action.
3188 $event->trigger();
3192 * Weaker version of require_login()
3194 * This is a weaker version of {@link require_login()} which only requires login
3195 * when called from within a course rather than the site page, unless
3196 * the forcelogin option is turned on.
3197 * @see require_login()
3199 * @package core_access
3200 * @category access
3202 * @param mixed $courseorid The course object or id in question
3203 * @param bool $autologinguest Allow autologin guests if that is wanted
3204 * @param object $cm Course activity module if known
3205 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3206 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3207 * in order to keep redirects working properly. MDL-14495
3208 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3209 * @return void
3210 * @throws coding_exception
3212 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3213 global $CFG, $PAGE, $SITE;
3214 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3215 or (!is_object($courseorid) and $courseorid == SITEID));
3216 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3217 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3218 // db queries so this is not really a performance concern, however it is obviously
3219 // better if you use get_fast_modinfo to get the cm before calling this.
3220 if (is_object($courseorid)) {
3221 $course = $courseorid;
3222 } else {
3223 $course = clone($SITE);
3225 $modinfo = get_fast_modinfo($course);
3226 $cm = $modinfo->get_cm($cm->id);
3228 if (!empty($CFG->forcelogin)) {
3229 // Login required for both SITE and courses.
3230 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3232 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3233 // Always login for hidden activities.
3234 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3236 } else if ($issite) {
3237 // Login for SITE not required.
3238 if ($cm and empty($cm->visible)) {
3239 // Hidden activities are not accessible without login.
3240 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3241 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3242 // Not-logged-in users do not have any group membership.
3243 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3244 } else {
3245 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3246 if (!empty($courseorid)) {
3247 if (is_object($courseorid)) {
3248 $course = $courseorid;
3249 } else {
3250 $course = clone($SITE);
3252 if ($cm) {
3253 if ($cm->course != $course->id) {
3254 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3256 $PAGE->set_cm($cm, $course);
3257 $PAGE->set_pagelayout('incourse');
3258 } else {
3259 $PAGE->set_course($course);
3261 } else {
3262 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3263 $PAGE->set_course($PAGE->course);
3265 // TODO: verify conditional activities here.
3266 user_accesstime_log(SITEID);
3267 return;
3270 } else {
3271 // Course login always required.
3272 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3277 * Require key login. Function terminates with error if key not found or incorrect.
3279 * @uses NO_MOODLE_COOKIES
3280 * @uses PARAM_ALPHANUM
3281 * @param string $script unique script identifier
3282 * @param int $instance optional instance id
3283 * @return int Instance ID
3285 function require_user_key_login($script, $instance=null) {
3286 global $DB;
3288 if (!NO_MOODLE_COOKIES) {
3289 print_error('sessioncookiesdisable');
3292 // Extra safety.
3293 \core\session\manager::write_close();
3295 $keyvalue = required_param('key', PARAM_ALPHANUM);
3297 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3298 print_error('invalidkey');
3301 if (!empty($key->validuntil) and $key->validuntil < time()) {
3302 print_error('expiredkey');
3305 if ($key->iprestriction) {
3306 $remoteaddr = getremoteaddr(null);
3307 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3308 print_error('ipmismatch');
3312 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3313 print_error('invaliduserid');
3316 // Emulate normal session.
3317 enrol_check_plugins($user);
3318 \core\session\manager::set_user($user);
3320 // Note we are not using normal login.
3321 if (!defined('USER_KEY_LOGIN')) {
3322 define('USER_KEY_LOGIN', true);
3325 // Return instance id - it might be empty.
3326 return $key->instance;
3330 * Creates a new private user access key.
3332 * @param string $script unique target identifier
3333 * @param int $userid
3334 * @param int $instance optional instance id
3335 * @param string $iprestriction optional ip restricted access
3336 * @param timestamp $validuntil key valid only until given data
3337 * @return string access key value
3339 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3340 global $DB;
3342 $key = new stdClass();
3343 $key->script = $script;
3344 $key->userid = $userid;
3345 $key->instance = $instance;
3346 $key->iprestriction = $iprestriction;
3347 $key->validuntil = $validuntil;
3348 $key->timecreated = time();
3350 // Something long and unique.
3351 $key->value = md5($userid.'_'.time().random_string(40));
3352 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3353 // Must be unique.
3354 $key->value = md5($userid.'_'.time().random_string(40));
3356 $DB->insert_record('user_private_key', $key);
3357 return $key->value;
3361 * Delete the user's new private user access keys for a particular script.
3363 * @param string $script unique target identifier
3364 * @param int $userid
3365 * @return void
3367 function delete_user_key($script, $userid) {
3368 global $DB;
3369 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3373 * Gets a private user access key (and creates one if one doesn't exist).
3375 * @param string $script unique target identifier
3376 * @param int $userid
3377 * @param int $instance optional instance id
3378 * @param string $iprestriction optional ip restricted access
3379 * @param timestamp $validuntil key valid only until given data
3380 * @return string access key value
3382 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3383 global $DB;
3385 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3386 'instance' => $instance, 'iprestriction' => $iprestriction,
3387 'validuntil' => $validuntil))) {
3388 return $key->value;
3389 } else {
3390 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3396 * Modify the user table by setting the currently logged in user's last login to now.
3398 * @return bool Always returns true
3400 function update_user_login_times() {
3401 global $USER, $DB;
3403 if (isguestuser()) {
3404 // Do not update guest access times/ips for performance.
3405 return true;
3408 $now = time();
3410 $user = new stdClass();
3411 $user->id = $USER->id;
3413 // Make sure all users that logged in have some firstaccess.
3414 if ($USER->firstaccess == 0) {
3415 $USER->firstaccess = $user->firstaccess = $now;
3418 // Store the previous current as lastlogin.
3419 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3421 $USER->currentlogin = $user->currentlogin = $now;
3423 // Function user_accesstime_log() may not update immediately, better do it here.
3424 $USER->lastaccess = $user->lastaccess = $now;
3425 $USER->lastip = $user->lastip = getremoteaddr();
3427 // Note: do not call user_update_user() here because this is part of the login process,
3428 // the login event means that these fields were updated.
3429 $DB->update_record('user', $user);
3430 return true;
3434 * Determines if a user has completed setting up their account.
3436 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3437 * @return bool
3439 function user_not_fully_set_up($user) {
3440 if (isguestuser($user)) {
3441 return false;
3443 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3447 * Check whether the user has exceeded the bounce threshold
3449 * @param stdClass $user A {@link $USER} object
3450 * @return bool true => User has exceeded bounce threshold
3452 function over_bounce_threshold($user) {
3453 global $CFG, $DB;
3455 if (empty($CFG->handlebounces)) {
3456 return false;
3459 if (empty($user->id)) {
3460 // No real (DB) user, nothing to do here.
3461 return false;
3464 // Set sensible defaults.
3465 if (empty($CFG->minbounces)) {
3466 $CFG->minbounces = 10;
3468 if (empty($CFG->bounceratio)) {
3469 $CFG->bounceratio = .20;
3471 $bouncecount = 0;
3472 $sendcount = 0;
3473 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3474 $bouncecount = $bounce->value;
3476 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3477 $sendcount = $send->value;
3479 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3483 * Used to increment or reset email sent count
3485 * @param stdClass $user object containing an id
3486 * @param bool $reset will reset the count to 0
3487 * @return void
3489 function set_send_count($user, $reset=false) {
3490 global $DB;
3492 if (empty($user->id)) {
3493 // No real (DB) user, nothing to do here.
3494 return;
3497 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3498 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3499 $DB->update_record('user_preferences', $pref);
3500 } else if (!empty($reset)) {
3501 // If it's not there and we're resetting, don't bother. Make a new one.
3502 $pref = new stdClass();
3503 $pref->name = 'email_send_count';
3504 $pref->value = 1;
3505 $pref->userid = $user->id;
3506 $DB->insert_record('user_preferences', $pref, false);
3511 * Increment or reset user's email bounce count
3513 * @param stdClass $user object containing an id
3514 * @param bool $reset will reset the count to 0
3516 function set_bounce_count($user, $reset=false) {
3517 global $DB;
3519 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3520 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3521 $DB->update_record('user_preferences', $pref);
3522 } else if (!empty($reset)) {
3523 // If it's not there and we're resetting, don't bother. Make a new one.
3524 $pref = new stdClass();
3525 $pref->name = 'email_bounce_count';
3526 $pref->value = 1;
3527 $pref->userid = $user->id;
3528 $DB->insert_record('user_preferences', $pref, false);
3533 * Determines if the logged in user is currently moving an activity
3535 * @param int $courseid The id of the course being tested
3536 * @return bool
3538 function ismoving($courseid) {
3539 global $USER;
3541 if (!empty($USER->activitycopy)) {
3542 return ($USER->activitycopycourse == $courseid);
3544 return false;
3548 * Returns a persons full name
3550 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3551 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3552 * specify one.
3554 * @param stdClass $user A {@link $USER} object to get full name of.
3555 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3556 * @return string
3558 function fullname($user, $override=false) {
3559 global $CFG, $SESSION;
3561 if (!isset($user->firstname) and !isset($user->lastname)) {
3562 return '';
3565 // Get all of the name fields.
3566 $allnames = get_all_user_name_fields();
3567 if ($CFG->debugdeveloper) {
3568 foreach ($allnames as $allname) {
3569 if (!array_key_exists($allname, $user)) {
3570 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3571 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3572 // Message has been sent, no point in sending the message multiple times.
3573 break;
3578 if (!$override) {
3579 if (!empty($CFG->forcefirstname)) {
3580 $user->firstname = $CFG->forcefirstname;
3582 if (!empty($CFG->forcelastname)) {
3583 $user->lastname = $CFG->forcelastname;
3587 if (!empty($SESSION->fullnamedisplay)) {
3588 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3591 $template = null;
3592 // If the fullnamedisplay setting is available, set the template to that.
3593 if (isset($CFG->fullnamedisplay)) {
3594 $template = $CFG->fullnamedisplay;
3596 // If the template is empty, or set to language, or $override is set, return the language string.
3597 if (empty($template) || $template == 'language' || $override) {
3598 return get_string('fullnamedisplay', null, $user);
3601 $requirednames = array();
3602 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3603 foreach ($allnames as $allname) {
3604 if (strpos($template, $allname) !== false) {
3605 $requirednames[] = $allname;
3609 $displayname = $template;
3610 // Switch in the actual data into the template.
3611 foreach ($requirednames as $altname) {
3612 if (isset($user->$altname)) {
3613 // Using empty() on the below if statement causes breakages.
3614 if ((string)$user->$altname == '') {
3615 $displayname = str_replace($altname, 'EMPTY', $displayname);
3616 } else {
3617 $displayname = str_replace($altname, $user->$altname, $displayname);
3619 } else {
3620 $displayname = str_replace($altname, 'EMPTY', $displayname);
3623 // Tidy up any misc. characters (Not perfect, but gets most characters).
3624 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3625 // katakana and parenthesis.
3626 $patterns = array();
3627 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3628 // filled in by a user.
3629 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3630 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3631 // This regular expression is to remove any double spaces in the display name.
3632 $patterns[] = '/\s{2,}/u';
3633 foreach ($patterns as $pattern) {
3634 $displayname = preg_replace($pattern, ' ', $displayname);
3637 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3638 $displayname = trim($displayname);
3639 if (empty($displayname)) {
3640 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3641 // people in general feel is a good setting to fall back on.
3642 $displayname = $user->firstname;
3644 return $displayname;
3648 * A centralised location for the all name fields. Returns an array / sql string snippet.
3650 * @param bool $returnsql True for an sql select field snippet.
3651 * @param string $tableprefix table query prefix to use in front of each field.
3652 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3653 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3654 * @return array|string All name fields.
3656 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null) {
3657 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3658 'lastnamephonetic' => 'lastnamephonetic',
3659 'middlename' => 'middlename',
3660 'alternatename' => 'alternatename',
3661 'firstname' => 'firstname',
3662 'lastname' => 'lastname');
3664 // Let's add a prefix to the array of user name fields if provided.
3665 if ($prefix) {
3666 foreach ($alternatenames as $key => $altname) {
3667 $alternatenames[$key] = $prefix . $altname;
3671 // Create an sql field snippet if requested.
3672 if ($returnsql) {
3673 if ($tableprefix) {
3674 if ($fieldprefix) {
3675 foreach ($alternatenames as $key => $altname) {
3676 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3678 } else {
3679 foreach ($alternatenames as $key => $altname) {
3680 $alternatenames[$key] = $tableprefix . '.' . $altname;
3684 $alternatenames = implode(',', $alternatenames);
3686 return $alternatenames;
3690 * Reduces lines of duplicated code for getting user name fields.
3692 * See also {@link user_picture::unalias()}
3694 * @param object $addtoobject Object to add user name fields to.
3695 * @param object $secondobject Object that contains user name field information.
3696 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3697 * @param array $additionalfields Additional fields to be matched with data in the second object.
3698 * The key can be set to the user table field name.
3699 * @return object User name fields.
3701 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3702 $fields = get_all_user_name_fields(false, null, $prefix);
3703 if ($additionalfields) {
3704 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3705 // the key is a number and then sets the key to the array value.
3706 foreach ($additionalfields as $key => $value) {
3707 if (is_numeric($key)) {
3708 $additionalfields[$value] = $prefix . $value;
3709 unset($additionalfields[$key]);
3710 } else {
3711 $additionalfields[$key] = $prefix . $value;
3714 $fields = array_merge($fields, $additionalfields);
3716 foreach ($fields as $key => $field) {
3717 // Important that we have all of the user name fields present in the object that we are sending back.
3718 $addtoobject->$key = '';
3719 if (isset($secondobject->$field)) {
3720 $addtoobject->$key = $secondobject->$field;
3723 return $addtoobject;
3727 * Returns an array of values in order of occurance in a provided string.
3728 * The key in the result is the character postion in the string.
3730 * @param array $values Values to be found in the string format
3731 * @param string $stringformat The string which may contain values being searched for.
3732 * @return array An array of values in order according to placement in the string format.
3734 function order_in_string($values, $stringformat) {
3735 $valuearray = array();
3736 foreach ($values as $value) {
3737 $pattern = "/$value\b/";
3738 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3739 if (preg_match($pattern, $stringformat)) {
3740 $replacement = "thing";
3741 // Replace the value with something more unique to ensure we get the right position when using strpos().
3742 $newformat = preg_replace($pattern, $replacement, $stringformat);
3743 $position = strpos($newformat, $replacement);
3744 $valuearray[$position] = $value;
3747 ksort($valuearray);
3748 return $valuearray;
3752 * Checks if current user is shown any extra fields when listing users.
3754 * @param object $context Context
3755 * @param array $already Array of fields that we're going to show anyway
3756 * so don't bother listing them
3757 * @return array Array of field names from user table, not including anything
3758 * listed in $already
3760 function get_extra_user_fields($context, $already = array()) {
3761 global $CFG;
3763 // Only users with permission get the extra fields.
3764 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3765 return array();
3768 // Split showuseridentity on comma.
3769 if (empty($CFG->showuseridentity)) {
3770 // Explode gives wrong result with empty string.
3771 $extra = array();
3772 } else {
3773 $extra = explode(',', $CFG->showuseridentity);
3775 $renumber = false;
3776 foreach ($extra as $key => $field) {
3777 if (in_array($field, $already)) {
3778 unset($extra[$key]);
3779 $renumber = true;
3782 if ($renumber) {
3783 // For consistency, if entries are removed from array, renumber it
3784 // so they are numbered as you would expect.
3785 $extra = array_merge($extra);
3787 return $extra;
3791 * If the current user is to be shown extra user fields when listing or
3792 * selecting users, returns a string suitable for including in an SQL select
3793 * clause to retrieve those fields.
3795 * @param context $context Context
3796 * @param string $alias Alias of user table, e.g. 'u' (default none)
3797 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3798 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3799 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3801 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3802 $fields = get_extra_user_fields($context, $already);
3803 $result = '';
3804 // Add punctuation for alias.
3805 if ($alias !== '') {
3806 $alias .= '.';
3808 foreach ($fields as $field) {
3809 $result .= ', ' . $alias . $field;
3810 if ($prefix) {
3811 $result .= ' AS ' . $prefix . $field;
3814 return $result;
3818 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3819 * @param string $field Field name, e.g. 'phone1'
3820 * @return string Text description taken from language file, e.g. 'Phone number'
3822 function get_user_field_name($field) {
3823 // Some fields have language strings which are not the same as field name.
3824 switch ($field) {
3825 case 'phone1' : {
3826 return get_string('phone');
3828 case 'url' : {
3829 return get_string('webpage');
3831 case 'icq' : {
3832 return get_string('icqnumber');
3834 case 'skype' : {
3835 return get_string('skypeid');
3837 case 'aim' : {
3838 return get_string('aimid');
3840 case 'yahoo' : {
3841 return get_string('yahooid');
3843 case 'msn' : {
3844 return get_string('msnid');
3847 // Otherwise just use the same lang string.
3848 return get_string($field);
3852 * Returns whether a given authentication plugin exists.
3854 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3855 * @return boolean Whether the plugin is available.
3857 function exists_auth_plugin($auth) {
3858 global $CFG;
3860 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3861 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3863 return false;
3867 * Checks if a given plugin is in the list of enabled authentication plugins.
3869 * @param string $auth Authentication plugin.
3870 * @return boolean Whether the plugin is enabled.
3872 function is_enabled_auth($auth) {
3873 if (empty($auth)) {
3874 return false;
3877 $enabled = get_enabled_auth_plugins();
3879 return in_array($auth, $enabled);
3883 * Returns an authentication plugin instance.
3885 * @param string $auth name of authentication plugin
3886 * @return auth_plugin_base An instance of the required authentication plugin.
3888 function get_auth_plugin($auth) {
3889 global $CFG;
3891 // Check the plugin exists first.
3892 if (! exists_auth_plugin($auth)) {
3893 print_error('authpluginnotfound', 'debug', '', $auth);
3896 // Return auth plugin instance.
3897 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3898 $class = "auth_plugin_$auth";
3899 return new $class;
3903 * Returns array of active auth plugins.
3905 * @param bool $fix fix $CFG->auth if needed
3906 * @return array
3908 function get_enabled_auth_plugins($fix=false) {
3909 global $CFG;
3911 $default = array('manual', 'nologin');
3913 if (empty($CFG->auth)) {
3914 $auths = array();
3915 } else {
3916 $auths = explode(',', $CFG->auth);
3919 if ($fix) {
3920 $auths = array_unique($auths);
3921 foreach ($auths as $k => $authname) {
3922 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3923 unset($auths[$k]);
3926 $newconfig = implode(',', $auths);
3927 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3928 set_config('auth', $newconfig);
3932 return (array_merge($default, $auths));
3936 * Returns true if an internal authentication method is being used.
3937 * if method not specified then, global default is assumed
3939 * @param string $auth Form of authentication required
3940 * @return bool
3942 function is_internal_auth($auth) {
3943 // Throws error if bad $auth.
3944 $authplugin = get_auth_plugin($auth);
3945 return $authplugin->is_internal();
3949 * Returns true if the user is a 'restored' one.
3951 * Used in the login process to inform the user and allow him/her to reset the password
3953 * @param string $username username to be checked
3954 * @return bool
3956 function is_restored_user($username) {
3957 global $CFG, $DB;
3959 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3963 * Returns an array of user fields
3965 * @return array User field/column names
3967 function get_user_fieldnames() {
3968 global $DB;
3970 $fieldarray = $DB->get_columns('user');
3971 unset($fieldarray['id']);
3972 $fieldarray = array_keys($fieldarray);
3974 return $fieldarray;
3978 * Creates a bare-bones user record
3980 * @todo Outline auth types and provide code example
3982 * @param string $username New user's username to add to record
3983 * @param string $password New user's password to add to record
3984 * @param string $auth Form of authentication required
3985 * @return stdClass A complete user object
3987 function create_user_record($username, $password, $auth = 'manual') {
3988 global $CFG, $DB;
3989 require_once($CFG->dirroot.'/user/profile/lib.php');
3990 require_once($CFG->dirroot.'/user/lib.php');
3992 // Just in case check text case.
3993 $username = trim(core_text::strtolower($username));
3995 $authplugin = get_auth_plugin($auth);
3996 $customfields = $authplugin->get_custom_user_profile_fields();
3997 $newuser = new stdClass();
3998 if ($newinfo = $authplugin->get_userinfo($username)) {
3999 $newinfo = truncate_userinfo($newinfo);
4000 foreach ($newinfo as $key => $value) {
4001 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
4002 $newuser->$key = $value;
4007 if (!empty($newuser->email)) {
4008 if (email_is_not_allowed($newuser->email)) {
4009 unset($newuser->email);
4013 if (!isset($newuser->city)) {
4014 $newuser->city = '';
4017 $newuser->auth = $auth;
4018 $newuser->username = $username;
4020 // Fix for MDL-8480
4021 // user CFG lang for user if $newuser->lang is empty
4022 // or $user->lang is not an installed language.
4023 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
4024 $newuser->lang = $CFG->lang;
4026 $newuser->confirmed = 1;
4027 $newuser->lastip = getremoteaddr();
4028 $newuser->timecreated = time();
4029 $newuser->timemodified = $newuser->timecreated;
4030 $newuser->mnethostid = $CFG->mnet_localhost_id;
4032 $newuser->id = user_create_user($newuser, false);
4034 // Save user profile data.
4035 profile_save_data($newuser);
4037 $user = get_complete_user_data('id', $newuser->id);
4038 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
4039 set_user_preference('auth_forcepasswordchange', 1, $user);
4041 // Set the password.
4042 update_internal_user_password($user, $password);
4044 return $user;
4048 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4050 * @param string $username user's username to update the record
4051 * @return stdClass A complete user object
4053 function update_user_record($username) {
4054 global $DB, $CFG;
4055 // Just in case check text case.
4056 $username = trim(core_text::strtolower($username));
4058 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
4059 return update_user_record_by_id($oldinfo->id);
4063 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4065 * @param int $id user id
4066 * @return stdClass A complete user object
4068 function update_user_record_by_id($id) {
4069 global $DB, $CFG;
4070 require_once($CFG->dirroot."/user/profile/lib.php");
4071 require_once($CFG->dirroot.'/user/lib.php');
4073 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
4074 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
4076 $newuser = array();
4077 $userauth = get_auth_plugin($oldinfo->auth);
4079 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
4080 $newinfo = truncate_userinfo($newinfo);
4081 $customfields = $userauth->get_custom_user_profile_fields();
4083 foreach ($newinfo as $key => $value) {
4084 $key = strtolower($key);
4085 $iscustom = in_array($key, $customfields);
4086 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4087 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4088 // Unknown or must not be changed.
4089 continue;
4091 $confval = $userauth->config->{'field_updatelocal_' . $key};
4092 $lockval = $userauth->config->{'field_lock_' . $key};
4093 if (empty($confval) || empty($lockval)) {
4094 continue;
4096 if ($confval === 'onlogin') {
4097 // MDL-4207 Don't overwrite modified user profile values with
4098 // empty LDAP values when 'unlocked if empty' is set. The purpose
4099 // of the setting 'unlocked if empty' is to allow the user to fill
4100 // in a value for the selected field _if LDAP is giving
4101 // nothing_ for this field. Thus it makes sense to let this value
4102 // stand in until LDAP is giving a value for this field.
4103 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4104 if ($iscustom || (in_array($key, $userauth->userfields) &&
4105 ((string)$oldinfo->$key !== (string)$value))) {
4106 $newuser[$key] = (string)$value;
4111 if ($newuser) {
4112 $newuser['id'] = $oldinfo->id;
4113 $newuser['timemodified'] = time();
4114 user_update_user((object) $newuser, false);
4116 // Save user profile data.
4117 profile_save_data((object) $newuser);
4121 return get_complete_user_data('id', $oldinfo->id);
4125 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4127 * @param array $info Array of user properties to truncate if needed
4128 * @return array The now truncated information that was passed in
4130 function truncate_userinfo(array $info) {
4131 // Define the limits.
4132 $limit = array(
4133 'username' => 100,
4134 'idnumber' => 255,
4135 'firstname' => 100,
4136 'lastname' => 100,
4137 'email' => 100,
4138 'icq' => 15,
4139 'phone1' => 20,
4140 'phone2' => 20,
4141 'institution' => 255,
4142 'department' => 255,
4143 'address' => 255,
4144 'city' => 120,
4145 'country' => 2,
4146 'url' => 255,
4149 // Apply where needed.
4150 foreach (array_keys($info) as $key) {
4151 if (!empty($limit[$key])) {
4152 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4156 return $info;
4160 * Marks user deleted in internal user database and notifies the auth plugin.
4161 * Also unenrols user from all roles and does other cleanup.
4163 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4165 * @param stdClass $user full user object before delete
4166 * @return boolean success
4167 * @throws coding_exception if invalid $user parameter detected
4169 function delete_user(stdClass $user) {
4170 global $CFG, $DB;
4171 require_once($CFG->libdir.'/grouplib.php');
4172 require_once($CFG->libdir.'/gradelib.php');
4173 require_once($CFG->dirroot.'/message/lib.php');
4174 require_once($CFG->dirroot.'/tag/lib.php');
4175 require_once($CFG->dirroot.'/user/lib.php');
4177 // Make sure nobody sends bogus record type as parameter.
4178 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4179 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4182 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4183 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4184 debugging('Attempt to delete unknown user account.');
4185 return false;
4188 // There must be always exactly one guest record, originally the guest account was identified by username only,
4189 // now we use $CFG->siteguest for performance reasons.
4190 if ($user->username === 'guest' or isguestuser($user)) {
4191 debugging('Guest user account can not be deleted.');
4192 return false;
4195 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4196 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4197 if ($user->auth === 'manual' and is_siteadmin($user)) {
4198 debugging('Local administrator accounts can not be deleted.');
4199 return false;
4202 // Keep user record before updating it, as we have to pass this to user_deleted event.
4203 $olduser = clone $user;
4205 // Keep a copy of user context, we need it for event.
4206 $usercontext = context_user::instance($user->id);
4208 // Delete all grades - backup is kept in grade_grades_history table.
4209 grade_user_delete($user->id);
4211 // Move unread messages from this user to read.
4212 message_move_userfrom_unread2read($user->id);
4214 // TODO: remove from cohorts using standard API here.
4216 // Remove user tags.
4217 tag_set('user', $user->id, array(), 'core', $usercontext->id);
4219 // Unconditionally unenrol from all courses.
4220 enrol_user_delete($user);
4222 // Unenrol from all roles in all contexts.
4223 // This might be slow but it is really needed - modules might do some extra cleanup!
4224 role_unassign_all(array('userid' => $user->id));
4226 // Now do a brute force cleanup.
4228 // Remove from all cohorts.
4229 $DB->delete_records('cohort_members', array('userid' => $user->id));
4231 // Remove from all groups.
4232 $DB->delete_records('groups_members', array('userid' => $user->id));
4234 // Brute force unenrol from all courses.
4235 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4237 // Purge user preferences.
4238 $DB->delete_records('user_preferences', array('userid' => $user->id));
4240 // Purge user extra profile info.
4241 $DB->delete_records('user_info_data', array('userid' => $user->id));
4243 // Last course access not necessary either.
4244 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4245 // Remove all user tokens.
4246 $DB->delete_records('external_tokens', array('userid' => $user->id));
4248 // Unauthorise the user for all services.
4249 $DB->delete_records('external_services_users', array('userid' => $user->id));
4251 // Remove users private keys.
4252 $DB->delete_records('user_private_key', array('userid' => $user->id));
4254 // Remove users customised pages.
4255 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4257 // Force logout - may fail if file based sessions used, sorry.
4258 \core\session\manager::kill_user_sessions($user->id);
4260 // Workaround for bulk deletes of users with the same email address.
4261 $delname = clean_param($user->email . "." . time(), PARAM_USERNAME);
4262 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4263 $delname++;
4266 // Mark internal user record as "deleted".
4267 $updateuser = new stdClass();
4268 $updateuser->id = $user->id;
4269 $updateuser->deleted = 1;
4270 $updateuser->username = $delname; // Remember it just in case.
4271 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4272 $updateuser->idnumber = ''; // Clear this field to free it up.
4273 $updateuser->picture = 0;
4274 $updateuser->timemodified = time();
4276 user_update_user($updateuser, false);
4278 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4279 context_helper::delete_instance(CONTEXT_USER, $user->id);
4281 // Any plugin that needs to cleanup should register this event.
4282 // Trigger event.
4283 $event = \core\event\user_deleted::create(
4284 array(
4285 'objectid' => $user->id,
4286 'relateduserid' => $user->id,
4287 'context' => $usercontext,
4288 'other' => array(
4289 'username' => $user->username,
4290 'email' => $user->email,
4291 'idnumber' => $user->idnumber,
4292 'picture' => $user->picture,
4293 'mnethostid' => $user->mnethostid
4297 $event->add_record_snapshot('user', $olduser);
4298 $event->trigger();
4300 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4301 // should know about this updated property persisted to the user's table.
4302 $user->timemodified = $updateuser->timemodified;
4304 // Notify auth plugin - do not block the delete even when plugin fails.
4305 $authplugin = get_auth_plugin($user->auth);
4306 $authplugin->user_delete($user);
4308 return true;
4312 * Retrieve the guest user object.
4314 * @return stdClass A {@link $USER} object
4316 function guest_user() {
4317 global $CFG, $DB;
4319 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4320 $newuser->confirmed = 1;
4321 $newuser->lang = $CFG->lang;
4322 $newuser->lastip = getremoteaddr();
4325 return $newuser;
4329 * Authenticates a user against the chosen authentication mechanism
4331 * Given a username and password, this function looks them
4332 * up using the currently selected authentication mechanism,
4333 * and if the authentication is successful, it returns a
4334 * valid $user object from the 'user' table.
4336 * Uses auth_ functions from the currently active auth module
4338 * After authenticate_user_login() returns success, you will need to
4339 * log that the user has logged in, and call complete_user_login() to set
4340 * the session up.
4342 * Note: this function works only with non-mnet accounts!
4344 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4345 * @param string $password User's password
4346 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4347 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4348 * @return stdClass|false A {@link $USER} object or false if error
4350 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4351 global $CFG, $DB;
4352 require_once("$CFG->libdir/authlib.php");
4354 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4355 // we have found the user
4357 } else if (!empty($CFG->authloginviaemail)) {
4358 if ($email = clean_param($username, PARAM_EMAIL)) {
4359 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4360 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4361 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4362 if (count($users) === 1) {
4363 // Use email for login only if unique.
4364 $user = reset($users);
4365 $user = get_complete_user_data('id', $user->id);
4366 $username = $user->username;
4368 unset($users);
4372 $authsenabled = get_enabled_auth_plugins();
4374 if ($user) {
4375 // Use manual if auth not set.
4376 $auth = empty($user->auth) ? 'manual' : $user->auth;
4377 if (!empty($user->suspended)) {
4378 $failurereason = AUTH_LOGIN_SUSPENDED;
4380 // Trigger login failed event.
4381 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4382 'other' => array('username' => $username, 'reason' => $failurereason)));
4383 $event->trigger();
4384 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4385 return false;
4387 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4388 // Legacy way to suspend user.
4389 $failurereason = AUTH_LOGIN_SUSPENDED;
4391 // Trigger login failed event.
4392 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4393 'other' => array('username' => $username, 'reason' => $failurereason)));
4394 $event->trigger();
4395 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4396 return false;
4398 $auths = array($auth);
4400 } else {
4401 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4402 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4403 $failurereason = AUTH_LOGIN_NOUSER;
4405 // Trigger login failed event.
4406 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4407 'reason' => $failurereason)));
4408 $event->trigger();
4409 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4410 return false;
4413 // Do not try to authenticate non-existent accounts when user creation is disabled.
4414 if (!empty($CFG->authpreventaccountcreation)) {
4415 $failurereason = AUTH_LOGIN_NOUSER;
4417 // Trigger login failed event.
4418 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4419 'reason' => $failurereason)));
4420 $event->trigger();
4422 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4423 $_SERVER['HTTP_USER_AGENT']);
4424 return false;
4427 // User does not exist.
4428 $auths = $authsenabled;
4429 $user = new stdClass();
4430 $user->id = 0;
4433 if ($ignorelockout) {
4434 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4435 // or this function is called from a SSO script.
4436 } else if ($user->id) {
4437 // Verify login lockout after other ways that may prevent user login.
4438 if (login_is_lockedout($user)) {
4439 $failurereason = AUTH_LOGIN_LOCKOUT;
4441 // Trigger login failed event.
4442 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4443 'other' => array('username' => $username, 'reason' => $failurereason)));
4444 $event->trigger();
4446 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4447 return false;
4449 } else {
4450 // We can not lockout non-existing accounts.
4453 foreach ($auths as $auth) {
4454 $authplugin = get_auth_plugin($auth);
4456 // On auth fail fall through to the next plugin.
4457 if (!$authplugin->user_login($username, $password)) {
4458 continue;
4461 // Successful authentication.
4462 if ($user->id) {
4463 // User already exists in database.
4464 if (empty($user->auth)) {
4465 // For some reason auth isn't set yet.
4466 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4467 $user->auth = $auth;
4470 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4471 // the current hash algorithm while we have access to the user's password.
4472 update_internal_user_password($user, $password);
4474 if ($authplugin->is_synchronised_with_external()) {
4475 // Update user record from external DB.
4476 $user = update_user_record_by_id($user->id);
4478 } else {
4479 // Create account, we verified above that user creation is allowed.
4480 $user = create_user_record($username, $password, $auth);
4483 $authplugin->sync_roles($user);
4485 foreach ($authsenabled as $hau) {
4486 $hauth = get_auth_plugin($hau);
4487 $hauth->user_authenticated_hook($user, $username, $password);
4490 if (empty($user->id)) {
4491 $failurereason = AUTH_LOGIN_NOUSER;
4492 // Trigger login failed event.
4493 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4494 'reason' => $failurereason)));
4495 $event->trigger();
4496 return false;
4499 if (!empty($user->suspended)) {
4500 // Just in case some auth plugin suspended account.
4501 $failurereason = AUTH_LOGIN_SUSPENDED;
4502 // Trigger login failed event.
4503 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4504 'other' => array('username' => $username, 'reason' => $failurereason)));
4505 $event->trigger();
4506 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4507 return false;
4510 login_attempt_valid($user);
4511 $failurereason = AUTH_LOGIN_OK;
4512 return $user;
4515 // Failed if all the plugins have failed.
4516 if (debugging('', DEBUG_ALL)) {
4517 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4520 if ($user->id) {
4521 login_attempt_failed($user);
4522 $failurereason = AUTH_LOGIN_FAILED;
4523 // Trigger login failed event.
4524 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4525 'other' => array('username' => $username, 'reason' => $failurereason)));
4526 $event->trigger();
4527 } else {
4528 $failurereason = AUTH_LOGIN_NOUSER;
4529 // Trigger login failed event.
4530 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4531 'reason' => $failurereason)));
4532 $event->trigger();
4535 return false;
4539 * Call to complete the user login process after authenticate_user_login()
4540 * has succeeded. It will setup the $USER variable and other required bits
4541 * and pieces.
4543 * NOTE:
4544 * - It will NOT log anything -- up to the caller to decide what to log.
4545 * - this function does not set any cookies any more!
4547 * @param stdClass $user
4548 * @return stdClass A {@link $USER} object - BC only, do not use
4550 function complete_user_login($user) {
4551 global $CFG, $USER;
4553 \core\session\manager::login_user($user);
4555 // Reload preferences from DB.
4556 unset($USER->preference);
4557 check_user_preferences_loaded($USER);
4559 // Update login times.
4560 update_user_login_times();
4562 // Extra session prefs init.
4563 set_login_session_preferences();
4565 // Trigger login event.
4566 $event = \core\event\user_loggedin::create(
4567 array(
4568 'userid' => $USER->id,
4569 'objectid' => $USER->id,
4570 'other' => array('username' => $USER->username),
4573 $event->trigger();
4575 if (isguestuser()) {
4576 // No need to continue when user is THE guest.
4577 return $USER;
4580 if (CLI_SCRIPT) {
4581 // We can redirect to password change URL only in browser.
4582 return $USER;
4585 // Select password change url.
4586 $userauth = get_auth_plugin($USER->auth);
4588 // Check whether the user should be changing password.
4589 if (get_user_preferences('auth_forcepasswordchange', false)) {
4590 if ($userauth->can_change_password()) {
4591 if ($changeurl = $userauth->change_password_url()) {
4592 redirect($changeurl);
4593 } else {
4594 redirect($CFG->httpswwwroot.'/login/change_password.php');
4596 } else {
4597 print_error('nopasswordchangeforced', 'auth');
4600 return $USER;
4604 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4606 * @param string $password String to check.
4607 * @return boolean True if the $password matches the format of an md5 sum.
4609 function password_is_legacy_hash($password) {
4610 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4614 * Compare password against hash stored in user object to determine if it is valid.
4616 * If necessary it also updates the stored hash to the current format.
4618 * @param stdClass $user (Password property may be updated).
4619 * @param string $password Plain text password.
4620 * @return bool True if password is valid.
4622 function validate_internal_user_password($user, $password) {
4623 global $CFG;
4624 require_once($CFG->libdir.'/password_compat/lib/password.php');
4626 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4627 // Internal password is not used at all, it can not validate.
4628 return false;
4631 // If hash isn't a legacy (md5) hash, validate using the library function.
4632 if (!password_is_legacy_hash($user->password)) {
4633 return password_verify($password, $user->password);
4636 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4637 // is valid we can then update it to the new algorithm.
4639 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4640 $validated = false;
4642 if ($user->password === md5($password.$sitesalt)
4643 or $user->password === md5($password)
4644 or $user->password === md5(addslashes($password).$sitesalt)
4645 or $user->password === md5(addslashes($password))) {
4646 // Note: we are intentionally using the addslashes() here because we
4647 // need to accept old password hashes of passwords with magic quotes.
4648 $validated = true;
4650 } else {
4651 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4652 $alt = 'passwordsaltalt'.$i;
4653 if (!empty($CFG->$alt)) {
4654 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4655 $validated = true;
4656 break;
4662 if ($validated) {
4663 // If the password matches the existing md5 hash, update to the
4664 // current hash algorithm while we have access to the user's password.
4665 update_internal_user_password($user, $password);
4668 return $validated;
4672 * Calculate hash for a plain text password.
4674 * @param string $password Plain text password to be hashed.
4675 * @param bool $fasthash If true, use a low cost factor when generating the hash
4676 * This is much faster to generate but makes the hash
4677 * less secure. It is used when lots of hashes need to
4678 * be generated quickly.
4679 * @return string The hashed password.
4681 * @throws moodle_exception If a problem occurs while generating the hash.
4683 function hash_internal_user_password($password, $fasthash = false) {
4684 global $CFG;
4685 require_once($CFG->libdir.'/password_compat/lib/password.php');
4687 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4688 $options = ($fasthash) ? array('cost' => 4) : array();
4690 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4692 if ($generatedhash === false || $generatedhash === null) {
4693 throw new moodle_exception('Failed to generate password hash.');
4696 return $generatedhash;
4700 * Update password hash in user object (if necessary).
4702 * The password is updated if:
4703 * 1. The password has changed (the hash of $user->password is different
4704 * to the hash of $password).
4705 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4706 * md5 algorithm).
4708 * Updating the password will modify the $user object and the database
4709 * record to use the current hashing algorithm.
4711 * @param stdClass $user User object (password property may be updated).
4712 * @param string $password Plain text password.
4713 * @return bool Always returns true.
4715 function update_internal_user_password($user, $password) {
4716 global $CFG, $DB;
4717 require_once($CFG->libdir.'/password_compat/lib/password.php');
4719 // Figure out what the hashed password should be.
4720 $authplugin = get_auth_plugin($user->auth);
4721 if ($authplugin->prevent_local_passwords()) {
4722 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4723 } else {
4724 $hashedpassword = hash_internal_user_password($password);
4727 // If verification fails then it means the password has changed.
4728 $passwordchanged = !password_verify($password, $user->password);
4729 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4731 if ($passwordchanged || $algorithmchanged) {
4732 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4733 $user->password = $hashedpassword;
4735 // Trigger event.
4736 $event = \core\event\user_updated::create(array(
4737 'objectid' => $user->id,
4738 'relateduserid' => $user->id,
4739 'context' => context_user::instance($user->id)
4741 $event->add_record_snapshot('user', $user);
4742 $event->trigger();
4745 return true;
4749 * Get a complete user record, which includes all the info in the user record.
4751 * Intended for setting as $USER session variable
4753 * @param string $field The user field to be checked for a given value.
4754 * @param string $value The value to match for $field.
4755 * @param int $mnethostid
4756 * @return mixed False, or A {@link $USER} object.
4758 function get_complete_user_data($field, $value, $mnethostid = null) {
4759 global $CFG, $DB;
4761 if (!$field || !$value) {
4762 return false;
4765 // Build the WHERE clause for an SQL query.
4766 $params = array('fieldval' => $value);
4767 $constraints = "$field = :fieldval AND deleted <> 1";
4769 // If we are loading user data based on anything other than id,
4770 // we must also restrict our search based on mnet host.
4771 if ($field != 'id') {
4772 if (empty($mnethostid)) {
4773 // If empty, we restrict to local users.
4774 $mnethostid = $CFG->mnet_localhost_id;
4777 if (!empty($mnethostid)) {
4778 $params['mnethostid'] = $mnethostid;
4779 $constraints .= " AND mnethostid = :mnethostid";
4782 // Get all the basic user data.
4783 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4784 return false;
4787 // Get various settings and preferences.
4789 // Preload preference cache.
4790 check_user_preferences_loaded($user);
4792 // Load course enrolment related stuff.
4793 $user->lastcourseaccess = array(); // During last session.
4794 $user->currentcourseaccess = array(); // During current session.
4795 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4796 foreach ($lastaccesses as $lastaccess) {
4797 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4801 $sql = "SELECT g.id, g.courseid
4802 FROM {groups} g, {groups_members} gm
4803 WHERE gm.groupid=g.id AND gm.userid=?";
4805 // This is a special hack to speedup calendar display.
4806 $user->groupmember = array();
4807 if (!isguestuser($user)) {
4808 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4809 foreach ($groups as $group) {
4810 if (!array_key_exists($group->courseid, $user->groupmember)) {
4811 $user->groupmember[$group->courseid] = array();
4813 $user->groupmember[$group->courseid][$group->id] = $group->id;
4818 // Add the custom profile fields to the user record.
4819 $user->profile = array();
4820 if (!isguestuser($user)) {
4821 require_once($CFG->dirroot.'/user/profile/lib.php');
4822 profile_load_custom_fields($user);
4825 // Rewrite some variables if necessary.
4826 if (!empty($user->description)) {
4827 // No need to cart all of it around.
4828 $user->description = true;
4830 if (isguestuser($user)) {
4831 // Guest language always same as site.
4832 $user->lang = $CFG->lang;
4833 // Name always in current language.
4834 $user->firstname = get_string('guestuser');
4835 $user->lastname = ' ';
4838 return $user;
4842 * Validate a password against the configured password policy
4844 * @param string $password the password to be checked against the password policy
4845 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4846 * @return bool true if the password is valid according to the policy. false otherwise.
4848 function check_password_policy($password, &$errmsg) {
4849 global $CFG;
4851 if (empty($CFG->passwordpolicy)) {
4852 return true;
4855 $errmsg = '';
4856 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4857 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4860 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4861 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4864 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4865 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4868 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4869 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4872 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4873 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4875 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4876 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4879 if ($errmsg == '') {
4880 return true;
4881 } else {
4882 return false;
4888 * When logging in, this function is run to set certain preferences for the current SESSION.
4890 function set_login_session_preferences() {
4891 global $SESSION;
4893 $SESSION->justloggedin = true;
4895 unset($SESSION->lang);
4896 unset($SESSION->forcelang);
4897 unset($SESSION->load_navigation_admin);
4902 * Delete a course, including all related data from the database, and any associated files.
4904 * @param mixed $courseorid The id of the course or course object to delete.
4905 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4906 * @return bool true if all the removals succeeded. false if there were any failures. If this
4907 * method returns false, some of the removals will probably have succeeded, and others
4908 * failed, but you have no way of knowing which.
4910 function delete_course($courseorid, $showfeedback = true) {
4911 global $DB;
4913 if (is_object($courseorid)) {
4914 $courseid = $courseorid->id;
4915 $course = $courseorid;
4916 } else {
4917 $courseid = $courseorid;
4918 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4919 return false;
4922 $context = context_course::instance($courseid);
4924 // Frontpage course can not be deleted!!
4925 if ($courseid == SITEID) {
4926 return false;
4929 // Make the course completely empty.
4930 remove_course_contents($courseid, $showfeedback);
4932 // Delete the course and related context instance.
4933 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4935 $DB->delete_records("course", array("id" => $courseid));
4936 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4938 // Reset all course related caches here.
4939 if (class_exists('format_base', false)) {
4940 format_base::reset_course_cache($courseid);
4943 // Trigger a course deleted event.
4944 $event = \core\event\course_deleted::create(array(
4945 'objectid' => $course->id,
4946 'context' => $context,
4947 'other' => array(
4948 'shortname' => $course->shortname,
4949 'fullname' => $course->fullname,
4950 'idnumber' => $course->idnumber
4953 $event->add_record_snapshot('course', $course);
4954 $event->trigger();
4956 return true;
4960 * Clear a course out completely, deleting all content but don't delete the course itself.
4962 * This function does not verify any permissions.
4964 * Please note this function also deletes all user enrolments,
4965 * enrolment instances and role assignments by default.
4967 * $options:
4968 * - 'keep_roles_and_enrolments' - false by default
4969 * - 'keep_groups_and_groupings' - false by default
4971 * @param int $courseid The id of the course that is being deleted
4972 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4973 * @param array $options extra options
4974 * @return bool true if all the removals succeeded. false if there were any failures. If this
4975 * method returns false, some of the removals will probably have succeeded, and others
4976 * failed, but you have no way of knowing which.
4978 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4979 global $CFG, $DB, $OUTPUT;
4981 require_once($CFG->libdir.'/badgeslib.php');
4982 require_once($CFG->libdir.'/completionlib.php');
4983 require_once($CFG->libdir.'/questionlib.php');
4984 require_once($CFG->libdir.'/gradelib.php');
4985 require_once($CFG->dirroot.'/group/lib.php');
4986 require_once($CFG->dirroot.'/tag/coursetagslib.php');
4987 require_once($CFG->dirroot.'/comment/lib.php');
4988 require_once($CFG->dirroot.'/rating/lib.php');
4989 require_once($CFG->dirroot.'/notes/lib.php');
4991 // Handle course badges.
4992 badges_handle_course_deletion($courseid);
4994 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4995 $strdeleted = get_string('deleted').' - ';
4997 // Some crazy wishlist of stuff we should skip during purging of course content.
4998 $options = (array)$options;
5000 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5001 $coursecontext = context_course::instance($courseid);
5002 $fs = get_file_storage();
5004 // Delete course completion information, this has to be done before grades and enrols.
5005 $cc = new completion_info($course);
5006 $cc->clear_criteria();
5007 if ($showfeedback) {
5008 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5011 // Remove all data from gradebook - this needs to be done before course modules
5012 // because while deleting this information, the system may need to reference
5013 // the course modules that own the grades.
5014 remove_course_grades($courseid, $showfeedback);
5015 remove_grade_letters($coursecontext, $showfeedback);
5017 // Delete course blocks in any all child contexts,
5018 // they may depend on modules so delete them first.
5019 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5020 foreach ($childcontexts as $childcontext) {
5021 blocks_delete_all_for_context($childcontext->id);
5023 unset($childcontexts);
5024 blocks_delete_all_for_context($coursecontext->id);
5025 if ($showfeedback) {
5026 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5029 // Delete every instance of every module,
5030 // this has to be done before deleting of course level stuff.
5031 $locations = core_component::get_plugin_list('mod');
5032 foreach ($locations as $modname => $moddir) {
5033 if ($modname === 'NEWMODULE') {
5034 continue;
5036 if ($module = $DB->get_record('modules', array('name' => $modname))) {
5037 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5038 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5039 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
5041 if ($instances = $DB->get_records($modname, array('course' => $course->id))) {
5042 foreach ($instances as $instance) {
5043 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
5044 // Delete activity context questions and question categories.
5045 question_delete_activity($cm, $showfeedback);
5047 if (function_exists($moddelete)) {
5048 // This purges all module data in related tables, extra user prefs, settings, etc.
5049 $moddelete($instance->id);
5050 } else {
5051 // NOTE: we should not allow installation of modules with missing delete support!
5052 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5053 $DB->delete_records($modname, array('id' => $instance->id));
5056 if ($cm) {
5057 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5058 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5059 $DB->delete_records('course_modules', array('id' => $cm->id));
5063 if (function_exists($moddeletecourse)) {
5064 // Execute ptional course cleanup callback.
5065 $moddeletecourse($course, $showfeedback);
5067 if ($instances and $showfeedback) {
5068 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5070 } else {
5071 // Ooops, this module is not properly installed, force-delete it in the next block.
5075 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5077 // Remove all data from availability and completion tables that is associated
5078 // with course-modules belonging to this course. Note this is done even if the
5079 // features are not enabled now, in case they were enabled previously.
5080 $DB->delete_records_select('course_modules_completion',
5081 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5082 array($courseid));
5084 // Remove course-module data.
5085 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5086 foreach ($cms as $cm) {
5087 if ($module = $DB->get_record('modules', array('id' => $cm->module))) {
5088 try {
5089 $DB->delete_records($module->name, array('id' => $cm->instance));
5090 } catch (Exception $e) {
5091 // Ignore weird or missing table problems.
5094 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5095 $DB->delete_records('course_modules', array('id' => $cm->id));
5098 if ($showfeedback) {
5099 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5102 // Cleanup the rest of plugins.
5103 $cleanuplugintypes = array('report', 'coursereport', 'format');
5104 foreach ($cleanuplugintypes as $type) {
5105 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
5106 foreach ($plugins as $plugin => $pluginfunction) {
5107 $pluginfunction($course->id, $showfeedback);
5109 if ($showfeedback) {
5110 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5114 // Delete questions and question categories.
5115 question_delete_course($course, $showfeedback);
5116 if ($showfeedback) {
5117 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5120 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5121 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5122 foreach ($childcontexts as $childcontext) {
5123 $childcontext->delete();
5125 unset($childcontexts);
5127 // Remove all roles and enrolments by default.
5128 if (empty($options['keep_roles_and_enrolments'])) {
5129 // This hack is used in restore when deleting contents of existing course.
5130 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5131 enrol_course_delete($course);
5132 if ($showfeedback) {
5133 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5137 // Delete any groups, removing members and grouping/course links first.
5138 if (empty($options['keep_groups_and_groupings'])) {
5139 groups_delete_groupings($course->id, $showfeedback);
5140 groups_delete_groups($course->id, $showfeedback);
5143 // Filters be gone!
5144 filter_delete_all_for_context($coursecontext->id);
5146 // Notes, you shall not pass!
5147 note_delete_all($course->id);
5149 // Die comments!
5150 comment::delete_comments($coursecontext->id);
5152 // Ratings are history too.
5153 $delopt = new stdclass();
5154 $delopt->contextid = $coursecontext->id;
5155 $rm = new rating_manager();
5156 $rm->delete_ratings($delopt);
5158 // Delete course tags.
5159 coursetag_delete_course_tags($course->id, $showfeedback);
5161 // Delete calendar events.
5162 $DB->delete_records('event', array('courseid' => $course->id));
5163 $fs->delete_area_files($coursecontext->id, 'calendar');
5165 // Delete all related records in other core tables that may have a courseid
5166 // This array stores the tables that need to be cleared, as
5167 // table_name => column_name that contains the course id.
5168 $tablestoclear = array(
5169 'log' => 'course', // Course logs (NOTE: this might be changed in the future).
5170 'backup_courses' => 'courseid', // Scheduled backup stuff.
5171 'user_lastaccess' => 'courseid', // User access info.
5173 foreach ($tablestoclear as $table => $col) {
5174 $DB->delete_records($table, array($col => $course->id));
5177 // Delete all course backup files.
5178 $fs->delete_area_files($coursecontext->id, 'backup');
5180 // Cleanup course record - remove links to deleted stuff.
5181 $oldcourse = new stdClass();
5182 $oldcourse->id = $course->id;
5183 $oldcourse->summary = '';
5184 $oldcourse->cacherev = 0;
5185 $oldcourse->legacyfiles = 0;
5186 $oldcourse->enablecompletion = 0;
5187 if (!empty($options['keep_groups_and_groupings'])) {
5188 $oldcourse->defaultgroupingid = 0;
5190 $DB->update_record('course', $oldcourse);
5192 // Delete course sections.
5193 $DB->delete_records('course_sections', array('course' => $course->id));
5195 // Delete legacy, section and any other course files.
5196 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5198 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5199 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5200 // Easy, do not delete the context itself...
5201 $coursecontext->delete_content();
5202 } else {
5203 // Hack alert!!!!
5204 // We can not drop all context stuff because it would bork enrolments and roles,
5205 // there might be also files used by enrol plugins...
5208 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5209 // also some non-standard unsupported plugins may try to store something there.
5210 fulldelete($CFG->dataroot.'/'.$course->id);
5212 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5213 $cachemodinfo = cache::make('core', 'coursemodinfo');
5214 $cachemodinfo->delete($courseid);
5216 // Trigger a course content deleted event.
5217 $event = \core\event\course_content_deleted::create(array(
5218 'objectid' => $course->id,
5219 'context' => $coursecontext,
5220 'other' => array('shortname' => $course->shortname,
5221 'fullname' => $course->fullname,
5222 'options' => $options) // Passing this for legacy reasons.
5224 $event->add_record_snapshot('course', $course);
5225 $event->trigger();
5227 return true;
5231 * Change dates in module - used from course reset.
5233 * @param string $modname forum, assignment, etc
5234 * @param array $fields array of date fields from mod table
5235 * @param int $timeshift time difference
5236 * @param int $courseid
5237 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5238 * @return bool success
5240 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5241 global $CFG, $DB;
5242 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5244 $return = true;
5245 $params = array($timeshift, $courseid);
5246 foreach ($fields as $field) {
5247 $updatesql = "UPDATE {".$modname."}
5248 SET $field = $field + ?
5249 WHERE course=? AND $field<>0";
5250 if ($modid) {
5251 $updatesql .= ' AND id=?';
5252 $params[] = $modid;
5254 $return = $DB->execute($updatesql, $params) && $return;
5257 $refreshfunction = $modname.'_refresh_events';
5258 if (function_exists($refreshfunction)) {
5259 $refreshfunction($courseid);
5262 return $return;
5266 * This function will empty a course of user data.
5267 * It will retain the activities and the structure of the course.
5269 * @param object $data an object containing all the settings including courseid (without magic quotes)
5270 * @return array status array of array component, item, error
5272 function reset_course_userdata($data) {
5273 global $CFG, $DB;
5274 require_once($CFG->libdir.'/gradelib.php');
5275 require_once($CFG->libdir.'/completionlib.php');
5276 require_once($CFG->dirroot.'/group/lib.php');
5278 $data->courseid = $data->id;
5279 $context = context_course::instance($data->courseid);
5281 $eventparams = array(
5282 'context' => $context,
5283 'courseid' => $data->id,
5284 'other' => array(
5285 'reset_options' => (array) $data
5288 $event = \core\event\course_reset_started::create($eventparams);
5289 $event->trigger();
5291 // Calculate the time shift of dates.
5292 if (!empty($data->reset_start_date)) {
5293 // Time part of course startdate should be zero.
5294 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5295 } else {
5296 $data->timeshift = 0;
5299 // Result array: component, item, error.
5300 $status = array();
5302 // Start the resetting.
5303 $componentstr = get_string('general');
5305 // Move the course start time.
5306 if (!empty($data->reset_start_date) and $data->timeshift) {
5307 // Change course start data.
5308 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5309 // Update all course and group events - do not move activity events.
5310 $updatesql = "UPDATE {event}
5311 SET timestart = timestart + ?
5312 WHERE courseid=? AND instance=0";
5313 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5315 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5318 if (!empty($data->reset_logs)) {
5319 $DB->delete_records('log', array('course' => $data->courseid));
5320 $status[] = array('component' => $componentstr, 'item' => get_string('deletelogs'), 'error' => false);
5323 if (!empty($data->reset_events)) {
5324 $DB->delete_records('event', array('courseid' => $data->courseid));
5325 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5328 if (!empty($data->reset_notes)) {
5329 require_once($CFG->dirroot.'/notes/lib.php');
5330 note_delete_all($data->courseid);
5331 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5334 if (!empty($data->delete_blog_associations)) {
5335 require_once($CFG->dirroot.'/blog/lib.php');
5336 blog_remove_associations_for_course($data->courseid);
5337 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5340 if (!empty($data->reset_completion)) {
5341 // Delete course and activity completion information.
5342 $course = $DB->get_record('course', array('id' => $data->courseid));
5343 $cc = new completion_info($course);
5344 $cc->delete_all_completion_data();
5345 $status[] = array('component' => $componentstr,
5346 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5349 $componentstr = get_string('roles');
5351 if (!empty($data->reset_roles_overrides)) {
5352 $children = $context->get_child_contexts();
5353 foreach ($children as $child) {
5354 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5356 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5357 // Force refresh for logged in users.
5358 $context->mark_dirty();
5359 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5362 if (!empty($data->reset_roles_local)) {
5363 $children = $context->get_child_contexts();
5364 foreach ($children as $child) {
5365 role_unassign_all(array('contextid' => $child->id));
5367 // Force refresh for logged in users.
5368 $context->mark_dirty();
5369 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5372 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5373 $data->unenrolled = array();
5374 if (!empty($data->unenrol_users)) {
5375 $plugins = enrol_get_plugins(true);
5376 $instances = enrol_get_instances($data->courseid, true);
5377 foreach ($instances as $key => $instance) {
5378 if (!isset($plugins[$instance->enrol])) {
5379 unset($instances[$key]);
5380 continue;
5384 foreach ($data->unenrol_users as $withroleid) {
5385 if ($withroleid) {
5386 $sql = "SELECT ue.*
5387 FROM {user_enrolments} ue
5388 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5389 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5390 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5391 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5393 } else {
5394 // Without any role assigned at course context.
5395 $sql = "SELECT ue.*
5396 FROM {user_enrolments} ue
5397 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5398 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5399 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5400 WHERE ra.id IS null";
5401 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5404 $rs = $DB->get_recordset_sql($sql, $params);
5405 foreach ($rs as $ue) {
5406 if (!isset($instances[$ue->enrolid])) {
5407 continue;
5409 $instance = $instances[$ue->enrolid];
5410 $plugin = $plugins[$instance->enrol];
5411 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5412 continue;
5415 $plugin->unenrol_user($instance, $ue->userid);
5416 $data->unenrolled[$ue->userid] = $ue->userid;
5418 $rs->close();
5421 if (!empty($data->unenrolled)) {
5422 $status[] = array(
5423 'component' => $componentstr,
5424 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5425 'error' => false
5429 $componentstr = get_string('groups');
5431 // Remove all group members.
5432 if (!empty($data->reset_groups_members)) {
5433 groups_delete_group_members($data->courseid);
5434 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5437 // Remove all groups.
5438 if (!empty($data->reset_groups_remove)) {
5439 groups_delete_groups($data->courseid, false);
5440 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5443 // Remove all grouping members.
5444 if (!empty($data->reset_groupings_members)) {
5445 groups_delete_groupings_groups($data->courseid, false);
5446 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5449 // Remove all groupings.
5450 if (!empty($data->reset_groupings_remove)) {
5451 groups_delete_groupings($data->courseid, false);
5452 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5455 // Look in every instance of every module for data to delete.
5456 $unsupportedmods = array();
5457 if ($allmods = $DB->get_records('modules') ) {
5458 foreach ($allmods as $mod) {
5459 $modname = $mod->name;
5460 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5461 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5462 if (file_exists($modfile)) {
5463 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5464 continue; // Skip mods with no instances.
5466 include_once($modfile);
5467 if (function_exists($moddeleteuserdata)) {
5468 $modstatus = $moddeleteuserdata($data);
5469 if (is_array($modstatus)) {
5470 $status = array_merge($status, $modstatus);
5471 } else {
5472 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5474 } else {
5475 $unsupportedmods[] = $mod;
5477 } else {
5478 debugging('Missing lib.php in '.$modname.' module!');
5483 // Mention unsupported mods.
5484 if (!empty($unsupportedmods)) {
5485 foreach ($unsupportedmods as $mod) {
5486 $status[] = array(
5487 'component' => get_string('modulenameplural', $mod->name),
5488 'item' => '',
5489 'error' => get_string('resetnotimplemented')
5494 $componentstr = get_string('gradebook', 'grades');
5495 // Reset gradebook,.
5496 if (!empty($data->reset_gradebook_items)) {
5497 remove_course_grades($data->courseid, false);
5498 grade_grab_course_grades($data->courseid);
5499 grade_regrade_final_grades($data->courseid);
5500 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5502 } else if (!empty($data->reset_gradebook_grades)) {
5503 grade_course_reset($data->courseid);
5504 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5506 // Reset comments.
5507 if (!empty($data->reset_comments)) {
5508 require_once($CFG->dirroot.'/comment/lib.php');
5509 comment::reset_course_page_comments($context);
5512 $event = \core\event\course_reset_ended::create($eventparams);
5513 $event->trigger();
5515 return $status;
5519 * Generate an email processing address.
5521 * @param int $modid
5522 * @param string $modargs
5523 * @return string Returns email processing address
5525 function generate_email_processing_address($modid, $modargs) {
5526 global $CFG;
5528 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5529 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5535 * @todo Finish documenting this function
5537 * @param string $modargs
5538 * @param string $body Currently unused
5540 function moodle_process_email($modargs, $body) {
5541 global $DB;
5543 // The first char should be an unencoded letter. We'll take this as an action.
5544 switch ($modargs{0}) {
5545 case 'B': { // Bounce.
5546 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5547 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5548 // Check the half md5 of their email.
5549 $md5check = substr(md5($user->email), 0, 16);
5550 if ($md5check == substr($modargs, -16)) {
5551 set_bounce_count($user);
5553 // Else maybe they've already changed it?
5556 break;
5557 // Maybe more later?
5561 // CORRESPONDENCE.
5564 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5566 * @param string $action 'get', 'buffer', 'close' or 'flush'
5567 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5569 function get_mailer($action='get') {
5570 global $CFG;
5572 /** @var moodle_phpmailer $mailer */
5573 static $mailer = null;
5574 static $counter = 0;
5576 if (!isset($CFG->smtpmaxbulk)) {
5577 $CFG->smtpmaxbulk = 1;
5580 if ($action == 'get') {
5581 $prevkeepalive = false;
5583 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5584 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5585 $counter++;
5586 // Reset the mailer.
5587 $mailer->Priority = 3;
5588 $mailer->CharSet = 'UTF-8'; // Our default.
5589 $mailer->ContentType = "text/plain";
5590 $mailer->Encoding = "8bit";
5591 $mailer->From = "root@localhost";
5592 $mailer->FromName = "Root User";
5593 $mailer->Sender = "";
5594 $mailer->Subject = "";
5595 $mailer->Body = "";
5596 $mailer->AltBody = "";
5597 $mailer->ConfirmReadingTo = "";
5599 $mailer->clearAllRecipients();
5600 $mailer->clearReplyTos();
5601 $mailer->clearAttachments();
5602 $mailer->clearCustomHeaders();
5603 return $mailer;
5606 $prevkeepalive = $mailer->SMTPKeepAlive;
5607 get_mailer('flush');
5610 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5611 $mailer = new moodle_phpmailer();
5613 $counter = 1;
5615 if ($CFG->smtphosts == 'qmail') {
5616 // Use Qmail system.
5617 $mailer->isQmail();
5619 } else if (empty($CFG->smtphosts)) {
5620 // Use PHP mail() = sendmail.
5621 $mailer->isMail();
5623 } else {
5624 // Use SMTP directly.
5625 $mailer->isSMTP();
5626 if (!empty($CFG->debugsmtp)) {
5627 $mailer->SMTPDebug = true;
5629 // Specify main and backup servers.
5630 $mailer->Host = $CFG->smtphosts;
5631 // Specify secure connection protocol.
5632 $mailer->SMTPSecure = $CFG->smtpsecure;
5633 // Use previous keepalive.
5634 $mailer->SMTPKeepAlive = $prevkeepalive;
5636 if ($CFG->smtpuser) {
5637 // Use SMTP authentication.
5638 $mailer->SMTPAuth = true;
5639 $mailer->Username = $CFG->smtpuser;
5640 $mailer->Password = $CFG->smtppass;
5644 return $mailer;
5647 $nothing = null;
5649 // Keep smtp session open after sending.
5650 if ($action == 'buffer') {
5651 if (!empty($CFG->smtpmaxbulk)) {
5652 get_mailer('flush');
5653 $m = get_mailer();
5654 if ($m->Mailer == 'smtp') {
5655 $m->SMTPKeepAlive = true;
5658 return $nothing;
5661 // Close smtp session, but continue buffering.
5662 if ($action == 'flush') {
5663 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5664 if (!empty($mailer->SMTPDebug)) {
5665 echo '<pre>'."\n";
5667 $mailer->SmtpClose();
5668 if (!empty($mailer->SMTPDebug)) {
5669 echo '</pre>';
5672 return $nothing;
5675 // Close smtp session, do not buffer anymore.
5676 if ($action == 'close') {
5677 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5678 get_mailer('flush');
5679 $mailer->SMTPKeepAlive = false;
5681 $mailer = null; // Better force new instance.
5682 return $nothing;
5687 * Send an email to a specified user
5689 * @param stdClass $user A {@link $USER} object
5690 * @param stdClass $from A {@link $USER} object
5691 * @param string $subject plain text subject line of the email
5692 * @param string $messagetext plain text version of the message
5693 * @param string $messagehtml complete html version of the message (optional)
5694 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
5695 * @param string $attachname the name of the file (extension indicates MIME)
5696 * @param bool $usetrueaddress determines whether $from email address should
5697 * be sent out. Will be overruled by user profile setting for maildisplay
5698 * @param string $replyto Email address to reply to
5699 * @param string $replytoname Name of reply to recipient
5700 * @param int $wordwrapwidth custom word wrap width, default 79
5701 * @return bool Returns true if mail was sent OK and false if there was an error.
5703 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5704 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5706 global $CFG;
5708 if (empty($user) or empty($user->id)) {
5709 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5710 return false;
5713 if (empty($user->email)) {
5714 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5715 return false;
5718 if (!empty($user->deleted)) {
5719 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5720 return false;
5723 if (defined('BEHAT_SITE_RUNNING')) {
5724 // Fake email sending in behat.
5725 return true;
5728 if (!empty($CFG->noemailever)) {
5729 // Hidden setting for development sites, set in config.php if needed.
5730 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5731 return true;
5734 if (!empty($CFG->divertallemailsto)) {
5735 $subject = "[DIVERTED {$user->email}] $subject";
5736 $user = clone($user);
5737 $user->email = $CFG->divertallemailsto;
5740 // Skip mail to suspended users.
5741 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5742 return true;
5745 if (!validate_email($user->email)) {
5746 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5747 $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
5748 error_log($invalidemail);
5749 if (CLI_SCRIPT) {
5750 mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
5752 return false;
5755 if (over_bounce_threshold($user)) {
5756 $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
5757 error_log($bouncemsg);
5758 if (CLI_SCRIPT) {
5759 mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
5761 return false;
5764 // If the user is a remote mnet user, parse the email text for URL to the
5765 // wwwroot and modify the url to direct the user's browser to login at their
5766 // home site (identity provider - idp) before hitting the link itself.
5767 if (is_mnet_remote_user($user)) {
5768 require_once($CFG->dirroot.'/mnet/lib.php');
5770 $jumpurl = mnet_get_idp_jump_url($user);
5771 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5773 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5774 $callback,
5775 $messagetext);
5776 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5777 $callback,
5778 $messagehtml);
5780 $mail = get_mailer();
5782 if (!empty($mail->SMTPDebug)) {
5783 echo '<pre>' . "\n";
5786 $temprecipients = array();
5787 $tempreplyto = array();
5789 $supportuser = core_user::get_support_user();
5791 // Make up an email address for handling bounces.
5792 if (!empty($CFG->handlebounces)) {
5793 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5794 $mail->Sender = generate_email_processing_address(0, $modargs);
5795 } else {
5796 $mail->Sender = $supportuser->email;
5799 if (!empty($CFG->emailonlyfromnoreplyaddress)) {
5800 $usetrueaddress = false;
5801 if (empty($replyto) && $from->maildisplay) {
5802 $replyto = $from->email;
5803 $replytoname = fullname($from);
5807 if (is_string($from)) { // So we can pass whatever we want if there is need.
5808 $mail->From = $CFG->noreplyaddress;
5809 $mail->FromName = $from;
5810 } else if ($usetrueaddress and $from->maildisplay) {
5811 $mail->From = $from->email;
5812 $mail->FromName = fullname($from);
5813 } else {
5814 $mail->From = $CFG->noreplyaddress;
5815 $mail->FromName = fullname($from);
5816 if (empty($replyto)) {
5817 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5821 if (!empty($replyto)) {
5822 $tempreplyto[] = array($replyto, $replytoname);
5825 $mail->Subject = substr($subject, 0, 900);
5827 $temprecipients[] = array($user->email, fullname($user));
5829 // Set word wrap.
5830 $mail->WordWrap = $wordwrapwidth;
5832 if (!empty($from->customheaders)) {
5833 // Add custom headers.
5834 if (is_array($from->customheaders)) {
5835 foreach ($from->customheaders as $customheader) {
5836 $mail->addCustomHeader($customheader);
5838 } else {
5839 $mail->addCustomHeader($from->customheaders);
5843 if (!empty($from->priority)) {
5844 $mail->Priority = $from->priority;
5847 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5848 // Don't ever send HTML to users who don't want it.
5849 $mail->isHTML(true);
5850 $mail->Encoding = 'quoted-printable';
5851 $mail->Body = $messagehtml;
5852 $mail->AltBody = "\n$messagetext\n";
5853 } else {
5854 $mail->IsHTML(false);
5855 $mail->Body = "\n$messagetext\n";
5858 if ($attachment && $attachname) {
5859 if (preg_match( "~\\.\\.~" , $attachment )) {
5860 // Security check for ".." in dir path.
5861 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5862 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5863 } else {
5864 require_once($CFG->libdir.'/filelib.php');
5865 $mimetype = mimeinfo('type', $attachname);
5866 $mail->addAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
5870 // Check if the email should be sent in an other charset then the default UTF-8.
5871 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5873 // Use the defined site mail charset or eventually the one preferred by the recipient.
5874 $charset = $CFG->sitemailcharset;
5875 if (!empty($CFG->allowusermailcharset)) {
5876 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5877 $charset = $useremailcharset;
5881 // Convert all the necessary strings if the charset is supported.
5882 $charsets = get_list_of_charsets();
5883 unset($charsets['UTF-8']);
5884 if (in_array($charset, $charsets)) {
5885 $mail->CharSet = $charset;
5886 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5887 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5888 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5889 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5891 foreach ($temprecipients as $key => $values) {
5892 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5894 foreach ($tempreplyto as $key => $values) {
5895 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5900 foreach ($temprecipients as $values) {
5901 $mail->addAddress($values[0], $values[1]);
5903 foreach ($tempreplyto as $values) {
5904 $mail->addReplyTo($values[0], $values[1]);
5907 if ($mail->send()) {
5908 set_send_count($user);
5909 if (!empty($mail->SMTPDebug)) {
5910 echo '</pre>';
5912 return true;
5913 } else {
5914 // Trigger event for failing to send email.
5915 $event = \core\event\email_failed::create(array(
5916 'context' => context_system::instance(),
5917 'userid' => $from->id,
5918 'relateduserid' => $user->id,
5919 'other' => array(
5920 'subject' => $subject,
5921 'message' => $messagetext,
5922 'errorinfo' => $mail->ErrorInfo
5925 $event->trigger();
5926 if (CLI_SCRIPT) {
5927 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5929 if (!empty($mail->SMTPDebug)) {
5930 echo '</pre>';
5932 return false;
5937 * Generate a signoff for emails based on support settings
5939 * @return string
5941 function generate_email_signoff() {
5942 global $CFG;
5944 $signoff = "\n";
5945 if (!empty($CFG->supportname)) {
5946 $signoff .= $CFG->supportname."\n";
5948 if (!empty($CFG->supportemail)) {
5949 $signoff .= $CFG->supportemail."\n";
5951 if (!empty($CFG->supportpage)) {
5952 $signoff .= $CFG->supportpage."\n";
5954 return $signoff;
5958 * Sets specified user's password and send the new password to the user via email.
5960 * @param stdClass $user A {@link $USER} object
5961 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
5962 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
5964 function setnew_password_and_mail($user, $fasthash = false) {
5965 global $CFG, $DB;
5967 // We try to send the mail in language the user understands,
5968 // unfortunately the filter_string() does not support alternative langs yet
5969 // so multilang will not work properly for site->fullname.
5970 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
5972 $site = get_site();
5974 $supportuser = core_user::get_support_user();
5976 $newpassword = generate_password();
5978 $hashedpassword = hash_internal_user_password($newpassword, $fasthash);
5979 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
5980 $user->password = $hashedpassword;
5982 // Trigger event.
5983 $event = \core\event\user_updated::create(array(
5984 'objectid' => $user->id,
5985 'relateduserid' => $user->id,
5986 'context' => context_user::instance($user->id)
5988 $event->add_record_snapshot('user', $user);
5989 $event->trigger();
5991 $a = new stdClass();
5992 $a->firstname = fullname($user, true);
5993 $a->sitename = format_string($site->fullname);
5994 $a->username = $user->username;
5995 $a->newpassword = $newpassword;
5996 $a->link = $CFG->wwwroot .'/login/';
5997 $a->signoff = generate_email_signoff();
5999 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6001 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6003 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6004 return email_to_user($user, $supportuser, $subject, $message);
6009 * Resets specified user's password and send the new password to the user via email.
6011 * @param stdClass $user A {@link $USER} object
6012 * @return bool Returns true if mail was sent OK and false if there was an error.
6014 function reset_password_and_mail($user) {
6015 global $CFG;
6017 $site = get_site();
6018 $supportuser = core_user::get_support_user();
6020 $userauth = get_auth_plugin($user->auth);
6021 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6022 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6023 return false;
6026 $newpassword = generate_password();
6028 if (!$userauth->user_update_password($user, $newpassword)) {
6029 print_error("cannotsetpassword");
6032 $a = new stdClass();
6033 $a->firstname = $user->firstname;
6034 $a->lastname = $user->lastname;
6035 $a->sitename = format_string($site->fullname);
6036 $a->username = $user->username;
6037 $a->newpassword = $newpassword;
6038 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
6039 $a->signoff = generate_email_signoff();
6041 $message = get_string('newpasswordtext', '', $a);
6043 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6045 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6047 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6048 return email_to_user($user, $supportuser, $subject, $message);
6052 * Send email to specified user with confirmation text and activation link.
6054 * @param stdClass $user A {@link $USER} object
6055 * @return bool Returns true if mail was sent OK and false if there was an error.
6057 function send_confirmation_email($user) {
6058 global $CFG;
6060 $site = get_site();
6061 $supportuser = core_user::get_support_user();
6063 $data = new stdClass();
6064 $data->firstname = fullname($user);
6065 $data->sitename = format_string($site->fullname);
6066 $data->admin = generate_email_signoff();
6068 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6070 $username = urlencode($user->username);
6071 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
6072 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
6073 $message = get_string('emailconfirmation', '', $data);
6074 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6076 $user->mailformat = 1; // Always send HTML version as well.
6078 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6079 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6083 * Sends a password change confirmation email.
6085 * @param stdClass $user A {@link $USER} object
6086 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6087 * @return bool Returns true if mail was sent OK and false if there was an error.
6089 function send_password_change_confirmation_email($user, $resetrecord) {
6090 global $CFG;
6092 $site = get_site();
6093 $supportuser = core_user::get_support_user();
6094 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6096 $data = new stdClass();
6097 $data->firstname = $user->firstname;
6098 $data->lastname = $user->lastname;
6099 $data->username = $user->username;
6100 $data->sitename = format_string($site->fullname);
6101 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6102 $data->admin = generate_email_signoff();
6103 $data->resetminutes = $pwresetmins;
6105 $message = get_string('emailresetconfirmation', '', $data);
6106 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6108 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6109 return email_to_user($user, $supportuser, $subject, $message);
6114 * Sends an email containinginformation on how to change your password.
6116 * @param stdClass $user A {@link $USER} object
6117 * @return bool Returns true if mail was sent OK and false if there was an error.
6119 function send_password_change_info($user) {
6120 global $CFG;
6122 $site = get_site();
6123 $supportuser = core_user::get_support_user();
6124 $systemcontext = context_system::instance();
6126 $data = new stdClass();
6127 $data->firstname = $user->firstname;
6128 $data->lastname = $user->lastname;
6129 $data->sitename = format_string($site->fullname);
6130 $data->admin = generate_email_signoff();
6132 $userauth = get_auth_plugin($user->auth);
6134 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6135 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6136 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6137 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6138 return email_to_user($user, $supportuser, $subject, $message);
6141 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6142 // We have some external url for password changing.
6143 $data->link .= $userauth->change_password_url();
6145 } else {
6146 // No way to change password, sorry.
6147 $data->link = '';
6150 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6151 $message = get_string('emailpasswordchangeinfo', '', $data);
6152 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6153 } else {
6154 $message = get_string('emailpasswordchangeinfofail', '', $data);
6155 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6158 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6159 return email_to_user($user, $supportuser, $subject, $message);
6164 * Check that an email is allowed. It returns an error message if there was a problem.
6166 * @param string $email Content of email
6167 * @return string|false
6169 function email_is_not_allowed($email) {
6170 global $CFG;
6172 if (!empty($CFG->allowemailaddresses)) {
6173 $allowed = explode(' ', $CFG->allowemailaddresses);
6174 foreach ($allowed as $allowedpattern) {
6175 $allowedpattern = trim($allowedpattern);
6176 if (!$allowedpattern) {
6177 continue;
6179 if (strpos($allowedpattern, '.') === 0) {
6180 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6181 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6182 return false;
6185 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6186 return false;
6189 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6191 } else if (!empty($CFG->denyemailaddresses)) {
6192 $denied = explode(' ', $CFG->denyemailaddresses);
6193 foreach ($denied as $deniedpattern) {
6194 $deniedpattern = trim($deniedpattern);
6195 if (!$deniedpattern) {
6196 continue;
6198 if (strpos($deniedpattern, '.') === 0) {
6199 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6200 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6201 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6204 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6205 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6210 return false;
6213 // FILE HANDLING.
6216 * Returns local file storage instance
6218 * @return file_storage
6220 function get_file_storage() {
6221 global $CFG;
6223 static $fs = null;
6225 if ($fs) {
6226 return $fs;
6229 require_once("$CFG->libdir/filelib.php");
6231 if (isset($CFG->filedir)) {
6232 $filedir = $CFG->filedir;
6233 } else {
6234 $filedir = $CFG->dataroot.'/filedir';
6237 if (isset($CFG->trashdir)) {
6238 $trashdirdir = $CFG->trashdir;
6239 } else {
6240 $trashdirdir = $CFG->dataroot.'/trashdir';
6243 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6245 return $fs;
6249 * Returns local file storage instance
6251 * @return file_browser
6253 function get_file_browser() {
6254 global $CFG;
6256 static $fb = null;
6258 if ($fb) {
6259 return $fb;
6262 require_once("$CFG->libdir/filelib.php");
6264 $fb = new file_browser();
6266 return $fb;
6270 * Returns file packer
6272 * @param string $mimetype default application/zip
6273 * @return file_packer
6275 function get_file_packer($mimetype='application/zip') {
6276 global $CFG;
6278 static $fp = array();
6280 if (isset($fp[$mimetype])) {
6281 return $fp[$mimetype];
6284 switch ($mimetype) {
6285 case 'application/zip':
6286 case 'application/vnd.moodle.profiling':
6287 $classname = 'zip_packer';
6288 break;
6290 case 'application/x-gzip' :
6291 $classname = 'tgz_packer';
6292 break;
6294 case 'application/vnd.moodle.backup':
6295 $classname = 'mbz_packer';
6296 break;
6298 default:
6299 return false;
6302 require_once("$CFG->libdir/filestorage/$classname.php");
6303 $fp[$mimetype] = new $classname();
6305 return $fp[$mimetype];
6309 * Returns current name of file on disk if it exists.
6311 * @param string $newfile File to be verified
6312 * @return string Current name of file on disk if true
6314 function valid_uploaded_file($newfile) {
6315 if (empty($newfile)) {
6316 return '';
6318 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6319 return $newfile['tmp_name'];
6320 } else {
6321 return '';
6326 * Returns the maximum size for uploading files.
6328 * There are seven possible upload limits:
6329 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6330 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6331 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6332 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6333 * 5. by the Moodle admin in $CFG->maxbytes
6334 * 6. by the teacher in the current course $course->maxbytes
6335 * 7. by the teacher for the current module, eg $assignment->maxbytes
6337 * These last two are passed to this function as arguments (in bytes).
6338 * Anything defined as 0 is ignored.
6339 * The smallest of all the non-zero numbers is returned.
6341 * @todo Finish documenting this function
6343 * @param int $sitebytes Set maximum size
6344 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6345 * @param int $modulebytes Current module ->maxbytes (in bytes)
6346 * @return int The maximum size for uploading files.
6348 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6350 if (! $filesize = ini_get('upload_max_filesize')) {
6351 $filesize = '5M';
6353 $minimumsize = get_real_size($filesize);
6355 if ($postsize = ini_get('post_max_size')) {
6356 $postsize = get_real_size($postsize);
6357 if ($postsize < $minimumsize) {
6358 $minimumsize = $postsize;
6362 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6363 $minimumsize = $sitebytes;
6366 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6367 $minimumsize = $coursebytes;
6370 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6371 $minimumsize = $modulebytes;
6374 return $minimumsize;
6378 * Returns the maximum size for uploading files for the current user
6380 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6382 * @param context $context The context in which to check user capabilities
6383 * @param int $sitebytes Set maximum size
6384 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6385 * @param int $modulebytes Current module ->maxbytes (in bytes)
6386 * @param stdClass $user The user
6387 * @return int The maximum size for uploading files.
6389 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6390 global $USER;
6392 if (empty($user)) {
6393 $user = $USER;
6396 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6397 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6400 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6404 * Returns an array of possible sizes in local language
6406 * Related to {@link get_max_upload_file_size()} - this function returns an
6407 * array of possible sizes in an array, translated to the
6408 * local language.
6410 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6412 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6413 * with the value set to 0. This option will be the first in the list.
6415 * @uses SORT_NUMERIC
6416 * @param int $sitebytes Set maximum size
6417 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6418 * @param int $modulebytes Current module ->maxbytes (in bytes)
6419 * @param int|array $custombytes custom upload size/s which will be added to list,
6420 * Only value/s smaller then maxsize will be added to list.
6421 * @return array
6423 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6424 global $CFG;
6426 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6427 return array();
6430 if ($sitebytes == 0) {
6431 // Will get the minimum of upload_max_filesize or post_max_size.
6432 $sitebytes = get_max_upload_file_size();
6435 $filesize = array();
6436 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6437 5242880, 10485760, 20971520, 52428800, 104857600);
6439 // If custombytes is given and is valid then add it to the list.
6440 if (is_number($custombytes) and $custombytes > 0) {
6441 $custombytes = (int)$custombytes;
6442 if (!in_array($custombytes, $sizelist)) {
6443 $sizelist[] = $custombytes;
6445 } else if (is_array($custombytes)) {
6446 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6449 // Allow maxbytes to be selected if it falls outside the above boundaries.
6450 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6451 // Note: get_real_size() is used in order to prevent problems with invalid values.
6452 $sizelist[] = get_real_size($CFG->maxbytes);
6455 foreach ($sizelist as $sizebytes) {
6456 if ($sizebytes < $maxsize && $sizebytes > 0) {
6457 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6461 $limitlevel = '';
6462 $displaysize = '';
6463 if ($modulebytes &&
6464 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6465 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6466 $limitlevel = get_string('activity', 'core');
6467 $displaysize = display_size($modulebytes);
6468 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6470 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6471 $limitlevel = get_string('course', 'core');
6472 $displaysize = display_size($coursebytes);
6473 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6475 } else if ($sitebytes) {
6476 $limitlevel = get_string('site', 'core');
6477 $displaysize = display_size($sitebytes);
6478 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6481 krsort($filesize, SORT_NUMERIC);
6482 if ($limitlevel) {
6483 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6484 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6487 return $filesize;
6491 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6493 * If excludefiles is defined, then that file/directory is ignored
6494 * If getdirs is true, then (sub)directories are included in the output
6495 * If getfiles is true, then files are included in the output
6496 * (at least one of these must be true!)
6498 * @todo Finish documenting this function. Add examples of $excludefile usage.
6500 * @param string $rootdir A given root directory to start from
6501 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6502 * @param bool $descend If true then subdirectories are recursed as well
6503 * @param bool $getdirs If true then (sub)directories are included in the output
6504 * @param bool $getfiles If true then files are included in the output
6505 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6507 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6509 $dirs = array();
6511 if (!$getdirs and !$getfiles) { // Nothing to show.
6512 return $dirs;
6515 if (!is_dir($rootdir)) { // Must be a directory.
6516 return $dirs;
6519 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6520 return $dirs;
6523 if (!is_array($excludefiles)) {
6524 $excludefiles = array($excludefiles);
6527 while (false !== ($file = readdir($dir))) {
6528 $firstchar = substr($file, 0, 1);
6529 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6530 continue;
6532 $fullfile = $rootdir .'/'. $file;
6533 if (filetype($fullfile) == 'dir') {
6534 if ($getdirs) {
6535 $dirs[] = $file;
6537 if ($descend) {
6538 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6539 foreach ($subdirs as $subdir) {
6540 $dirs[] = $file .'/'. $subdir;
6543 } else if ($getfiles) {
6544 $dirs[] = $file;
6547 closedir($dir);
6549 asort($dirs);
6551 return $dirs;
6556 * Adds up all the files in a directory and works out the size.
6558 * @param string $rootdir The directory to start from
6559 * @param string $excludefile A file to exclude when summing directory size
6560 * @return int The summed size of all files and subfiles within the root directory
6562 function get_directory_size($rootdir, $excludefile='') {
6563 global $CFG;
6565 // Do it this way if we can, it's much faster.
6566 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6567 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6568 $output = null;
6569 $return = null;
6570 exec($command, $output, $return);
6571 if (is_array($output)) {
6572 // We told it to return k.
6573 return get_real_size(intval($output[0]).'k');
6577 if (!is_dir($rootdir)) {
6578 // Must be a directory.
6579 return 0;
6582 if (!$dir = @opendir($rootdir)) {
6583 // Can't open it for some reason.
6584 return 0;
6587 $size = 0;
6589 while (false !== ($file = readdir($dir))) {
6590 $firstchar = substr($file, 0, 1);
6591 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6592 continue;
6594 $fullfile = $rootdir .'/'. $file;
6595 if (filetype($fullfile) == 'dir') {
6596 $size += get_directory_size($fullfile, $excludefile);
6597 } else {
6598 $size += filesize($fullfile);
6601 closedir($dir);
6603 return $size;
6607 * Converts bytes into display form
6609 * @static string $gb Localized string for size in gigabytes
6610 * @static string $mb Localized string for size in megabytes
6611 * @static string $kb Localized string for size in kilobytes
6612 * @static string $b Localized string for size in bytes
6613 * @param int $size The size to convert to human readable form
6614 * @return string
6616 function display_size($size) {
6618 static $gb, $mb, $kb, $b;
6620 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6621 return get_string('unlimited');
6624 if (empty($gb)) {
6625 $gb = get_string('sizegb');
6626 $mb = get_string('sizemb');
6627 $kb = get_string('sizekb');
6628 $b = get_string('sizeb');
6631 if ($size >= 1073741824) {
6632 $size = round($size / 1073741824 * 10) / 10 . $gb;
6633 } else if ($size >= 1048576) {
6634 $size = round($size / 1048576 * 10) / 10 . $mb;
6635 } else if ($size >= 1024) {
6636 $size = round($size / 1024 * 10) / 10 . $kb;
6637 } else {
6638 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6640 return $size;
6644 * Cleans a given filename by removing suspicious or troublesome characters
6646 * @see clean_param()
6647 * @param string $string file name
6648 * @return string cleaned file name
6650 function clean_filename($string) {
6651 return clean_param($string, PARAM_FILE);
6655 // STRING TRANSLATION.
6658 * Returns the code for the current language
6660 * @category string
6661 * @return string
6663 function current_language() {
6664 global $CFG, $USER, $SESSION, $COURSE;
6666 if (!empty($SESSION->forcelang)) {
6667 // Allows overriding course-forced language (useful for admins to check
6668 // issues in courses whose language they don't understand).
6669 // Also used by some code to temporarily get language-related information in a
6670 // specific language (see force_current_language()).
6671 $return = $SESSION->forcelang;
6673 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6674 // Course language can override all other settings for this page.
6675 $return = $COURSE->lang;
6677 } else if (!empty($SESSION->lang)) {
6678 // Session language can override other settings.
6679 $return = $SESSION->lang;
6681 } else if (!empty($USER->lang)) {
6682 $return = $USER->lang;
6684 } else if (isset($CFG->lang)) {
6685 $return = $CFG->lang;
6687 } else {
6688 $return = 'en';
6691 // Just in case this slipped in from somewhere by accident.
6692 $return = str_replace('_utf8', '', $return);
6694 return $return;
6698 * Returns parent language of current active language if defined
6700 * @category string
6701 * @param string $lang null means current language
6702 * @return string
6704 function get_parent_language($lang=null) {
6706 // Let's hack around the current language.
6707 if (!empty($lang)) {
6708 $oldforcelang = force_current_language($lang);
6711 $parentlang = get_string('parentlanguage', 'langconfig');
6712 if ($parentlang === 'en') {
6713 $parentlang = '';
6716 // Let's hack around the current language.
6717 if (!empty($lang)) {
6718 force_current_language($oldforcelang);
6721 return $parentlang;
6725 * Force the current language to get strings and dates localised in the given language.
6727 * After calling this function, all strings will be provided in the given language
6728 * until this function is called again, or equivalent code is run.
6730 * @param string $language
6731 * @return string previous $SESSION->forcelang value
6733 function force_current_language($language) {
6734 global $SESSION;
6735 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6736 if ($language !== $sessionforcelang) {
6737 // Seting forcelang to null or an empty string disables it's effect.
6738 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6739 $SESSION->forcelang = $language;
6740 moodle_setlocale();
6743 return $sessionforcelang;
6747 * Returns current string_manager instance.
6749 * The param $forcereload is needed for CLI installer only where the string_manager instance
6750 * must be replaced during the install.php script life time.
6752 * @category string
6753 * @param bool $forcereload shall the singleton be released and new instance created instead?
6754 * @return core_string_manager
6756 function get_string_manager($forcereload=false) {
6757 global $CFG;
6759 static $singleton = null;
6761 if ($forcereload) {
6762 $singleton = null;
6764 if ($singleton === null) {
6765 if (empty($CFG->early_install_lang)) {
6767 if (empty($CFG->langlist)) {
6768 $translist = array();
6769 } else {
6770 $translist = explode(',', $CFG->langlist);
6773 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6775 } else {
6776 $singleton = new core_string_manager_install();
6780 return $singleton;
6784 * Returns a localized string.
6786 * Returns the translated string specified by $identifier as
6787 * for $module. Uses the same format files as STphp.
6788 * $a is an object, string or number that can be used
6789 * within translation strings
6791 * eg 'hello {$a->firstname} {$a->lastname}'
6792 * or 'hello {$a}'
6794 * If you would like to directly echo the localized string use
6795 * the function {@link print_string()}
6797 * Example usage of this function involves finding the string you would
6798 * like a local equivalent of and using its identifier and module information
6799 * to retrieve it.<br/>
6800 * If you open moodle/lang/en/moodle.php and look near line 278
6801 * you will find a string to prompt a user for their word for 'course'
6802 * <code>
6803 * $string['course'] = 'Course';
6804 * </code>
6805 * So if you want to display the string 'Course'
6806 * in any language that supports it on your site
6807 * you just need to use the identifier 'course'
6808 * <code>
6809 * $mystring = '<strong>'. get_string('course') .'</strong>';
6810 * or
6811 * </code>
6812 * If the string you want is in another file you'd take a slightly
6813 * different approach. Looking in moodle/lang/en/calendar.php you find
6814 * around line 75:
6815 * <code>
6816 * $string['typecourse'] = 'Course event';
6817 * </code>
6818 * If you want to display the string "Course event" in any language
6819 * supported you would use the identifier 'typecourse' and the module 'calendar'
6820 * (because it is in the file calendar.php):
6821 * <code>
6822 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6823 * </code>
6825 * As a last resort, should the identifier fail to map to a string
6826 * the returned string will be [[ $identifier ]]
6828 * In Moodle 2.3 there is a new argument to this function $lazyload.
6829 * Setting $lazyload to true causes get_string to return a lang_string object
6830 * rather than the string itself. The fetching of the string is then put off until
6831 * the string object is first used. The object can be used by calling it's out
6832 * method or by casting the object to a string, either directly e.g.
6833 * (string)$stringobject
6834 * or indirectly by using the string within another string or echoing it out e.g.
6835 * echo $stringobject
6836 * return "<p>{$stringobject}</p>";
6837 * It is worth noting that using $lazyload and attempting to use the string as an
6838 * array key will cause a fatal error as objects cannot be used as array keys.
6839 * But you should never do that anyway!
6840 * For more information {@link lang_string}
6842 * @category string
6843 * @param string $identifier The key identifier for the localized string
6844 * @param string $component The module where the key identifier is stored,
6845 * usually expressed as the filename in the language pack without the
6846 * .php on the end but can also be written as mod/forum or grade/export/xls.
6847 * If none is specified then moodle.php is used.
6848 * @param string|object|array $a An object, string or number that can be used
6849 * within translation strings
6850 * @param bool $lazyload If set to true a string object is returned instead of
6851 * the string itself. The string then isn't calculated until it is first used.
6852 * @return string The localized string.
6853 * @throws coding_exception
6855 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6856 global $CFG;
6858 // If the lazy load argument has been supplied return a lang_string object
6859 // instead.
6860 // We need to make sure it is true (and a bool) as you will see below there
6861 // used to be a forth argument at one point.
6862 if ($lazyload === true) {
6863 return new lang_string($identifier, $component, $a);
6866 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6867 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6870 // There is now a forth argument again, this time it is a boolean however so
6871 // we can still check for the old extralocations parameter.
6872 if (!is_bool($lazyload) && !empty($lazyload)) {
6873 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6876 if (strpos($component, '/') !== false) {
6877 debugging('The module name you passed to get_string is the deprecated format ' .
6878 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6879 $componentpath = explode('/', $component);
6881 switch ($componentpath[0]) {
6882 case 'mod':
6883 $component = $componentpath[1];
6884 break;
6885 case 'blocks':
6886 case 'block':
6887 $component = 'block_'.$componentpath[1];
6888 break;
6889 case 'enrol':
6890 $component = 'enrol_'.$componentpath[1];
6891 break;
6892 case 'format':
6893 $component = 'format_'.$componentpath[1];
6894 break;
6895 case 'grade':
6896 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6897 break;
6901 $result = get_string_manager()->get_string($identifier, $component, $a);
6903 // Debugging feature lets you display string identifier and component.
6904 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6905 $result .= ' {' . $identifier . '/' . $component . '}';
6907 return $result;
6911 * Converts an array of strings to their localized value.
6913 * @param array $array An array of strings
6914 * @param string $component The language module that these strings can be found in.
6915 * @return stdClass translated strings.
6917 function get_strings($array, $component = '') {
6918 $string = new stdClass;
6919 foreach ($array as $item) {
6920 $string->$item = get_string($item, $component);
6922 return $string;
6926 * Prints out a translated string.
6928 * Prints out a translated string using the return value from the {@link get_string()} function.
6930 * Example usage of this function when the string is in the moodle.php file:<br/>
6931 * <code>
6932 * echo '<strong>';
6933 * print_string('course');
6934 * echo '</strong>';
6935 * </code>
6937 * Example usage of this function when the string is not in the moodle.php file:<br/>
6938 * <code>
6939 * echo '<h1>';
6940 * print_string('typecourse', 'calendar');
6941 * echo '</h1>';
6942 * </code>
6944 * @category string
6945 * @param string $identifier The key identifier for the localized string
6946 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6947 * @param string|object|array $a An object, string or number that can be used within translation strings
6949 function print_string($identifier, $component = '', $a = null) {
6950 echo get_string($identifier, $component, $a);
6954 * Returns a list of charset codes
6956 * Returns a list of charset codes. It's hardcoded, so they should be added manually
6957 * (checking that such charset is supported by the texlib library!)
6959 * @return array And associative array with contents in the form of charset => charset
6961 function get_list_of_charsets() {
6963 $charsets = array(
6964 'EUC-JP' => 'EUC-JP',
6965 'ISO-2022-JP'=> 'ISO-2022-JP',
6966 'ISO-8859-1' => 'ISO-8859-1',
6967 'SHIFT-JIS' => 'SHIFT-JIS',
6968 'GB2312' => 'GB2312',
6969 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
6970 'UTF-8' => 'UTF-8');
6972 asort($charsets);
6974 return $charsets;
6978 * Returns a list of valid and compatible themes
6980 * @return array
6982 function get_list_of_themes() {
6983 global $CFG;
6985 $themes = array();
6987 if (!empty($CFG->themelist)) { // Use admin's list of themes.
6988 $themelist = explode(',', $CFG->themelist);
6989 } else {
6990 $themelist = array_keys(core_component::get_plugin_list("theme"));
6993 foreach ($themelist as $key => $themename) {
6994 $theme = theme_config::load($themename);
6995 $themes[$themename] = $theme;
6998 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7000 return $themes;
7004 * Returns a list of timezones in the current language
7006 * @return array
7008 function get_list_of_timezones() {
7009 global $DB;
7011 static $timezones;
7013 if (!empty($timezones)) { // This function has been called recently.
7014 return $timezones;
7017 $timezones = array();
7019 if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
7020 foreach ($rawtimezones as $timezone) {
7021 if (!empty($timezone->name)) {
7022 if (get_string_manager()->string_exists(strtolower($timezone->name), 'timezones')) {
7023 $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
7024 } else {
7025 $timezones[$timezone->name] = $timezone->name;
7027 if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found.
7028 $timezones[$timezone->name] = $timezone->name;
7034 asort($timezones);
7036 for ($i = -13; $i <= 13; $i += .5) {
7037 $tzstring = 'UTC';
7038 if ($i < 0) {
7039 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
7040 } else if ($i > 0) {
7041 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
7042 } else {
7043 $timezones[sprintf("%.1f", $i)] = $tzstring;
7047 return $timezones;
7051 * Factory function for emoticon_manager
7053 * @return emoticon_manager singleton
7055 function get_emoticon_manager() {
7056 static $singleton = null;
7058 if (is_null($singleton)) {
7059 $singleton = new emoticon_manager();
7062 return $singleton;
7066 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7068 * Whenever this manager mentiones 'emoticon object', the following data
7069 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7070 * altidentifier and altcomponent
7072 * @see admin_setting_emoticons
7074 * @copyright 2010 David Mudrak
7075 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7077 class emoticon_manager {
7080 * Returns the currently enabled emoticons
7082 * @return array of emoticon objects
7084 public function get_emoticons() {
7085 global $CFG;
7087 if (empty($CFG->emoticons)) {
7088 return array();
7091 $emoticons = $this->decode_stored_config($CFG->emoticons);
7093 if (!is_array($emoticons)) {
7094 // Something is wrong with the format of stored setting.
7095 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7096 return array();
7099 return $emoticons;
7103 * Converts emoticon object into renderable pix_emoticon object
7105 * @param stdClass $emoticon emoticon object
7106 * @param array $attributes explicit HTML attributes to set
7107 * @return pix_emoticon
7109 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7110 $stringmanager = get_string_manager();
7111 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7112 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7113 } else {
7114 $alt = s($emoticon->text);
7116 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7120 * Encodes the array of emoticon objects into a string storable in config table
7122 * @see self::decode_stored_config()
7123 * @param array $emoticons array of emtocion objects
7124 * @return string
7126 public function encode_stored_config(array $emoticons) {
7127 return json_encode($emoticons);
7131 * Decodes the string into an array of emoticon objects
7133 * @see self::encode_stored_config()
7134 * @param string $encoded
7135 * @return string|null
7137 public function decode_stored_config($encoded) {
7138 $decoded = json_decode($encoded);
7139 if (!is_array($decoded)) {
7140 return null;
7142 return $decoded;
7146 * Returns default set of emoticons supported by Moodle
7148 * @return array of sdtClasses
7150 public function default_emoticons() {
7151 return array(
7152 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7153 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7154 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7155 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7156 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7157 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7158 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7159 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7160 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7161 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7162 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7163 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7164 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7165 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7166 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7167 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7168 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7169 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7170 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7171 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7172 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7173 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7174 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7175 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7176 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7177 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7178 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7179 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7180 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7181 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7186 * Helper method preparing the stdClass with the emoticon properties
7188 * @param string|array $text or array of strings
7189 * @param string $imagename to be used by {@link pix_emoticon}
7190 * @param string $altidentifier alternative string identifier, null for no alt
7191 * @param string $altcomponent where the alternative string is defined
7192 * @param string $imagecomponent to be used by {@link pix_emoticon}
7193 * @return stdClass
7195 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7196 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7197 return (object)array(
7198 'text' => $text,
7199 'imagename' => $imagename,
7200 'imagecomponent' => $imagecomponent,
7201 'altidentifier' => $altidentifier,
7202 'altcomponent' => $altcomponent,
7207 // ENCRYPTION.
7210 * rc4encrypt
7212 * @param string $data Data to encrypt.
7213 * @return string The now encrypted data.
7215 function rc4encrypt($data) {
7216 return endecrypt(get_site_identifier(), $data, '');
7220 * rc4decrypt
7222 * @param string $data Data to decrypt.
7223 * @return string The now decrypted data.
7225 function rc4decrypt($data) {
7226 return endecrypt(get_site_identifier(), $data, 'de');
7230 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7232 * @todo Finish documenting this function
7234 * @param string $pwd The password to use when encrypting or decrypting
7235 * @param string $data The data to be decrypted/encrypted
7236 * @param string $case Either 'de' for decrypt or '' for encrypt
7237 * @return string
7239 function endecrypt ($pwd, $data, $case) {
7241 if ($case == 'de') {
7242 $data = urldecode($data);
7245 $key[] = '';
7246 $box[] = '';
7247 $pwdlength = strlen($pwd);
7249 for ($i = 0; $i <= 255; $i++) {
7250 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7251 $box[$i] = $i;
7254 $x = 0;
7256 for ($i = 0; $i <= 255; $i++) {
7257 $x = ($x + $box[$i] + $key[$i]) % 256;
7258 $tempswap = $box[$i];
7259 $box[$i] = $box[$x];
7260 $box[$x] = $tempswap;
7263 $cipher = '';
7265 $a = 0;
7266 $j = 0;
7268 for ($i = 0; $i < strlen($data); $i++) {
7269 $a = ($a + 1) % 256;
7270 $j = ($j + $box[$a]) % 256;
7271 $temp = $box[$a];
7272 $box[$a] = $box[$j];
7273 $box[$j] = $temp;
7274 $k = $box[(($box[$a] + $box[$j]) % 256)];
7275 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7276 $cipher .= chr($cipherby);
7279 if ($case == 'de') {
7280 $cipher = urldecode(urlencode($cipher));
7281 } else {
7282 $cipher = urlencode($cipher);
7285 return $cipher;
7288 // ENVIRONMENT CHECKING.
7291 * This method validates a plug name. It is much faster than calling clean_param.
7293 * @param string $name a string that might be a plugin name.
7294 * @return bool if this string is a valid plugin name.
7296 function is_valid_plugin_name($name) {
7297 // This does not work for 'mod', bad luck, use any other type.
7298 return core_component::is_valid_plugin_name('tool', $name);
7302 * Get a list of all the plugins of a given type that define a certain API function
7303 * in a certain file. The plugin component names and function names are returned.
7305 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7306 * @param string $function the part of the name of the function after the
7307 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7308 * names like report_courselist_hook.
7309 * @param string $file the name of file within the plugin that defines the
7310 * function. Defaults to lib.php.
7311 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7312 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7314 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7315 $pluginfunctions = array();
7316 $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, $file, true);
7317 foreach ($pluginswithfile as $plugin => $notused) {
7318 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7320 if (function_exists($fullfunction)) {
7321 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7322 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
7324 } else if ($plugintype === 'mod') {
7325 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7326 $shortfunction = $plugin . '_' . $function;
7327 if (function_exists($shortfunction)) {
7328 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
7332 return $pluginfunctions;
7336 * Lists plugin-like directories within specified directory
7338 * This function was originally used for standard Moodle plugins, please use
7339 * new core_component::get_plugin_list() now.
7341 * This function is used for general directory listing and backwards compatility.
7343 * @param string $directory relative directory from root
7344 * @param string $exclude dir name to exclude from the list (defaults to none)
7345 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7346 * @return array Sorted array of directory names found under the requested parameters
7348 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7349 global $CFG;
7351 $plugins = array();
7353 if (empty($basedir)) {
7354 $basedir = $CFG->dirroot .'/'. $directory;
7356 } else {
7357 $basedir = $basedir .'/'. $directory;
7360 if ($CFG->debugdeveloper and empty($exclude)) {
7361 // Make sure devs do not use this to list normal plugins,
7362 // this is intended for general directories that are not plugins!
7364 $subtypes = core_component::get_plugin_types();
7365 if (in_array($basedir, $subtypes)) {
7366 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7368 unset($subtypes);
7371 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7372 if (!$dirhandle = opendir($basedir)) {
7373 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7374 return array();
7376 while (false !== ($dir = readdir($dirhandle))) {
7377 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7378 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7379 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7380 continue;
7382 if (filetype($basedir .'/'. $dir) != 'dir') {
7383 continue;
7385 $plugins[] = $dir;
7387 closedir($dirhandle);
7389 if ($plugins) {
7390 asort($plugins);
7392 return $plugins;
7396 * Invoke plugin's callback functions
7398 * @param string $type plugin type e.g. 'mod'
7399 * @param string $name plugin name
7400 * @param string $feature feature name
7401 * @param string $action feature's action
7402 * @param array $params parameters of callback function, should be an array
7403 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7404 * @return mixed
7406 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7408 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7409 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7413 * Invoke component's callback functions
7415 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7416 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7417 * @param array $params parameters of callback function
7418 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7419 * @return mixed
7421 function component_callback($component, $function, array $params = array(), $default = null) {
7423 $functionname = component_callback_exists($component, $function);
7425 if ($functionname) {
7426 // Function exists, so just return function result.
7427 $ret = call_user_func_array($functionname, $params);
7428 if (is_null($ret)) {
7429 return $default;
7430 } else {
7431 return $ret;
7434 return $default;
7438 * Determine if a component callback exists and return the function name to call. Note that this
7439 * function will include the required library files so that the functioname returned can be
7440 * called directly.
7442 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7443 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7444 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7445 * @throws coding_exception if invalid component specfied
7447 function component_callback_exists($component, $function) {
7448 global $CFG; // This is needed for the inclusions.
7450 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7451 if (empty($cleancomponent)) {
7452 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7454 $component = $cleancomponent;
7456 list($type, $name) = core_component::normalize_component($component);
7457 $component = $type . '_' . $name;
7459 $oldfunction = $name.'_'.$function;
7460 $function = $component.'_'.$function;
7462 $dir = core_component::get_component_directory($component);
7463 if (empty($dir)) {
7464 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7467 // Load library and look for function.
7468 if (file_exists($dir.'/lib.php')) {
7469 require_once($dir.'/lib.php');
7472 if (!function_exists($function) and function_exists($oldfunction)) {
7473 if ($type !== 'mod' and $type !== 'core') {
7474 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7476 $function = $oldfunction;
7479 if (function_exists($function)) {
7480 return $function;
7482 return false;
7486 * Checks whether a plugin supports a specified feature.
7488 * @param string $type Plugin type e.g. 'mod'
7489 * @param string $name Plugin name e.g. 'forum'
7490 * @param string $feature Feature code (FEATURE_xx constant)
7491 * @param mixed $default default value if feature support unknown
7492 * @return mixed Feature result (false if not supported, null if feature is unknown,
7493 * otherwise usually true but may have other feature-specific value such as array)
7494 * @throws coding_exception
7496 function plugin_supports($type, $name, $feature, $default = null) {
7497 global $CFG;
7499 if ($type === 'mod' and $name === 'NEWMODULE') {
7500 // Somebody forgot to rename the module template.
7501 return false;
7504 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7505 if (empty($component)) {
7506 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7509 $function = null;
7511 if ($type === 'mod') {
7512 // We need this special case because we support subplugins in modules,
7513 // otherwise it would end up in infinite loop.
7514 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7515 include_once("$CFG->dirroot/mod/$name/lib.php");
7516 $function = $component.'_supports';
7517 if (!function_exists($function)) {
7518 // Legacy non-frankenstyle function name.
7519 $function = $name.'_supports';
7523 } else {
7524 if (!$path = core_component::get_plugin_directory($type, $name)) {
7525 // Non existent plugin type.
7526 return false;
7528 if (file_exists("$path/lib.php")) {
7529 include_once("$path/lib.php");
7530 $function = $component.'_supports';
7534 if ($function and function_exists($function)) {
7535 $supports = $function($feature);
7536 if (is_null($supports)) {
7537 // Plugin does not know - use default.
7538 return $default;
7539 } else {
7540 return $supports;
7544 // Plugin does not care, so use default.
7545 return $default;
7549 * Returns true if the current version of PHP is greater that the specified one.
7551 * @todo Check PHP version being required here is it too low?
7553 * @param string $version The version of php being tested.
7554 * @return bool
7556 function check_php_version($version='5.2.4') {
7557 return (version_compare(phpversion(), $version) >= 0);
7561 * Determine if moodle installation requires update.
7563 * Checks version numbers of main code and all plugins to see
7564 * if there are any mismatches.
7566 * @return bool
7568 function moodle_needs_upgrading() {
7569 global $CFG;
7571 if (empty($CFG->version)) {
7572 return true;
7575 // There is no need to purge plugininfo caches here because
7576 // these caches are not used during upgrade and they are purged after
7577 // every upgrade.
7579 if (empty($CFG->allversionshash)) {
7580 return true;
7583 $hash = core_component::get_all_versions_hash();
7585 return ($hash !== $CFG->allversionshash);
7589 * Returns the major version of this site
7591 * Moodle version numbers consist of three numbers separated by a dot, for
7592 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7593 * called major version. This function extracts the major version from either
7594 * $CFG->release (default) or eventually from the $release variable defined in
7595 * the main version.php.
7597 * @param bool $fromdisk should the version if source code files be used
7598 * @return string|false the major version like '2.3', false if could not be determined
7600 function moodle_major_version($fromdisk = false) {
7601 global $CFG;
7603 if ($fromdisk) {
7604 $release = null;
7605 require($CFG->dirroot.'/version.php');
7606 if (empty($release)) {
7607 return false;
7610 } else {
7611 if (empty($CFG->release)) {
7612 return false;
7614 $release = $CFG->release;
7617 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7618 return $matches[0];
7619 } else {
7620 return false;
7624 // MISCELLANEOUS.
7627 * Sets the system locale
7629 * @category string
7630 * @param string $locale Can be used to force a locale
7632 function moodle_setlocale($locale='') {
7633 global $CFG;
7635 static $currentlocale = ''; // Last locale caching.
7637 $oldlocale = $currentlocale;
7639 // Fetch the correct locale based on ostype.
7640 if ($CFG->ostype == 'WINDOWS') {
7641 $stringtofetch = 'localewin';
7642 } else {
7643 $stringtofetch = 'locale';
7646 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7647 if (!empty($locale)) {
7648 $currentlocale = $locale;
7649 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7650 $currentlocale = $CFG->locale;
7651 } else {
7652 $currentlocale = get_string($stringtofetch, 'langconfig');
7655 // Do nothing if locale already set up.
7656 if ($oldlocale == $currentlocale) {
7657 return;
7660 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7661 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7662 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7664 // Get current values.
7665 $monetary= setlocale (LC_MONETARY, 0);
7666 $numeric = setlocale (LC_NUMERIC, 0);
7667 $ctype = setlocale (LC_CTYPE, 0);
7668 if ($CFG->ostype != 'WINDOWS') {
7669 $messages= setlocale (LC_MESSAGES, 0);
7671 // Set locale to all.
7672 $result = setlocale (LC_ALL, $currentlocale);
7673 // If setting of locale fails try the other utf8 or utf-8 variant,
7674 // some operating systems support both (Debian), others just one (OSX).
7675 if ($result === false) {
7676 if (stripos($currentlocale, '.UTF-8') !== false) {
7677 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7678 setlocale (LC_ALL, $newlocale);
7679 } else if (stripos($currentlocale, '.UTF8') !== false) {
7680 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7681 setlocale (LC_ALL, $newlocale);
7684 // Set old values.
7685 setlocale (LC_MONETARY, $monetary);
7686 setlocale (LC_NUMERIC, $numeric);
7687 if ($CFG->ostype != 'WINDOWS') {
7688 setlocale (LC_MESSAGES, $messages);
7690 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7691 // To workaround a well-known PHP problem with Turkish letter Ii.
7692 setlocale (LC_CTYPE, $ctype);
7697 * Count words in a string.
7699 * Words are defined as things between whitespace.
7701 * @category string
7702 * @param string $string The text to be searched for words.
7703 * @return int The count of words in the specified string
7705 function count_words($string) {
7706 $string = strip_tags($string);
7707 // Decode HTML entities.
7708 $string = html_entity_decode($string);
7709 // Replace underscores (which are classed as word characters) with spaces.
7710 $string = preg_replace('/_/u', ' ', $string);
7711 // Remove any characters that shouldn't be treated as word boundaries.
7712 $string = preg_replace('/[\'’-]/u', '', $string);
7713 // Remove dots and commas from within numbers only.
7714 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7716 return count(preg_split('/\w\b/u', $string)) - 1;
7720 * Count letters in a string.
7722 * Letters are defined as chars not in tags and different from whitespace.
7724 * @category string
7725 * @param string $string The text to be searched for letters.
7726 * @return int The count of letters in the specified text.
7728 function count_letters($string) {
7729 $string = strip_tags($string); // Tags are out now.
7730 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7732 return core_text::strlen($string);
7736 * Generate and return a random string of the specified length.
7738 * @param int $length The length of the string to be created.
7739 * @return string
7741 function random_string ($length=15) {
7742 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7743 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7744 $pool .= '0123456789';
7745 $poollen = strlen($pool);
7746 $string = '';
7747 for ($i = 0; $i < $length; $i++) {
7748 $string .= substr($pool, (mt_rand()%($poollen)), 1);
7750 return $string;
7754 * Generate a complex random string (useful for md5 salts)
7756 * This function is based on the above {@link random_string()} however it uses a
7757 * larger pool of characters and generates a string between 24 and 32 characters
7759 * @param int $length Optional if set generates a string to exactly this length
7760 * @return string
7762 function complex_random_string($length=null) {
7763 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7764 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7765 $poollen = strlen($pool);
7766 if ($length===null) {
7767 $length = floor(rand(24, 32));
7769 $string = '';
7770 for ($i = 0; $i < $length; $i++) {
7771 $string .= $pool[(mt_rand()%$poollen)];
7773 return $string;
7777 * Given some text (which may contain HTML) and an ideal length,
7778 * this function truncates the text neatly on a word boundary if possible
7780 * @category string
7781 * @param string $text text to be shortened
7782 * @param int $ideal ideal string length
7783 * @param boolean $exact if false, $text will not be cut mid-word
7784 * @param string $ending The string to append if the passed string is truncated
7785 * @return string $truncate shortened string
7787 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7788 // If the plain text is shorter than the maximum length, return the whole text.
7789 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7790 return $text;
7793 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7794 // and only tag in its 'line'.
7795 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7797 $totallength = core_text::strlen($ending);
7798 $truncate = '';
7800 // This array stores information about open and close tags and their position
7801 // in the truncated string. Each item in the array is an object with fields
7802 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7803 // (byte position in truncated text).
7804 $tagdetails = array();
7806 foreach ($lines as $linematchings) {
7807 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7808 if (!empty($linematchings[1])) {
7809 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7810 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7811 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7812 // Record closing tag.
7813 $tagdetails[] = (object) array(
7814 'open' => false,
7815 'tag' => core_text::strtolower($tagmatchings[1]),
7816 'pos' => core_text::strlen($truncate),
7819 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7820 // Record opening tag.
7821 $tagdetails[] = (object) array(
7822 'open' => true,
7823 'tag' => core_text::strtolower($tagmatchings[1]),
7824 'pos' => core_text::strlen($truncate),
7828 // Add html-tag to $truncate'd text.
7829 $truncate .= $linematchings[1];
7832 // Calculate the length of the plain text part of the line; handle entities as one character.
7833 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7834 if ($totallength + $contentlength > $ideal) {
7835 // The number of characters which are left.
7836 $left = $ideal - $totallength;
7837 $entitieslength = 0;
7838 // Search for html entities.
7839 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)) {
7840 // Calculate the real length of all entities in the legal range.
7841 foreach ($entities[0] as $entity) {
7842 if ($entity[1]+1-$entitieslength <= $left) {
7843 $left--;
7844 $entitieslength += core_text::strlen($entity[0]);
7845 } else {
7846 // No more characters left.
7847 break;
7851 $breakpos = $left + $entitieslength;
7853 // If the words shouldn't be cut in the middle...
7854 if (!$exact) {
7855 // Search the last occurence of a space.
7856 for (; $breakpos > 0; $breakpos--) {
7857 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
7858 if ($char === '.' or $char === ' ') {
7859 $breakpos += 1;
7860 break;
7861 } else if (strlen($char) > 2) {
7862 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7863 $breakpos += 1;
7864 break;
7869 if ($breakpos == 0) {
7870 // This deals with the test_shorten_text_no_spaces case.
7871 $breakpos = $left + $entitieslength;
7872 } else if ($breakpos > $left + $entitieslength) {
7873 // This deals with the previous for loop breaking on the first char.
7874 $breakpos = $left + $entitieslength;
7877 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
7878 // Maximum length is reached, so get off the loop.
7879 break;
7880 } else {
7881 $truncate .= $linematchings[2];
7882 $totallength += $contentlength;
7885 // If the maximum length is reached, get off the loop.
7886 if ($totallength >= $ideal) {
7887 break;
7891 // Add the defined ending to the text.
7892 $truncate .= $ending;
7894 // Now calculate the list of open html tags based on the truncate position.
7895 $opentags = array();
7896 foreach ($tagdetails as $taginfo) {
7897 if ($taginfo->open) {
7898 // Add tag to the beginning of $opentags list.
7899 array_unshift($opentags, $taginfo->tag);
7900 } else {
7901 // Can have multiple exact same open tags, close the last one.
7902 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
7903 if ($pos !== false) {
7904 unset($opentags[$pos]);
7909 // Close all unclosed html-tags.
7910 foreach ($opentags as $tag) {
7911 $truncate .= '</' . $tag . '>';
7914 return $truncate;
7919 * Given dates in seconds, how many weeks is the date from startdate
7920 * The first week is 1, the second 2 etc ...
7922 * @param int $startdate Timestamp for the start date
7923 * @param int $thedate Timestamp for the end date
7924 * @return string
7926 function getweek ($startdate, $thedate) {
7927 if ($thedate < $startdate) {
7928 return 0;
7931 return floor(($thedate - $startdate) / WEEKSECS) + 1;
7935 * Returns a randomly generated password of length $maxlen. inspired by
7937 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
7938 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
7940 * @param int $maxlen The maximum size of the password being generated.
7941 * @return string
7943 function generate_password($maxlen=10) {
7944 global $CFG;
7946 if (empty($CFG->passwordpolicy)) {
7947 $fillers = PASSWORD_DIGITS;
7948 $wordlist = file($CFG->wordlist);
7949 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7950 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7951 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
7952 $password = $word1 . $filler1 . $word2;
7953 } else {
7954 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
7955 $digits = $CFG->minpassworddigits;
7956 $lower = $CFG->minpasswordlower;
7957 $upper = $CFG->minpasswordupper;
7958 $nonalphanum = $CFG->minpasswordnonalphanum;
7959 $total = $lower + $upper + $digits + $nonalphanum;
7960 // Var minlength should be the greater one of the two ( $minlen and $total ).
7961 $minlen = $minlen < $total ? $total : $minlen;
7962 // Var maxlen can never be smaller than minlen.
7963 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
7964 $additional = $maxlen - $total;
7966 // Make sure we have enough characters to fulfill
7967 // complexity requirements.
7968 $passworddigits = PASSWORD_DIGITS;
7969 while ($digits > strlen($passworddigits)) {
7970 $passworddigits .= PASSWORD_DIGITS;
7972 $passwordlower = PASSWORD_LOWER;
7973 while ($lower > strlen($passwordlower)) {
7974 $passwordlower .= PASSWORD_LOWER;
7976 $passwordupper = PASSWORD_UPPER;
7977 while ($upper > strlen($passwordupper)) {
7978 $passwordupper .= PASSWORD_UPPER;
7980 $passwordnonalphanum = PASSWORD_NONALPHANUM;
7981 while ($nonalphanum > strlen($passwordnonalphanum)) {
7982 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
7985 // Now mix and shuffle it all.
7986 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
7987 substr(str_shuffle ($passwordupper), 0, $upper) .
7988 substr(str_shuffle ($passworddigits), 0, $digits) .
7989 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
7990 substr(str_shuffle ($passwordlower .
7991 $passwordupper .
7992 $passworddigits .
7993 $passwordnonalphanum), 0 , $additional));
7996 return substr ($password, 0, $maxlen);
8000 * Given a float, prints it nicely.
8001 * Localized floats must not be used in calculations!
8003 * The stripzeros feature is intended for making numbers look nicer in small
8004 * areas where it is not necessary to indicate the degree of accuracy by showing
8005 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8006 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8008 * @param float $float The float to print
8009 * @param int $decimalpoints The number of decimal places to print.
8010 * @param bool $localized use localized decimal separator
8011 * @param bool $stripzeros If true, removes final zeros after decimal point
8012 * @return string locale float
8014 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8015 if (is_null($float)) {
8016 return '';
8018 if ($localized) {
8019 $separator = get_string('decsep', 'langconfig');
8020 } else {
8021 $separator = '.';
8023 $result = number_format($float, $decimalpoints, $separator, '');
8024 if ($stripzeros) {
8025 // Remove zeros and final dot if not needed.
8026 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8028 return $result;
8032 * Converts locale specific floating point/comma number back to standard PHP float value
8033 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8035 * @param string $localefloat locale aware float representation
8036 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8037 * @return mixed float|bool - false or the parsed float.
8039 function unformat_float($localefloat, $strict = false) {
8040 $localefloat = trim($localefloat);
8042 if ($localefloat == '') {
8043 return null;
8046 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8047 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8049 if ($strict && !is_numeric($localefloat)) {
8050 return false;
8053 return (float)$localefloat;
8057 * Given a simple array, this shuffles it up just like shuffle()
8058 * Unlike PHP's shuffle() this function works on any machine.
8060 * @param array $array The array to be rearranged
8061 * @return array
8063 function swapshuffle($array) {
8065 $last = count($array) - 1;
8066 for ($i = 0; $i <= $last; $i++) {
8067 $from = rand(0, $last);
8068 $curr = $array[$i];
8069 $array[$i] = $array[$from];
8070 $array[$from] = $curr;
8072 return $array;
8076 * Like {@link swapshuffle()}, but works on associative arrays
8078 * @param array $array The associative array to be rearranged
8079 * @return array
8081 function swapshuffle_assoc($array) {
8083 $newarray = array();
8084 $newkeys = swapshuffle(array_keys($array));
8086 foreach ($newkeys as $newkey) {
8087 $newarray[$newkey] = $array[$newkey];
8089 return $newarray;
8093 * Given an arbitrary array, and a number of draws,
8094 * this function returns an array with that amount
8095 * of items. The indexes are retained.
8097 * @todo Finish documenting this function
8099 * @param array $array
8100 * @param int $draws
8101 * @return array
8103 function draw_rand_array($array, $draws) {
8105 $return = array();
8107 $last = count($array);
8109 if ($draws > $last) {
8110 $draws = $last;
8113 while ($draws > 0) {
8114 $last--;
8116 $keys = array_keys($array);
8117 $rand = rand(0, $last);
8119 $return[$keys[$rand]] = $array[$keys[$rand]];
8120 unset($array[$keys[$rand]]);
8122 $draws--;
8125 return $return;
8129 * Calculate the difference between two microtimes
8131 * @param string $a The first Microtime
8132 * @param string $b The second Microtime
8133 * @return string
8135 function microtime_diff($a, $b) {
8136 list($adec, $asec) = explode(' ', $a);
8137 list($bdec, $bsec) = explode(' ', $b);
8138 return $bsec - $asec + $bdec - $adec;
8142 * Given a list (eg a,b,c,d,e) this function returns
8143 * an array of 1->a, 2->b, 3->c etc
8145 * @param string $list The string to explode into array bits
8146 * @param string $separator The separator used within the list string
8147 * @return array The now assembled array
8149 function make_menu_from_list($list, $separator=',') {
8151 $array = array_reverse(explode($separator, $list), true);
8152 foreach ($array as $key => $item) {
8153 $outarray[$key+1] = trim($item);
8155 return $outarray;
8159 * Creates an array that represents all the current grades that
8160 * can be chosen using the given grading type.
8162 * Negative numbers
8163 * are scales, zero is no grade, and positive numbers are maximum
8164 * grades.
8166 * @todo Finish documenting this function or better deprecated this completely!
8168 * @param int $gradingtype
8169 * @return array
8171 function make_grades_menu($gradingtype) {
8172 global $DB;
8174 $grades = array();
8175 if ($gradingtype < 0) {
8176 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8177 return make_menu_from_list($scale->scale);
8179 } else if ($gradingtype > 0) {
8180 for ($i=$gradingtype; $i>=0; $i--) {
8181 $grades[$i] = $i .' / '. $gradingtype;
8183 return $grades;
8185 return $grades;
8189 * This function returns the number of activities using the given scale in the given course.
8191 * @param int $courseid The course ID to check.
8192 * @param int $scaleid The scale ID to check
8193 * @return int
8195 function course_scale_used($courseid, $scaleid) {
8196 global $CFG, $DB;
8198 $return = 0;
8200 if (!empty($scaleid)) {
8201 if ($cms = get_course_mods($courseid)) {
8202 foreach ($cms as $cm) {
8203 // Check cm->name/lib.php exists.
8204 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
8205 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
8206 $functionname = $cm->modname.'_scale_used';
8207 if (function_exists($functionname)) {
8208 if ($functionname($cm->instance, $scaleid)) {
8209 $return++;
8216 // Check if any course grade item makes use of the scale.
8217 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8219 // Check if any outcome in the course makes use of the scale.
8220 $return += $DB->count_records_sql("SELECT COUNT('x')
8221 FROM {grade_outcomes_courses} goc,
8222 {grade_outcomes} go
8223 WHERE go.id = goc.outcomeid
8224 AND go.scaleid = ? AND goc.courseid = ?",
8225 array($scaleid, $courseid));
8227 return $return;
8231 * This function returns the number of activities using scaleid in the entire site
8233 * @param int $scaleid
8234 * @param array $courses
8235 * @return int
8237 function site_scale_used($scaleid, &$courses) {
8238 $return = 0;
8240 if (!is_array($courses) || count($courses) == 0) {
8241 $courses = get_courses("all", false, "c.id, c.shortname");
8244 if (!empty($scaleid)) {
8245 if (is_array($courses) && count($courses) > 0) {
8246 foreach ($courses as $course) {
8247 $return += course_scale_used($course->id, $scaleid);
8251 return $return;
8255 * make_unique_id_code
8257 * @todo Finish documenting this function
8259 * @uses $_SERVER
8260 * @param string $extra Extra string to append to the end of the code
8261 * @return string
8263 function make_unique_id_code($extra = '') {
8265 $hostname = 'unknownhost';
8266 if (!empty($_SERVER['HTTP_HOST'])) {
8267 $hostname = $_SERVER['HTTP_HOST'];
8268 } else if (!empty($_ENV['HTTP_HOST'])) {
8269 $hostname = $_ENV['HTTP_HOST'];
8270 } else if (!empty($_SERVER['SERVER_NAME'])) {
8271 $hostname = $_SERVER['SERVER_NAME'];
8272 } else if (!empty($_ENV['SERVER_NAME'])) {
8273 $hostname = $_ENV['SERVER_NAME'];
8276 $date = gmdate("ymdHis");
8278 $random = random_string(6);
8280 if ($extra) {
8281 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8282 } else {
8283 return $hostname .'+'. $date .'+'. $random;
8289 * Function to check the passed address is within the passed subnet
8291 * The parameter is a comma separated string of subnet definitions.
8292 * Subnet strings can be in one of three formats:
8293 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8294 * 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)
8295 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8296 * Code for type 1 modified from user posted comments by mediator at
8297 * {@link http://au.php.net/manual/en/function.ip2long.php}
8299 * @param string $addr The address you are checking
8300 * @param string $subnetstr The string of subnet addresses
8301 * @return bool
8303 function address_in_subnet($addr, $subnetstr) {
8305 if ($addr == '0.0.0.0') {
8306 return false;
8308 $subnets = explode(',', $subnetstr);
8309 $found = false;
8310 $addr = trim($addr);
8311 $addr = cleanremoteaddr($addr, false); // Normalise.
8312 if ($addr === null) {
8313 return false;
8315 $addrparts = explode(':', $addr);
8317 $ipv6 = strpos($addr, ':');
8319 foreach ($subnets as $subnet) {
8320 $subnet = trim($subnet);
8321 if ($subnet === '') {
8322 continue;
8325 if (strpos($subnet, '/') !== false) {
8326 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8327 list($ip, $mask) = explode('/', $subnet);
8328 $mask = trim($mask);
8329 if (!is_number($mask)) {
8330 continue; // Incorect mask number, eh?
8332 $ip = cleanremoteaddr($ip, false); // Normalise.
8333 if ($ip === null) {
8334 continue;
8336 if (strpos($ip, ':') !== false) {
8337 // IPv6.
8338 if (!$ipv6) {
8339 continue;
8341 if ($mask > 128 or $mask < 0) {
8342 continue; // Nonsense.
8344 if ($mask == 0) {
8345 return true; // Any address.
8347 if ($mask == 128) {
8348 if ($ip === $addr) {
8349 return true;
8351 continue;
8353 $ipparts = explode(':', $ip);
8354 $modulo = $mask % 16;
8355 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8356 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8357 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8358 if ($modulo == 0) {
8359 return true;
8361 $pos = ($mask-$modulo)/16;
8362 $ipnet = hexdec($ipparts[$pos]);
8363 $addrnet = hexdec($addrparts[$pos]);
8364 $mask = 0xffff << (16 - $modulo);
8365 if (($addrnet & $mask) == ($ipnet & $mask)) {
8366 return true;
8370 } else {
8371 // IPv4.
8372 if ($ipv6) {
8373 continue;
8375 if ($mask > 32 or $mask < 0) {
8376 continue; // Nonsense.
8378 if ($mask == 0) {
8379 return true;
8381 if ($mask == 32) {
8382 if ($ip === $addr) {
8383 return true;
8385 continue;
8387 $mask = 0xffffffff << (32 - $mask);
8388 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8389 return true;
8393 } else if (strpos($subnet, '-') !== false) {
8394 // 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.
8395 $parts = explode('-', $subnet);
8396 if (count($parts) != 2) {
8397 continue;
8400 if (strpos($subnet, ':') !== false) {
8401 // IPv6.
8402 if (!$ipv6) {
8403 continue;
8405 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8406 if ($ipstart === null) {
8407 continue;
8409 $ipparts = explode(':', $ipstart);
8410 $start = hexdec(array_pop($ipparts));
8411 $ipparts[] = trim($parts[1]);
8412 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8413 if ($ipend === null) {
8414 continue;
8416 $ipparts[7] = '';
8417 $ipnet = implode(':', $ipparts);
8418 if (strpos($addr, $ipnet) !== 0) {
8419 continue;
8421 $ipparts = explode(':', $ipend);
8422 $end = hexdec($ipparts[7]);
8424 $addrend = hexdec($addrparts[7]);
8426 if (($addrend >= $start) and ($addrend <= $end)) {
8427 return true;
8430 } else {
8431 // IPv4.
8432 if ($ipv6) {
8433 continue;
8435 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8436 if ($ipstart === null) {
8437 continue;
8439 $ipparts = explode('.', $ipstart);
8440 $ipparts[3] = trim($parts[1]);
8441 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8442 if ($ipend === null) {
8443 continue;
8446 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8447 return true;
8451 } else {
8452 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8453 if (strpos($subnet, ':') !== false) {
8454 // IPv6.
8455 if (!$ipv6) {
8456 continue;
8458 $parts = explode(':', $subnet);
8459 $count = count($parts);
8460 if ($parts[$count-1] === '') {
8461 unset($parts[$count-1]); // Trim trailing :'s.
8462 $count--;
8463 $subnet = implode('.', $parts);
8465 $isip = cleanremoteaddr($subnet, false); // Normalise.
8466 if ($isip !== null) {
8467 if ($isip === $addr) {
8468 return true;
8470 continue;
8471 } else if ($count > 8) {
8472 continue;
8474 $zeros = array_fill(0, 8-$count, '0');
8475 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8476 if (address_in_subnet($addr, $subnet)) {
8477 return true;
8480 } else {
8481 // IPv4.
8482 if ($ipv6) {
8483 continue;
8485 $parts = explode('.', $subnet);
8486 $count = count($parts);
8487 if ($parts[$count-1] === '') {
8488 unset($parts[$count-1]); // Trim trailing .
8489 $count--;
8490 $subnet = implode('.', $parts);
8492 if ($count == 4) {
8493 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8494 if ($subnet === $addr) {
8495 return true;
8497 continue;
8498 } else if ($count > 4) {
8499 continue;
8501 $zeros = array_fill(0, 4-$count, '0');
8502 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8503 if (address_in_subnet($addr, $subnet)) {
8504 return true;
8510 return false;
8514 * For outputting debugging info
8516 * @param string $string The string to write
8517 * @param string $eol The end of line char(s) to use
8518 * @param string $sleep Period to make the application sleep
8519 * This ensures any messages have time to display before redirect
8521 function mtrace($string, $eol="\n", $sleep=0) {
8523 if (defined('STDOUT') and !PHPUNIT_TEST) {
8524 fwrite(STDOUT, $string.$eol);
8525 } else {
8526 echo $string . $eol;
8529 flush();
8531 // Delay to keep message on user's screen in case of subsequent redirect.
8532 if ($sleep) {
8533 sleep($sleep);
8538 * Replace 1 or more slashes or backslashes to 1 slash
8540 * @param string $path The path to strip
8541 * @return string the path with double slashes removed
8543 function cleardoubleslashes ($path) {
8544 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8548 * Is current ip in give list?
8550 * @param string $list
8551 * @return bool
8553 function remoteip_in_list($list) {
8554 $inlist = false;
8555 $clientip = getremoteaddr(null);
8557 if (!$clientip) {
8558 // Ensure access on cli.
8559 return true;
8562 $list = explode("\n", $list);
8563 foreach ($list as $subnet) {
8564 $subnet = trim($subnet);
8565 if (address_in_subnet($clientip, $subnet)) {
8566 $inlist = true;
8567 break;
8570 return $inlist;
8574 * Returns most reliable client address
8576 * @param string $default If an address can't be determined, then return this
8577 * @return string The remote IP address
8579 function getremoteaddr($default='0.0.0.0') {
8580 global $CFG;
8582 if (empty($CFG->getremoteaddrconf)) {
8583 // This will happen, for example, before just after the upgrade, as the
8584 // user is redirected to the admin screen.
8585 $variablestoskip = 0;
8586 } else {
8587 $variablestoskip = $CFG->getremoteaddrconf;
8589 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8590 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8591 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8592 return $address ? $address : $default;
8595 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8596 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8597 $address = cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
8598 return $address ? $address : $default;
8601 if (!empty($_SERVER['REMOTE_ADDR'])) {
8602 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8603 return $address ? $address : $default;
8604 } else {
8605 return $default;
8610 * Cleans an ip address. Internal addresses are now allowed.
8611 * (Originally local addresses were not allowed.)
8613 * @param string $addr IPv4 or IPv6 address
8614 * @param bool $compress use IPv6 address compression
8615 * @return string normalised ip address string, null if error
8617 function cleanremoteaddr($addr, $compress=false) {
8618 $addr = trim($addr);
8620 // TODO: maybe add a separate function is_addr_public() or something like this.
8622 if (strpos($addr, ':') !== false) {
8623 // Can be only IPv6.
8624 $parts = explode(':', $addr);
8625 $count = count($parts);
8627 if (strpos($parts[$count-1], '.') !== false) {
8628 // Legacy ipv4 notation.
8629 $last = array_pop($parts);
8630 $ipv4 = cleanremoteaddr($last, true);
8631 if ($ipv4 === null) {
8632 return null;
8634 $bits = explode('.', $ipv4);
8635 $parts[] = dechex($bits[0]).dechex($bits[1]);
8636 $parts[] = dechex($bits[2]).dechex($bits[3]);
8637 $count = count($parts);
8638 $addr = implode(':', $parts);
8641 if ($count < 3 or $count > 8) {
8642 return null; // Severly malformed.
8645 if ($count != 8) {
8646 if (strpos($addr, '::') === false) {
8647 return null; // Malformed.
8649 // Uncompress.
8650 $insertat = array_search('', $parts, true);
8651 $missing = array_fill(0, 1 + 8 - $count, '0');
8652 array_splice($parts, $insertat, 1, $missing);
8653 foreach ($parts as $key => $part) {
8654 if ($part === '') {
8655 $parts[$key] = '0';
8660 $adr = implode(':', $parts);
8661 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8662 return null; // Incorrect format - sorry.
8665 // Normalise 0s and case.
8666 $parts = array_map('hexdec', $parts);
8667 $parts = array_map('dechex', $parts);
8669 $result = implode(':', $parts);
8671 if (!$compress) {
8672 return $result;
8675 if ($result === '0:0:0:0:0:0:0:0') {
8676 return '::'; // All addresses.
8679 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8680 if ($compressed !== $result) {
8681 return $compressed;
8684 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8685 if ($compressed !== $result) {
8686 return $compressed;
8689 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8690 if ($compressed !== $result) {
8691 return $compressed;
8694 return $result;
8697 // First get all things that look like IPv4 addresses.
8698 $parts = array();
8699 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8700 return null;
8702 unset($parts[0]);
8704 foreach ($parts as $key => $match) {
8705 if ($match > 255) {
8706 return null;
8708 $parts[$key] = (int)$match; // Normalise 0s.
8711 return implode('.', $parts);
8715 * This function will make a complete copy of anything it's given,
8716 * regardless of whether it's an object or not.
8718 * @param mixed $thing Something you want cloned
8719 * @return mixed What ever it is you passed it
8721 function fullclone($thing) {
8722 return unserialize(serialize($thing));
8726 * If new messages are waiting for the current user, then insert
8727 * JavaScript to pop up the messaging window into the page
8729 * @return void
8731 function message_popup_window() {
8732 global $USER, $DB, $PAGE, $CFG;
8734 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
8735 return;
8738 if (!isloggedin() || isguestuser()) {
8739 return;
8742 if (!isset($USER->message_lastpopup)) {
8743 $USER->message_lastpopup = 0;
8744 } else if ($USER->message_lastpopup > (time()-120)) {
8745 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8746 return;
8749 // A quick query to check whether the user has new messages.
8750 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
8751 if ($messagecount<1) {
8752 return;
8755 // Got unread messages so now do another query that joins with the user table.
8756 $namefields = get_all_user_name_fields(true, 'u');
8757 $messagesql = "SELECT m.id, m.smallmessage, m.fullmessageformat, m.notification, $namefields
8758 FROM {message} m
8759 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8760 JOIN {message_processors} p ON mw.processorid=p.id
8761 JOIN {user} u ON m.useridfrom=u.id
8762 WHERE m.useridto = :userid
8763 AND p.name='popup'";
8765 // If the user was last notified over an hour ago we can re-notify them of old messages
8766 // so don't worry about when the new message was sent.
8767 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
8768 if (!$lastnotifiedlongago) {
8769 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8772 $messageusers = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
8774 // If we have new messages to notify the user about.
8775 if (!empty($messageusers)) {
8777 $strmessages = '';
8778 if (count($messageusers)>1) {
8779 $strmessages = get_string('unreadnewmessages', 'message', count($messageusers));
8780 } else {
8781 $messageusers = reset($messageusers);
8783 // Show who the message is from if its not a notification.
8784 if (!$messageusers->notification) {
8785 $strmessages = get_string('unreadnewmessage', 'message', fullname($messageusers) );
8788 // Try to display the small version of the message.
8789 $smallmessage = null;
8790 if (!empty($messageusers->smallmessage)) {
8791 // Display the first 200 chars of the message in the popup.
8792 $smallmessage = null;
8793 if (core_text::strlen($messageusers->smallmessage) > 200) {
8794 $smallmessage = core_text::substr($messageusers->smallmessage, 0, 200).'...';
8795 } else {
8796 $smallmessage = $messageusers->smallmessage;
8799 // Prevent html symbols being displayed.
8800 if ($messageusers->fullmessageformat == FORMAT_HTML) {
8801 $smallmessage = html_to_text($smallmessage);
8802 } else {
8803 $smallmessage = s($smallmessage);
8805 } else if ($messageusers->notification) {
8806 // Its a notification with no smallmessage so just say they have a notification.
8807 $smallmessage = get_string('unreadnewnotification', 'message');
8809 if (!empty($smallmessage)) {
8810 $strmessages .= '<div id="usermessage">'.s($smallmessage).'</div>';
8814 $strgomessage = get_string('gotomessages', 'message');
8815 $strstaymessage = get_string('ignore', 'admin');
8817 $notificationsound = null;
8818 $beep = get_user_preferences('message_beepnewmessage', '');
8819 if (!empty($beep)) {
8820 // Browsers will work down this list until they find something they support.
8821 $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
8822 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
8823 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8824 $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8826 $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8829 $url = $CFG->wwwroot.'/message/index.php';
8830 $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8831 html_writer::start_tag('div', array('id' => 'newmessagetext')).
8832 $strmessages.
8833 html_writer::end_tag('div').
8835 $notificationsound.
8836 html_writer::start_tag('div', array('id' => 'newmessagelinks')).
8837 html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
8838 html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
8839 html_writer::end_tag('div');
8840 html_writer::end_tag('div');
8842 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
8844 $USER->message_lastpopup = time();
8849 * Used to make sure that $min <= $value <= $max
8851 * Make sure that value is between min, and max
8853 * @param int $min The minimum value
8854 * @param int $value The value to check
8855 * @param int $max The maximum value
8856 * @return int
8858 function bounded_number($min, $value, $max) {
8859 if ($value < $min) {
8860 return $min;
8862 if ($value > $max) {
8863 return $max;
8865 return $value;
8869 * Check if there is a nested array within the passed array
8871 * @param array $array
8872 * @return bool true if there is a nested array false otherwise
8874 function array_is_nested($array) {
8875 foreach ($array as $value) {
8876 if (is_array($value)) {
8877 return true;
8880 return false;
8884 * get_performance_info() pairs up with init_performance_info()
8885 * loaded in setup.php. Returns an array with 'html' and 'txt'
8886 * values ready for use, and each of the individual stats provided
8887 * separately as well.
8889 * @return array
8891 function get_performance_info() {
8892 global $CFG, $PERF, $DB, $PAGE;
8894 $info = array();
8895 $info['html'] = ''; // Holds userfriendly HTML representation.
8896 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8898 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8900 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8901 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8903 if (function_exists('memory_get_usage')) {
8904 $info['memory_total'] = memory_get_usage();
8905 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8906 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8907 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8908 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8911 if (function_exists('memory_get_peak_usage')) {
8912 $info['memory_peak'] = memory_get_peak_usage();
8913 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8914 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8917 $inc = get_included_files();
8918 $info['includecount'] = count($inc);
8919 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8920 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8922 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8923 // We can not track more performance before installation or before PAGE init, sorry.
8924 return $info;
8927 $filtermanager = filter_manager::instance();
8928 if (method_exists($filtermanager, 'get_performance_summary')) {
8929 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8930 $info = array_merge($filterinfo, $info);
8931 foreach ($filterinfo as $key => $value) {
8932 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8933 $info['txt'] .= "$key: $value ";
8937 $stringmanager = get_string_manager();
8938 if (method_exists($stringmanager, 'get_performance_summary')) {
8939 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8940 $info = array_merge($filterinfo, $info);
8941 foreach ($filterinfo as $key => $value) {
8942 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8943 $info['txt'] .= "$key: $value ";
8947 if (!empty($PERF->logwrites)) {
8948 $info['logwrites'] = $PERF->logwrites;
8949 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8950 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8953 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
8954 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
8955 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8957 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
8958 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
8959 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
8961 if (function_exists('posix_times')) {
8962 $ptimes = posix_times();
8963 if (is_array($ptimes)) {
8964 foreach ($ptimes as $key => $val) {
8965 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
8967 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
8968 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8972 // Grab the load average for the last minute.
8973 // /proc will only work under some linux configurations
8974 // while uptime is there under MacOSX/Darwin and other unices.
8975 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
8976 list($serverload) = explode(' ', $loadavg[0]);
8977 unset($loadavg);
8978 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
8979 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
8980 $serverload = $matches[1];
8981 } else {
8982 trigger_error('Could not parse uptime output!');
8985 if (!empty($serverload)) {
8986 $info['serverload'] = $serverload;
8987 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
8988 $info['txt'] .= "serverload: {$info['serverload']} ";
8991 // Display size of session if session started.
8992 if ($si = \core\session\manager::get_performance_info()) {
8993 $info['sessionsize'] = $si['size'];
8994 $info['html'] .= $si['html'];
8995 $info['txt'] .= $si['txt'];
8998 if ($stats = cache_helper::get_stats()) {
8999 $html = '<span class="cachesused">';
9000 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
9001 $text = 'Caches used (hits/misses/sets): ';
9002 $hits = 0;
9003 $misses = 0;
9004 $sets = 0;
9005 foreach ($stats as $definition => $stores) {
9006 $html .= '<span class="cache-definition-stats">';
9007 $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
9008 $text .= "$definition {";
9009 foreach ($stores as $store => $data) {
9010 $hits += $data['hits'];
9011 $misses += $data['misses'];
9012 $sets += $data['sets'];
9013 if ($data['hits'] == 0 and $data['misses'] > 0) {
9014 $cachestoreclass = 'nohits';
9015 } else if ($data['hits'] < $data['misses']) {
9016 $cachestoreclass = 'lowhits';
9017 } else {
9018 $cachestoreclass = 'hihits';
9020 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9021 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
9023 $html .= '</span>';
9024 $text .= '} ';
9026 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
9027 $html .= '</span> ';
9028 $info['cachesused'] = "$hits / $misses / $sets";
9029 $info['html'] .= $html;
9030 $info['txt'] .= $text.'. ';
9031 } else {
9032 $info['cachesused'] = '0 / 0 / 0';
9033 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
9034 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9037 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
9038 return $info;
9042 * Legacy function.
9044 * @todo Document this function linux people
9046 function apd_get_profiling() {
9047 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
9051 * Delete directory or only its content
9053 * @param string $dir directory path
9054 * @param bool $contentonly
9055 * @return bool success, true also if dir does not exist
9057 function remove_dir($dir, $contentonly=false) {
9058 if (!file_exists($dir)) {
9059 // Nothing to do.
9060 return true;
9062 if (!$handle = opendir($dir)) {
9063 return false;
9065 $result = true;
9066 while (false!==($item = readdir($handle))) {
9067 if ($item != '.' && $item != '..') {
9068 if (is_dir($dir.'/'.$item)) {
9069 $result = remove_dir($dir.'/'.$item) && $result;
9070 } else {
9071 $result = unlink($dir.'/'.$item) && $result;
9075 closedir($handle);
9076 if ($contentonly) {
9077 clearstatcache(); // Make sure file stat cache is properly invalidated.
9078 return $result;
9080 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9081 clearstatcache(); // Make sure file stat cache is properly invalidated.
9082 return $result;
9086 * Detect if an object or a class contains a given property
9087 * will take an actual object or the name of a class
9089 * @param mix $obj Name of class or real object to test
9090 * @param string $property name of property to find
9091 * @return bool true if property exists
9093 function object_property_exists( $obj, $property ) {
9094 if (is_string( $obj )) {
9095 $properties = get_class_vars( $obj );
9096 } else {
9097 $properties = get_object_vars( $obj );
9099 return array_key_exists( $property, $properties );
9103 * Converts an object into an associative array
9105 * This function converts an object into an associative array by iterating
9106 * over its public properties. Because this function uses the foreach
9107 * construct, Iterators are respected. It works recursively on arrays of objects.
9108 * Arrays and simple values are returned as is.
9110 * If class has magic properties, it can implement IteratorAggregate
9111 * and return all available properties in getIterator()
9113 * @param mixed $var
9114 * @return array
9116 function convert_to_array($var) {
9117 $result = array();
9119 // Loop over elements/properties.
9120 foreach ($var as $key => $value) {
9121 // Recursively convert objects.
9122 if (is_object($value) || is_array($value)) {
9123 $result[$key] = convert_to_array($value);
9124 } else {
9125 // Simple values are untouched.
9126 $result[$key] = $value;
9129 return $result;
9133 * Detect a custom script replacement in the data directory that will
9134 * replace an existing moodle script
9136 * @return string|bool full path name if a custom script exists, false if no custom script exists
9138 function custom_script_path() {
9139 global $CFG, $SCRIPT;
9141 if ($SCRIPT === null) {
9142 // Probably some weird external script.
9143 return false;
9146 $scriptpath = $CFG->customscripts . $SCRIPT;
9148 // Check the custom script exists.
9149 if (file_exists($scriptpath) and is_file($scriptpath)) {
9150 return $scriptpath;
9151 } else {
9152 return false;
9157 * Returns whether or not the user object is a remote MNET user. This function
9158 * is in moodlelib because it does not rely on loading any of the MNET code.
9160 * @param object $user A valid user object
9161 * @return bool True if the user is from a remote Moodle.
9163 function is_mnet_remote_user($user) {
9164 global $CFG;
9166 if (!isset($CFG->mnet_localhost_id)) {
9167 include_once($CFG->dirroot . '/mnet/lib.php');
9168 $env = new mnet_environment();
9169 $env->init();
9170 unset($env);
9173 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9177 * This function will search for browser prefereed languages, setting Moodle
9178 * to use the best one available if $SESSION->lang is undefined
9180 function setup_lang_from_browser() {
9181 global $CFG, $SESSION, $USER;
9183 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9184 // Lang is defined in session or user profile, nothing to do.
9185 return;
9188 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9189 return;
9192 // Extract and clean langs from headers.
9193 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9194 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9195 $rawlangs = explode(',', $rawlangs); // Convert to array.
9196 $langs = array();
9198 $order = 1.0;
9199 foreach ($rawlangs as $lang) {
9200 if (strpos($lang, ';') === false) {
9201 $langs[(string)$order] = $lang;
9202 $order = $order-0.01;
9203 } else {
9204 $parts = explode(';', $lang);
9205 $pos = strpos($parts[1], '=');
9206 $langs[substr($parts[1], $pos+1)] = $parts[0];
9209 krsort($langs, SORT_NUMERIC);
9211 // Look for such langs under standard locations.
9212 foreach ($langs as $lang) {
9213 // Clean it properly for include.
9214 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9215 if (get_string_manager()->translation_exists($lang, false)) {
9216 // Lang exists, set it in session.
9217 $SESSION->lang = $lang;
9218 // We have finished. Go out.
9219 break;
9222 return;
9226 * Check if $url matches anything in proxybypass list
9228 * Any errors just result in the proxy being used (least bad)
9230 * @param string $url url to check
9231 * @return boolean true if we should bypass the proxy
9233 function is_proxybypass( $url ) {
9234 global $CFG;
9236 // Sanity check.
9237 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9238 return false;
9241 // Get the host part out of the url.
9242 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9243 return false;
9246 // Get the possible bypass hosts into an array.
9247 $matches = explode( ',', $CFG->proxybypass );
9249 // Check for a match.
9250 // (IPs need to match the left hand side and hosts the right of the url,
9251 // but we can recklessly check both as there can't be a false +ve).
9252 foreach ($matches as $match) {
9253 $match = trim($match);
9255 // Try for IP match (Left side).
9256 $lhs = substr($host, 0, strlen($match));
9257 if (strcasecmp($match, $lhs)==0) {
9258 return true;
9261 // Try for host match (Right side).
9262 $rhs = substr($host, -strlen($match));
9263 if (strcasecmp($match, $rhs)==0) {
9264 return true;
9268 // Nothing matched.
9269 return false;
9273 * Check if the passed navigation is of the new style
9275 * @param mixed $navigation
9276 * @return bool true for yes false for no
9278 function is_newnav($navigation) {
9279 if (is_array($navigation) && !empty($navigation['newnav'])) {
9280 return true;
9281 } else {
9282 return false;
9287 * Checks whether the given variable name is defined as a variable within the given object.
9289 * This will NOT work with stdClass objects, which have no class variables.
9291 * @param string $var The variable name
9292 * @param object $object The object to check
9293 * @return boolean
9295 function in_object_vars($var, $object) {
9296 $classvars = get_class_vars(get_class($object));
9297 $classvars = array_keys($classvars);
9298 return in_array($var, $classvars);
9302 * Returns an array without repeated objects.
9303 * This function is similar to array_unique, but for arrays that have objects as values
9305 * @param array $array
9306 * @param bool $keepkeyassoc
9307 * @return array
9309 function object_array_unique($array, $keepkeyassoc = true) {
9310 $duplicatekeys = array();
9311 $tmp = array();
9313 foreach ($array as $key => $val) {
9314 // Convert objects to arrays, in_array() does not support objects.
9315 if (is_object($val)) {
9316 $val = (array)$val;
9319 if (!in_array($val, $tmp)) {
9320 $tmp[] = $val;
9321 } else {
9322 $duplicatekeys[] = $key;
9326 foreach ($duplicatekeys as $key) {
9327 unset($array[$key]);
9330 return $keepkeyassoc ? $array : array_values($array);
9334 * Is a userid the primary administrator?
9336 * @param int $userid int id of user to check
9337 * @return boolean
9339 function is_primary_admin($userid) {
9340 $primaryadmin = get_admin();
9342 if ($userid == $primaryadmin->id) {
9343 return true;
9344 } else {
9345 return false;
9350 * Returns the site identifier
9352 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9354 function get_site_identifier() {
9355 global $CFG;
9356 // Check to see if it is missing. If so, initialise it.
9357 if (empty($CFG->siteidentifier)) {
9358 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9360 // Return it.
9361 return $CFG->siteidentifier;
9365 * Check whether the given password has no more than the specified
9366 * number of consecutive identical characters.
9368 * @param string $password password to be checked against the password policy
9369 * @param integer $maxchars maximum number of consecutive identical characters
9370 * @return bool
9372 function check_consecutive_identical_characters($password, $maxchars) {
9374 if ($maxchars < 1) {
9375 return true; // Zero 0 is to disable this check.
9377 if (strlen($password) <= $maxchars) {
9378 return true; // Too short to fail this test.
9381 $previouschar = '';
9382 $consecutivecount = 1;
9383 foreach (str_split($password) as $char) {
9384 if ($char != $previouschar) {
9385 $consecutivecount = 1;
9386 } else {
9387 $consecutivecount++;
9388 if ($consecutivecount > $maxchars) {
9389 return false; // Check failed already.
9393 $previouschar = $char;
9396 return true;
9400 * Helper function to do partial function binding.
9401 * so we can use it for preg_replace_callback, for example
9402 * this works with php functions, user functions, static methods and class methods
9403 * it returns you a callback that you can pass on like so:
9405 * $callback = partial('somefunction', $arg1, $arg2);
9406 * or
9407 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9408 * or even
9409 * $obj = new someclass();
9410 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9412 * and then the arguments that are passed through at calltime are appended to the argument list.
9414 * @param mixed $function a php callback
9415 * @param mixed $arg1,... $argv arguments to partially bind with
9416 * @return array Array callback
9418 function partial() {
9419 if (!class_exists('partial')) {
9421 * Used to manage function binding.
9422 * @copyright 2009 Penny Leach
9423 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9425 class partial{
9426 /** @var array */
9427 public $values = array();
9428 /** @var string The function to call as a callback. */
9429 public $func;
9431 * Constructor
9432 * @param string $func
9433 * @param array $args
9435 public function __construct($func, $args) {
9436 $this->values = $args;
9437 $this->func = $func;
9440 * Calls the callback function.
9441 * @return mixed
9443 public function method() {
9444 $args = func_get_args();
9445 return call_user_func_array($this->func, array_merge($this->values, $args));
9449 $args = func_get_args();
9450 $func = array_shift($args);
9451 $p = new partial($func, $args);
9452 return array($p, 'method');
9456 * helper function to load up and initialise the mnet environment
9457 * this must be called before you use mnet functions.
9459 * @return mnet_environment the equivalent of old $MNET global
9461 function get_mnet_environment() {
9462 global $CFG;
9463 require_once($CFG->dirroot . '/mnet/lib.php');
9464 static $instance = null;
9465 if (empty($instance)) {
9466 $instance = new mnet_environment();
9467 $instance->init();
9469 return $instance;
9473 * during xmlrpc server code execution, any code wishing to access
9474 * information about the remote peer must use this to get it.
9476 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9478 function get_mnet_remote_client() {
9479 if (!defined('MNET_SERVER')) {
9480 debugging(get_string('notinxmlrpcserver', 'mnet'));
9481 return false;
9483 global $MNET_REMOTE_CLIENT;
9484 if (isset($MNET_REMOTE_CLIENT)) {
9485 return $MNET_REMOTE_CLIENT;
9487 return false;
9491 * during the xmlrpc server code execution, this will be called
9492 * to setup the object returned by {@link get_mnet_remote_client}
9494 * @param mnet_remote_client $client the client to set up
9495 * @throws moodle_exception
9497 function set_mnet_remote_client($client) {
9498 if (!defined('MNET_SERVER')) {
9499 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9501 global $MNET_REMOTE_CLIENT;
9502 $MNET_REMOTE_CLIENT = $client;
9506 * return the jump url for a given remote user
9507 * this is used for rewriting forum post links in emails, etc
9509 * @param stdclass $user the user to get the idp url for
9511 function mnet_get_idp_jump_url($user) {
9512 global $CFG;
9514 static $mnetjumps = array();
9515 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9516 $idp = mnet_get_peer_host($user->mnethostid);
9517 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9518 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9520 return $mnetjumps[$user->mnethostid];
9524 * Gets the homepage to use for the current user
9526 * @return int One of HOMEPAGE_*
9528 function get_home_page() {
9529 global $CFG;
9531 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9532 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9533 return HOMEPAGE_MY;
9534 } else {
9535 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9538 return HOMEPAGE_SITE;
9542 * Gets the name of a course to be displayed when showing a list of courses.
9543 * By default this is just $course->fullname but user can configure it. The
9544 * result of this function should be passed through print_string.
9545 * @param stdClass|course_in_list $course Moodle course object
9546 * @return string Display name of course (either fullname or short + fullname)
9548 function get_course_display_name_for_list($course) {
9549 global $CFG;
9550 if (!empty($CFG->courselistshortnames)) {
9551 if (!($course instanceof stdClass)) {
9552 $course = (object)convert_to_array($course);
9554 return get_string('courseextendednamedisplay', '', $course);
9555 } else {
9556 return $course->fullname;
9561 * The lang_string class
9563 * This special class is used to create an object representation of a string request.
9564 * It is special because processing doesn't occur until the object is first used.
9565 * The class was created especially to aid performance in areas where strings were
9566 * required to be generated but were not necessarily used.
9567 * As an example the admin tree when generated uses over 1500 strings, of which
9568 * normally only 1/3 are ever actually printed at any time.
9569 * The performance advantage is achieved by not actually processing strings that
9570 * arn't being used, as such reducing the processing required for the page.
9572 * How to use the lang_string class?
9573 * There are two methods of using the lang_string class, first through the
9574 * forth argument of the get_string function, and secondly directly.
9575 * The following are examples of both.
9576 * 1. Through get_string calls e.g.
9577 * $string = get_string($identifier, $component, $a, true);
9578 * $string = get_string('yes', 'moodle', null, true);
9579 * 2. Direct instantiation
9580 * $string = new lang_string($identifier, $component, $a, $lang);
9581 * $string = new lang_string('yes');
9583 * How do I use a lang_string object?
9584 * The lang_string object makes use of a magic __toString method so that you
9585 * are able to use the object exactly as you would use a string in most cases.
9586 * This means you are able to collect it into a variable and then directly
9587 * echo it, or concatenate it into another string, or similar.
9588 * The other thing you can do is manually get the string by calling the
9589 * lang_strings out method e.g.
9590 * $string = new lang_string('yes');
9591 * $string->out();
9592 * Also worth noting is that the out method can take one argument, $lang which
9593 * allows the developer to change the language on the fly.
9595 * When should I use a lang_string object?
9596 * The lang_string object is designed to be used in any situation where a
9597 * string may not be needed, but needs to be generated.
9598 * The admin tree is a good example of where lang_string objects should be
9599 * used.
9600 * A more practical example would be any class that requries strings that may
9601 * not be printed (after all classes get renderer by renderers and who knows
9602 * what they will do ;))
9604 * When should I not use a lang_string object?
9605 * Don't use lang_strings when you are going to use a string immediately.
9606 * There is no need as it will be processed immediately and there will be no
9607 * advantage, and in fact perhaps a negative hit as a class has to be
9608 * instantiated for a lang_string object, however get_string won't require
9609 * that.
9611 * Limitations:
9612 * 1. You cannot use a lang_string object as an array offset. Doing so will
9613 * result in PHP throwing an error. (You can use it as an object property!)
9615 * @package core
9616 * @category string
9617 * @copyright 2011 Sam Hemelryk
9618 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9620 class lang_string {
9622 /** @var string The strings identifier */
9623 protected $identifier;
9624 /** @var string The strings component. Default '' */
9625 protected $component = '';
9626 /** @var array|stdClass Any arguments required for the string. Default null */
9627 protected $a = null;
9628 /** @var string The language to use when processing the string. Default null */
9629 protected $lang = null;
9631 /** @var string The processed string (once processed) */
9632 protected $string = null;
9635 * A special boolean. If set to true then the object has been woken up and
9636 * cannot be regenerated. If this is set then $this->string MUST be used.
9637 * @var bool
9639 protected $forcedstring = false;
9642 * Constructs a lang_string object
9644 * This function should do as little processing as possible to ensure the best
9645 * performance for strings that won't be used.
9647 * @param string $identifier The strings identifier
9648 * @param string $component The strings component
9649 * @param stdClass|array $a Any arguments the string requires
9650 * @param string $lang The language to use when processing the string.
9651 * @throws coding_exception
9653 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9654 if (empty($component)) {
9655 $component = 'moodle';
9658 $this->identifier = $identifier;
9659 $this->component = $component;
9660 $this->lang = $lang;
9662 // We MUST duplicate $a to ensure that it if it changes by reference those
9663 // changes are not carried across.
9664 // To do this we always ensure $a or its properties/values are strings
9665 // and that any properties/values that arn't convertable are forgotten.
9666 if (!empty($a)) {
9667 if (is_scalar($a)) {
9668 $this->a = $a;
9669 } else if ($a instanceof lang_string) {
9670 $this->a = $a->out();
9671 } else if (is_object($a) or is_array($a)) {
9672 $a = (array)$a;
9673 $this->a = array();
9674 foreach ($a as $key => $value) {
9675 // Make sure conversion errors don't get displayed (results in '').
9676 if (is_array($value)) {
9677 $this->a[$key] = '';
9678 } else if (is_object($value)) {
9679 if (method_exists($value, '__toString')) {
9680 $this->a[$key] = $value->__toString();
9681 } else {
9682 $this->a[$key] = '';
9684 } else {
9685 $this->a[$key] = (string)$value;
9691 if (debugging(false, DEBUG_DEVELOPER)) {
9692 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9693 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9695 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9696 throw new coding_exception('Invalid string compontent. Please check your string definition');
9698 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9699 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9705 * Processes the string.
9707 * This function actually processes the string, stores it in the string property
9708 * and then returns it.
9709 * You will notice that this function is VERY similar to the get_string method.
9710 * That is because it is pretty much doing the same thing.
9711 * However as this function is an upgrade it isn't as tolerant to backwards
9712 * compatibility.
9714 * @return string
9715 * @throws coding_exception
9717 protected function get_string() {
9718 global $CFG;
9720 // Check if we need to process the string.
9721 if ($this->string === null) {
9722 // Check the quality of the identifier.
9723 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9724 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);
9727 // Process the string.
9728 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9729 // Debugging feature lets you display string identifier and component.
9730 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9731 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9734 // Return the string.
9735 return $this->string;
9739 * Returns the string
9741 * @param string $lang The langauge to use when processing the string
9742 * @return string
9744 public function out($lang = null) {
9745 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9746 if ($this->forcedstring) {
9747 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9748 return $this->get_string();
9750 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9751 return $translatedstring->out();
9753 return $this->get_string();
9757 * Magic __toString method for printing a string
9759 * @return string
9761 public function __toString() {
9762 return $this->get_string();
9766 * Magic __set_state method used for var_export
9768 * @return string
9770 public function __set_state() {
9771 return $this->get_string();
9775 * Prepares the lang_string for sleep and stores only the forcedstring and
9776 * string properties... the string cannot be regenerated so we need to ensure
9777 * it is generated for this.
9779 * @return string
9781 public function __sleep() {
9782 $this->get_string();
9783 $this->forcedstring = true;
9784 return array('forcedstring', 'string', 'lang');