MDL-52927 qtype ddwtos and ddimageortext focus using keyboard
[moodle.git] / lib / moodlelib.php
blob5e045816adfed677b9d0eac18333158ebb7cdd2f
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 (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
421 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
423 /** Type of module */
424 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425 /** True if module supports intro editor */
426 define('FEATURE_MOD_INTRO', 'mod_intro');
427 /** True if module has default completion */
428 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
430 define('FEATURE_COMMENT', 'comment');
432 define('FEATURE_RATE', 'rate');
433 /** True if module supports backup/restore of moodle2 format */
434 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
436 /** True if module can show description on course main page */
437 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
439 /** True if module uses the question bank */
440 define('FEATURE_USES_QUESTIONS', 'usesquestions');
442 /** Unspecified module archetype */
443 define('MOD_ARCHETYPE_OTHER', 0);
444 /** Resource-like type module */
445 define('MOD_ARCHETYPE_RESOURCE', 1);
446 /** Assignment module archetype */
447 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
448 /** System (not user-addable) module archetype */
449 define('MOD_ARCHETYPE_SYSTEM', 3);
451 /** Return this from modname_get_types callback to use default display in activity chooser */
452 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
455 * Security token used for allowing access
456 * from external application such as web services.
457 * Scripts do not use any session, performance is relatively
458 * low because we need to load access info in each request.
459 * Scripts are executed in parallel.
461 define('EXTERNAL_TOKEN_PERMANENT', 0);
464 * Security token used for allowing access
465 * of embedded applications, the code is executed in the
466 * active user session. Token is invalidated after user logs out.
467 * Scripts are executed serially - normal session locking is used.
469 define('EXTERNAL_TOKEN_EMBEDDED', 1);
472 * The home page should be the site home
474 define('HOMEPAGE_SITE', 0);
476 * The home page should be the users my page
478 define('HOMEPAGE_MY', 1);
480 * The home page can be chosen by the user
482 define('HOMEPAGE_USER', 2);
485 * Hub directory url (should be moodle.org)
487 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
491 * Moodle.org url (should be moodle.org)
493 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
496 * Moodle mobile app service name
498 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
501 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
503 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
506 * Course display settings: display all sections on one page.
508 define('COURSE_DISPLAY_SINGLEPAGE', 0);
510 * Course display settings: split pages into a page per section.
512 define('COURSE_DISPLAY_MULTIPAGE', 1);
515 * Authentication constant: String used in password field when password is not stored.
517 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
519 // PARAMETER HANDLING.
522 * Returns a particular value for the named variable, taken from
523 * POST or GET. If the parameter doesn't exist then an error is
524 * thrown because we require this variable.
526 * This function should be used to initialise all required values
527 * in a script that are based on parameters. Usually it will be
528 * used like this:
529 * $id = required_param('id', PARAM_INT);
531 * Please note the $type parameter is now required and the value can not be array.
533 * @param string $parname the name of the page parameter we want
534 * @param string $type expected type of parameter
535 * @return mixed
536 * @throws coding_exception
538 function required_param($parname, $type) {
539 if (func_num_args() != 2 or empty($parname) or empty($type)) {
540 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
542 // POST has precedence.
543 if (isset($_POST[$parname])) {
544 $param = $_POST[$parname];
545 } else if (isset($_GET[$parname])) {
546 $param = $_GET[$parname];
547 } else {
548 print_error('missingparam', '', '', $parname);
551 if (is_array($param)) {
552 debugging('Invalid array parameter detected in required_param(): '.$parname);
553 // TODO: switch to fatal error in Moodle 2.3.
554 return required_param_array($parname, $type);
557 return clean_param($param, $type);
561 * Returns a particular array value for the named variable, taken from
562 * POST or GET. If the parameter doesn't exist then an error is
563 * thrown because we require this variable.
565 * This function should be used to initialise all required values
566 * in a script that are based on parameters. Usually it will be
567 * used like this:
568 * $ids = required_param_array('ids', PARAM_INT);
570 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
572 * @param string $parname the name of the page parameter we want
573 * @param string $type expected type of parameter
574 * @return array
575 * @throws coding_exception
577 function required_param_array($parname, $type) {
578 if (func_num_args() != 2 or empty($parname) or empty($type)) {
579 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
581 // POST has precedence.
582 if (isset($_POST[$parname])) {
583 $param = $_POST[$parname];
584 } else if (isset($_GET[$parname])) {
585 $param = $_GET[$parname];
586 } else {
587 print_error('missingparam', '', '', $parname);
589 if (!is_array($param)) {
590 print_error('missingparam', '', '', $parname);
593 $result = array();
594 foreach ($param as $key => $value) {
595 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
596 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
597 continue;
599 $result[$key] = clean_param($value, $type);
602 return $result;
606 * Returns a particular value for the named variable, taken from
607 * POST or GET, otherwise returning a given default.
609 * This function should be used to initialise all optional values
610 * in a script that are based on parameters. Usually it will be
611 * used like this:
612 * $name = optional_param('name', 'Fred', PARAM_TEXT);
614 * Please note the $type parameter is now required and the value can not be array.
616 * @param string $parname the name of the page parameter we want
617 * @param mixed $default the default value to return if nothing is found
618 * @param string $type expected type of parameter
619 * @return mixed
620 * @throws coding_exception
622 function optional_param($parname, $default, $type) {
623 if (func_num_args() != 3 or empty($parname) or empty($type)) {
624 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
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)) {
1033 // Simulate the HTTPS version of the site.
1034 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1036 if ($param === $CFG->wwwroot) {
1037 // Exact match;
1038 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1039 // Exact match;
1040 } else if (preg_match(':^/:', $param)) {
1041 // Root-relative, ok!
1042 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1043 // Absolute, and matches our wwwroot.
1044 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
1045 // Absolute, and matches our httpswwwroot.
1046 } else {
1047 // Relative - let's make sure there are no tricks.
1048 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1049 // Looks ok.
1050 } else {
1051 $param = '';
1055 return $param;
1057 case PARAM_PEM:
1058 $param = trim($param);
1059 // PEM formatted strings may contain letters/numbers and the symbols:
1060 // forward slash: /
1061 // plus sign: +
1062 // equal sign: =
1063 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1064 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1065 list($wholething, $body) = $matches;
1066 unset($wholething, $matches);
1067 $b64 = clean_param($body, PARAM_BASE64);
1068 if (!empty($b64)) {
1069 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1070 } else {
1071 return '';
1074 return '';
1076 case PARAM_BASE64:
1077 if (!empty($param)) {
1078 // PEM formatted strings may contain letters/numbers and the symbols
1079 // forward slash: /
1080 // plus sign: +
1081 // equal sign: =.
1082 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1083 return '';
1085 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1086 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1087 // than (or equal to) 64 characters long.
1088 for ($i=0, $j=count($lines); $i < $j; $i++) {
1089 if ($i + 1 == $j) {
1090 if (64 < strlen($lines[$i])) {
1091 return '';
1093 continue;
1096 if (64 != strlen($lines[$i])) {
1097 return '';
1100 return implode("\n", $lines);
1101 } else {
1102 return '';
1105 case PARAM_TAG:
1106 $param = fix_utf8($param);
1107 // Please note it is not safe to use the tag name directly anywhere,
1108 // it must be processed with s(), urlencode() before embedding anywhere.
1109 // Remove some nasties.
1110 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1111 // Convert many whitespace chars into one.
1112 $param = preg_replace('/\s+/u', ' ', $param);
1113 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1114 return $param;
1116 case PARAM_TAGLIST:
1117 $param = fix_utf8($param);
1118 $tags = explode(',', $param);
1119 $result = array();
1120 foreach ($tags as $tag) {
1121 $res = clean_param($tag, PARAM_TAG);
1122 if ($res !== '') {
1123 $result[] = $res;
1126 if ($result) {
1127 return implode(',', $result);
1128 } else {
1129 return '';
1132 case PARAM_CAPABILITY:
1133 if (get_capability_info($param)) {
1134 return $param;
1135 } else {
1136 return '';
1139 case PARAM_PERMISSION:
1140 $param = (int)$param;
1141 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1142 return $param;
1143 } else {
1144 return CAP_INHERIT;
1147 case PARAM_AUTH:
1148 $param = clean_param($param, PARAM_PLUGIN);
1149 if (empty($param)) {
1150 return '';
1151 } else if (exists_auth_plugin($param)) {
1152 return $param;
1153 } else {
1154 return '';
1157 case PARAM_LANG:
1158 $param = clean_param($param, PARAM_SAFEDIR);
1159 if (get_string_manager()->translation_exists($param)) {
1160 return $param;
1161 } else {
1162 // Specified language is not installed or param malformed.
1163 return '';
1166 case PARAM_THEME:
1167 $param = clean_param($param, PARAM_PLUGIN);
1168 if (empty($param)) {
1169 return '';
1170 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1171 return $param;
1172 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1173 return $param;
1174 } else {
1175 // Specified theme is not installed.
1176 return '';
1179 case PARAM_USERNAME:
1180 $param = fix_utf8($param);
1181 $param = trim($param);
1182 // Convert uppercase to lowercase MDL-16919.
1183 $param = core_text::strtolower($param);
1184 if (empty($CFG->extendedusernamechars)) {
1185 $param = str_replace(" " , "", $param);
1186 // Regular expression, eliminate all chars EXCEPT:
1187 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1188 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1190 return $param;
1192 case PARAM_EMAIL:
1193 $param = fix_utf8($param);
1194 if (validate_email($param)) {
1195 return $param;
1196 } else {
1197 return '';
1200 case PARAM_STRINGID:
1201 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1202 return $param;
1203 } else {
1204 return '';
1207 case PARAM_TIMEZONE:
1208 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1209 $param = fix_utf8($param);
1210 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1211 if (preg_match($timezonepattern, $param)) {
1212 return $param;
1213 } else {
1214 return '';
1217 default:
1218 // Doh! throw error, switched parameters in optional_param or another serious problem.
1219 print_error("unknownparamtype", '', '', $type);
1224 * Makes sure the data is using valid utf8, invalid characters are discarded.
1226 * Note: this function is not intended for full objects with methods and private properties.
1228 * @param mixed $value
1229 * @return mixed with proper utf-8 encoding
1231 function fix_utf8($value) {
1232 if (is_null($value) or $value === '') {
1233 return $value;
1235 } else if (is_string($value)) {
1236 if ((string)(int)$value === $value) {
1237 // Shortcut.
1238 return $value;
1240 // No null bytes expected in our data, so let's remove it.
1241 $value = str_replace("\0", '', $value);
1243 // Note: this duplicates min_fix_utf8() intentionally.
1244 static $buggyiconv = null;
1245 if ($buggyiconv === null) {
1246 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1249 if ($buggyiconv) {
1250 if (function_exists('mb_convert_encoding')) {
1251 $subst = mb_substitute_character();
1252 mb_substitute_character('');
1253 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1254 mb_substitute_character($subst);
1256 } else {
1257 // Warn admins on admin/index.php page.
1258 $result = $value;
1261 } else {
1262 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1265 return $result;
1267 } else if (is_array($value)) {
1268 foreach ($value as $k => $v) {
1269 $value[$k] = fix_utf8($v);
1271 return $value;
1273 } else if (is_object($value)) {
1274 // Do not modify original.
1275 $value = clone($value);
1276 foreach ($value as $k => $v) {
1277 $value->$k = fix_utf8($v);
1279 return $value;
1281 } else {
1282 // This is some other type, no utf-8 here.
1283 return $value;
1288 * Return true if given value is integer or string with integer value
1290 * @param mixed $value String or Int
1291 * @return bool true if number, false if not
1293 function is_number($value) {
1294 if (is_int($value)) {
1295 return true;
1296 } else if (is_string($value)) {
1297 return ((string)(int)$value) === $value;
1298 } else {
1299 return false;
1304 * Returns host part from url.
1306 * @param string $url full url
1307 * @return string host, null if not found
1309 function get_host_from_url($url) {
1310 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1311 if ($matches) {
1312 return $matches[1];
1314 return null;
1318 * Tests whether anything was returned by text editor
1320 * This function is useful for testing whether something you got back from
1321 * the HTML editor actually contains anything. Sometimes the HTML editor
1322 * appear to be empty, but actually you get back a <br> tag or something.
1324 * @param string $string a string containing HTML.
1325 * @return boolean does the string contain any actual content - that is text,
1326 * images, objects, etc.
1328 function html_is_blank($string) {
1329 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1333 * Set a key in global configuration
1335 * Set a key/value pair in both this session's {@link $CFG} global variable
1336 * and in the 'config' database table for future sessions.
1338 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1339 * In that case it doesn't affect $CFG.
1341 * A NULL value will delete the entry.
1343 * NOTE: this function is called from lib/db/upgrade.php
1345 * @param string $name the key to set
1346 * @param string $value the value to set (without magic quotes)
1347 * @param string $plugin (optional) the plugin scope, default null
1348 * @return bool true or exception
1350 function set_config($name, $value, $plugin=null) {
1351 global $CFG, $DB;
1353 if (empty($plugin)) {
1354 if (!array_key_exists($name, $CFG->config_php_settings)) {
1355 // So it's defined for this invocation at least.
1356 if (is_null($value)) {
1357 unset($CFG->$name);
1358 } else {
1359 // Settings from db are always strings.
1360 $CFG->$name = (string)$value;
1364 if ($DB->get_field('config', 'name', array('name' => $name))) {
1365 if ($value === null) {
1366 $DB->delete_records('config', array('name' => $name));
1367 } else {
1368 $DB->set_field('config', 'value', $value, array('name' => $name));
1370 } else {
1371 if ($value !== null) {
1372 $config = new stdClass();
1373 $config->name = $name;
1374 $config->value = $value;
1375 $DB->insert_record('config', $config, false);
1378 if ($name === 'siteidentifier') {
1379 cache_helper::update_site_identifier($value);
1381 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1382 } else {
1383 // Plugin scope.
1384 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1385 if ($value===null) {
1386 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1387 } else {
1388 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1390 } else {
1391 if ($value !== null) {
1392 $config = new stdClass();
1393 $config->plugin = $plugin;
1394 $config->name = $name;
1395 $config->value = $value;
1396 $DB->insert_record('config_plugins', $config, false);
1399 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1402 return true;
1406 * Get configuration values from the global config table
1407 * or the config_plugins table.
1409 * If called with one parameter, it will load all the config
1410 * variables for one plugin, and return them as an object.
1412 * If called with 2 parameters it will return a string single
1413 * value or false if the value is not found.
1415 * NOTE: this function is called from lib/db/upgrade.php
1417 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1418 * that we need only fetch it once per request.
1419 * @param string $plugin full component name
1420 * @param string $name default null
1421 * @return mixed hash-like object or single value, return false no config found
1422 * @throws dml_exception
1424 function get_config($plugin, $name = null) {
1425 global $CFG, $DB;
1427 static $siteidentifier = null;
1429 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1430 $forced =& $CFG->config_php_settings;
1431 $iscore = true;
1432 $plugin = 'core';
1433 } else {
1434 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1435 $forced =& $CFG->forced_plugin_settings[$plugin];
1436 } else {
1437 $forced = array();
1439 $iscore = false;
1442 if ($siteidentifier === null) {
1443 try {
1444 // This may fail during installation.
1445 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1446 // install the database.
1447 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1448 } catch (dml_exception $ex) {
1449 // Set siteidentifier to false. We don't want to trip this continually.
1450 $siteidentifier = false;
1451 throw $ex;
1455 if (!empty($name)) {
1456 if (array_key_exists($name, $forced)) {
1457 return (string)$forced[$name];
1458 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1459 return $siteidentifier;
1463 $cache = cache::make('core', 'config');
1464 $result = $cache->get($plugin);
1465 if ($result === false) {
1466 // The user is after a recordset.
1467 if (!$iscore) {
1468 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1469 } else {
1470 // This part is not really used any more, but anyway...
1471 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1473 $cache->set($plugin, $result);
1476 if (!empty($name)) {
1477 if (array_key_exists($name, $result)) {
1478 return $result[$name];
1480 return false;
1483 if ($plugin === 'core') {
1484 $result['siteidentifier'] = $siteidentifier;
1487 foreach ($forced as $key => $value) {
1488 if (is_null($value) or is_array($value) or is_object($value)) {
1489 // We do not want any extra mess here, just real settings that could be saved in db.
1490 unset($result[$key]);
1491 } else {
1492 // Convert to string as if it went through the DB.
1493 $result[$key] = (string)$value;
1497 return (object)$result;
1501 * Removes a key from global configuration.
1503 * NOTE: this function is called from lib/db/upgrade.php
1505 * @param string $name the key to set
1506 * @param string $plugin (optional) the plugin scope
1507 * @return boolean whether the operation succeeded.
1509 function unset_config($name, $plugin=null) {
1510 global $CFG, $DB;
1512 if (empty($plugin)) {
1513 unset($CFG->$name);
1514 $DB->delete_records('config', array('name' => $name));
1515 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1516 } else {
1517 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1518 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1521 return true;
1525 * Remove all the config variables for a given plugin.
1527 * NOTE: this function is called from lib/db/upgrade.php
1529 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1530 * @return boolean whether the operation succeeded.
1532 function unset_all_config_for_plugin($plugin) {
1533 global $DB;
1534 // Delete from the obvious config_plugins first.
1535 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1536 // Next delete any suspect settings from config.
1537 $like = $DB->sql_like('name', '?', true, true, false, '|');
1538 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1539 $DB->delete_records_select('config', $like, $params);
1540 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1541 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1543 return true;
1547 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1549 * All users are verified if they still have the necessary capability.
1551 * @param string $value the value of the config setting.
1552 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1553 * @param bool $includeadmins include administrators.
1554 * @return array of user objects.
1556 function get_users_from_config($value, $capability, $includeadmins = true) {
1557 if (empty($value) or $value === '$@NONE@$') {
1558 return array();
1561 // We have to make sure that users still have the necessary capability,
1562 // it should be faster to fetch them all first and then test if they are present
1563 // instead of validating them one-by-one.
1564 $users = get_users_by_capability(context_system::instance(), $capability);
1565 if ($includeadmins) {
1566 $admins = get_admins();
1567 foreach ($admins as $admin) {
1568 $users[$admin->id] = $admin;
1572 if ($value === '$@ALL@$') {
1573 return $users;
1576 $result = array(); // Result in correct order.
1577 $allowed = explode(',', $value);
1578 foreach ($allowed as $uid) {
1579 if (isset($users[$uid])) {
1580 $user = $users[$uid];
1581 $result[$user->id] = $user;
1585 return $result;
1590 * Invalidates browser caches and cached data in temp.
1592 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1593 * {@link phpunit_util::reset_dataroot()}
1595 * @return void
1597 function purge_all_caches() {
1598 global $CFG, $DB;
1600 reset_text_filters_cache();
1601 js_reset_all_caches();
1602 theme_reset_all_caches();
1603 get_string_manager()->reset_caches();
1604 core_text::reset_caches();
1605 if (class_exists('core_plugin_manager')) {
1606 core_plugin_manager::reset_caches();
1609 // Bump up cacherev field for all courses.
1610 try {
1611 increment_revision_number('course', 'cacherev', '');
1612 } catch (moodle_exception $e) {
1613 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1616 $DB->reset_caches();
1617 cache_helper::purge_all();
1619 // Purge all other caches: rss, simplepie, etc.
1620 remove_dir($CFG->cachedir.'', true);
1622 // Make sure cache dir is writable, throws exception if not.
1623 make_cache_directory('');
1625 // This is the only place where we purge local caches, we are only adding files there.
1626 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1627 remove_dir($CFG->localcachedir, true);
1628 set_config('localcachedirpurged', time());
1629 make_localcache_directory('', true);
1630 \core\task\manager::clear_static_caches();
1634 * Get volatile flags
1636 * @param string $type
1637 * @param int $changedsince default null
1638 * @return array records array
1640 function get_cache_flags($type, $changedsince = null) {
1641 global $DB;
1643 $params = array('type' => $type, 'expiry' => time());
1644 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1645 if ($changedsince !== null) {
1646 $params['changedsince'] = $changedsince;
1647 $sqlwhere .= " AND timemodified > :changedsince";
1649 $cf = array();
1650 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1651 foreach ($flags as $flag) {
1652 $cf[$flag->name] = $flag->value;
1655 return $cf;
1659 * Get volatile flags
1661 * @param string $type
1662 * @param string $name
1663 * @param int $changedsince default null
1664 * @return string|false The cache flag value or false
1666 function get_cache_flag($type, $name, $changedsince=null) {
1667 global $DB;
1669 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1671 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1672 if ($changedsince !== null) {
1673 $params['changedsince'] = $changedsince;
1674 $sqlwhere .= " AND timemodified > :changedsince";
1677 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1681 * Set a volatile flag
1683 * @param string $type the "type" namespace for the key
1684 * @param string $name the key to set
1685 * @param string $value the value to set (without magic quotes) - null will remove the flag
1686 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1687 * @return bool Always returns true
1689 function set_cache_flag($type, $name, $value, $expiry = null) {
1690 global $DB;
1692 $timemodified = time();
1693 if ($expiry === null || $expiry < $timemodified) {
1694 $expiry = $timemodified + 24 * 60 * 60;
1695 } else {
1696 $expiry = (int)$expiry;
1699 if ($value === null) {
1700 unset_cache_flag($type, $name);
1701 return true;
1704 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1705 // This is a potential problem in DEBUG_DEVELOPER.
1706 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1707 return true; // No need to update.
1709 $f->value = $value;
1710 $f->expiry = $expiry;
1711 $f->timemodified = $timemodified;
1712 $DB->update_record('cache_flags', $f);
1713 } else {
1714 $f = new stdClass();
1715 $f->flagtype = $type;
1716 $f->name = $name;
1717 $f->value = $value;
1718 $f->expiry = $expiry;
1719 $f->timemodified = $timemodified;
1720 $DB->insert_record('cache_flags', $f);
1722 return true;
1726 * Removes a single volatile flag
1728 * @param string $type the "type" namespace for the key
1729 * @param string $name the key to set
1730 * @return bool
1732 function unset_cache_flag($type, $name) {
1733 global $DB;
1734 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1735 return true;
1739 * Garbage-collect volatile flags
1741 * @return bool Always returns true
1743 function gc_cache_flags() {
1744 global $DB;
1745 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1746 return true;
1749 // USER PREFERENCE API.
1752 * Refresh user preference cache. This is used most often for $USER
1753 * object that is stored in session, but it also helps with performance in cron script.
1755 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1757 * @package core
1758 * @category preference
1759 * @access public
1760 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1761 * @param int $cachelifetime Cache life time on the current page (in seconds)
1762 * @throws coding_exception
1763 * @return null
1765 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1766 global $DB;
1767 // Static cache, we need to check on each page load, not only every 2 minutes.
1768 static $loadedusers = array();
1770 if (!isset($user->id)) {
1771 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1774 if (empty($user->id) or isguestuser($user->id)) {
1775 // No permanent storage for not-logged-in users and guest.
1776 if (!isset($user->preference)) {
1777 $user->preference = array();
1779 return;
1782 $timenow = time();
1784 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1785 // Already loaded at least once on this page. Are we up to date?
1786 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1787 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1788 return;
1790 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1791 // No change since the lastcheck on this page.
1792 $user->preference['_lastloaded'] = $timenow;
1793 return;
1797 // OK, so we have to reload all preferences.
1798 $loadedusers[$user->id] = true;
1799 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1800 $user->preference['_lastloaded'] = $timenow;
1804 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1806 * NOTE: internal function, do not call from other code.
1808 * @package core
1809 * @access private
1810 * @param integer $userid the user whose prefs were changed.
1812 function mark_user_preferences_changed($userid) {
1813 global $CFG;
1815 if (empty($userid) or isguestuser($userid)) {
1816 // No cache flags for guest and not-logged-in users.
1817 return;
1820 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1824 * Sets a preference for the specified user.
1826 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1828 * @package core
1829 * @category preference
1830 * @access public
1831 * @param string $name The key to set as preference for the specified user
1832 * @param string $value The value to set for the $name key in the specified user's
1833 * record, null means delete current value.
1834 * @param stdClass|int|null $user A moodle user object or id, null means current user
1835 * @throws coding_exception
1836 * @return bool Always true or exception
1838 function set_user_preference($name, $value, $user = null) {
1839 global $USER, $DB;
1841 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1842 throw new coding_exception('Invalid preference name in set_user_preference() call');
1845 if (is_null($value)) {
1846 // Null means delete current.
1847 return unset_user_preference($name, $user);
1848 } else if (is_object($value)) {
1849 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1850 } else if (is_array($value)) {
1851 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1853 // Value column maximum length is 1333 characters.
1854 $value = (string)$value;
1855 if (core_text::strlen($value) > 1333) {
1856 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1859 if (is_null($user)) {
1860 $user = $USER;
1861 } else if (isset($user->id)) {
1862 // It is a valid object.
1863 } else if (is_numeric($user)) {
1864 $user = (object)array('id' => (int)$user);
1865 } else {
1866 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1869 check_user_preferences_loaded($user);
1871 if (empty($user->id) or isguestuser($user->id)) {
1872 // No permanent storage for not-logged-in users and guest.
1873 $user->preference[$name] = $value;
1874 return true;
1877 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1878 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1879 // Preference already set to this value.
1880 return true;
1882 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1884 } else {
1885 $preference = new stdClass();
1886 $preference->userid = $user->id;
1887 $preference->name = $name;
1888 $preference->value = $value;
1889 $DB->insert_record('user_preferences', $preference);
1892 // Update value in cache.
1893 $user->preference[$name] = $value;
1895 // Set reload flag for other sessions.
1896 mark_user_preferences_changed($user->id);
1898 return true;
1902 * Sets a whole array of preferences for the current user
1904 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1906 * @package core
1907 * @category preference
1908 * @access public
1909 * @param array $prefarray An array of key/value pairs to be set
1910 * @param stdClass|int|null $user A moodle user object or id, null means current user
1911 * @return bool Always true or exception
1913 function set_user_preferences(array $prefarray, $user = null) {
1914 foreach ($prefarray as $name => $value) {
1915 set_user_preference($name, $value, $user);
1917 return true;
1921 * Unsets a preference completely by deleting it from the database
1923 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1925 * @package core
1926 * @category preference
1927 * @access public
1928 * @param string $name The key to unset as preference for the specified user
1929 * @param stdClass|int|null $user A moodle user object or id, null means current user
1930 * @throws coding_exception
1931 * @return bool Always true or exception
1933 function unset_user_preference($name, $user = null) {
1934 global $USER, $DB;
1936 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1937 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1940 if (is_null($user)) {
1941 $user = $USER;
1942 } else if (isset($user->id)) {
1943 // It is a valid object.
1944 } else if (is_numeric($user)) {
1945 $user = (object)array('id' => (int)$user);
1946 } else {
1947 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1950 check_user_preferences_loaded($user);
1952 if (empty($user->id) or isguestuser($user->id)) {
1953 // No permanent storage for not-logged-in user and guest.
1954 unset($user->preference[$name]);
1955 return true;
1958 // Delete from DB.
1959 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1961 // Delete the preference from cache.
1962 unset($user->preference[$name]);
1964 // Set reload flag for other sessions.
1965 mark_user_preferences_changed($user->id);
1967 return true;
1971 * Used to fetch user preference(s)
1973 * If no arguments are supplied this function will return
1974 * all of the current user preferences as an array.
1976 * If a name is specified then this function
1977 * attempts to return that particular preference value. If
1978 * none is found, then the optional value $default is returned,
1979 * otherwise null.
1981 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1983 * @package core
1984 * @category preference
1985 * @access public
1986 * @param string $name Name of the key to use in finding a preference value
1987 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1988 * @param stdClass|int|null $user A moodle user object or id, null means current user
1989 * @throws coding_exception
1990 * @return string|mixed|null A string containing the value of a single preference. An
1991 * array with all of the preferences or null
1993 function get_user_preferences($name = null, $default = null, $user = null) {
1994 global $USER;
1996 if (is_null($name)) {
1997 // All prefs.
1998 } else if (is_numeric($name) or $name === '_lastloaded') {
1999 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2002 if (is_null($user)) {
2003 $user = $USER;
2004 } else if (isset($user->id)) {
2005 // Is a valid object.
2006 } else if (is_numeric($user)) {
2007 $user = (object)array('id' => (int)$user);
2008 } else {
2009 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2012 check_user_preferences_loaded($user);
2014 if (empty($name)) {
2015 // All values.
2016 return $user->preference;
2017 } else if (isset($user->preference[$name])) {
2018 // The single string value.
2019 return $user->preference[$name];
2020 } else {
2021 // Default value (null if not specified).
2022 return $default;
2026 // FUNCTIONS FOR HANDLING TIME.
2029 * Given Gregorian date parts in user time produce a GMT timestamp.
2031 * @package core
2032 * @category time
2033 * @param int $year The year part to create timestamp of
2034 * @param int $month The month part to create timestamp of
2035 * @param int $day The day part to create timestamp of
2036 * @param int $hour The hour part to create timestamp of
2037 * @param int $minute The minute part to create timestamp of
2038 * @param int $second The second part to create timestamp of
2039 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2040 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2041 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2042 * applied only if timezone is 99 or string.
2043 * @return int GMT timestamp
2045 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2046 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2047 $date->setDate((int)$year, (int)$month, (int)$day);
2048 $date->setTime((int)$hour, (int)$minute, (int)$second);
2050 $time = $date->getTimestamp();
2052 // Moodle BC DST stuff.
2053 if (!$applydst) {
2054 $time += dst_offset_on($time, $timezone);
2057 return $time;
2062 * Format a date/time (seconds) as weeks, days, hours etc as needed
2064 * Given an amount of time in seconds, returns string
2065 * formatted nicely as weeks, days, hours etc as needed
2067 * @package core
2068 * @category time
2069 * @uses MINSECS
2070 * @uses HOURSECS
2071 * @uses DAYSECS
2072 * @uses YEARSECS
2073 * @param int $totalsecs Time in seconds
2074 * @param stdClass $str Should be a time object
2075 * @return string A nicely formatted date/time string
2077 function format_time($totalsecs, $str = null) {
2079 $totalsecs = abs($totalsecs);
2081 if (!$str) {
2082 // Create the str structure the slow way.
2083 $str = new stdClass();
2084 $str->day = get_string('day');
2085 $str->days = get_string('days');
2086 $str->hour = get_string('hour');
2087 $str->hours = get_string('hours');
2088 $str->min = get_string('min');
2089 $str->mins = get_string('mins');
2090 $str->sec = get_string('sec');
2091 $str->secs = get_string('secs');
2092 $str->year = get_string('year');
2093 $str->years = get_string('years');
2096 $years = floor($totalsecs/YEARSECS);
2097 $remainder = $totalsecs - ($years*YEARSECS);
2098 $days = floor($remainder/DAYSECS);
2099 $remainder = $totalsecs - ($days*DAYSECS);
2100 $hours = floor($remainder/HOURSECS);
2101 $remainder = $remainder - ($hours*HOURSECS);
2102 $mins = floor($remainder/MINSECS);
2103 $secs = $remainder - ($mins*MINSECS);
2105 $ss = ($secs == 1) ? $str->sec : $str->secs;
2106 $sm = ($mins == 1) ? $str->min : $str->mins;
2107 $sh = ($hours == 1) ? $str->hour : $str->hours;
2108 $sd = ($days == 1) ? $str->day : $str->days;
2109 $sy = ($years == 1) ? $str->year : $str->years;
2111 $oyears = '';
2112 $odays = '';
2113 $ohours = '';
2114 $omins = '';
2115 $osecs = '';
2117 if ($years) {
2118 $oyears = $years .' '. $sy;
2120 if ($days) {
2121 $odays = $days .' '. $sd;
2123 if ($hours) {
2124 $ohours = $hours .' '. $sh;
2126 if ($mins) {
2127 $omins = $mins .' '. $sm;
2129 if ($secs) {
2130 $osecs = $secs .' '. $ss;
2133 if ($years) {
2134 return trim($oyears .' '. $odays);
2136 if ($days) {
2137 return trim($odays .' '. $ohours);
2139 if ($hours) {
2140 return trim($ohours .' '. $omins);
2142 if ($mins) {
2143 return trim($omins .' '. $osecs);
2145 if ($secs) {
2146 return $osecs;
2148 return get_string('now');
2152 * Returns a formatted string that represents a date in user time.
2154 * @package core
2155 * @category time
2156 * @param int $date the timestamp in UTC, as obtained from the database.
2157 * @param string $format strftime format. You should probably get this using
2158 * get_string('strftime...', 'langconfig');
2159 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2160 * not 99 then daylight saving will not be added.
2161 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2162 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2163 * If false then the leading zero is maintained.
2164 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2165 * @return string the formatted date/time.
2167 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2168 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2169 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2173 * Returns a formatted date ensuring it is UTF-8.
2175 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2176 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2178 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2179 * @param string $format strftime format.
2180 * @param int|float|string $tz the user timezone
2181 * @return string the formatted date/time.
2182 * @since Moodle 2.3.3
2184 function date_format_string($date, $format, $tz = 99) {
2185 global $CFG;
2187 $localewincharset = null;
2188 // Get the calendar type user is using.
2189 if ($CFG->ostype == 'WINDOWS') {
2190 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2191 $localewincharset = $calendartype->locale_win_charset();
2194 if ($localewincharset) {
2195 $format = core_text::convert($format, 'utf-8', $localewincharset);
2198 date_default_timezone_set(core_date::get_user_timezone($tz));
2199 $datestring = strftime($format, $date);
2200 core_date::set_default_server_timezone();
2202 if ($localewincharset) {
2203 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2206 return $datestring;
2210 * Given a $time timestamp in GMT (seconds since epoch),
2211 * returns an array that represents the Gregorian date in user time
2213 * @package core
2214 * @category time
2215 * @param int $time Timestamp in GMT
2216 * @param float|int|string $timezone user timezone
2217 * @return array An array that represents the date in user time
2219 function usergetdate($time, $timezone=99) {
2220 date_default_timezone_set(core_date::get_user_timezone($timezone));
2221 $result = getdate($time);
2222 core_date::set_default_server_timezone();
2224 return $result;
2228 * Given a GMT timestamp (seconds since epoch), offsets it by
2229 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2231 * NOTE: this function does not include DST properly,
2232 * you should use the PHP date stuff instead!
2234 * @package core
2235 * @category time
2236 * @param int $date Timestamp in GMT
2237 * @param float|int|string $timezone user timezone
2238 * @return int
2240 function usertime($date, $timezone=99) {
2241 $userdate = new DateTime('@' . $date);
2242 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2243 $dst = dst_offset_on($date, $timezone);
2245 return $date - $userdate->getOffset() + $dst;
2249 * Given a time, return the GMT timestamp of the most recent midnight
2250 * for the current user.
2252 * @package core
2253 * @category time
2254 * @param int $date Timestamp in GMT
2255 * @param float|int|string $timezone user timezone
2256 * @return int Returns a GMT timestamp
2258 function usergetmidnight($date, $timezone=99) {
2260 $userdate = usergetdate($date, $timezone);
2262 // Time of midnight of this user's day, in GMT.
2263 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2268 * Returns a string that prints the user's timezone
2270 * @package core
2271 * @category time
2272 * @param float|int|string $timezone user timezone
2273 * @return string
2275 function usertimezone($timezone=99) {
2276 $tz = core_date::get_user_timezone($timezone);
2277 return core_date::get_localised_timezone($tz);
2281 * Returns a float or a string which denotes the user's timezone
2282 * 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)
2283 * means that for this timezone there are also DST rules to be taken into account
2284 * Checks various settings and picks the most dominant of those which have a value
2286 * @package core
2287 * @category time
2288 * @param float|int|string $tz timezone to calculate GMT time offset before
2289 * calculating user timezone, 99 is default user timezone
2290 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2291 * @return float|string
2293 function get_user_timezone($tz = 99) {
2294 global $USER, $CFG;
2296 $timezones = array(
2297 $tz,
2298 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2299 isset($USER->timezone) ? $USER->timezone : 99,
2300 isset($CFG->timezone) ? $CFG->timezone : 99,
2303 $tz = 99;
2305 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2306 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2307 $tz = $next['value'];
2309 return is_numeric($tz) ? (float) $tz : $tz;
2313 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2314 * - Note: Daylight saving only works for string timezones and not for float.
2316 * @package core
2317 * @category time
2318 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2319 * @param int|float|string $strtimezone user timezone
2320 * @return int
2322 function dst_offset_on($time, $strtimezone = null) {
2323 $tz = core_date::get_user_timezone($strtimezone);
2324 $date = new DateTime('@' . $time);
2325 $date->setTimezone(new DateTimeZone($tz));
2326 if ($date->format('I') == '1') {
2327 if ($tz === 'Australia/Lord_Howe') {
2328 return 1800;
2330 return 3600;
2332 return 0;
2336 * Calculates when the day appears in specific month
2338 * @package core
2339 * @category time
2340 * @param int $startday starting day of the month
2341 * @param int $weekday The day when week starts (normally taken from user preferences)
2342 * @param int $month The month whose day is sought
2343 * @param int $year The year of the month whose day is sought
2344 * @return int
2346 function find_day_in_month($startday, $weekday, $month, $year) {
2347 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2349 $daysinmonth = days_in_month($month, $year);
2350 $daysinweek = count($calendartype->get_weekdays());
2352 if ($weekday == -1) {
2353 // Don't care about weekday, so return:
2354 // abs($startday) if $startday != -1
2355 // $daysinmonth otherwise.
2356 return ($startday == -1) ? $daysinmonth : abs($startday);
2359 // From now on we 're looking for a specific weekday.
2360 // Give "end of month" its actual value, since we know it.
2361 if ($startday == -1) {
2362 $startday = -1 * $daysinmonth;
2365 // Starting from day $startday, the sign is the direction.
2366 if ($startday < 1) {
2367 $startday = abs($startday);
2368 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2370 // This is the last such weekday of the month.
2371 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2372 if ($lastinmonth > $daysinmonth) {
2373 $lastinmonth -= $daysinweek;
2376 // Find the first such weekday <= $startday.
2377 while ($lastinmonth > $startday) {
2378 $lastinmonth -= $daysinweek;
2381 return $lastinmonth;
2382 } else {
2383 $indexweekday = dayofweek($startday, $month, $year);
2385 $diff = $weekday - $indexweekday;
2386 if ($diff < 0) {
2387 $diff += $daysinweek;
2390 // This is the first such weekday of the month equal to or after $startday.
2391 $firstfromindex = $startday + $diff;
2393 return $firstfromindex;
2398 * Calculate the number of days in a given month
2400 * @package core
2401 * @category time
2402 * @param int $month The month whose day count is sought
2403 * @param int $year The year of the month whose day count is sought
2404 * @return int
2406 function days_in_month($month, $year) {
2407 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2408 return $calendartype->get_num_days_in_month($year, $month);
2412 * Calculate the position in the week of a specific calendar day
2414 * @package core
2415 * @category time
2416 * @param int $day The day of the date whose position in the week is sought
2417 * @param int $month The month of the date whose position in the week is sought
2418 * @param int $year The year of the date whose position in the week is sought
2419 * @return int
2421 function dayofweek($day, $month, $year) {
2422 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2423 return $calendartype->get_weekday($year, $month, $day);
2426 // USER AUTHENTICATION AND LOGIN.
2429 * Returns full login url.
2431 * @return string login url
2433 function get_login_url() {
2434 global $CFG;
2436 $url = "$CFG->wwwroot/login/index.php";
2438 if (!empty($CFG->loginhttps)) {
2439 $url = str_replace('http:', 'https:', $url);
2442 return $url;
2446 * This function checks that the current user is logged in and has the
2447 * required privileges
2449 * This function checks that the current user is logged in, and optionally
2450 * whether they are allowed to be in a particular course and view a particular
2451 * course module.
2452 * If they are not logged in, then it redirects them to the site login unless
2453 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2454 * case they are automatically logged in as guests.
2455 * If $courseid is given and the user is not enrolled in that course then the
2456 * user is redirected to the course enrolment page.
2457 * If $cm is given and the course module is hidden and the user is not a teacher
2458 * in the course then the user is redirected to the course home page.
2460 * When $cm parameter specified, this function sets page layout to 'module'.
2461 * You need to change it manually later if some other layout needed.
2463 * @package core_access
2464 * @category access
2466 * @param mixed $courseorid id of the course or course object
2467 * @param bool $autologinguest default true
2468 * @param object $cm course module object
2469 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2470 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2471 * in order to keep redirects working properly. MDL-14495
2472 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2473 * @return mixed Void, exit, and die depending on path
2474 * @throws coding_exception
2475 * @throws require_login_exception
2477 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2478 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2480 // Must not redirect when byteserving already started.
2481 if (!empty($_SERVER['HTTP_RANGE'])) {
2482 $preventredirect = true;
2485 if (AJAX_SCRIPT) {
2486 // We cannot redirect for AJAX scripts either.
2487 $preventredirect = true;
2490 // Setup global $COURSE, themes, language and locale.
2491 if (!empty($courseorid)) {
2492 if (is_object($courseorid)) {
2493 $course = $courseorid;
2494 } else if ($courseorid == SITEID) {
2495 $course = clone($SITE);
2496 } else {
2497 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2499 if ($cm) {
2500 if ($cm->course != $course->id) {
2501 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2503 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2504 if (!($cm instanceof cm_info)) {
2505 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2506 // db queries so this is not really a performance concern, however it is obviously
2507 // better if you use get_fast_modinfo to get the cm before calling this.
2508 $modinfo = get_fast_modinfo($course);
2509 $cm = $modinfo->get_cm($cm->id);
2512 } else {
2513 // Do not touch global $COURSE via $PAGE->set_course(),
2514 // the reasons is we need to be able to call require_login() at any time!!
2515 $course = $SITE;
2516 if ($cm) {
2517 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2521 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2522 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2523 // risk leading the user back to the AJAX request URL.
2524 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2525 $setwantsurltome = false;
2528 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2529 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2530 if ($preventredirect) {
2531 throw new require_login_session_timeout_exception();
2532 } else {
2533 if ($setwantsurltome) {
2534 $SESSION->wantsurl = qualified_me();
2536 redirect(get_login_url());
2540 // If the user is not even logged in yet then make sure they are.
2541 if (!isloggedin()) {
2542 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2543 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2544 // Misconfigured site guest, just redirect to login page.
2545 redirect(get_login_url());
2546 exit; // Never reached.
2548 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2549 complete_user_login($guest);
2550 $USER->autologinguest = true;
2551 $SESSION->lang = $lang;
2552 } else {
2553 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2554 if ($preventredirect) {
2555 throw new require_login_exception('You are not logged in');
2558 if ($setwantsurltome) {
2559 $SESSION->wantsurl = qualified_me();
2562 $referer = get_local_referer(false);
2563 if (!empty($referer)) {
2564 $SESSION->fromurl = $referer;
2567 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2568 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2569 foreach($authsequence as $authname) {
2570 $authplugin = get_auth_plugin($authname);
2571 $authplugin->pre_loginpage_hook();
2572 if (isloggedin()) {
2573 break;
2577 // If we're still not logged in then go to the login page
2578 if (!isloggedin()) {
2579 redirect(get_login_url());
2580 exit; // Never reached.
2585 // Loginas as redirection if needed.
2586 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2587 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2588 if ($USER->loginascontext->instanceid != $course->id) {
2589 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2594 // Check whether the user should be changing password (but only if it is REALLY them).
2595 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2596 $userauth = get_auth_plugin($USER->auth);
2597 if ($userauth->can_change_password() and !$preventredirect) {
2598 if ($setwantsurltome) {
2599 $SESSION->wantsurl = qualified_me();
2601 if ($changeurl = $userauth->change_password_url()) {
2602 // Use plugin custom url.
2603 redirect($changeurl);
2604 } else {
2605 // Use moodle internal method.
2606 if (empty($CFG->loginhttps)) {
2607 redirect($CFG->wwwroot .'/login/change_password.php');
2608 } else {
2609 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2610 redirect($wwwroot .'/login/change_password.php');
2613 } else {
2614 print_error('nopasswordchangeforced', 'auth');
2618 // Check that the user account is properly set up.
2619 if (user_not_fully_set_up($USER)) {
2620 if ($preventredirect) {
2621 throw new require_login_exception('User not fully set-up');
2623 if ($setwantsurltome) {
2624 $SESSION->wantsurl = qualified_me();
2626 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2629 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2630 sesskey();
2632 // Do not bother admins with any formalities.
2633 if (is_siteadmin()) {
2634 // Set the global $COURSE.
2635 if ($cm) {
2636 $PAGE->set_cm($cm, $course);
2637 $PAGE->set_pagelayout('incourse');
2638 } else if (!empty($courseorid)) {
2639 $PAGE->set_course($course);
2641 // Set accesstime or the user will appear offline which messes up messaging.
2642 user_accesstime_log($course->id);
2643 return;
2646 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2647 if (!$USER->policyagreed and !is_siteadmin()) {
2648 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2649 if ($preventredirect) {
2650 throw new require_login_exception('Policy not agreed');
2652 if ($setwantsurltome) {
2653 $SESSION->wantsurl = qualified_me();
2655 redirect($CFG->wwwroot .'/user/policy.php');
2656 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2657 if ($preventredirect) {
2658 throw new require_login_exception('Policy not agreed');
2660 if ($setwantsurltome) {
2661 $SESSION->wantsurl = qualified_me();
2663 redirect($CFG->wwwroot .'/user/policy.php');
2667 // Fetch the system context, the course context, and prefetch its child contexts.
2668 $sysctx = context_system::instance();
2669 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2670 if ($cm) {
2671 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2672 } else {
2673 $cmcontext = null;
2676 // If the site is currently under maintenance, then print a message.
2677 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2678 if ($preventredirect) {
2679 throw new require_login_exception('Maintenance in progress');
2682 print_maintenance_message();
2685 // Make sure the course itself is not hidden.
2686 if ($course->id == SITEID) {
2687 // Frontpage can not be hidden.
2688 } else {
2689 if (is_role_switched($course->id)) {
2690 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2691 } else {
2692 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2693 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2694 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2695 if ($preventredirect) {
2696 throw new require_login_exception('Course is hidden');
2698 $PAGE->set_context(null);
2699 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2700 // the navigation will mess up when trying to find it.
2701 navigation_node::override_active_url(new moodle_url('/'));
2702 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2707 // Is the user enrolled?
2708 if ($course->id == SITEID) {
2709 // Everybody is enrolled on the frontpage.
2710 } else {
2711 if (\core\session\manager::is_loggedinas()) {
2712 // Make sure the REAL person can access this course first.
2713 $realuser = \core\session\manager::get_realuser();
2714 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2715 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2716 if ($preventredirect) {
2717 throw new require_login_exception('Invalid course login-as access');
2719 $PAGE->set_context(null);
2720 echo $OUTPUT->header();
2721 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2725 $access = false;
2727 if (is_role_switched($course->id)) {
2728 // Ok, user had to be inside this course before the switch.
2729 $access = true;
2731 } else if (is_viewing($coursecontext, $USER)) {
2732 // Ok, no need to mess with enrol.
2733 $access = true;
2735 } else {
2736 if (isset($USER->enrol['enrolled'][$course->id])) {
2737 if ($USER->enrol['enrolled'][$course->id] > time()) {
2738 $access = true;
2739 if (isset($USER->enrol['tempguest'][$course->id])) {
2740 unset($USER->enrol['tempguest'][$course->id]);
2741 remove_temp_course_roles($coursecontext);
2743 } else {
2744 // Expired.
2745 unset($USER->enrol['enrolled'][$course->id]);
2748 if (isset($USER->enrol['tempguest'][$course->id])) {
2749 if ($USER->enrol['tempguest'][$course->id] == 0) {
2750 $access = true;
2751 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2752 $access = true;
2753 } else {
2754 // Expired.
2755 unset($USER->enrol['tempguest'][$course->id]);
2756 remove_temp_course_roles($coursecontext);
2760 if (!$access) {
2761 // Cache not ok.
2762 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2763 if ($until !== false) {
2764 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2765 if ($until == 0) {
2766 $until = ENROL_MAX_TIMESTAMP;
2768 $USER->enrol['enrolled'][$course->id] = $until;
2769 $access = true;
2771 } else {
2772 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2773 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2774 $enrols = enrol_get_plugins(true);
2775 // First ask all enabled enrol instances in course if they want to auto enrol user.
2776 foreach ($instances as $instance) {
2777 if (!isset($enrols[$instance->enrol])) {
2778 continue;
2780 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2781 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2782 if ($until !== false) {
2783 if ($until == 0) {
2784 $until = ENROL_MAX_TIMESTAMP;
2786 $USER->enrol['enrolled'][$course->id] = $until;
2787 $access = true;
2788 break;
2791 // If not enrolled yet try to gain temporary guest access.
2792 if (!$access) {
2793 foreach ($instances as $instance) {
2794 if (!isset($enrols[$instance->enrol])) {
2795 continue;
2797 // Get a duration for the guest access, a timestamp in the future or false.
2798 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2799 if ($until !== false and $until > time()) {
2800 $USER->enrol['tempguest'][$course->id] = $until;
2801 $access = true;
2802 break;
2810 if (!$access) {
2811 if ($preventredirect) {
2812 throw new require_login_exception('Not enrolled');
2814 if ($setwantsurltome) {
2815 $SESSION->wantsurl = qualified_me();
2817 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2821 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2822 if ($cm && !$cm->uservisible) {
2823 if ($preventredirect) {
2824 throw new require_login_exception('Activity is hidden');
2826 if ($course->id != SITEID) {
2827 $url = new moodle_url('/course/view.php', array('id' => $course->id));
2828 } else {
2829 $url = new moodle_url('/');
2831 redirect($url, get_string('activityiscurrentlyhidden'));
2834 // Set the global $COURSE.
2835 if ($cm) {
2836 $PAGE->set_cm($cm, $course);
2837 $PAGE->set_pagelayout('incourse');
2838 } else if (!empty($courseorid)) {
2839 $PAGE->set_course($course);
2842 // Finally access granted, update lastaccess times.
2843 user_accesstime_log($course->id);
2848 * This function just makes sure a user is logged out.
2850 * @package core_access
2851 * @category access
2853 function require_logout() {
2854 global $USER, $DB;
2856 if (!isloggedin()) {
2857 // This should not happen often, no need for hooks or events here.
2858 \core\session\manager::terminate_current();
2859 return;
2862 // Execute hooks before action.
2863 $authplugins = array();
2864 $authsequence = get_enabled_auth_plugins();
2865 foreach ($authsequence as $authname) {
2866 $authplugins[$authname] = get_auth_plugin($authname);
2867 $authplugins[$authname]->prelogout_hook();
2870 // Store info that gets removed during logout.
2871 $sid = session_id();
2872 $event = \core\event\user_loggedout::create(
2873 array(
2874 'userid' => $USER->id,
2875 'objectid' => $USER->id,
2876 'other' => array('sessionid' => $sid),
2879 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2880 $event->add_record_snapshot('sessions', $session);
2883 // Clone of $USER object to be used by auth plugins.
2884 $user = fullclone($USER);
2886 // Delete session record and drop $_SESSION content.
2887 \core\session\manager::terminate_current();
2889 // Trigger event AFTER action.
2890 $event->trigger();
2892 // Hook to execute auth plugins redirection after event trigger.
2893 foreach ($authplugins as $authplugin) {
2894 $authplugin->postlogout_hook($user);
2899 * Weaker version of require_login()
2901 * This is a weaker version of {@link require_login()} which only requires login
2902 * when called from within a course rather than the site page, unless
2903 * the forcelogin option is turned on.
2904 * @see require_login()
2906 * @package core_access
2907 * @category access
2909 * @param mixed $courseorid The course object or id in question
2910 * @param bool $autologinguest Allow autologin guests if that is wanted
2911 * @param object $cm Course activity module if known
2912 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2913 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2914 * in order to keep redirects working properly. MDL-14495
2915 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2916 * @return void
2917 * @throws coding_exception
2919 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2920 global $CFG, $PAGE, $SITE;
2921 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2922 or (!is_object($courseorid) and $courseorid == SITEID));
2923 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2924 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2925 // db queries so this is not really a performance concern, however it is obviously
2926 // better if you use get_fast_modinfo to get the cm before calling this.
2927 if (is_object($courseorid)) {
2928 $course = $courseorid;
2929 } else {
2930 $course = clone($SITE);
2932 $modinfo = get_fast_modinfo($course);
2933 $cm = $modinfo->get_cm($cm->id);
2935 if (!empty($CFG->forcelogin)) {
2936 // Login required for both SITE and courses.
2937 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2939 } else if ($issite && !empty($cm) and !$cm->uservisible) {
2940 // Always login for hidden activities.
2941 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2943 } else if ($issite) {
2944 // Login for SITE not required.
2945 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
2946 if (!empty($courseorid)) {
2947 if (is_object($courseorid)) {
2948 $course = $courseorid;
2949 } else {
2950 $course = clone $SITE;
2952 if ($cm) {
2953 if ($cm->course != $course->id) {
2954 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2956 $PAGE->set_cm($cm, $course);
2957 $PAGE->set_pagelayout('incourse');
2958 } else {
2959 $PAGE->set_course($course);
2961 } else {
2962 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
2963 $PAGE->set_course($PAGE->course);
2965 user_accesstime_log(SITEID);
2966 return;
2968 } else {
2969 // Course login always required.
2970 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2975 * Require key login. Function terminates with error if key not found or incorrect.
2977 * @uses NO_MOODLE_COOKIES
2978 * @uses PARAM_ALPHANUM
2979 * @param string $script unique script identifier
2980 * @param int $instance optional instance id
2981 * @return int Instance ID
2983 function require_user_key_login($script, $instance=null) {
2984 global $DB;
2986 if (!NO_MOODLE_COOKIES) {
2987 print_error('sessioncookiesdisable');
2990 // Extra safety.
2991 \core\session\manager::write_close();
2993 $keyvalue = required_param('key', PARAM_ALPHANUM);
2995 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
2996 print_error('invalidkey');
2999 if (!empty($key->validuntil) and $key->validuntil < time()) {
3000 print_error('expiredkey');
3003 if ($key->iprestriction) {
3004 $remoteaddr = getremoteaddr(null);
3005 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3006 print_error('ipmismatch');
3010 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3011 print_error('invaliduserid');
3014 // Emulate normal session.
3015 enrol_check_plugins($user);
3016 \core\session\manager::set_user($user);
3018 // Note we are not using normal login.
3019 if (!defined('USER_KEY_LOGIN')) {
3020 define('USER_KEY_LOGIN', true);
3023 // Return instance id - it might be empty.
3024 return $key->instance;
3028 * Creates a new private user access key.
3030 * @param string $script unique target identifier
3031 * @param int $userid
3032 * @param int $instance optional instance id
3033 * @param string $iprestriction optional ip restricted access
3034 * @param timestamp $validuntil key valid only until given data
3035 * @return string access key value
3037 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3038 global $DB;
3040 $key = new stdClass();
3041 $key->script = $script;
3042 $key->userid = $userid;
3043 $key->instance = $instance;
3044 $key->iprestriction = $iprestriction;
3045 $key->validuntil = $validuntil;
3046 $key->timecreated = time();
3048 // Something long and unique.
3049 $key->value = md5($userid.'_'.time().random_string(40));
3050 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3051 // Must be unique.
3052 $key->value = md5($userid.'_'.time().random_string(40));
3054 $DB->insert_record('user_private_key', $key);
3055 return $key->value;
3059 * Delete the user's new private user access keys for a particular script.
3061 * @param string $script unique target identifier
3062 * @param int $userid
3063 * @return void
3065 function delete_user_key($script, $userid) {
3066 global $DB;
3067 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3071 * Gets a private user access key (and creates one if one doesn't exist).
3073 * @param string $script unique target identifier
3074 * @param int $userid
3075 * @param int $instance optional instance id
3076 * @param string $iprestriction optional ip restricted access
3077 * @param timestamp $validuntil key valid only until given data
3078 * @return string access key value
3080 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3081 global $DB;
3083 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3084 'instance' => $instance, 'iprestriction' => $iprestriction,
3085 'validuntil' => $validuntil))) {
3086 return $key->value;
3087 } else {
3088 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3094 * Modify the user table by setting the currently logged in user's last login to now.
3096 * @return bool Always returns true
3098 function update_user_login_times() {
3099 global $USER, $DB;
3101 if (isguestuser()) {
3102 // Do not update guest access times/ips for performance.
3103 return true;
3106 $now = time();
3108 $user = new stdClass();
3109 $user->id = $USER->id;
3111 // Make sure all users that logged in have some firstaccess.
3112 if ($USER->firstaccess == 0) {
3113 $USER->firstaccess = $user->firstaccess = $now;
3116 // Store the previous current as lastlogin.
3117 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3119 $USER->currentlogin = $user->currentlogin = $now;
3121 // Function user_accesstime_log() may not update immediately, better do it here.
3122 $USER->lastaccess = $user->lastaccess = $now;
3123 $USER->lastip = $user->lastip = getremoteaddr();
3125 // Note: do not call user_update_user() here because this is part of the login process,
3126 // the login event means that these fields were updated.
3127 $DB->update_record('user', $user);
3128 return true;
3132 * Determines if a user has completed setting up their account.
3134 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3135 * @return bool
3137 function user_not_fully_set_up($user) {
3138 if (isguestuser($user)) {
3139 return false;
3141 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3145 * Check whether the user has exceeded the bounce threshold
3147 * @param stdClass $user A {@link $USER} object
3148 * @return bool true => User has exceeded bounce threshold
3150 function over_bounce_threshold($user) {
3151 global $CFG, $DB;
3153 if (empty($CFG->handlebounces)) {
3154 return false;
3157 if (empty($user->id)) {
3158 // No real (DB) user, nothing to do here.
3159 return false;
3162 // Set sensible defaults.
3163 if (empty($CFG->minbounces)) {
3164 $CFG->minbounces = 10;
3166 if (empty($CFG->bounceratio)) {
3167 $CFG->bounceratio = .20;
3169 $bouncecount = 0;
3170 $sendcount = 0;
3171 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3172 $bouncecount = $bounce->value;
3174 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3175 $sendcount = $send->value;
3177 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3181 * Used to increment or reset email sent count
3183 * @param stdClass $user object containing an id
3184 * @param bool $reset will reset the count to 0
3185 * @return void
3187 function set_send_count($user, $reset=false) {
3188 global $DB;
3190 if (empty($user->id)) {
3191 // No real (DB) user, nothing to do here.
3192 return;
3195 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3196 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3197 $DB->update_record('user_preferences', $pref);
3198 } else if (!empty($reset)) {
3199 // If it's not there and we're resetting, don't bother. Make a new one.
3200 $pref = new stdClass();
3201 $pref->name = 'email_send_count';
3202 $pref->value = 1;
3203 $pref->userid = $user->id;
3204 $DB->insert_record('user_preferences', $pref, false);
3209 * Increment or reset user's email bounce count
3211 * @param stdClass $user object containing an id
3212 * @param bool $reset will reset the count to 0
3214 function set_bounce_count($user, $reset=false) {
3215 global $DB;
3217 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3218 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3219 $DB->update_record('user_preferences', $pref);
3220 } else if (!empty($reset)) {
3221 // If it's not there and we're resetting, don't bother. Make a new one.
3222 $pref = new stdClass();
3223 $pref->name = 'email_bounce_count';
3224 $pref->value = 1;
3225 $pref->userid = $user->id;
3226 $DB->insert_record('user_preferences', $pref, false);
3231 * Determines if the logged in user is currently moving an activity
3233 * @param int $courseid The id of the course being tested
3234 * @return bool
3236 function ismoving($courseid) {
3237 global $USER;
3239 if (!empty($USER->activitycopy)) {
3240 return ($USER->activitycopycourse == $courseid);
3242 return false;
3246 * Returns a persons full name
3248 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3249 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3250 * specify one.
3252 * @param stdClass $user A {@link $USER} object to get full name of.
3253 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3254 * @return string
3256 function fullname($user, $override=false) {
3257 global $CFG, $SESSION;
3259 if (!isset($user->firstname) and !isset($user->lastname)) {
3260 return '';
3263 // Get all of the name fields.
3264 $allnames = get_all_user_name_fields();
3265 if ($CFG->debugdeveloper) {
3266 foreach ($allnames as $allname) {
3267 if (!property_exists($user, $allname)) {
3268 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3269 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3270 // Message has been sent, no point in sending the message multiple times.
3271 break;
3276 if (!$override) {
3277 if (!empty($CFG->forcefirstname)) {
3278 $user->firstname = $CFG->forcefirstname;
3280 if (!empty($CFG->forcelastname)) {
3281 $user->lastname = $CFG->forcelastname;
3285 if (!empty($SESSION->fullnamedisplay)) {
3286 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3289 $template = null;
3290 // If the fullnamedisplay setting is available, set the template to that.
3291 if (isset($CFG->fullnamedisplay)) {
3292 $template = $CFG->fullnamedisplay;
3294 // If the template is empty, or set to language, return the language string.
3295 if ((empty($template) || $template == 'language') && !$override) {
3296 return get_string('fullnamedisplay', null, $user);
3299 // Check to see if we are displaying according to the alternative full name format.
3300 if ($override) {
3301 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3302 // Default to show just the user names according to the fullnamedisplay string.
3303 return get_string('fullnamedisplay', null, $user);
3304 } else {
3305 // If the override is true, then change the template to use the complete name.
3306 $template = $CFG->alternativefullnameformat;
3310 $requirednames = array();
3311 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3312 foreach ($allnames as $allname) {
3313 if (strpos($template, $allname) !== false) {
3314 $requirednames[] = $allname;
3318 $displayname = $template;
3319 // Switch in the actual data into the template.
3320 foreach ($requirednames as $altname) {
3321 if (isset($user->$altname)) {
3322 // Using empty() on the below if statement causes breakages.
3323 if ((string)$user->$altname == '') {
3324 $displayname = str_replace($altname, 'EMPTY', $displayname);
3325 } else {
3326 $displayname = str_replace($altname, $user->$altname, $displayname);
3328 } else {
3329 $displayname = str_replace($altname, 'EMPTY', $displayname);
3332 // Tidy up any misc. characters (Not perfect, but gets most characters).
3333 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3334 // katakana and parenthesis.
3335 $patterns = array();
3336 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3337 // filled in by a user.
3338 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3339 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3340 // This regular expression is to remove any double spaces in the display name.
3341 $patterns[] = '/\s{2,}/u';
3342 foreach ($patterns as $pattern) {
3343 $displayname = preg_replace($pattern, ' ', $displayname);
3346 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3347 $displayname = trim($displayname);
3348 if (empty($displayname)) {
3349 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3350 // people in general feel is a good setting to fall back on.
3351 $displayname = $user->firstname;
3353 return $displayname;
3357 * A centralised location for the all name fields. Returns an array / sql string snippet.
3359 * @param bool $returnsql True for an sql select field snippet.
3360 * @param string $tableprefix table query prefix to use in front of each field.
3361 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3362 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3363 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3364 * @return array|string All name fields.
3366 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3367 // This array is provided in this order because when called by fullname() (above) if firstname is before
3368 // firstnamephonetic str_replace() will change the wrong placeholder.
3369 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3370 'lastnamephonetic' => 'lastnamephonetic',
3371 'middlename' => 'middlename',
3372 'alternatename' => 'alternatename',
3373 'firstname' => 'firstname',
3374 'lastname' => 'lastname');
3376 // Let's add a prefix to the array of user name fields if provided.
3377 if ($prefix) {
3378 foreach ($alternatenames as $key => $altname) {
3379 $alternatenames[$key] = $prefix . $altname;
3383 // If we want the end result to have firstname and lastname at the front / top of the result.
3384 if ($order) {
3385 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3386 for ($i = 0; $i < 2; $i++) {
3387 // Get the last element.
3388 $lastelement = end($alternatenames);
3389 // Remove it from the array.
3390 unset($alternatenames[$lastelement]);
3391 // Put the element back on the top of the array.
3392 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3396 // Create an sql field snippet if requested.
3397 if ($returnsql) {
3398 if ($tableprefix) {
3399 if ($fieldprefix) {
3400 foreach ($alternatenames as $key => $altname) {
3401 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3403 } else {
3404 foreach ($alternatenames as $key => $altname) {
3405 $alternatenames[$key] = $tableprefix . '.' . $altname;
3409 $alternatenames = implode(',', $alternatenames);
3411 return $alternatenames;
3415 * Reduces lines of duplicated code for getting user name fields.
3417 * See also {@link user_picture::unalias()}
3419 * @param object $addtoobject Object to add user name fields to.
3420 * @param object $secondobject Object that contains user name field information.
3421 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3422 * @param array $additionalfields Additional fields to be matched with data in the second object.
3423 * The key can be set to the user table field name.
3424 * @return object User name fields.
3426 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3427 $fields = get_all_user_name_fields(false, null, $prefix);
3428 if ($additionalfields) {
3429 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3430 // the key is a number and then sets the key to the array value.
3431 foreach ($additionalfields as $key => $value) {
3432 if (is_numeric($key)) {
3433 $additionalfields[$value] = $prefix . $value;
3434 unset($additionalfields[$key]);
3435 } else {
3436 $additionalfields[$key] = $prefix . $value;
3439 $fields = array_merge($fields, $additionalfields);
3441 foreach ($fields as $key => $field) {
3442 // Important that we have all of the user name fields present in the object that we are sending back.
3443 $addtoobject->$key = '';
3444 if (isset($secondobject->$field)) {
3445 $addtoobject->$key = $secondobject->$field;
3448 return $addtoobject;
3452 * Returns an array of values in order of occurance in a provided string.
3453 * The key in the result is the character postion in the string.
3455 * @param array $values Values to be found in the string format
3456 * @param string $stringformat The string which may contain values being searched for.
3457 * @return array An array of values in order according to placement in the string format.
3459 function order_in_string($values, $stringformat) {
3460 $valuearray = array();
3461 foreach ($values as $value) {
3462 $pattern = "/$value\b/";
3463 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3464 if (preg_match($pattern, $stringformat)) {
3465 $replacement = "thing";
3466 // Replace the value with something more unique to ensure we get the right position when using strpos().
3467 $newformat = preg_replace($pattern, $replacement, $stringformat);
3468 $position = strpos($newformat, $replacement);
3469 $valuearray[$position] = $value;
3472 ksort($valuearray);
3473 return $valuearray;
3477 * Checks if current user is shown any extra fields when listing users.
3479 * @param object $context Context
3480 * @param array $already Array of fields that we're going to show anyway
3481 * so don't bother listing them
3482 * @return array Array of field names from user table, not including anything
3483 * listed in $already
3485 function get_extra_user_fields($context, $already = array()) {
3486 global $CFG;
3488 // Only users with permission get the extra fields.
3489 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3490 return array();
3493 // Split showuseridentity on comma.
3494 if (empty($CFG->showuseridentity)) {
3495 // Explode gives wrong result with empty string.
3496 $extra = array();
3497 } else {
3498 $extra = explode(',', $CFG->showuseridentity);
3500 $renumber = false;
3501 foreach ($extra as $key => $field) {
3502 if (in_array($field, $already)) {
3503 unset($extra[$key]);
3504 $renumber = true;
3507 if ($renumber) {
3508 // For consistency, if entries are removed from array, renumber it
3509 // so they are numbered as you would expect.
3510 $extra = array_merge($extra);
3512 return $extra;
3516 * If the current user is to be shown extra user fields when listing or
3517 * selecting users, returns a string suitable for including in an SQL select
3518 * clause to retrieve those fields.
3520 * @param context $context Context
3521 * @param string $alias Alias of user table, e.g. 'u' (default none)
3522 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3523 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3524 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3526 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3527 $fields = get_extra_user_fields($context, $already);
3528 $result = '';
3529 // Add punctuation for alias.
3530 if ($alias !== '') {
3531 $alias .= '.';
3533 foreach ($fields as $field) {
3534 $result .= ', ' . $alias . $field;
3535 if ($prefix) {
3536 $result .= ' AS ' . $prefix . $field;
3539 return $result;
3543 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3544 * @param string $field Field name, e.g. 'phone1'
3545 * @return string Text description taken from language file, e.g. 'Phone number'
3547 function get_user_field_name($field) {
3548 // Some fields have language strings which are not the same as field name.
3549 switch ($field) {
3550 case 'url' : {
3551 return get_string('webpage');
3553 case 'icq' : {
3554 return get_string('icqnumber');
3556 case 'skype' : {
3557 return get_string('skypeid');
3559 case 'aim' : {
3560 return get_string('aimid');
3562 case 'yahoo' : {
3563 return get_string('yahooid');
3565 case 'msn' : {
3566 return get_string('msnid');
3569 // Otherwise just use the same lang string.
3570 return get_string($field);
3574 * Returns whether a given authentication plugin exists.
3576 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3577 * @return boolean Whether the plugin is available.
3579 function exists_auth_plugin($auth) {
3580 global $CFG;
3582 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3583 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3585 return false;
3589 * Checks if a given plugin is in the list of enabled authentication plugins.
3591 * @param string $auth Authentication plugin.
3592 * @return boolean Whether the plugin is enabled.
3594 function is_enabled_auth($auth) {
3595 if (empty($auth)) {
3596 return false;
3599 $enabled = get_enabled_auth_plugins();
3601 return in_array($auth, $enabled);
3605 * Returns an authentication plugin instance.
3607 * @param string $auth name of authentication plugin
3608 * @return auth_plugin_base An instance of the required authentication plugin.
3610 function get_auth_plugin($auth) {
3611 global $CFG;
3613 // Check the plugin exists first.
3614 if (! exists_auth_plugin($auth)) {
3615 print_error('authpluginnotfound', 'debug', '', $auth);
3618 // Return auth plugin instance.
3619 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3620 $class = "auth_plugin_$auth";
3621 return new $class;
3625 * Returns array of active auth plugins.
3627 * @param bool $fix fix $CFG->auth if needed
3628 * @return array
3630 function get_enabled_auth_plugins($fix=false) {
3631 global $CFG;
3633 $default = array('manual', 'nologin');
3635 if (empty($CFG->auth)) {
3636 $auths = array();
3637 } else {
3638 $auths = explode(',', $CFG->auth);
3641 if ($fix) {
3642 $auths = array_unique($auths);
3643 foreach ($auths as $k => $authname) {
3644 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3645 unset($auths[$k]);
3648 $newconfig = implode(',', $auths);
3649 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3650 set_config('auth', $newconfig);
3654 return (array_merge($default, $auths));
3658 * Returns true if an internal authentication method is being used.
3659 * if method not specified then, global default is assumed
3661 * @param string $auth Form of authentication required
3662 * @return bool
3664 function is_internal_auth($auth) {
3665 // Throws error if bad $auth.
3666 $authplugin = get_auth_plugin($auth);
3667 return $authplugin->is_internal();
3671 * Returns true if the user is a 'restored' one.
3673 * Used in the login process to inform the user and allow him/her to reset the password
3675 * @param string $username username to be checked
3676 * @return bool
3678 function is_restored_user($username) {
3679 global $CFG, $DB;
3681 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3685 * Returns an array of user fields
3687 * @return array User field/column names
3689 function get_user_fieldnames() {
3690 global $DB;
3692 $fieldarray = $DB->get_columns('user');
3693 unset($fieldarray['id']);
3694 $fieldarray = array_keys($fieldarray);
3696 return $fieldarray;
3700 * Creates a bare-bones user record
3702 * @todo Outline auth types and provide code example
3704 * @param string $username New user's username to add to record
3705 * @param string $password New user's password to add to record
3706 * @param string $auth Form of authentication required
3707 * @return stdClass A complete user object
3709 function create_user_record($username, $password, $auth = 'manual') {
3710 global $CFG, $DB;
3711 require_once($CFG->dirroot.'/user/profile/lib.php');
3712 require_once($CFG->dirroot.'/user/lib.php');
3714 // Just in case check text case.
3715 $username = trim(core_text::strtolower($username));
3717 $authplugin = get_auth_plugin($auth);
3718 $customfields = $authplugin->get_custom_user_profile_fields();
3719 $newuser = new stdClass();
3720 if ($newinfo = $authplugin->get_userinfo($username)) {
3721 $newinfo = truncate_userinfo($newinfo);
3722 foreach ($newinfo as $key => $value) {
3723 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3724 $newuser->$key = $value;
3729 if (!empty($newuser->email)) {
3730 if (email_is_not_allowed($newuser->email)) {
3731 unset($newuser->email);
3735 if (!isset($newuser->city)) {
3736 $newuser->city = '';
3739 $newuser->auth = $auth;
3740 $newuser->username = $username;
3742 // Fix for MDL-8480
3743 // user CFG lang for user if $newuser->lang is empty
3744 // or $user->lang is not an installed language.
3745 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3746 $newuser->lang = $CFG->lang;
3748 $newuser->confirmed = 1;
3749 $newuser->lastip = getremoteaddr();
3750 $newuser->timecreated = time();
3751 $newuser->timemodified = $newuser->timecreated;
3752 $newuser->mnethostid = $CFG->mnet_localhost_id;
3754 $newuser->id = user_create_user($newuser, false, false);
3756 // Save user profile data.
3757 profile_save_data($newuser);
3759 $user = get_complete_user_data('id', $newuser->id);
3760 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3761 set_user_preference('auth_forcepasswordchange', 1, $user);
3763 // Set the password.
3764 update_internal_user_password($user, $password);
3766 // Trigger event.
3767 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3769 return $user;
3773 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3775 * @param string $username user's username to update the record
3776 * @return stdClass A complete user object
3778 function update_user_record($username) {
3779 global $DB, $CFG;
3780 // Just in case check text case.
3781 $username = trim(core_text::strtolower($username));
3783 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3784 return update_user_record_by_id($oldinfo->id);
3788 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3790 * @param int $id user id
3791 * @return stdClass A complete user object
3793 function update_user_record_by_id($id) {
3794 global $DB, $CFG;
3795 require_once($CFG->dirroot."/user/profile/lib.php");
3796 require_once($CFG->dirroot.'/user/lib.php');
3798 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3799 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3801 $newuser = array();
3802 $userauth = get_auth_plugin($oldinfo->auth);
3804 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3805 $newinfo = truncate_userinfo($newinfo);
3806 $customfields = $userauth->get_custom_user_profile_fields();
3808 foreach ($newinfo as $key => $value) {
3809 $iscustom = in_array($key, $customfields);
3810 if (!$iscustom) {
3811 $key = strtolower($key);
3813 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3814 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3815 // Unknown or must not be changed.
3816 continue;
3818 $confval = $userauth->config->{'field_updatelocal_' . $key};
3819 $lockval = $userauth->config->{'field_lock_' . $key};
3820 if (empty($confval) || empty($lockval)) {
3821 continue;
3823 if ($confval === 'onlogin') {
3824 // MDL-4207 Don't overwrite modified user profile values with
3825 // empty LDAP values when 'unlocked if empty' is set. The purpose
3826 // of the setting 'unlocked if empty' is to allow the user to fill
3827 // in a value for the selected field _if LDAP is giving
3828 // nothing_ for this field. Thus it makes sense to let this value
3829 // stand in until LDAP is giving a value for this field.
3830 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3831 if ($iscustom || (in_array($key, $userauth->userfields) &&
3832 ((string)$oldinfo->$key !== (string)$value))) {
3833 $newuser[$key] = (string)$value;
3838 if ($newuser) {
3839 $newuser['id'] = $oldinfo->id;
3840 $newuser['timemodified'] = time();
3841 user_update_user((object) $newuser, false, false);
3843 // Save user profile data.
3844 profile_save_data((object) $newuser);
3846 // Trigger event.
3847 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
3851 return get_complete_user_data('id', $oldinfo->id);
3855 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
3857 * @param array $info Array of user properties to truncate if needed
3858 * @return array The now truncated information that was passed in
3860 function truncate_userinfo(array $info) {
3861 // Define the limits.
3862 $limit = array(
3863 'username' => 100,
3864 'idnumber' => 255,
3865 'firstname' => 100,
3866 'lastname' => 100,
3867 'email' => 100,
3868 'icq' => 15,
3869 'phone1' => 20,
3870 'phone2' => 20,
3871 'institution' => 255,
3872 'department' => 255,
3873 'address' => 255,
3874 'city' => 120,
3875 'country' => 2,
3876 'url' => 255,
3879 // Apply where needed.
3880 foreach (array_keys($info) as $key) {
3881 if (!empty($limit[$key])) {
3882 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
3886 return $info;
3890 * Marks user deleted in internal user database and notifies the auth plugin.
3891 * Also unenrols user from all roles and does other cleanup.
3893 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3895 * @param stdClass $user full user object before delete
3896 * @return boolean success
3897 * @throws coding_exception if invalid $user parameter detected
3899 function delete_user(stdClass $user) {
3900 global $CFG, $DB;
3901 require_once($CFG->libdir.'/grouplib.php');
3902 require_once($CFG->libdir.'/gradelib.php');
3903 require_once($CFG->dirroot.'/message/lib.php');
3904 require_once($CFG->dirroot.'/user/lib.php');
3906 // Make sure nobody sends bogus record type as parameter.
3907 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
3908 throw new coding_exception('Invalid $user parameter in delete_user() detected');
3911 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
3912 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
3913 debugging('Attempt to delete unknown user account.');
3914 return false;
3917 // There must be always exactly one guest record, originally the guest account was identified by username only,
3918 // now we use $CFG->siteguest for performance reasons.
3919 if ($user->username === 'guest' or isguestuser($user)) {
3920 debugging('Guest user account can not be deleted.');
3921 return false;
3924 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
3925 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
3926 if ($user->auth === 'manual' and is_siteadmin($user)) {
3927 debugging('Local administrator accounts can not be deleted.');
3928 return false;
3931 // Keep user record before updating it, as we have to pass this to user_deleted event.
3932 $olduser = clone $user;
3934 // Keep a copy of user context, we need it for event.
3935 $usercontext = context_user::instance($user->id);
3937 // Delete all grades - backup is kept in grade_grades_history table.
3938 grade_user_delete($user->id);
3940 // Move unread messages from this user to read.
3941 message_move_userfrom_unread2read($user->id);
3943 // TODO: remove from cohorts using standard API here.
3945 // Remove user tags.
3946 core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
3948 // Unconditionally unenrol from all courses.
3949 enrol_user_delete($user);
3951 // Unenrol from all roles in all contexts.
3952 // This might be slow but it is really needed - modules might do some extra cleanup!
3953 role_unassign_all(array('userid' => $user->id));
3955 // Now do a brute force cleanup.
3957 // Remove from all cohorts.
3958 $DB->delete_records('cohort_members', array('userid' => $user->id));
3960 // Remove from all groups.
3961 $DB->delete_records('groups_members', array('userid' => $user->id));
3963 // Brute force unenrol from all courses.
3964 $DB->delete_records('user_enrolments', array('userid' => $user->id));
3966 // Purge user preferences.
3967 $DB->delete_records('user_preferences', array('userid' => $user->id));
3969 // Purge user extra profile info.
3970 $DB->delete_records('user_info_data', array('userid' => $user->id));
3972 // Purge log of previous password hashes.
3973 $DB->delete_records('user_password_history', array('userid' => $user->id));
3975 // Last course access not necessary either.
3976 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
3977 // Remove all user tokens.
3978 $DB->delete_records('external_tokens', array('userid' => $user->id));
3980 // Unauthorise the user for all services.
3981 $DB->delete_records('external_services_users', array('userid' => $user->id));
3983 // Remove users private keys.
3984 $DB->delete_records('user_private_key', array('userid' => $user->id));
3986 // Remove users customised pages.
3987 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
3989 // Force logout - may fail if file based sessions used, sorry.
3990 \core\session\manager::kill_user_sessions($user->id);
3992 // Generate username from email address, or a fake email.
3993 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
3994 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
3996 // Workaround for bulk deletes of users with the same email address.
3997 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
3998 $delname++;
4001 // Mark internal user record as "deleted".
4002 $updateuser = new stdClass();
4003 $updateuser->id = $user->id;
4004 $updateuser->deleted = 1;
4005 $updateuser->username = $delname; // Remember it just in case.
4006 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4007 $updateuser->idnumber = ''; // Clear this field to free it up.
4008 $updateuser->picture = 0;
4009 $updateuser->timemodified = time();
4011 // Don't trigger update event, as user is being deleted.
4012 user_update_user($updateuser, false, false);
4014 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4015 context_helper::delete_instance(CONTEXT_USER, $user->id);
4017 // Any plugin that needs to cleanup should register this event.
4018 // Trigger event.
4019 $event = \core\event\user_deleted::create(
4020 array(
4021 'objectid' => $user->id,
4022 'relateduserid' => $user->id,
4023 'context' => $usercontext,
4024 'other' => array(
4025 'username' => $user->username,
4026 'email' => $user->email,
4027 'idnumber' => $user->idnumber,
4028 'picture' => $user->picture,
4029 'mnethostid' => $user->mnethostid
4033 $event->add_record_snapshot('user', $olduser);
4034 $event->trigger();
4036 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4037 // should know about this updated property persisted to the user's table.
4038 $user->timemodified = $updateuser->timemodified;
4040 // Notify auth plugin - do not block the delete even when plugin fails.
4041 $authplugin = get_auth_plugin($user->auth);
4042 $authplugin->user_delete($user);
4044 return true;
4048 * Retrieve the guest user object.
4050 * @return stdClass A {@link $USER} object
4052 function guest_user() {
4053 global $CFG, $DB;
4055 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4056 $newuser->confirmed = 1;
4057 $newuser->lang = $CFG->lang;
4058 $newuser->lastip = getremoteaddr();
4061 return $newuser;
4065 * Authenticates a user against the chosen authentication mechanism
4067 * Given a username and password, this function looks them
4068 * up using the currently selected authentication mechanism,
4069 * and if the authentication is successful, it returns a
4070 * valid $user object from the 'user' table.
4072 * Uses auth_ functions from the currently active auth module
4074 * After authenticate_user_login() returns success, you will need to
4075 * log that the user has logged in, and call complete_user_login() to set
4076 * the session up.
4078 * Note: this function works only with non-mnet accounts!
4080 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4081 * @param string $password User's password
4082 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4083 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4084 * @return stdClass|false A {@link $USER} object or false if error
4086 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4087 global $CFG, $DB;
4088 require_once("$CFG->libdir/authlib.php");
4090 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4091 // we have found the user
4093 } else if (!empty($CFG->authloginviaemail)) {
4094 if ($email = clean_param($username, PARAM_EMAIL)) {
4095 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4096 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4097 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4098 if (count($users) === 1) {
4099 // Use email for login only if unique.
4100 $user = reset($users);
4101 $user = get_complete_user_data('id', $user->id);
4102 $username = $user->username;
4104 unset($users);
4108 $authsenabled = get_enabled_auth_plugins();
4110 if ($user) {
4111 // Use manual if auth not set.
4112 $auth = empty($user->auth) ? 'manual' : $user->auth;
4113 if (!empty($user->suspended)) {
4114 $failurereason = AUTH_LOGIN_SUSPENDED;
4116 // Trigger login failed event.
4117 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4118 'other' => array('username' => $username, 'reason' => $failurereason)));
4119 $event->trigger();
4120 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4121 return false;
4123 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4124 // Legacy way to suspend user.
4125 $failurereason = AUTH_LOGIN_SUSPENDED;
4127 // Trigger login failed event.
4128 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4129 'other' => array('username' => $username, 'reason' => $failurereason)));
4130 $event->trigger();
4131 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4132 return false;
4134 $auths = array($auth);
4136 } else {
4137 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4138 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4139 $failurereason = AUTH_LOGIN_NOUSER;
4141 // Trigger login failed event.
4142 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4143 'reason' => $failurereason)));
4144 $event->trigger();
4145 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4146 return false;
4149 // User does not exist.
4150 $auths = $authsenabled;
4151 $user = new stdClass();
4152 $user->id = 0;
4155 if ($ignorelockout) {
4156 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4157 // or this function is called from a SSO script.
4158 } else if ($user->id) {
4159 // Verify login lockout after other ways that may prevent user login.
4160 if (login_is_lockedout($user)) {
4161 $failurereason = AUTH_LOGIN_LOCKOUT;
4163 // Trigger login failed event.
4164 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4165 'other' => array('username' => $username, 'reason' => $failurereason)));
4166 $event->trigger();
4168 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4169 return false;
4171 } else {
4172 // We can not lockout non-existing accounts.
4175 foreach ($auths as $auth) {
4176 $authplugin = get_auth_plugin($auth);
4178 // On auth fail fall through to the next plugin.
4179 if (!$authplugin->user_login($username, $password)) {
4180 continue;
4183 // Successful authentication.
4184 if ($user->id) {
4185 // User already exists in database.
4186 if (empty($user->auth)) {
4187 // For some reason auth isn't set yet.
4188 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4189 $user->auth = $auth;
4192 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4193 // the current hash algorithm while we have access to the user's password.
4194 update_internal_user_password($user, $password);
4196 if ($authplugin->is_synchronised_with_external()) {
4197 // Update user record from external DB.
4198 $user = update_user_record_by_id($user->id);
4200 } else {
4201 // The user is authenticated but user creation may be disabled.
4202 if (!empty($CFG->authpreventaccountcreation)) {
4203 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4205 // Trigger login failed event.
4206 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4207 'reason' => $failurereason)));
4208 $event->trigger();
4210 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4211 $_SERVER['HTTP_USER_AGENT']);
4212 return false;
4213 } else {
4214 $user = create_user_record($username, $password, $auth);
4218 $authplugin->sync_roles($user);
4220 foreach ($authsenabled as $hau) {
4221 $hauth = get_auth_plugin($hau);
4222 $hauth->user_authenticated_hook($user, $username, $password);
4225 if (empty($user->id)) {
4226 $failurereason = AUTH_LOGIN_NOUSER;
4227 // Trigger login failed event.
4228 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4229 'reason' => $failurereason)));
4230 $event->trigger();
4231 return false;
4234 if (!empty($user->suspended)) {
4235 // Just in case some auth plugin suspended account.
4236 $failurereason = AUTH_LOGIN_SUSPENDED;
4237 // Trigger login failed event.
4238 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4239 'other' => array('username' => $username, 'reason' => $failurereason)));
4240 $event->trigger();
4241 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4242 return false;
4245 login_attempt_valid($user);
4246 $failurereason = AUTH_LOGIN_OK;
4247 return $user;
4250 // Failed if all the plugins have failed.
4251 if (debugging('', DEBUG_ALL)) {
4252 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4255 if ($user->id) {
4256 login_attempt_failed($user);
4257 $failurereason = AUTH_LOGIN_FAILED;
4258 // Trigger login failed event.
4259 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4260 'other' => array('username' => $username, 'reason' => $failurereason)));
4261 $event->trigger();
4262 } else {
4263 $failurereason = AUTH_LOGIN_NOUSER;
4264 // Trigger login failed event.
4265 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4266 'reason' => $failurereason)));
4267 $event->trigger();
4270 return false;
4274 * Call to complete the user login process after authenticate_user_login()
4275 * has succeeded. It will setup the $USER variable and other required bits
4276 * and pieces.
4278 * NOTE:
4279 * - It will NOT log anything -- up to the caller to decide what to log.
4280 * - this function does not set any cookies any more!
4282 * @param stdClass $user
4283 * @return stdClass A {@link $USER} object - BC only, do not use
4285 function complete_user_login($user) {
4286 global $CFG, $USER;
4288 \core\session\manager::login_user($user);
4290 // Reload preferences from DB.
4291 unset($USER->preference);
4292 check_user_preferences_loaded($USER);
4294 // Update login times.
4295 update_user_login_times();
4297 // Extra session prefs init.
4298 set_login_session_preferences();
4300 // Trigger login event.
4301 $event = \core\event\user_loggedin::create(
4302 array(
4303 'userid' => $USER->id,
4304 'objectid' => $USER->id,
4305 'other' => array('username' => $USER->username),
4308 $event->trigger();
4310 if (isguestuser()) {
4311 // No need to continue when user is THE guest.
4312 return $USER;
4315 if (CLI_SCRIPT) {
4316 // We can redirect to password change URL only in browser.
4317 return $USER;
4320 // Select password change url.
4321 $userauth = get_auth_plugin($USER->auth);
4323 // Check whether the user should be changing password.
4324 if (get_user_preferences('auth_forcepasswordchange', false)) {
4325 if ($userauth->can_change_password()) {
4326 if ($changeurl = $userauth->change_password_url()) {
4327 redirect($changeurl);
4328 } else {
4329 redirect($CFG->httpswwwroot.'/login/change_password.php');
4331 } else {
4332 print_error('nopasswordchangeforced', 'auth');
4335 return $USER;
4339 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4341 * @param string $password String to check.
4342 * @return boolean True if the $password matches the format of an md5 sum.
4344 function password_is_legacy_hash($password) {
4345 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4349 * Compare password against hash stored in user object to determine if it is valid.
4351 * If necessary it also updates the stored hash to the current format.
4353 * @param stdClass $user (Password property may be updated).
4354 * @param string $password Plain text password.
4355 * @return bool True if password is valid.
4357 function validate_internal_user_password($user, $password) {
4358 global $CFG;
4359 require_once($CFG->libdir.'/password_compat/lib/password.php');
4361 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4362 // Internal password is not used at all, it can not validate.
4363 return false;
4366 // If hash isn't a legacy (md5) hash, validate using the library function.
4367 if (!password_is_legacy_hash($user->password)) {
4368 return password_verify($password, $user->password);
4371 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4372 // is valid we can then update it to the new algorithm.
4374 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4375 $validated = false;
4377 if ($user->password === md5($password.$sitesalt)
4378 or $user->password === md5($password)
4379 or $user->password === md5(addslashes($password).$sitesalt)
4380 or $user->password === md5(addslashes($password))) {
4381 // Note: we are intentionally using the addslashes() here because we
4382 // need to accept old password hashes of passwords with magic quotes.
4383 $validated = true;
4385 } else {
4386 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4387 $alt = 'passwordsaltalt'.$i;
4388 if (!empty($CFG->$alt)) {
4389 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4390 $validated = true;
4391 break;
4397 if ($validated) {
4398 // If the password matches the existing md5 hash, update to the
4399 // current hash algorithm while we have access to the user's password.
4400 update_internal_user_password($user, $password);
4403 return $validated;
4407 * Calculate hash for a plain text password.
4409 * @param string $password Plain text password to be hashed.
4410 * @param bool $fasthash If true, use a low cost factor when generating the hash
4411 * This is much faster to generate but makes the hash
4412 * less secure. It is used when lots of hashes need to
4413 * be generated quickly.
4414 * @return string The hashed password.
4416 * @throws moodle_exception If a problem occurs while generating the hash.
4418 function hash_internal_user_password($password, $fasthash = false) {
4419 global $CFG;
4420 require_once($CFG->libdir.'/password_compat/lib/password.php');
4422 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4423 $options = ($fasthash) ? array('cost' => 4) : array();
4425 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4427 if ($generatedhash === false || $generatedhash === null) {
4428 throw new moodle_exception('Failed to generate password hash.');
4431 return $generatedhash;
4435 * Update password hash in user object (if necessary).
4437 * The password is updated if:
4438 * 1. The password has changed (the hash of $user->password is different
4439 * to the hash of $password).
4440 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4441 * md5 algorithm).
4443 * Updating the password will modify the $user object and the database
4444 * record to use the current hashing algorithm.
4446 * @param stdClass $user User object (password property may be updated).
4447 * @param string $password Plain text password.
4448 * @param bool $fasthash If true, use a low cost factor when generating the hash
4449 * This is much faster to generate but makes the hash
4450 * less secure. It is used when lots of hashes need to
4451 * be generated quickly.
4452 * @return bool Always returns true.
4454 function update_internal_user_password($user, $password, $fasthash = false) {
4455 global $CFG, $DB;
4456 require_once($CFG->libdir.'/password_compat/lib/password.php');
4458 // Figure out what the hashed password should be.
4459 if (!isset($user->auth)) {
4460 debugging('User record in update_internal_user_password() must include field auth',
4461 DEBUG_DEVELOPER);
4462 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4464 $authplugin = get_auth_plugin($user->auth);
4465 if ($authplugin->prevent_local_passwords()) {
4466 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4467 } else {
4468 $hashedpassword = hash_internal_user_password($password, $fasthash);
4471 $algorithmchanged = false;
4473 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4474 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4475 $passwordchanged = ($user->password !== $hashedpassword);
4477 } else if (isset($user->password)) {
4478 // If verification fails then it means the password has changed.
4479 $passwordchanged = !password_verify($password, $user->password);
4480 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4481 } else {
4482 // While creating new user, password in unset in $user object, to avoid
4483 // saving it with user_create()
4484 $passwordchanged = true;
4487 if ($passwordchanged || $algorithmchanged) {
4488 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4489 $user->password = $hashedpassword;
4491 // Trigger event.
4492 $user = $DB->get_record('user', array('id' => $user->id));
4493 \core\event\user_password_updated::create_from_user($user)->trigger();
4496 return true;
4500 * Get a complete user record, which includes all the info in the user record.
4502 * Intended for setting as $USER session variable
4504 * @param string $field The user field to be checked for a given value.
4505 * @param string $value The value to match for $field.
4506 * @param int $mnethostid
4507 * @return mixed False, or A {@link $USER} object.
4509 function get_complete_user_data($field, $value, $mnethostid = null) {
4510 global $CFG, $DB;
4512 if (!$field || !$value) {
4513 return false;
4516 // Build the WHERE clause for an SQL query.
4517 $params = array('fieldval' => $value);
4518 $constraints = "$field = :fieldval AND deleted <> 1";
4520 // If we are loading user data based on anything other than id,
4521 // we must also restrict our search based on mnet host.
4522 if ($field != 'id') {
4523 if (empty($mnethostid)) {
4524 // If empty, we restrict to local users.
4525 $mnethostid = $CFG->mnet_localhost_id;
4528 if (!empty($mnethostid)) {
4529 $params['mnethostid'] = $mnethostid;
4530 $constraints .= " AND mnethostid = :mnethostid";
4533 // Get all the basic user data.
4534 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4535 return false;
4538 // Get various settings and preferences.
4540 // Preload preference cache.
4541 check_user_preferences_loaded($user);
4543 // Load course enrolment related stuff.
4544 $user->lastcourseaccess = array(); // During last session.
4545 $user->currentcourseaccess = array(); // During current session.
4546 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4547 foreach ($lastaccesses as $lastaccess) {
4548 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4552 $sql = "SELECT g.id, g.courseid
4553 FROM {groups} g, {groups_members} gm
4554 WHERE gm.groupid=g.id AND gm.userid=?";
4556 // This is a special hack to speedup calendar display.
4557 $user->groupmember = array();
4558 if (!isguestuser($user)) {
4559 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4560 foreach ($groups as $group) {
4561 if (!array_key_exists($group->courseid, $user->groupmember)) {
4562 $user->groupmember[$group->courseid] = array();
4564 $user->groupmember[$group->courseid][$group->id] = $group->id;
4569 // Add the custom profile fields to the user record.
4570 $user->profile = array();
4571 if (!isguestuser($user)) {
4572 require_once($CFG->dirroot.'/user/profile/lib.php');
4573 profile_load_custom_fields($user);
4576 // Rewrite some variables if necessary.
4577 if (!empty($user->description)) {
4578 // No need to cart all of it around.
4579 $user->description = true;
4581 if (isguestuser($user)) {
4582 // Guest language always same as site.
4583 $user->lang = $CFG->lang;
4584 // Name always in current language.
4585 $user->firstname = get_string('guestuser');
4586 $user->lastname = ' ';
4589 return $user;
4593 * Validate a password against the configured password policy
4595 * @param string $password the password to be checked against the password policy
4596 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4597 * @return bool true if the password is valid according to the policy. false otherwise.
4599 function check_password_policy($password, &$errmsg) {
4600 global $CFG;
4602 if (empty($CFG->passwordpolicy)) {
4603 return true;
4606 $errmsg = '';
4607 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4608 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4611 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4612 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4615 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4616 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4619 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4620 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4623 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4624 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4626 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4627 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4630 if ($errmsg == '') {
4631 return true;
4632 } else {
4633 return false;
4639 * When logging in, this function is run to set certain preferences for the current SESSION.
4641 function set_login_session_preferences() {
4642 global $SESSION;
4644 $SESSION->justloggedin = true;
4646 unset($SESSION->lang);
4647 unset($SESSION->forcelang);
4648 unset($SESSION->load_navigation_admin);
4653 * Delete a course, including all related data from the database, and any associated files.
4655 * @param mixed $courseorid The id of the course or course object to delete.
4656 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4657 * @return bool true if all the removals succeeded. false if there were any failures. If this
4658 * method returns false, some of the removals will probably have succeeded, and others
4659 * failed, but you have no way of knowing which.
4661 function delete_course($courseorid, $showfeedback = true) {
4662 global $DB;
4664 if (is_object($courseorid)) {
4665 $courseid = $courseorid->id;
4666 $course = $courseorid;
4667 } else {
4668 $courseid = $courseorid;
4669 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4670 return false;
4673 $context = context_course::instance($courseid);
4675 // Frontpage course can not be deleted!!
4676 if ($courseid == SITEID) {
4677 return false;
4680 // Make the course completely empty.
4681 remove_course_contents($courseid, $showfeedback);
4683 // Delete the course and related context instance.
4684 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4686 $DB->delete_records("course", array("id" => $courseid));
4687 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4689 // Reset all course related caches here.
4690 if (class_exists('format_base', false)) {
4691 format_base::reset_course_cache($courseid);
4694 // Trigger a course deleted event.
4695 $event = \core\event\course_deleted::create(array(
4696 'objectid' => $course->id,
4697 'context' => $context,
4698 'other' => array(
4699 'shortname' => $course->shortname,
4700 'fullname' => $course->fullname,
4701 'idnumber' => $course->idnumber
4704 $event->add_record_snapshot('course', $course);
4705 $event->trigger();
4707 return true;
4711 * Clear a course out completely, deleting all content but don't delete the course itself.
4713 * This function does not verify any permissions.
4715 * Please note this function also deletes all user enrolments,
4716 * enrolment instances and role assignments by default.
4718 * $options:
4719 * - 'keep_roles_and_enrolments' - false by default
4720 * - 'keep_groups_and_groupings' - false by default
4722 * @param int $courseid The id of the course that is being deleted
4723 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4724 * @param array $options extra options
4725 * @return bool true if all the removals succeeded. false if there were any failures. If this
4726 * method returns false, some of the removals will probably have succeeded, and others
4727 * failed, but you have no way of knowing which.
4729 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4730 global $CFG, $DB, $OUTPUT;
4732 require_once($CFG->libdir.'/badgeslib.php');
4733 require_once($CFG->libdir.'/completionlib.php');
4734 require_once($CFG->libdir.'/questionlib.php');
4735 require_once($CFG->libdir.'/gradelib.php');
4736 require_once($CFG->dirroot.'/group/lib.php');
4737 require_once($CFG->dirroot.'/comment/lib.php');
4738 require_once($CFG->dirroot.'/rating/lib.php');
4739 require_once($CFG->dirroot.'/notes/lib.php');
4741 // Handle course badges.
4742 badges_handle_course_deletion($courseid);
4744 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4745 $strdeleted = get_string('deleted').' - ';
4747 // Some crazy wishlist of stuff we should skip during purging of course content.
4748 $options = (array)$options;
4750 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4751 $coursecontext = context_course::instance($courseid);
4752 $fs = get_file_storage();
4754 // Delete course completion information, this has to be done before grades and enrols.
4755 $cc = new completion_info($course);
4756 $cc->clear_criteria();
4757 if ($showfeedback) {
4758 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4761 // Remove all data from gradebook - this needs to be done before course modules
4762 // because while deleting this information, the system may need to reference
4763 // the course modules that own the grades.
4764 remove_course_grades($courseid, $showfeedback);
4765 remove_grade_letters($coursecontext, $showfeedback);
4767 // Delete course blocks in any all child contexts,
4768 // they may depend on modules so delete them first.
4769 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4770 foreach ($childcontexts as $childcontext) {
4771 blocks_delete_all_for_context($childcontext->id);
4773 unset($childcontexts);
4774 blocks_delete_all_for_context($coursecontext->id);
4775 if ($showfeedback) {
4776 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4779 // Delete every instance of every module,
4780 // this has to be done before deleting of course level stuff.
4781 $locations = core_component::get_plugin_list('mod');
4782 foreach ($locations as $modname => $moddir) {
4783 if ($modname === 'NEWMODULE') {
4784 continue;
4786 if ($module = $DB->get_record('modules', array('name' => $modname))) {
4787 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
4788 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
4789 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
4791 if ($instances = $DB->get_records($modname, array('course' => $course->id))) {
4792 foreach ($instances as $instance) {
4793 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
4794 // Delete activity context questions and question categories.
4795 question_delete_activity($cm, $showfeedback);
4797 if (function_exists($moddelete)) {
4798 // This purges all module data in related tables, extra user prefs, settings, etc.
4799 $moddelete($instance->id);
4800 } else {
4801 // NOTE: we should not allow installation of modules with missing delete support!
4802 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4803 $DB->delete_records($modname, array('id' => $instance->id));
4806 if ($cm) {
4807 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
4808 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4809 $DB->delete_records('course_modules', array('id' => $cm->id));
4813 if (function_exists($moddeletecourse)) {
4814 // Execute ptional course cleanup callback.
4815 $moddeletecourse($course, $showfeedback);
4817 if ($instances and $showfeedback) {
4818 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4820 } else {
4821 // Ooops, this module is not properly installed, force-delete it in the next block.
4825 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
4827 // Remove all data from availability and completion tables that is associated
4828 // with course-modules belonging to this course. Note this is done even if the
4829 // features are not enabled now, in case they were enabled previously.
4830 $DB->delete_records_select('course_modules_completion',
4831 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4832 array($courseid));
4834 // Remove course-module data.
4835 $cms = $DB->get_records('course_modules', array('course' => $course->id));
4836 foreach ($cms as $cm) {
4837 if ($module = $DB->get_record('modules', array('id' => $cm->module))) {
4838 try {
4839 $DB->delete_records($module->name, array('id' => $cm->instance));
4840 } catch (Exception $e) {
4841 // Ignore weird or missing table problems.
4844 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4845 $DB->delete_records('course_modules', array('id' => $cm->id));
4848 if ($showfeedback) {
4849 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
4852 // Cleanup the rest of plugins.
4853 $cleanuplugintypes = array('report', 'coursereport', 'format');
4854 $callbacks = get_plugins_with_function('delete_course', 'lib.php');
4855 foreach ($cleanuplugintypes as $type) {
4856 if (!empty($callbacks[$type])) {
4857 foreach ($callbacks[$type] as $pluginfunction) {
4858 $pluginfunction($course->id, $showfeedback);
4861 if ($showfeedback) {
4862 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
4866 // Delete questions and question categories.
4867 question_delete_course($course, $showfeedback);
4868 if ($showfeedback) {
4869 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
4872 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
4873 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4874 foreach ($childcontexts as $childcontext) {
4875 $childcontext->delete();
4877 unset($childcontexts);
4879 // Remove all roles and enrolments by default.
4880 if (empty($options['keep_roles_and_enrolments'])) {
4881 // This hack is used in restore when deleting contents of existing course.
4882 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
4883 enrol_course_delete($course);
4884 if ($showfeedback) {
4885 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
4889 // Delete any groups, removing members and grouping/course links first.
4890 if (empty($options['keep_groups_and_groupings'])) {
4891 groups_delete_groupings($course->id, $showfeedback);
4892 groups_delete_groups($course->id, $showfeedback);
4895 // Filters be gone!
4896 filter_delete_all_for_context($coursecontext->id);
4898 // Notes, you shall not pass!
4899 note_delete_all($course->id);
4901 // Die comments!
4902 comment::delete_comments($coursecontext->id);
4904 // Ratings are history too.
4905 $delopt = new stdclass();
4906 $delopt->contextid = $coursecontext->id;
4907 $rm = new rating_manager();
4908 $rm->delete_ratings($delopt);
4910 // Delete course tags.
4911 core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
4913 // Delete calendar events.
4914 $DB->delete_records('event', array('courseid' => $course->id));
4915 $fs->delete_area_files($coursecontext->id, 'calendar');
4917 // Delete all related records in other core tables that may have a courseid
4918 // This array stores the tables that need to be cleared, as
4919 // table_name => column_name that contains the course id.
4920 $tablestoclear = array(
4921 'backup_courses' => 'courseid', // Scheduled backup stuff.
4922 'user_lastaccess' => 'courseid', // User access info.
4924 foreach ($tablestoclear as $table => $col) {
4925 $DB->delete_records($table, array($col => $course->id));
4928 // Delete all course backup files.
4929 $fs->delete_area_files($coursecontext->id, 'backup');
4931 // Cleanup course record - remove links to deleted stuff.
4932 $oldcourse = new stdClass();
4933 $oldcourse->id = $course->id;
4934 $oldcourse->summary = '';
4935 $oldcourse->cacherev = 0;
4936 $oldcourse->legacyfiles = 0;
4937 if (!empty($options['keep_groups_and_groupings'])) {
4938 $oldcourse->defaultgroupingid = 0;
4940 $DB->update_record('course', $oldcourse);
4942 // Delete course sections.
4943 $DB->delete_records('course_sections', array('course' => $course->id));
4945 // Delete legacy, section and any other course files.
4946 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
4948 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
4949 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
4950 // Easy, do not delete the context itself...
4951 $coursecontext->delete_content();
4952 } else {
4953 // Hack alert!!!!
4954 // We can not drop all context stuff because it would bork enrolments and roles,
4955 // there might be also files used by enrol plugins...
4958 // Delete legacy files - just in case some files are still left there after conversion to new file api,
4959 // also some non-standard unsupported plugins may try to store something there.
4960 fulldelete($CFG->dataroot.'/'.$course->id);
4962 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
4963 $cachemodinfo = cache::make('core', 'coursemodinfo');
4964 $cachemodinfo->delete($courseid);
4966 // Trigger a course content deleted event.
4967 $event = \core\event\course_content_deleted::create(array(
4968 'objectid' => $course->id,
4969 'context' => $coursecontext,
4970 'other' => array('shortname' => $course->shortname,
4971 'fullname' => $course->fullname,
4972 'options' => $options) // Passing this for legacy reasons.
4974 $event->add_record_snapshot('course', $course);
4975 $event->trigger();
4977 return true;
4981 * Change dates in module - used from course reset.
4983 * @param string $modname forum, assignment, etc
4984 * @param array $fields array of date fields from mod table
4985 * @param int $timeshift time difference
4986 * @param int $courseid
4987 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
4988 * @return bool success
4990 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
4991 global $CFG, $DB;
4992 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
4994 $return = true;
4995 $params = array($timeshift, $courseid);
4996 foreach ($fields as $field) {
4997 $updatesql = "UPDATE {".$modname."}
4998 SET $field = $field + ?
4999 WHERE course=? AND $field<>0";
5000 if ($modid) {
5001 $updatesql .= ' AND id=?';
5002 $params[] = $modid;
5004 $return = $DB->execute($updatesql, $params) && $return;
5007 $refreshfunction = $modname.'_refresh_events';
5008 if (function_exists($refreshfunction)) {
5009 $refreshfunction($courseid);
5012 return $return;
5016 * This function will empty a course of user data.
5017 * It will retain the activities and the structure of the course.
5019 * @param object $data an object containing all the settings including courseid (without magic quotes)
5020 * @return array status array of array component, item, error
5022 function reset_course_userdata($data) {
5023 global $CFG, $DB;
5024 require_once($CFG->libdir.'/gradelib.php');
5025 require_once($CFG->libdir.'/completionlib.php');
5026 require_once($CFG->dirroot.'/group/lib.php');
5028 $data->courseid = $data->id;
5029 $context = context_course::instance($data->courseid);
5031 $eventparams = array(
5032 'context' => $context,
5033 'courseid' => $data->id,
5034 'other' => array(
5035 'reset_options' => (array) $data
5038 $event = \core\event\course_reset_started::create($eventparams);
5039 $event->trigger();
5041 // Calculate the time shift of dates.
5042 if (!empty($data->reset_start_date)) {
5043 // Time part of course startdate should be zero.
5044 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5045 } else {
5046 $data->timeshift = 0;
5049 // Result array: component, item, error.
5050 $status = array();
5052 // Start the resetting.
5053 $componentstr = get_string('general');
5055 // Move the course start time.
5056 if (!empty($data->reset_start_date) and $data->timeshift) {
5057 // Change course start data.
5058 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5059 // Update all course and group events - do not move activity events.
5060 $updatesql = "UPDATE {event}
5061 SET timestart = timestart + ?
5062 WHERE courseid=? AND instance=0";
5063 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5065 // Update any date activity restrictions.
5066 if ($CFG->enableavailability) {
5067 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5070 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5073 if (!empty($data->reset_events)) {
5074 $DB->delete_records('event', array('courseid' => $data->courseid));
5075 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5078 if (!empty($data->reset_notes)) {
5079 require_once($CFG->dirroot.'/notes/lib.php');
5080 note_delete_all($data->courseid);
5081 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5084 if (!empty($data->delete_blog_associations)) {
5085 require_once($CFG->dirroot.'/blog/lib.php');
5086 blog_remove_associations_for_course($data->courseid);
5087 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5090 if (!empty($data->reset_completion)) {
5091 // Delete course and activity completion information.
5092 $course = $DB->get_record('course', array('id' => $data->courseid));
5093 $cc = new completion_info($course);
5094 $cc->delete_all_completion_data();
5095 $status[] = array('component' => $componentstr,
5096 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5099 $componentstr = get_string('roles');
5101 if (!empty($data->reset_roles_overrides)) {
5102 $children = $context->get_child_contexts();
5103 foreach ($children as $child) {
5104 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5106 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5107 // Force refresh for logged in users.
5108 $context->mark_dirty();
5109 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5112 if (!empty($data->reset_roles_local)) {
5113 $children = $context->get_child_contexts();
5114 foreach ($children as $child) {
5115 role_unassign_all(array('contextid' => $child->id));
5117 // Force refresh for logged in users.
5118 $context->mark_dirty();
5119 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5122 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5123 $data->unenrolled = array();
5124 if (!empty($data->unenrol_users)) {
5125 $plugins = enrol_get_plugins(true);
5126 $instances = enrol_get_instances($data->courseid, true);
5127 foreach ($instances as $key => $instance) {
5128 if (!isset($plugins[$instance->enrol])) {
5129 unset($instances[$key]);
5130 continue;
5134 foreach ($data->unenrol_users as $withroleid) {
5135 if ($withroleid) {
5136 $sql = "SELECT ue.*
5137 FROM {user_enrolments} ue
5138 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5139 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5140 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5141 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5143 } else {
5144 // Without any role assigned at course context.
5145 $sql = "SELECT ue.*
5146 FROM {user_enrolments} ue
5147 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5148 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5149 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5150 WHERE ra.id IS null";
5151 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5154 $rs = $DB->get_recordset_sql($sql, $params);
5155 foreach ($rs as $ue) {
5156 if (!isset($instances[$ue->enrolid])) {
5157 continue;
5159 $instance = $instances[$ue->enrolid];
5160 $plugin = $plugins[$instance->enrol];
5161 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5162 continue;
5165 $plugin->unenrol_user($instance, $ue->userid);
5166 $data->unenrolled[$ue->userid] = $ue->userid;
5168 $rs->close();
5171 if (!empty($data->unenrolled)) {
5172 $status[] = array(
5173 'component' => $componentstr,
5174 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5175 'error' => false
5179 $componentstr = get_string('groups');
5181 // Remove all group members.
5182 if (!empty($data->reset_groups_members)) {
5183 groups_delete_group_members($data->courseid);
5184 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5187 // Remove all groups.
5188 if (!empty($data->reset_groups_remove)) {
5189 groups_delete_groups($data->courseid, false);
5190 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5193 // Remove all grouping members.
5194 if (!empty($data->reset_groupings_members)) {
5195 groups_delete_groupings_groups($data->courseid, false);
5196 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5199 // Remove all groupings.
5200 if (!empty($data->reset_groupings_remove)) {
5201 groups_delete_groupings($data->courseid, false);
5202 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5205 // Look in every instance of every module for data to delete.
5206 $unsupportedmods = array();
5207 if ($allmods = $DB->get_records('modules') ) {
5208 foreach ($allmods as $mod) {
5209 $modname = $mod->name;
5210 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5211 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5212 if (file_exists($modfile)) {
5213 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5214 continue; // Skip mods with no instances.
5216 include_once($modfile);
5217 if (function_exists($moddeleteuserdata)) {
5218 $modstatus = $moddeleteuserdata($data);
5219 if (is_array($modstatus)) {
5220 $status = array_merge($status, $modstatus);
5221 } else {
5222 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5224 } else {
5225 $unsupportedmods[] = $mod;
5227 } else {
5228 debugging('Missing lib.php in '.$modname.' module!');
5233 // Mention unsupported mods.
5234 if (!empty($unsupportedmods)) {
5235 foreach ($unsupportedmods as $mod) {
5236 $status[] = array(
5237 'component' => get_string('modulenameplural', $mod->name),
5238 'item' => '',
5239 'error' => get_string('resetnotimplemented')
5244 $componentstr = get_string('gradebook', 'grades');
5245 // Reset gradebook,.
5246 if (!empty($data->reset_gradebook_items)) {
5247 remove_course_grades($data->courseid, false);
5248 grade_grab_course_grades($data->courseid);
5249 grade_regrade_final_grades($data->courseid);
5250 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5252 } else if (!empty($data->reset_gradebook_grades)) {
5253 grade_course_reset($data->courseid);
5254 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5256 // Reset comments.
5257 if (!empty($data->reset_comments)) {
5258 require_once($CFG->dirroot.'/comment/lib.php');
5259 comment::reset_course_page_comments($context);
5262 $event = \core\event\course_reset_ended::create($eventparams);
5263 $event->trigger();
5265 return $status;
5269 * Generate an email processing address.
5271 * @param int $modid
5272 * @param string $modargs
5273 * @return string Returns email processing address
5275 function generate_email_processing_address($modid, $modargs) {
5276 global $CFG;
5278 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5279 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5285 * @todo Finish documenting this function
5287 * @param string $modargs
5288 * @param string $body Currently unused
5290 function moodle_process_email($modargs, $body) {
5291 global $DB;
5293 // The first char should be an unencoded letter. We'll take this as an action.
5294 switch ($modargs{0}) {
5295 case 'B': { // Bounce.
5296 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5297 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5298 // Check the half md5 of their email.
5299 $md5check = substr(md5($user->email), 0, 16);
5300 if ($md5check == substr($modargs, -16)) {
5301 set_bounce_count($user);
5303 // Else maybe they've already changed it?
5306 break;
5307 // Maybe more later?
5311 // CORRESPONDENCE.
5314 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5316 * @param string $action 'get', 'buffer', 'close' or 'flush'
5317 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5319 function get_mailer($action='get') {
5320 global $CFG;
5322 /** @var moodle_phpmailer $mailer */
5323 static $mailer = null;
5324 static $counter = 0;
5326 if (!isset($CFG->smtpmaxbulk)) {
5327 $CFG->smtpmaxbulk = 1;
5330 if ($action == 'get') {
5331 $prevkeepalive = false;
5333 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5334 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5335 $counter++;
5336 // Reset the mailer.
5337 $mailer->Priority = 3;
5338 $mailer->CharSet = 'UTF-8'; // Our default.
5339 $mailer->ContentType = "text/plain";
5340 $mailer->Encoding = "8bit";
5341 $mailer->From = "root@localhost";
5342 $mailer->FromName = "Root User";
5343 $mailer->Sender = "";
5344 $mailer->Subject = "";
5345 $mailer->Body = "";
5346 $mailer->AltBody = "";
5347 $mailer->ConfirmReadingTo = "";
5349 $mailer->clearAllRecipients();
5350 $mailer->clearReplyTos();
5351 $mailer->clearAttachments();
5352 $mailer->clearCustomHeaders();
5353 return $mailer;
5356 $prevkeepalive = $mailer->SMTPKeepAlive;
5357 get_mailer('flush');
5360 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5361 $mailer = new moodle_phpmailer();
5363 $counter = 1;
5365 if ($CFG->smtphosts == 'qmail') {
5366 // Use Qmail system.
5367 $mailer->isQmail();
5369 } else if (empty($CFG->smtphosts)) {
5370 // Use PHP mail() = sendmail.
5371 $mailer->isMail();
5373 } else {
5374 // Use SMTP directly.
5375 $mailer->isSMTP();
5376 if (!empty($CFG->debugsmtp)) {
5377 $mailer->SMTPDebug = true;
5379 // Specify main and backup servers.
5380 $mailer->Host = $CFG->smtphosts;
5381 // Specify secure connection protocol.
5382 $mailer->SMTPSecure = $CFG->smtpsecure;
5383 // Use previous keepalive.
5384 $mailer->SMTPKeepAlive = $prevkeepalive;
5386 if ($CFG->smtpuser) {
5387 // Use SMTP authentication.
5388 $mailer->SMTPAuth = true;
5389 $mailer->Username = $CFG->smtpuser;
5390 $mailer->Password = $CFG->smtppass;
5394 return $mailer;
5397 $nothing = null;
5399 // Keep smtp session open after sending.
5400 if ($action == 'buffer') {
5401 if (!empty($CFG->smtpmaxbulk)) {
5402 get_mailer('flush');
5403 $m = get_mailer();
5404 if ($m->Mailer == 'smtp') {
5405 $m->SMTPKeepAlive = true;
5408 return $nothing;
5411 // Close smtp session, but continue buffering.
5412 if ($action == 'flush') {
5413 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5414 if (!empty($mailer->SMTPDebug)) {
5415 echo '<pre>'."\n";
5417 $mailer->SmtpClose();
5418 if (!empty($mailer->SMTPDebug)) {
5419 echo '</pre>';
5422 return $nothing;
5425 // Close smtp session, do not buffer anymore.
5426 if ($action == 'close') {
5427 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5428 get_mailer('flush');
5429 $mailer->SMTPKeepAlive = false;
5431 $mailer = null; // Better force new instance.
5432 return $nothing;
5437 * Send an email to a specified user
5439 * @param stdClass $user A {@link $USER} object
5440 * @param stdClass $from A {@link $USER} object
5441 * @param string $subject plain text subject line of the email
5442 * @param string $messagetext plain text version of the message
5443 * @param string $messagehtml complete html version of the message (optional)
5444 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5445 * @param string $attachname the name of the file (extension indicates MIME)
5446 * @param bool $usetrueaddress determines whether $from email address should
5447 * be sent out. Will be overruled by user profile setting for maildisplay
5448 * @param string $replyto Email address to reply to
5449 * @param string $replytoname Name of reply to recipient
5450 * @param int $wordwrapwidth custom word wrap width, default 79
5451 * @return bool Returns true if mail was sent OK and false if there was an error.
5453 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5454 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5456 global $CFG;
5458 if (empty($user) or empty($user->id)) {
5459 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5460 return false;
5463 if (empty($user->email)) {
5464 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5465 return false;
5468 if (!empty($user->deleted)) {
5469 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5470 return false;
5473 if (defined('BEHAT_SITE_RUNNING')) {
5474 // Fake email sending in behat.
5475 return true;
5478 if (!empty($CFG->noemailever)) {
5479 // Hidden setting for development sites, set in config.php if needed.
5480 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5481 return true;
5484 if (!empty($CFG->divertallemailsto)) {
5485 $subject = "[DIVERTED {$user->email}] $subject";
5486 $user = clone($user);
5487 $user->email = $CFG->divertallemailsto;
5490 // Skip mail to suspended users.
5491 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5492 return true;
5495 if (!validate_email($user->email)) {
5496 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5497 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5498 return false;
5501 if (over_bounce_threshold($user)) {
5502 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5503 return false;
5506 // TLD .invalid is specifically reserved for invalid domain names.
5507 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5508 if (substr($user->email, -8) == '.invalid') {
5509 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5510 return true; // This is not an error.
5513 // If the user is a remote mnet user, parse the email text for URL to the
5514 // wwwroot and modify the url to direct the user's browser to login at their
5515 // home site (identity provider - idp) before hitting the link itself.
5516 if (is_mnet_remote_user($user)) {
5517 require_once($CFG->dirroot.'/mnet/lib.php');
5519 $jumpurl = mnet_get_idp_jump_url($user);
5520 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5522 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5523 $callback,
5524 $messagetext);
5525 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5526 $callback,
5527 $messagehtml);
5529 $mail = get_mailer();
5531 if (!empty($mail->SMTPDebug)) {
5532 echo '<pre>' . "\n";
5535 $temprecipients = array();
5536 $tempreplyto = array();
5538 $supportuser = core_user::get_support_user();
5540 // Make up an email address for handling bounces.
5541 if (!empty($CFG->handlebounces)) {
5542 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5543 $mail->Sender = generate_email_processing_address(0, $modargs);
5544 } else {
5545 $mail->Sender = $supportuser->email;
5548 if (!empty($CFG->emailonlyfromnoreplyaddress)) {
5549 $usetrueaddress = false;
5550 if (empty($replyto) && $from->maildisplay) {
5551 $replyto = $from->email;
5552 $replytoname = fullname($from);
5556 if (is_string($from)) { // So we can pass whatever we want if there is need.
5557 $mail->From = $CFG->noreplyaddress;
5558 $mail->FromName = $from;
5559 } else if ($usetrueaddress and $from->maildisplay) {
5560 $mail->From = $from->email;
5561 $mail->FromName = fullname($from);
5562 } else {
5563 $mail->From = $CFG->noreplyaddress;
5564 $mail->FromName = fullname($from);
5565 if (empty($replyto)) {
5566 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5570 if (!empty($replyto)) {
5571 $tempreplyto[] = array($replyto, $replytoname);
5574 $mail->Subject = substr($subject, 0, 900);
5576 $temprecipients[] = array($user->email, fullname($user));
5578 // Set word wrap.
5579 $mail->WordWrap = $wordwrapwidth;
5581 if (!empty($from->customheaders)) {
5582 // Add custom headers.
5583 if (is_array($from->customheaders)) {
5584 foreach ($from->customheaders as $customheader) {
5585 $mail->addCustomHeader($customheader);
5587 } else {
5588 $mail->addCustomHeader($from->customheaders);
5592 // If the X-PHP-Originating-Script email header is on then also add an additional
5593 // header with details of where exactly in moodle the email was triggered from,
5594 // either a call to message_send() or to email_to_user().
5595 if (ini_get('mail.add_x_header')) {
5597 $stack = debug_backtrace(false);
5598 $origin = $stack[0];
5600 foreach ($stack as $depth => $call) {
5601 if ($call['function'] == 'message_send') {
5602 $origin = $call;
5606 $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
5607 . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
5608 $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
5611 if (!empty($from->priority)) {
5612 $mail->Priority = $from->priority;
5615 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5616 // Don't ever send HTML to users who don't want it.
5617 $mail->isHTML(true);
5618 $mail->Encoding = 'quoted-printable';
5619 $mail->Body = $messagehtml;
5620 $mail->AltBody = "\n$messagetext\n";
5621 } else {
5622 $mail->IsHTML(false);
5623 $mail->Body = "\n$messagetext\n";
5626 if ($attachment && $attachname) {
5627 if (preg_match( "~\\.\\.~" , $attachment )) {
5628 // Security check for ".." in dir path.
5629 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5630 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5631 } else {
5632 require_once($CFG->libdir.'/filelib.php');
5633 $mimetype = mimeinfo('type', $attachname);
5635 $attachmentpath = $attachment;
5637 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5638 $attachpath = str_replace('\\', '/', $attachmentpath);
5639 // Make sure both variables are normalised before comparing.
5640 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
5642 // If the attachment is a full path to a file in the tempdir, use it as is,
5643 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5644 if (strpos($attachpath, $temppath) !== 0) {
5645 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5648 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5652 // Check if the email should be sent in an other charset then the default UTF-8.
5653 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5655 // Use the defined site mail charset or eventually the one preferred by the recipient.
5656 $charset = $CFG->sitemailcharset;
5657 if (!empty($CFG->allowusermailcharset)) {
5658 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5659 $charset = $useremailcharset;
5663 // Convert all the necessary strings if the charset is supported.
5664 $charsets = get_list_of_charsets();
5665 unset($charsets['UTF-8']);
5666 if (in_array($charset, $charsets)) {
5667 $mail->CharSet = $charset;
5668 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5669 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5670 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5671 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5673 foreach ($temprecipients as $key => $values) {
5674 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5676 foreach ($tempreplyto as $key => $values) {
5677 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5682 foreach ($temprecipients as $values) {
5683 $mail->addAddress($values[0], $values[1]);
5685 foreach ($tempreplyto as $values) {
5686 $mail->addReplyTo($values[0], $values[1]);
5689 if ($mail->send()) {
5690 set_send_count($user);
5691 if (!empty($mail->SMTPDebug)) {
5692 echo '</pre>';
5694 return true;
5695 } else {
5696 // Trigger event for failing to send email.
5697 $event = \core\event\email_failed::create(array(
5698 'context' => context_system::instance(),
5699 'userid' => $from->id,
5700 'relateduserid' => $user->id,
5701 'other' => array(
5702 'subject' => $subject,
5703 'message' => $messagetext,
5704 'errorinfo' => $mail->ErrorInfo
5707 $event->trigger();
5708 if (CLI_SCRIPT) {
5709 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5711 if (!empty($mail->SMTPDebug)) {
5712 echo '</pre>';
5714 return false;
5719 * Generate a signoff for emails based on support settings
5721 * @return string
5723 function generate_email_signoff() {
5724 global $CFG;
5726 $signoff = "\n";
5727 if (!empty($CFG->supportname)) {
5728 $signoff .= $CFG->supportname."\n";
5730 if (!empty($CFG->supportemail)) {
5731 $signoff .= $CFG->supportemail."\n";
5733 if (!empty($CFG->supportpage)) {
5734 $signoff .= $CFG->supportpage."\n";
5736 return $signoff;
5740 * Sets specified user's password and send the new password to the user via email.
5742 * @param stdClass $user A {@link $USER} object
5743 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
5744 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
5746 function setnew_password_and_mail($user, $fasthash = false) {
5747 global $CFG, $DB;
5749 // We try to send the mail in language the user understands,
5750 // unfortunately the filter_string() does not support alternative langs yet
5751 // so multilang will not work properly for site->fullname.
5752 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
5754 $site = get_site();
5756 $supportuser = core_user::get_support_user();
5758 $newpassword = generate_password();
5760 update_internal_user_password($user, $newpassword, $fasthash);
5762 $a = new stdClass();
5763 $a->firstname = fullname($user, true);
5764 $a->sitename = format_string($site->fullname);
5765 $a->username = $user->username;
5766 $a->newpassword = $newpassword;
5767 $a->link = $CFG->wwwroot .'/login/';
5768 $a->signoff = generate_email_signoff();
5770 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
5772 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
5774 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5775 return email_to_user($user, $supportuser, $subject, $message);
5780 * Resets specified user's password and send the new password to the user via email.
5782 * @param stdClass $user A {@link $USER} object
5783 * @return bool Returns true if mail was sent OK and false if there was an error.
5785 function reset_password_and_mail($user) {
5786 global $CFG;
5788 $site = get_site();
5789 $supportuser = core_user::get_support_user();
5791 $userauth = get_auth_plugin($user->auth);
5792 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
5793 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
5794 return false;
5797 $newpassword = generate_password();
5799 if (!$userauth->user_update_password($user, $newpassword)) {
5800 print_error("cannotsetpassword");
5803 $a = new stdClass();
5804 $a->firstname = $user->firstname;
5805 $a->lastname = $user->lastname;
5806 $a->sitename = format_string($site->fullname);
5807 $a->username = $user->username;
5808 $a->newpassword = $newpassword;
5809 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
5810 $a->signoff = generate_email_signoff();
5812 $message = get_string('newpasswordtext', '', $a);
5814 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
5816 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
5818 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5819 return email_to_user($user, $supportuser, $subject, $message);
5823 * Send email to specified user with confirmation text and activation link.
5825 * @param stdClass $user A {@link $USER} object
5826 * @return bool Returns true if mail was sent OK and false if there was an error.
5828 function send_confirmation_email($user) {
5829 global $CFG;
5831 $site = get_site();
5832 $supportuser = core_user::get_support_user();
5834 $data = new stdClass();
5835 $data->firstname = fullname($user);
5836 $data->sitename = format_string($site->fullname);
5837 $data->admin = generate_email_signoff();
5839 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
5841 $username = urlencode($user->username);
5842 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
5843 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
5844 $message = get_string('emailconfirmation', '', $data);
5845 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
5847 $user->mailformat = 1; // Always send HTML version as well.
5849 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5850 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
5854 * Sends a password change confirmation email.
5856 * @param stdClass $user A {@link $USER} object
5857 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
5858 * @return bool Returns true if mail was sent OK and false if there was an error.
5860 function send_password_change_confirmation_email($user, $resetrecord) {
5861 global $CFG;
5863 $site = get_site();
5864 $supportuser = core_user::get_support_user();
5865 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
5867 $data = new stdClass();
5868 $data->firstname = $user->firstname;
5869 $data->lastname = $user->lastname;
5870 $data->username = $user->username;
5871 $data->sitename = format_string($site->fullname);
5872 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
5873 $data->admin = generate_email_signoff();
5874 $data->resetminutes = $pwresetmins;
5876 $message = get_string('emailresetconfirmation', '', $data);
5877 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
5879 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5880 return email_to_user($user, $supportuser, $subject, $message);
5885 * Sends an email containinginformation on how to change your password.
5887 * @param stdClass $user A {@link $USER} object
5888 * @return bool Returns true if mail was sent OK and false if there was an error.
5890 function send_password_change_info($user) {
5891 global $CFG;
5893 $site = get_site();
5894 $supportuser = core_user::get_support_user();
5895 $systemcontext = context_system::instance();
5897 $data = new stdClass();
5898 $data->firstname = $user->firstname;
5899 $data->lastname = $user->lastname;
5900 $data->sitename = format_string($site->fullname);
5901 $data->admin = generate_email_signoff();
5903 $userauth = get_auth_plugin($user->auth);
5905 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
5906 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
5907 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5908 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5909 return email_to_user($user, $supportuser, $subject, $message);
5912 if ($userauth->can_change_password() and $userauth->change_password_url()) {
5913 // We have some external url for password changing.
5914 $data->link .= $userauth->change_password_url();
5916 } else {
5917 // No way to change password, sorry.
5918 $data->link = '';
5921 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
5922 $message = get_string('emailpasswordchangeinfo', '', $data);
5923 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5924 } else {
5925 $message = get_string('emailpasswordchangeinfofail', '', $data);
5926 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5929 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5930 return email_to_user($user, $supportuser, $subject, $message);
5935 * Check that an email is allowed. It returns an error message if there was a problem.
5937 * @param string $email Content of email
5938 * @return string|false
5940 function email_is_not_allowed($email) {
5941 global $CFG;
5943 if (!empty($CFG->allowemailaddresses)) {
5944 $allowed = explode(' ', $CFG->allowemailaddresses);
5945 foreach ($allowed as $allowedpattern) {
5946 $allowedpattern = trim($allowedpattern);
5947 if (!$allowedpattern) {
5948 continue;
5950 if (strpos($allowedpattern, '.') === 0) {
5951 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
5952 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
5953 return false;
5956 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
5957 return false;
5960 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
5962 } else if (!empty($CFG->denyemailaddresses)) {
5963 $denied = explode(' ', $CFG->denyemailaddresses);
5964 foreach ($denied as $deniedpattern) {
5965 $deniedpattern = trim($deniedpattern);
5966 if (!$deniedpattern) {
5967 continue;
5969 if (strpos($deniedpattern, '.') === 0) {
5970 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
5971 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
5972 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
5975 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
5976 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
5981 return false;
5984 // FILE HANDLING.
5987 * Returns local file storage instance
5989 * @return file_storage
5991 function get_file_storage() {
5992 global $CFG;
5994 static $fs = null;
5996 if ($fs) {
5997 return $fs;
6000 require_once("$CFG->libdir/filelib.php");
6002 if (isset($CFG->filedir)) {
6003 $filedir = $CFG->filedir;
6004 } else {
6005 $filedir = $CFG->dataroot.'/filedir';
6008 if (isset($CFG->trashdir)) {
6009 $trashdirdir = $CFG->trashdir;
6010 } else {
6011 $trashdirdir = $CFG->dataroot.'/trashdir';
6014 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6016 return $fs;
6020 * Returns local file storage instance
6022 * @return file_browser
6024 function get_file_browser() {
6025 global $CFG;
6027 static $fb = null;
6029 if ($fb) {
6030 return $fb;
6033 require_once("$CFG->libdir/filelib.php");
6035 $fb = new file_browser();
6037 return $fb;
6041 * Returns file packer
6043 * @param string $mimetype default application/zip
6044 * @return file_packer
6046 function get_file_packer($mimetype='application/zip') {
6047 global $CFG;
6049 static $fp = array();
6051 if (isset($fp[$mimetype])) {
6052 return $fp[$mimetype];
6055 switch ($mimetype) {
6056 case 'application/zip':
6057 case 'application/vnd.moodle.profiling':
6058 $classname = 'zip_packer';
6059 break;
6061 case 'application/x-gzip' :
6062 $classname = 'tgz_packer';
6063 break;
6065 case 'application/vnd.moodle.backup':
6066 $classname = 'mbz_packer';
6067 break;
6069 default:
6070 return false;
6073 require_once("$CFG->libdir/filestorage/$classname.php");
6074 $fp[$mimetype] = new $classname();
6076 return $fp[$mimetype];
6080 * Returns current name of file on disk if it exists.
6082 * @param string $newfile File to be verified
6083 * @return string Current name of file on disk if true
6085 function valid_uploaded_file($newfile) {
6086 if (empty($newfile)) {
6087 return '';
6089 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6090 return $newfile['tmp_name'];
6091 } else {
6092 return '';
6097 * Returns the maximum size for uploading files.
6099 * There are seven possible upload limits:
6100 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6101 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6102 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6103 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6104 * 5. by the Moodle admin in $CFG->maxbytes
6105 * 6. by the teacher in the current course $course->maxbytes
6106 * 7. by the teacher for the current module, eg $assignment->maxbytes
6108 * These last two are passed to this function as arguments (in bytes).
6109 * Anything defined as 0 is ignored.
6110 * The smallest of all the non-zero numbers is returned.
6112 * @todo Finish documenting this function
6114 * @param int $sitebytes Set maximum size
6115 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6116 * @param int $modulebytes Current module ->maxbytes (in bytes)
6117 * @return int The maximum size for uploading files.
6119 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6121 if (! $filesize = ini_get('upload_max_filesize')) {
6122 $filesize = '5M';
6124 $minimumsize = get_real_size($filesize);
6126 if ($postsize = ini_get('post_max_size')) {
6127 $postsize = get_real_size($postsize);
6128 if ($postsize < $minimumsize) {
6129 $minimumsize = $postsize;
6133 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6134 $minimumsize = $sitebytes;
6137 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6138 $minimumsize = $coursebytes;
6141 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6142 $minimumsize = $modulebytes;
6145 return $minimumsize;
6149 * Returns the maximum size for uploading files for the current user
6151 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6153 * @param context $context The context in which to check user capabilities
6154 * @param int $sitebytes Set maximum size
6155 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6156 * @param int $modulebytes Current module ->maxbytes (in bytes)
6157 * @param stdClass $user The user
6158 * @return int The maximum size for uploading files.
6160 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6161 global $USER;
6163 if (empty($user)) {
6164 $user = $USER;
6167 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6168 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6171 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6175 * Returns an array of possible sizes in local language
6177 * Related to {@link get_max_upload_file_size()} - this function returns an
6178 * array of possible sizes in an array, translated to the
6179 * local language.
6181 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6183 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6184 * with the value set to 0. This option will be the first in the list.
6186 * @uses SORT_NUMERIC
6187 * @param int $sitebytes Set maximum size
6188 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6189 * @param int $modulebytes Current module ->maxbytes (in bytes)
6190 * @param int|array $custombytes custom upload size/s which will be added to list,
6191 * Only value/s smaller then maxsize will be added to list.
6192 * @return array
6194 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6195 global $CFG;
6197 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6198 return array();
6201 if ($sitebytes == 0) {
6202 // Will get the minimum of upload_max_filesize or post_max_size.
6203 $sitebytes = get_max_upload_file_size();
6206 $filesize = array();
6207 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6208 5242880, 10485760, 20971520, 52428800, 104857600);
6210 // If custombytes is given and is valid then add it to the list.
6211 if (is_number($custombytes) and $custombytes > 0) {
6212 $custombytes = (int)$custombytes;
6213 if (!in_array($custombytes, $sizelist)) {
6214 $sizelist[] = $custombytes;
6216 } else if (is_array($custombytes)) {
6217 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6220 // Allow maxbytes to be selected if it falls outside the above boundaries.
6221 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6222 // Note: get_real_size() is used in order to prevent problems with invalid values.
6223 $sizelist[] = get_real_size($CFG->maxbytes);
6226 foreach ($sizelist as $sizebytes) {
6227 if ($sizebytes < $maxsize && $sizebytes > 0) {
6228 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6232 $limitlevel = '';
6233 $displaysize = '';
6234 if ($modulebytes &&
6235 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6236 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6237 $limitlevel = get_string('activity', 'core');
6238 $displaysize = display_size($modulebytes);
6239 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6241 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6242 $limitlevel = get_string('course', 'core');
6243 $displaysize = display_size($coursebytes);
6244 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6246 } else if ($sitebytes) {
6247 $limitlevel = get_string('site', 'core');
6248 $displaysize = display_size($sitebytes);
6249 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6252 krsort($filesize, SORT_NUMERIC);
6253 if ($limitlevel) {
6254 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6255 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6258 return $filesize;
6262 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6264 * If excludefiles is defined, then that file/directory is ignored
6265 * If getdirs is true, then (sub)directories are included in the output
6266 * If getfiles is true, then files are included in the output
6267 * (at least one of these must be true!)
6269 * @todo Finish documenting this function. Add examples of $excludefile usage.
6271 * @param string $rootdir A given root directory to start from
6272 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6273 * @param bool $descend If true then subdirectories are recursed as well
6274 * @param bool $getdirs If true then (sub)directories are included in the output
6275 * @param bool $getfiles If true then files are included in the output
6276 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6278 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6280 $dirs = array();
6282 if (!$getdirs and !$getfiles) { // Nothing to show.
6283 return $dirs;
6286 if (!is_dir($rootdir)) { // Must be a directory.
6287 return $dirs;
6290 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6291 return $dirs;
6294 if (!is_array($excludefiles)) {
6295 $excludefiles = array($excludefiles);
6298 while (false !== ($file = readdir($dir))) {
6299 $firstchar = substr($file, 0, 1);
6300 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6301 continue;
6303 $fullfile = $rootdir .'/'. $file;
6304 if (filetype($fullfile) == 'dir') {
6305 if ($getdirs) {
6306 $dirs[] = $file;
6308 if ($descend) {
6309 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6310 foreach ($subdirs as $subdir) {
6311 $dirs[] = $file .'/'. $subdir;
6314 } else if ($getfiles) {
6315 $dirs[] = $file;
6318 closedir($dir);
6320 asort($dirs);
6322 return $dirs;
6327 * Adds up all the files in a directory and works out the size.
6329 * @param string $rootdir The directory to start from
6330 * @param string $excludefile A file to exclude when summing directory size
6331 * @return int The summed size of all files and subfiles within the root directory
6333 function get_directory_size($rootdir, $excludefile='') {
6334 global $CFG;
6336 // Do it this way if we can, it's much faster.
6337 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6338 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6339 $output = null;
6340 $return = null;
6341 exec($command, $output, $return);
6342 if (is_array($output)) {
6343 // We told it to return k.
6344 return get_real_size(intval($output[0]).'k');
6348 if (!is_dir($rootdir)) {
6349 // Must be a directory.
6350 return 0;
6353 if (!$dir = @opendir($rootdir)) {
6354 // Can't open it for some reason.
6355 return 0;
6358 $size = 0;
6360 while (false !== ($file = readdir($dir))) {
6361 $firstchar = substr($file, 0, 1);
6362 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6363 continue;
6365 $fullfile = $rootdir .'/'. $file;
6366 if (filetype($fullfile) == 'dir') {
6367 $size += get_directory_size($fullfile, $excludefile);
6368 } else {
6369 $size += filesize($fullfile);
6372 closedir($dir);
6374 return $size;
6378 * Converts bytes into display form
6380 * @static string $gb Localized string for size in gigabytes
6381 * @static string $mb Localized string for size in megabytes
6382 * @static string $kb Localized string for size in kilobytes
6383 * @static string $b Localized string for size in bytes
6384 * @param int $size The size to convert to human readable form
6385 * @return string
6387 function display_size($size) {
6389 static $gb, $mb, $kb, $b;
6391 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6392 return get_string('unlimited');
6395 if (empty($gb)) {
6396 $gb = get_string('sizegb');
6397 $mb = get_string('sizemb');
6398 $kb = get_string('sizekb');
6399 $b = get_string('sizeb');
6402 if ($size >= 1073741824) {
6403 $size = round($size / 1073741824 * 10) / 10 . $gb;
6404 } else if ($size >= 1048576) {
6405 $size = round($size / 1048576 * 10) / 10 . $mb;
6406 } else if ($size >= 1024) {
6407 $size = round($size / 1024 * 10) / 10 . $kb;
6408 } else {
6409 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6411 return $size;
6415 * Cleans a given filename by removing suspicious or troublesome characters
6417 * @see clean_param()
6418 * @param string $string file name
6419 * @return string cleaned file name
6421 function clean_filename($string) {
6422 return clean_param($string, PARAM_FILE);
6426 // STRING TRANSLATION.
6429 * Returns the code for the current language
6431 * @category string
6432 * @return string
6434 function current_language() {
6435 global $CFG, $USER, $SESSION, $COURSE;
6437 if (!empty($SESSION->forcelang)) {
6438 // Allows overriding course-forced language (useful for admins to check
6439 // issues in courses whose language they don't understand).
6440 // Also used by some code to temporarily get language-related information in a
6441 // specific language (see force_current_language()).
6442 $return = $SESSION->forcelang;
6444 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6445 // Course language can override all other settings for this page.
6446 $return = $COURSE->lang;
6448 } else if (!empty($SESSION->lang)) {
6449 // Session language can override other settings.
6450 $return = $SESSION->lang;
6452 } else if (!empty($USER->lang)) {
6453 $return = $USER->lang;
6455 } else if (isset($CFG->lang)) {
6456 $return = $CFG->lang;
6458 } else {
6459 $return = 'en';
6462 // Just in case this slipped in from somewhere by accident.
6463 $return = str_replace('_utf8', '', $return);
6465 return $return;
6469 * Returns parent language of current active language if defined
6471 * @category string
6472 * @param string $lang null means current language
6473 * @return string
6475 function get_parent_language($lang=null) {
6477 // Let's hack around the current language.
6478 if (!empty($lang)) {
6479 $oldforcelang = force_current_language($lang);
6482 $parentlang = get_string('parentlanguage', 'langconfig');
6483 if ($parentlang === 'en') {
6484 $parentlang = '';
6487 // Let's hack around the current language.
6488 if (!empty($lang)) {
6489 force_current_language($oldforcelang);
6492 return $parentlang;
6496 * Force the current language to get strings and dates localised in the given language.
6498 * After calling this function, all strings will be provided in the given language
6499 * until this function is called again, or equivalent code is run.
6501 * @param string $language
6502 * @return string previous $SESSION->forcelang value
6504 function force_current_language($language) {
6505 global $SESSION;
6506 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6507 if ($language !== $sessionforcelang) {
6508 // Seting forcelang to null or an empty string disables it's effect.
6509 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6510 $SESSION->forcelang = $language;
6511 moodle_setlocale();
6514 return $sessionforcelang;
6518 * Returns current string_manager instance.
6520 * The param $forcereload is needed for CLI installer only where the string_manager instance
6521 * must be replaced during the install.php script life time.
6523 * @category string
6524 * @param bool $forcereload shall the singleton be released and new instance created instead?
6525 * @return core_string_manager
6527 function get_string_manager($forcereload=false) {
6528 global $CFG;
6530 static $singleton = null;
6532 if ($forcereload) {
6533 $singleton = null;
6535 if ($singleton === null) {
6536 if (empty($CFG->early_install_lang)) {
6538 if (empty($CFG->langlist)) {
6539 $translist = array();
6540 } else {
6541 $translist = explode(',', $CFG->langlist);
6544 if (!empty($CFG->config_php_settings['customstringmanager'])) {
6545 $classname = $CFG->config_php_settings['customstringmanager'];
6547 if (class_exists($classname)) {
6548 $implements = class_implements($classname);
6550 if (isset($implements['core_string_manager'])) {
6551 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
6552 return $singleton;
6554 } else {
6555 debugging('Unable to instantiate custom string manager: class '.$classname.
6556 ' does not implement the core_string_manager interface.');
6559 } else {
6560 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6564 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6566 } else {
6567 $singleton = new core_string_manager_install();
6571 return $singleton;
6575 * Returns a localized string.
6577 * Returns the translated string specified by $identifier as
6578 * for $module. Uses the same format files as STphp.
6579 * $a is an object, string or number that can be used
6580 * within translation strings
6582 * eg 'hello {$a->firstname} {$a->lastname}'
6583 * or 'hello {$a}'
6585 * If you would like to directly echo the localized string use
6586 * the function {@link print_string()}
6588 * Example usage of this function involves finding the string you would
6589 * like a local equivalent of and using its identifier and module information
6590 * to retrieve it.<br/>
6591 * If you open moodle/lang/en/moodle.php and look near line 278
6592 * you will find a string to prompt a user for their word for 'course'
6593 * <code>
6594 * $string['course'] = 'Course';
6595 * </code>
6596 * So if you want to display the string 'Course'
6597 * in any language that supports it on your site
6598 * you just need to use the identifier 'course'
6599 * <code>
6600 * $mystring = '<strong>'. get_string('course') .'</strong>';
6601 * or
6602 * </code>
6603 * If the string you want is in another file you'd take a slightly
6604 * different approach. Looking in moodle/lang/en/calendar.php you find
6605 * around line 75:
6606 * <code>
6607 * $string['typecourse'] = 'Course event';
6608 * </code>
6609 * If you want to display the string "Course event" in any language
6610 * supported you would use the identifier 'typecourse' and the module 'calendar'
6611 * (because it is in the file calendar.php):
6612 * <code>
6613 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6614 * </code>
6616 * As a last resort, should the identifier fail to map to a string
6617 * the returned string will be [[ $identifier ]]
6619 * In Moodle 2.3 there is a new argument to this function $lazyload.
6620 * Setting $lazyload to true causes get_string to return a lang_string object
6621 * rather than the string itself. The fetching of the string is then put off until
6622 * the string object is first used. The object can be used by calling it's out
6623 * method or by casting the object to a string, either directly e.g.
6624 * (string)$stringobject
6625 * or indirectly by using the string within another string or echoing it out e.g.
6626 * echo $stringobject
6627 * return "<p>{$stringobject}</p>";
6628 * It is worth noting that using $lazyload and attempting to use the string as an
6629 * array key will cause a fatal error as objects cannot be used as array keys.
6630 * But you should never do that anyway!
6631 * For more information {@link lang_string}
6633 * @category string
6634 * @param string $identifier The key identifier for the localized string
6635 * @param string $component The module where the key identifier is stored,
6636 * usually expressed as the filename in the language pack without the
6637 * .php on the end but can also be written as mod/forum or grade/export/xls.
6638 * If none is specified then moodle.php is used.
6639 * @param string|object|array $a An object, string or number that can be used
6640 * within translation strings
6641 * @param bool $lazyload If set to true a string object is returned instead of
6642 * the string itself. The string then isn't calculated until it is first used.
6643 * @return string The localized string.
6644 * @throws coding_exception
6646 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6647 global $CFG;
6649 // If the lazy load argument has been supplied return a lang_string object
6650 // instead.
6651 // We need to make sure it is true (and a bool) as you will see below there
6652 // used to be a forth argument at one point.
6653 if ($lazyload === true) {
6654 return new lang_string($identifier, $component, $a);
6657 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6658 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6661 // There is now a forth argument again, this time it is a boolean however so
6662 // we can still check for the old extralocations parameter.
6663 if (!is_bool($lazyload) && !empty($lazyload)) {
6664 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6667 if (strpos($component, '/') !== false) {
6668 debugging('The module name you passed to get_string is the deprecated format ' .
6669 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6670 $componentpath = explode('/', $component);
6672 switch ($componentpath[0]) {
6673 case 'mod':
6674 $component = $componentpath[1];
6675 break;
6676 case 'blocks':
6677 case 'block':
6678 $component = 'block_'.$componentpath[1];
6679 break;
6680 case 'enrol':
6681 $component = 'enrol_'.$componentpath[1];
6682 break;
6683 case 'format':
6684 $component = 'format_'.$componentpath[1];
6685 break;
6686 case 'grade':
6687 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6688 break;
6692 $result = get_string_manager()->get_string($identifier, $component, $a);
6694 // Debugging feature lets you display string identifier and component.
6695 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6696 $result .= ' {' . $identifier . '/' . $component . '}';
6698 return $result;
6702 * Converts an array of strings to their localized value.
6704 * @param array $array An array of strings
6705 * @param string $component The language module that these strings can be found in.
6706 * @return stdClass translated strings.
6708 function get_strings($array, $component = '') {
6709 $string = new stdClass;
6710 foreach ($array as $item) {
6711 $string->$item = get_string($item, $component);
6713 return $string;
6717 * Prints out a translated string.
6719 * Prints out a translated string using the return value from the {@link get_string()} function.
6721 * Example usage of this function when the string is in the moodle.php file:<br/>
6722 * <code>
6723 * echo '<strong>';
6724 * print_string('course');
6725 * echo '</strong>';
6726 * </code>
6728 * Example usage of this function when the string is not in the moodle.php file:<br/>
6729 * <code>
6730 * echo '<h1>';
6731 * print_string('typecourse', 'calendar');
6732 * echo '</h1>';
6733 * </code>
6735 * @category string
6736 * @param string $identifier The key identifier for the localized string
6737 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6738 * @param string|object|array $a An object, string or number that can be used within translation strings
6740 function print_string($identifier, $component = '', $a = null) {
6741 echo get_string($identifier, $component, $a);
6745 * Returns a list of charset codes
6747 * Returns a list of charset codes. It's hardcoded, so they should be added manually
6748 * (checking that such charset is supported by the texlib library!)
6750 * @return array And associative array with contents in the form of charset => charset
6752 function get_list_of_charsets() {
6754 $charsets = array(
6755 'EUC-JP' => 'EUC-JP',
6756 'ISO-2022-JP'=> 'ISO-2022-JP',
6757 'ISO-8859-1' => 'ISO-8859-1',
6758 'SHIFT-JIS' => 'SHIFT-JIS',
6759 'GB2312' => 'GB2312',
6760 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
6761 'UTF-8' => 'UTF-8');
6763 asort($charsets);
6765 return $charsets;
6769 * Returns a list of valid and compatible themes
6771 * @return array
6773 function get_list_of_themes() {
6774 global $CFG;
6776 $themes = array();
6778 if (!empty($CFG->themelist)) { // Use admin's list of themes.
6779 $themelist = explode(',', $CFG->themelist);
6780 } else {
6781 $themelist = array_keys(core_component::get_plugin_list("theme"));
6784 foreach ($themelist as $key => $themename) {
6785 $theme = theme_config::load($themename);
6786 $themes[$themename] = $theme;
6789 core_collator::asort_objects_by_method($themes, 'get_theme_name');
6791 return $themes;
6795 * Factory function for emoticon_manager
6797 * @return emoticon_manager singleton
6799 function get_emoticon_manager() {
6800 static $singleton = null;
6802 if (is_null($singleton)) {
6803 $singleton = new emoticon_manager();
6806 return $singleton;
6810 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
6812 * Whenever this manager mentiones 'emoticon object', the following data
6813 * structure is expected: stdClass with properties text, imagename, imagecomponent,
6814 * altidentifier and altcomponent
6816 * @see admin_setting_emoticons
6818 * @copyright 2010 David Mudrak
6819 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6821 class emoticon_manager {
6824 * Returns the currently enabled emoticons
6826 * @return array of emoticon objects
6828 public function get_emoticons() {
6829 global $CFG;
6831 if (empty($CFG->emoticons)) {
6832 return array();
6835 $emoticons = $this->decode_stored_config($CFG->emoticons);
6837 if (!is_array($emoticons)) {
6838 // Something is wrong with the format of stored setting.
6839 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
6840 return array();
6843 return $emoticons;
6847 * Converts emoticon object into renderable pix_emoticon object
6849 * @param stdClass $emoticon emoticon object
6850 * @param array $attributes explicit HTML attributes to set
6851 * @return pix_emoticon
6853 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
6854 $stringmanager = get_string_manager();
6855 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
6856 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
6857 } else {
6858 $alt = s($emoticon->text);
6860 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
6864 * Encodes the array of emoticon objects into a string storable in config table
6866 * @see self::decode_stored_config()
6867 * @param array $emoticons array of emtocion objects
6868 * @return string
6870 public function encode_stored_config(array $emoticons) {
6871 return json_encode($emoticons);
6875 * Decodes the string into an array of emoticon objects
6877 * @see self::encode_stored_config()
6878 * @param string $encoded
6879 * @return string|null
6881 public function decode_stored_config($encoded) {
6882 $decoded = json_decode($encoded);
6883 if (!is_array($decoded)) {
6884 return null;
6886 return $decoded;
6890 * Returns default set of emoticons supported by Moodle
6892 * @return array of sdtClasses
6894 public function default_emoticons() {
6895 return array(
6896 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
6897 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
6898 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
6899 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
6900 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
6901 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
6902 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
6903 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
6904 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
6905 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
6906 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
6907 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
6908 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
6909 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
6910 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
6911 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
6912 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
6913 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
6914 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
6915 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
6916 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
6917 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
6918 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
6919 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
6920 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
6921 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
6922 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
6923 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
6924 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
6925 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
6930 * Helper method preparing the stdClass with the emoticon properties
6932 * @param string|array $text or array of strings
6933 * @param string $imagename to be used by {@link pix_emoticon}
6934 * @param string $altidentifier alternative string identifier, null for no alt
6935 * @param string $altcomponent where the alternative string is defined
6936 * @param string $imagecomponent to be used by {@link pix_emoticon}
6937 * @return stdClass
6939 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
6940 $altcomponent = 'core_pix', $imagecomponent = 'core') {
6941 return (object)array(
6942 'text' => $text,
6943 'imagename' => $imagename,
6944 'imagecomponent' => $imagecomponent,
6945 'altidentifier' => $altidentifier,
6946 'altcomponent' => $altcomponent,
6951 // ENCRYPTION.
6954 * rc4encrypt
6956 * @param string $data Data to encrypt.
6957 * @return string The now encrypted data.
6959 function rc4encrypt($data) {
6960 return endecrypt(get_site_identifier(), $data, '');
6964 * rc4decrypt
6966 * @param string $data Data to decrypt.
6967 * @return string The now decrypted data.
6969 function rc4decrypt($data) {
6970 return endecrypt(get_site_identifier(), $data, 'de');
6974 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
6976 * @todo Finish documenting this function
6978 * @param string $pwd The password to use when encrypting or decrypting
6979 * @param string $data The data to be decrypted/encrypted
6980 * @param string $case Either 'de' for decrypt or '' for encrypt
6981 * @return string
6983 function endecrypt ($pwd, $data, $case) {
6985 if ($case == 'de') {
6986 $data = urldecode($data);
6989 $key[] = '';
6990 $box[] = '';
6991 $pwdlength = strlen($pwd);
6993 for ($i = 0; $i <= 255; $i++) {
6994 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
6995 $box[$i] = $i;
6998 $x = 0;
7000 for ($i = 0; $i <= 255; $i++) {
7001 $x = ($x + $box[$i] + $key[$i]) % 256;
7002 $tempswap = $box[$i];
7003 $box[$i] = $box[$x];
7004 $box[$x] = $tempswap;
7007 $cipher = '';
7009 $a = 0;
7010 $j = 0;
7012 for ($i = 0; $i < strlen($data); $i++) {
7013 $a = ($a + 1) % 256;
7014 $j = ($j + $box[$a]) % 256;
7015 $temp = $box[$a];
7016 $box[$a] = $box[$j];
7017 $box[$j] = $temp;
7018 $k = $box[(($box[$a] + $box[$j]) % 256)];
7019 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7020 $cipher .= chr($cipherby);
7023 if ($case == 'de') {
7024 $cipher = urldecode(urlencode($cipher));
7025 } else {
7026 $cipher = urlencode($cipher);
7029 return $cipher;
7032 // ENVIRONMENT CHECKING.
7035 * This method validates a plug name. It is much faster than calling clean_param.
7037 * @param string $name a string that might be a plugin name.
7038 * @return bool if this string is a valid plugin name.
7040 function is_valid_plugin_name($name) {
7041 // This does not work for 'mod', bad luck, use any other type.
7042 return core_component::is_valid_plugin_name('tool', $name);
7046 * Get a list of all the plugins of a given type that define a certain API function
7047 * in a certain file. The plugin component names and function names are returned.
7049 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7050 * @param string $function the part of the name of the function after the
7051 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7052 * names like report_courselist_hook.
7053 * @param string $file the name of file within the plugin that defines the
7054 * function. Defaults to lib.php.
7055 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7056 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7058 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7059 global $CFG;
7061 // We don't include here as all plugin types files would be included.
7062 $plugins = get_plugins_with_function($function, $file, false);
7064 if (empty($plugins[$plugintype])) {
7065 return array();
7068 $allplugins = core_component::get_plugin_list($plugintype);
7070 // Reformat the array and include the files.
7071 $pluginfunctions = array();
7072 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7074 // Check that it has not been removed and the file is still available.
7075 if (!empty($allplugins[$pluginname])) {
7077 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7078 if (file_exists($filepath)) {
7079 include_once($filepath);
7080 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7085 return $pluginfunctions;
7089 * Get a list of all the plugins that define a certain API function in a certain file.
7091 * @param string $function the part of the name of the function after the
7092 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7093 * names like report_courselist_hook.
7094 * @param string $file the name of file within the plugin that defines the
7095 * function. Defaults to lib.php.
7096 * @param bool $include Whether to include the files that contain the functions or not.
7097 * @return array with [plugintype][plugin] = functionname
7099 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7100 global $CFG;
7102 $cache = \cache::make('core', 'plugin_functions');
7104 // Including both although I doubt that we will find two functions definitions with the same name.
7105 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7106 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7108 if ($pluginfunctions = $cache->get($key)) {
7110 // Checking that the files are still available.
7111 foreach ($pluginfunctions as $plugintype => $plugins) {
7113 $allplugins = \core_component::get_plugin_list($plugintype);
7114 foreach ($plugins as $plugin => $fullpath) {
7116 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7117 if (empty($allplugins[$plugin])) {
7118 unset($pluginfunctions[$plugintype][$plugin]);
7119 continue;
7122 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7123 if ($include && $fileexists) {
7124 // Include the files if it was requested.
7125 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7126 } else if (!$fileexists) {
7127 // If the file is not available any more it should not be returned.
7128 unset($pluginfunctions[$plugintype][$plugin]);
7132 return $pluginfunctions;
7135 $pluginfunctions = array();
7137 // To fill the cached. Also, everything should continue working with cache disabled.
7138 $plugintypes = \core_component::get_plugin_types();
7139 foreach ($plugintypes as $plugintype => $unused) {
7141 // We need to include files here.
7142 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7143 foreach ($pluginswithfile as $plugin => $notused) {
7145 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7147 $pluginfunction = false;
7148 if (function_exists($fullfunction)) {
7149 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7150 $pluginfunction = $fullfunction;
7152 } else if ($plugintype === 'mod') {
7153 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7154 $shortfunction = $plugin . '_' . $function;
7155 if (function_exists($shortfunction)) {
7156 $pluginfunction = $shortfunction;
7160 if ($pluginfunction) {
7161 if (empty($pluginfunctions[$plugintype])) {
7162 $pluginfunctions[$plugintype] = array();
7164 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7169 $cache->set($key, $pluginfunctions);
7171 return $pluginfunctions;
7176 * Lists plugin-like directories within specified directory
7178 * This function was originally used for standard Moodle plugins, please use
7179 * new core_component::get_plugin_list() now.
7181 * This function is used for general directory listing and backwards compatility.
7183 * @param string $directory relative directory from root
7184 * @param string $exclude dir name to exclude from the list (defaults to none)
7185 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7186 * @return array Sorted array of directory names found under the requested parameters
7188 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7189 global $CFG;
7191 $plugins = array();
7193 if (empty($basedir)) {
7194 $basedir = $CFG->dirroot .'/'. $directory;
7196 } else {
7197 $basedir = $basedir .'/'. $directory;
7200 if ($CFG->debugdeveloper and empty($exclude)) {
7201 // Make sure devs do not use this to list normal plugins,
7202 // this is intended for general directories that are not plugins!
7204 $subtypes = core_component::get_plugin_types();
7205 if (in_array($basedir, $subtypes)) {
7206 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7208 unset($subtypes);
7211 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7212 if (!$dirhandle = opendir($basedir)) {
7213 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7214 return array();
7216 while (false !== ($dir = readdir($dirhandle))) {
7217 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7218 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7219 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7220 continue;
7222 if (filetype($basedir .'/'. $dir) != 'dir') {
7223 continue;
7225 $plugins[] = $dir;
7227 closedir($dirhandle);
7229 if ($plugins) {
7230 asort($plugins);
7232 return $plugins;
7236 * Invoke plugin's callback functions
7238 * @param string $type plugin type e.g. 'mod'
7239 * @param string $name plugin name
7240 * @param string $feature feature name
7241 * @param string $action feature's action
7242 * @param array $params parameters of callback function, should be an array
7243 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7244 * @return mixed
7246 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7248 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7249 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7253 * Invoke component's callback functions
7255 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7256 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7257 * @param array $params parameters of callback function
7258 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7259 * @return mixed
7261 function component_callback($component, $function, array $params = array(), $default = null) {
7263 $functionname = component_callback_exists($component, $function);
7265 if ($functionname) {
7266 // Function exists, so just return function result.
7267 $ret = call_user_func_array($functionname, $params);
7268 if (is_null($ret)) {
7269 return $default;
7270 } else {
7271 return $ret;
7274 return $default;
7278 * Determine if a component callback exists and return the function name to call. Note that this
7279 * function will include the required library files so that the functioname returned can be
7280 * called directly.
7282 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7283 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7284 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7285 * @throws coding_exception if invalid component specfied
7287 function component_callback_exists($component, $function) {
7288 global $CFG; // This is needed for the inclusions.
7290 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7291 if (empty($cleancomponent)) {
7292 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7294 $component = $cleancomponent;
7296 list($type, $name) = core_component::normalize_component($component);
7297 $component = $type . '_' . $name;
7299 $oldfunction = $name.'_'.$function;
7300 $function = $component.'_'.$function;
7302 $dir = core_component::get_component_directory($component);
7303 if (empty($dir)) {
7304 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7307 // Load library and look for function.
7308 if (file_exists($dir.'/lib.php')) {
7309 require_once($dir.'/lib.php');
7312 if (!function_exists($function) and function_exists($oldfunction)) {
7313 if ($type !== 'mod' and $type !== 'core') {
7314 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7316 $function = $oldfunction;
7319 if (function_exists($function)) {
7320 return $function;
7322 return false;
7326 * Checks whether a plugin supports a specified feature.
7328 * @param string $type Plugin type e.g. 'mod'
7329 * @param string $name Plugin name e.g. 'forum'
7330 * @param string $feature Feature code (FEATURE_xx constant)
7331 * @param mixed $default default value if feature support unknown
7332 * @return mixed Feature result (false if not supported, null if feature is unknown,
7333 * otherwise usually true but may have other feature-specific value such as array)
7334 * @throws coding_exception
7336 function plugin_supports($type, $name, $feature, $default = null) {
7337 global $CFG;
7339 if ($type === 'mod' and $name === 'NEWMODULE') {
7340 // Somebody forgot to rename the module template.
7341 return false;
7344 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7345 if (empty($component)) {
7346 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7349 $function = null;
7351 if ($type === 'mod') {
7352 // We need this special case because we support subplugins in modules,
7353 // otherwise it would end up in infinite loop.
7354 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7355 include_once("$CFG->dirroot/mod/$name/lib.php");
7356 $function = $component.'_supports';
7357 if (!function_exists($function)) {
7358 // Legacy non-frankenstyle function name.
7359 $function = $name.'_supports';
7363 } else {
7364 if (!$path = core_component::get_plugin_directory($type, $name)) {
7365 // Non existent plugin type.
7366 return false;
7368 if (file_exists("$path/lib.php")) {
7369 include_once("$path/lib.php");
7370 $function = $component.'_supports';
7374 if ($function and function_exists($function)) {
7375 $supports = $function($feature);
7376 if (is_null($supports)) {
7377 // Plugin does not know - use default.
7378 return $default;
7379 } else {
7380 return $supports;
7384 // Plugin does not care, so use default.
7385 return $default;
7389 * Returns true if the current version of PHP is greater that the specified one.
7391 * @todo Check PHP version being required here is it too low?
7393 * @param string $version The version of php being tested.
7394 * @return bool
7396 function check_php_version($version='5.2.4') {
7397 return (version_compare(phpversion(), $version) >= 0);
7401 * Determine if moodle installation requires update.
7403 * Checks version numbers of main code and all plugins to see
7404 * if there are any mismatches.
7406 * @return bool
7408 function moodle_needs_upgrading() {
7409 global $CFG;
7411 if (empty($CFG->version)) {
7412 return true;
7415 // There is no need to purge plugininfo caches here because
7416 // these caches are not used during upgrade and they are purged after
7417 // every upgrade.
7419 if (empty($CFG->allversionshash)) {
7420 return true;
7423 $hash = core_component::get_all_versions_hash();
7425 return ($hash !== $CFG->allversionshash);
7429 * Returns the major version of this site
7431 * Moodle version numbers consist of three numbers separated by a dot, for
7432 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7433 * called major version. This function extracts the major version from either
7434 * $CFG->release (default) or eventually from the $release variable defined in
7435 * the main version.php.
7437 * @param bool $fromdisk should the version if source code files be used
7438 * @return string|false the major version like '2.3', false if could not be determined
7440 function moodle_major_version($fromdisk = false) {
7441 global $CFG;
7443 if ($fromdisk) {
7444 $release = null;
7445 require($CFG->dirroot.'/version.php');
7446 if (empty($release)) {
7447 return false;
7450 } else {
7451 if (empty($CFG->release)) {
7452 return false;
7454 $release = $CFG->release;
7457 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7458 return $matches[0];
7459 } else {
7460 return false;
7464 // MISCELLANEOUS.
7467 * Sets the system locale
7469 * @category string
7470 * @param string $locale Can be used to force a locale
7472 function moodle_setlocale($locale='') {
7473 global $CFG;
7475 static $currentlocale = ''; // Last locale caching.
7477 $oldlocale = $currentlocale;
7479 // Fetch the correct locale based on ostype.
7480 if ($CFG->ostype == 'WINDOWS') {
7481 $stringtofetch = 'localewin';
7482 } else {
7483 $stringtofetch = 'locale';
7486 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7487 if (!empty($locale)) {
7488 $currentlocale = $locale;
7489 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7490 $currentlocale = $CFG->locale;
7491 } else {
7492 $currentlocale = get_string($stringtofetch, 'langconfig');
7495 // Do nothing if locale already set up.
7496 if ($oldlocale == $currentlocale) {
7497 return;
7500 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7501 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7502 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7504 // Get current values.
7505 $monetary= setlocale (LC_MONETARY, 0);
7506 $numeric = setlocale (LC_NUMERIC, 0);
7507 $ctype = setlocale (LC_CTYPE, 0);
7508 if ($CFG->ostype != 'WINDOWS') {
7509 $messages= setlocale (LC_MESSAGES, 0);
7511 // Set locale to all.
7512 $result = setlocale (LC_ALL, $currentlocale);
7513 // If setting of locale fails try the other utf8 or utf-8 variant,
7514 // some operating systems support both (Debian), others just one (OSX).
7515 if ($result === false) {
7516 if (stripos($currentlocale, '.UTF-8') !== false) {
7517 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7518 setlocale (LC_ALL, $newlocale);
7519 } else if (stripos($currentlocale, '.UTF8') !== false) {
7520 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7521 setlocale (LC_ALL, $newlocale);
7524 // Set old values.
7525 setlocale (LC_MONETARY, $monetary);
7526 setlocale (LC_NUMERIC, $numeric);
7527 if ($CFG->ostype != 'WINDOWS') {
7528 setlocale (LC_MESSAGES, $messages);
7530 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7531 // To workaround a well-known PHP problem with Turkish letter Ii.
7532 setlocale (LC_CTYPE, $ctype);
7537 * Count words in a string.
7539 * Words are defined as things between whitespace.
7541 * @category string
7542 * @param string $string The text to be searched for words.
7543 * @return int The count of words in the specified string
7545 function count_words($string) {
7546 $string = strip_tags($string);
7547 // Decode HTML entities.
7548 $string = html_entity_decode($string);
7549 // Replace underscores (which are classed as word characters) with spaces.
7550 $string = preg_replace('/_/u', ' ', $string);
7551 // Remove any characters that shouldn't be treated as word boundaries.
7552 $string = preg_replace('/[\'"’-]/u', '', $string);
7553 // Remove dots and commas from within numbers only.
7554 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7556 return count(preg_split('/\w\b/u', $string)) - 1;
7560 * Count letters in a string.
7562 * Letters are defined as chars not in tags and different from whitespace.
7564 * @category string
7565 * @param string $string The text to be searched for letters.
7566 * @return int The count of letters in the specified text.
7568 function count_letters($string) {
7569 $string = strip_tags($string); // Tags are out now.
7570 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7572 return core_text::strlen($string);
7576 * Generate and return a random string of the specified length.
7578 * @param int $length The length of the string to be created.
7579 * @return string
7581 function random_string($length=15) {
7582 $randombytes = random_bytes_emulate($length);
7583 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7584 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7585 $pool .= '0123456789';
7586 $poollen = strlen($pool);
7587 $string = '';
7588 for ($i = 0; $i < $length; $i++) {
7589 $rand = ord($randombytes[$i]);
7590 $string .= substr($pool, ($rand%($poollen)), 1);
7592 return $string;
7596 * Generate a complex random string (useful for md5 salts)
7598 * This function is based on the above {@link random_string()} however it uses a
7599 * larger pool of characters and generates a string between 24 and 32 characters
7601 * @param int $length Optional if set generates a string to exactly this length
7602 * @return string
7604 function complex_random_string($length=null) {
7605 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7606 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7607 $poollen = strlen($pool);
7608 if ($length===null) {
7609 $length = floor(rand(24, 32));
7611 $randombytes = random_bytes_emulate($length);
7612 $string = '';
7613 for ($i = 0; $i < $length; $i++) {
7614 $rand = ord($randombytes[$i]);
7615 $string .= $pool[($rand%$poollen)];
7617 return $string;
7621 * Try to generates cryptographically secure pseudo-random bytes.
7623 * Note this is achieved by fallbacking between:
7624 * - PHP 7 random_bytes().
7625 * - OpenSSL openssl_random_pseudo_bytes().
7626 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
7628 * @param int $length requested length in bytes
7629 * @return string binary data
7631 function random_bytes_emulate($length) {
7632 global $CFG;
7633 if ($length <= 0) {
7634 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
7635 return '';
7637 if (function_exists('random_bytes')) {
7638 // Use PHP 7 goodness.
7639 $hash = @random_bytes($length);
7640 if ($hash !== false) {
7641 return $hash;
7644 if (function_exists('openssl_random_pseudo_bytes')) {
7645 // For PHP 5.3 and later with openssl extension.
7646 $hash = openssl_random_pseudo_bytes($length);
7647 if ($hash !== false) {
7648 return $hash;
7652 // Bad luck, there is no reliable random generator, let's just hash some unique stuff that is hard to guess.
7653 $hash = sha1(serialize($CFG) . serialize($_SERVER) . microtime(true) . uniqid('', true), true);
7654 // NOTE: the last param in sha1() is true, this means we are getting 20 bytes, not 40 chars as usual.
7655 if ($length <= 20) {
7656 return substr($hash, 0, $length);
7658 return $hash . random_bytes_emulate($length - 20);
7662 * Given some text (which may contain HTML) and an ideal length,
7663 * this function truncates the text neatly on a word boundary if possible
7665 * @category string
7666 * @param string $text text to be shortened
7667 * @param int $ideal ideal string length
7668 * @param boolean $exact if false, $text will not be cut mid-word
7669 * @param string $ending The string to append if the passed string is truncated
7670 * @return string $truncate shortened string
7672 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7673 // If the plain text is shorter than the maximum length, return the whole text.
7674 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7675 return $text;
7678 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7679 // and only tag in its 'line'.
7680 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7682 $totallength = core_text::strlen($ending);
7683 $truncate = '';
7685 // This array stores information about open and close tags and their position
7686 // in the truncated string. Each item in the array is an object with fields
7687 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7688 // (byte position in truncated text).
7689 $tagdetails = array();
7691 foreach ($lines as $linematchings) {
7692 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7693 if (!empty($linematchings[1])) {
7694 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7695 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7696 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7697 // Record closing tag.
7698 $tagdetails[] = (object) array(
7699 'open' => false,
7700 'tag' => core_text::strtolower($tagmatchings[1]),
7701 'pos' => core_text::strlen($truncate),
7704 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7705 // Record opening tag.
7706 $tagdetails[] = (object) array(
7707 'open' => true,
7708 'tag' => core_text::strtolower($tagmatchings[1]),
7709 'pos' => core_text::strlen($truncate),
7711 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
7712 $tagdetails[] = (object) array(
7713 'open' => true,
7714 'tag' => core_text::strtolower('if'),
7715 'pos' => core_text::strlen($truncate),
7717 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
7718 $tagdetails[] = (object) array(
7719 'open' => false,
7720 'tag' => core_text::strtolower('if'),
7721 'pos' => core_text::strlen($truncate),
7725 // Add html-tag to $truncate'd text.
7726 $truncate .= $linematchings[1];
7729 // Calculate the length of the plain text part of the line; handle entities as one character.
7730 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7731 if ($totallength + $contentlength > $ideal) {
7732 // The number of characters which are left.
7733 $left = $ideal - $totallength;
7734 $entitieslength = 0;
7735 // Search for html entities.
7736 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)) {
7737 // Calculate the real length of all entities in the legal range.
7738 foreach ($entities[0] as $entity) {
7739 if ($entity[1]+1-$entitieslength <= $left) {
7740 $left--;
7741 $entitieslength += core_text::strlen($entity[0]);
7742 } else {
7743 // No more characters left.
7744 break;
7748 $breakpos = $left + $entitieslength;
7750 // If the words shouldn't be cut in the middle...
7751 if (!$exact) {
7752 // Search the last occurence of a space.
7753 for (; $breakpos > 0; $breakpos--) {
7754 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
7755 if ($char === '.' or $char === ' ') {
7756 $breakpos += 1;
7757 break;
7758 } else if (strlen($char) > 2) {
7759 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7760 $breakpos += 1;
7761 break;
7766 if ($breakpos == 0) {
7767 // This deals with the test_shorten_text_no_spaces case.
7768 $breakpos = $left + $entitieslength;
7769 } else if ($breakpos > $left + $entitieslength) {
7770 // This deals with the previous for loop breaking on the first char.
7771 $breakpos = $left + $entitieslength;
7774 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
7775 // Maximum length is reached, so get off the loop.
7776 break;
7777 } else {
7778 $truncate .= $linematchings[2];
7779 $totallength += $contentlength;
7782 // If the maximum length is reached, get off the loop.
7783 if ($totallength >= $ideal) {
7784 break;
7788 // Add the defined ending to the text.
7789 $truncate .= $ending;
7791 // Now calculate the list of open html tags based on the truncate position.
7792 $opentags = array();
7793 foreach ($tagdetails as $taginfo) {
7794 if ($taginfo->open) {
7795 // Add tag to the beginning of $opentags list.
7796 array_unshift($opentags, $taginfo->tag);
7797 } else {
7798 // Can have multiple exact same open tags, close the last one.
7799 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
7800 if ($pos !== false) {
7801 unset($opentags[$pos]);
7806 // Close all unclosed html-tags.
7807 foreach ($opentags as $tag) {
7808 if ($tag === 'if') {
7809 $truncate .= '<!--<![endif]-->';
7810 } else {
7811 $truncate .= '</' . $tag . '>';
7815 return $truncate;
7820 * Given dates in seconds, how many weeks is the date from startdate
7821 * The first week is 1, the second 2 etc ...
7823 * @param int $startdate Timestamp for the start date
7824 * @param int $thedate Timestamp for the end date
7825 * @return string
7827 function getweek ($startdate, $thedate) {
7828 if ($thedate < $startdate) {
7829 return 0;
7832 return floor(($thedate - $startdate) / WEEKSECS) + 1;
7836 * Returns a randomly generated password of length $maxlen. inspired by
7838 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
7839 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
7841 * @param int $maxlen The maximum size of the password being generated.
7842 * @return string
7844 function generate_password($maxlen=10) {
7845 global $CFG;
7847 if (empty($CFG->passwordpolicy)) {
7848 $fillers = PASSWORD_DIGITS;
7849 $wordlist = file($CFG->wordlist);
7850 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7851 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7852 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
7853 $password = $word1 . $filler1 . $word2;
7854 } else {
7855 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
7856 $digits = $CFG->minpassworddigits;
7857 $lower = $CFG->minpasswordlower;
7858 $upper = $CFG->minpasswordupper;
7859 $nonalphanum = $CFG->minpasswordnonalphanum;
7860 $total = $lower + $upper + $digits + $nonalphanum;
7861 // Var minlength should be the greater one of the two ( $minlen and $total ).
7862 $minlen = $minlen < $total ? $total : $minlen;
7863 // Var maxlen can never be smaller than minlen.
7864 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
7865 $additional = $maxlen - $total;
7867 // Make sure we have enough characters to fulfill
7868 // complexity requirements.
7869 $passworddigits = PASSWORD_DIGITS;
7870 while ($digits > strlen($passworddigits)) {
7871 $passworddigits .= PASSWORD_DIGITS;
7873 $passwordlower = PASSWORD_LOWER;
7874 while ($lower > strlen($passwordlower)) {
7875 $passwordlower .= PASSWORD_LOWER;
7877 $passwordupper = PASSWORD_UPPER;
7878 while ($upper > strlen($passwordupper)) {
7879 $passwordupper .= PASSWORD_UPPER;
7881 $passwordnonalphanum = PASSWORD_NONALPHANUM;
7882 while ($nonalphanum > strlen($passwordnonalphanum)) {
7883 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
7886 // Now mix and shuffle it all.
7887 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
7888 substr(str_shuffle ($passwordupper), 0, $upper) .
7889 substr(str_shuffle ($passworddigits), 0, $digits) .
7890 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
7891 substr(str_shuffle ($passwordlower .
7892 $passwordupper .
7893 $passworddigits .
7894 $passwordnonalphanum), 0 , $additional));
7897 return substr ($password, 0, $maxlen);
7901 * Given a float, prints it nicely.
7902 * Localized floats must not be used in calculations!
7904 * The stripzeros feature is intended for making numbers look nicer in small
7905 * areas where it is not necessary to indicate the degree of accuracy by showing
7906 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
7907 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
7909 * @param float $float The float to print
7910 * @param int $decimalpoints The number of decimal places to print.
7911 * @param bool $localized use localized decimal separator
7912 * @param bool $stripzeros If true, removes final zeros after decimal point
7913 * @return string locale float
7915 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
7916 if (is_null($float)) {
7917 return '';
7919 if ($localized) {
7920 $separator = get_string('decsep', 'langconfig');
7921 } else {
7922 $separator = '.';
7924 $result = number_format($float, $decimalpoints, $separator, '');
7925 if ($stripzeros) {
7926 // Remove zeros and final dot if not needed.
7927 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
7929 return $result;
7933 * Converts locale specific floating point/comma number back to standard PHP float value
7934 * Do NOT try to do any math operations before this conversion on any user submitted floats!
7936 * @param string $localefloat locale aware float representation
7937 * @param bool $strict If true, then check the input and return false if it is not a valid number.
7938 * @return mixed float|bool - false or the parsed float.
7940 function unformat_float($localefloat, $strict = false) {
7941 $localefloat = trim($localefloat);
7943 if ($localefloat == '') {
7944 return null;
7947 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
7948 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
7950 if ($strict && !is_numeric($localefloat)) {
7951 return false;
7954 return (float)$localefloat;
7958 * Given a simple array, this shuffles it up just like shuffle()
7959 * Unlike PHP's shuffle() this function works on any machine.
7961 * @param array $array The array to be rearranged
7962 * @return array
7964 function swapshuffle($array) {
7966 $last = count($array) - 1;
7967 for ($i = 0; $i <= $last; $i++) {
7968 $from = rand(0, $last);
7969 $curr = $array[$i];
7970 $array[$i] = $array[$from];
7971 $array[$from] = $curr;
7973 return $array;
7977 * Like {@link swapshuffle()}, but works on associative arrays
7979 * @param array $array The associative array to be rearranged
7980 * @return array
7982 function swapshuffle_assoc($array) {
7984 $newarray = array();
7985 $newkeys = swapshuffle(array_keys($array));
7987 foreach ($newkeys as $newkey) {
7988 $newarray[$newkey] = $array[$newkey];
7990 return $newarray;
7994 * Given an arbitrary array, and a number of draws,
7995 * this function returns an array with that amount
7996 * of items. The indexes are retained.
7998 * @todo Finish documenting this function
8000 * @param array $array
8001 * @param int $draws
8002 * @return array
8004 function draw_rand_array($array, $draws) {
8006 $return = array();
8008 $last = count($array);
8010 if ($draws > $last) {
8011 $draws = $last;
8014 while ($draws > 0) {
8015 $last--;
8017 $keys = array_keys($array);
8018 $rand = rand(0, $last);
8020 $return[$keys[$rand]] = $array[$keys[$rand]];
8021 unset($array[$keys[$rand]]);
8023 $draws--;
8026 return $return;
8030 * Calculate the difference between two microtimes
8032 * @param string $a The first Microtime
8033 * @param string $b The second Microtime
8034 * @return string
8036 function microtime_diff($a, $b) {
8037 list($adec, $asec) = explode(' ', $a);
8038 list($bdec, $bsec) = explode(' ', $b);
8039 return $bsec - $asec + $bdec - $adec;
8043 * Given a list (eg a,b,c,d,e) this function returns
8044 * an array of 1->a, 2->b, 3->c etc
8046 * @param string $list The string to explode into array bits
8047 * @param string $separator The separator used within the list string
8048 * @return array The now assembled array
8050 function make_menu_from_list($list, $separator=',') {
8052 $array = array_reverse(explode($separator, $list), true);
8053 foreach ($array as $key => $item) {
8054 $outarray[$key+1] = trim($item);
8056 return $outarray;
8060 * Creates an array that represents all the current grades that
8061 * can be chosen using the given grading type.
8063 * Negative numbers
8064 * are scales, zero is no grade, and positive numbers are maximum
8065 * grades.
8067 * @todo Finish documenting this function or better deprecated this completely!
8069 * @param int $gradingtype
8070 * @return array
8072 function make_grades_menu($gradingtype) {
8073 global $DB;
8075 $grades = array();
8076 if ($gradingtype < 0) {
8077 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8078 return make_menu_from_list($scale->scale);
8080 } else if ($gradingtype > 0) {
8081 for ($i=$gradingtype; $i>=0; $i--) {
8082 $grades[$i] = $i .' / '. $gradingtype;
8084 return $grades;
8086 return $grades;
8090 * This function returns the number of activities using the given scale in the given course.
8092 * @param int $courseid The course ID to check.
8093 * @param int $scaleid The scale ID to check
8094 * @return int
8096 function course_scale_used($courseid, $scaleid) {
8097 global $CFG, $DB;
8099 $return = 0;
8101 if (!empty($scaleid)) {
8102 if ($cms = get_course_mods($courseid)) {
8103 foreach ($cms as $cm) {
8104 // Check cm->name/lib.php exists.
8105 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
8106 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
8107 $functionname = $cm->modname.'_scale_used';
8108 if (function_exists($functionname)) {
8109 if ($functionname($cm->instance, $scaleid)) {
8110 $return++;
8117 // Check if any course grade item makes use of the scale.
8118 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8120 // Check if any outcome in the course makes use of the scale.
8121 $return += $DB->count_records_sql("SELECT COUNT('x')
8122 FROM {grade_outcomes_courses} goc,
8123 {grade_outcomes} go
8124 WHERE go.id = goc.outcomeid
8125 AND go.scaleid = ? AND goc.courseid = ?",
8126 array($scaleid, $courseid));
8128 return $return;
8132 * This function returns the number of activities using scaleid in the entire site
8134 * @param int $scaleid
8135 * @param array $courses
8136 * @return int
8138 function site_scale_used($scaleid, &$courses) {
8139 $return = 0;
8141 if (!is_array($courses) || count($courses) == 0) {
8142 $courses = get_courses("all", false, "c.id, c.shortname");
8145 if (!empty($scaleid)) {
8146 if (is_array($courses) && count($courses) > 0) {
8147 foreach ($courses as $course) {
8148 $return += course_scale_used($course->id, $scaleid);
8152 return $return;
8156 * make_unique_id_code
8158 * @todo Finish documenting this function
8160 * @uses $_SERVER
8161 * @param string $extra Extra string to append to the end of the code
8162 * @return string
8164 function make_unique_id_code($extra = '') {
8166 $hostname = 'unknownhost';
8167 if (!empty($_SERVER['HTTP_HOST'])) {
8168 $hostname = $_SERVER['HTTP_HOST'];
8169 } else if (!empty($_ENV['HTTP_HOST'])) {
8170 $hostname = $_ENV['HTTP_HOST'];
8171 } else if (!empty($_SERVER['SERVER_NAME'])) {
8172 $hostname = $_SERVER['SERVER_NAME'];
8173 } else if (!empty($_ENV['SERVER_NAME'])) {
8174 $hostname = $_ENV['SERVER_NAME'];
8177 $date = gmdate("ymdHis");
8179 $random = random_string(6);
8181 if ($extra) {
8182 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8183 } else {
8184 return $hostname .'+'. $date .'+'. $random;
8190 * Function to check the passed address is within the passed subnet
8192 * The parameter is a comma separated string of subnet definitions.
8193 * Subnet strings can be in one of three formats:
8194 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8195 * 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)
8196 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8197 * Code for type 1 modified from user posted comments by mediator at
8198 * {@link http://au.php.net/manual/en/function.ip2long.php}
8200 * @param string $addr The address you are checking
8201 * @param string $subnetstr The string of subnet addresses
8202 * @return bool
8204 function address_in_subnet($addr, $subnetstr) {
8206 if ($addr == '0.0.0.0') {
8207 return false;
8209 $subnets = explode(',', $subnetstr);
8210 $found = false;
8211 $addr = trim($addr);
8212 $addr = cleanremoteaddr($addr, false); // Normalise.
8213 if ($addr === null) {
8214 return false;
8216 $addrparts = explode(':', $addr);
8218 $ipv6 = strpos($addr, ':');
8220 foreach ($subnets as $subnet) {
8221 $subnet = trim($subnet);
8222 if ($subnet === '') {
8223 continue;
8226 if (strpos($subnet, '/') !== false) {
8227 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8228 list($ip, $mask) = explode('/', $subnet);
8229 $mask = trim($mask);
8230 if (!is_number($mask)) {
8231 continue; // Incorect mask number, eh?
8233 $ip = cleanremoteaddr($ip, false); // Normalise.
8234 if ($ip === null) {
8235 continue;
8237 if (strpos($ip, ':') !== false) {
8238 // IPv6.
8239 if (!$ipv6) {
8240 continue;
8242 if ($mask > 128 or $mask < 0) {
8243 continue; // Nonsense.
8245 if ($mask == 0) {
8246 return true; // Any address.
8248 if ($mask == 128) {
8249 if ($ip === $addr) {
8250 return true;
8252 continue;
8254 $ipparts = explode(':', $ip);
8255 $modulo = $mask % 16;
8256 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8257 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8258 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8259 if ($modulo == 0) {
8260 return true;
8262 $pos = ($mask-$modulo)/16;
8263 $ipnet = hexdec($ipparts[$pos]);
8264 $addrnet = hexdec($addrparts[$pos]);
8265 $mask = 0xffff << (16 - $modulo);
8266 if (($addrnet & $mask) == ($ipnet & $mask)) {
8267 return true;
8271 } else {
8272 // IPv4.
8273 if ($ipv6) {
8274 continue;
8276 if ($mask > 32 or $mask < 0) {
8277 continue; // Nonsense.
8279 if ($mask == 0) {
8280 return true;
8282 if ($mask == 32) {
8283 if ($ip === $addr) {
8284 return true;
8286 continue;
8288 $mask = 0xffffffff << (32 - $mask);
8289 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8290 return true;
8294 } else if (strpos($subnet, '-') !== false) {
8295 // 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.
8296 $parts = explode('-', $subnet);
8297 if (count($parts) != 2) {
8298 continue;
8301 if (strpos($subnet, ':') !== false) {
8302 // IPv6.
8303 if (!$ipv6) {
8304 continue;
8306 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8307 if ($ipstart === null) {
8308 continue;
8310 $ipparts = explode(':', $ipstart);
8311 $start = hexdec(array_pop($ipparts));
8312 $ipparts[] = trim($parts[1]);
8313 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8314 if ($ipend === null) {
8315 continue;
8317 $ipparts[7] = '';
8318 $ipnet = implode(':', $ipparts);
8319 if (strpos($addr, $ipnet) !== 0) {
8320 continue;
8322 $ipparts = explode(':', $ipend);
8323 $end = hexdec($ipparts[7]);
8325 $addrend = hexdec($addrparts[7]);
8327 if (($addrend >= $start) and ($addrend <= $end)) {
8328 return true;
8331 } else {
8332 // IPv4.
8333 if ($ipv6) {
8334 continue;
8336 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8337 if ($ipstart === null) {
8338 continue;
8340 $ipparts = explode('.', $ipstart);
8341 $ipparts[3] = trim($parts[1]);
8342 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8343 if ($ipend === null) {
8344 continue;
8347 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8348 return true;
8352 } else {
8353 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8354 if (strpos($subnet, ':') !== false) {
8355 // IPv6.
8356 if (!$ipv6) {
8357 continue;
8359 $parts = explode(':', $subnet);
8360 $count = count($parts);
8361 if ($parts[$count-1] === '') {
8362 unset($parts[$count-1]); // Trim trailing :'s.
8363 $count--;
8364 $subnet = implode('.', $parts);
8366 $isip = cleanremoteaddr($subnet, false); // Normalise.
8367 if ($isip !== null) {
8368 if ($isip === $addr) {
8369 return true;
8371 continue;
8372 } else if ($count > 8) {
8373 continue;
8375 $zeros = array_fill(0, 8-$count, '0');
8376 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8377 if (address_in_subnet($addr, $subnet)) {
8378 return true;
8381 } else {
8382 // IPv4.
8383 if ($ipv6) {
8384 continue;
8386 $parts = explode('.', $subnet);
8387 $count = count($parts);
8388 if ($parts[$count-1] === '') {
8389 unset($parts[$count-1]); // Trim trailing .
8390 $count--;
8391 $subnet = implode('.', $parts);
8393 if ($count == 4) {
8394 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8395 if ($subnet === $addr) {
8396 return true;
8398 continue;
8399 } else if ($count > 4) {
8400 continue;
8402 $zeros = array_fill(0, 4-$count, '0');
8403 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8404 if (address_in_subnet($addr, $subnet)) {
8405 return true;
8411 return false;
8415 * For outputting debugging info
8417 * @param string $string The string to write
8418 * @param string $eol The end of line char(s) to use
8419 * @param string $sleep Period to make the application sleep
8420 * This ensures any messages have time to display before redirect
8422 function mtrace($string, $eol="\n", $sleep=0) {
8424 if (defined('STDOUT') and !PHPUNIT_TEST) {
8425 fwrite(STDOUT, $string.$eol);
8426 } else {
8427 echo $string . $eol;
8430 flush();
8432 // Delay to keep message on user's screen in case of subsequent redirect.
8433 if ($sleep) {
8434 sleep($sleep);
8439 * Replace 1 or more slashes or backslashes to 1 slash
8441 * @param string $path The path to strip
8442 * @return string the path with double slashes removed
8444 function cleardoubleslashes ($path) {
8445 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8449 * Is current ip in give list?
8451 * @param string $list
8452 * @return bool
8454 function remoteip_in_list($list) {
8455 $inlist = false;
8456 $clientip = getremoteaddr(null);
8458 if (!$clientip) {
8459 // Ensure access on cli.
8460 return true;
8463 $list = explode("\n", $list);
8464 foreach ($list as $subnet) {
8465 $subnet = trim($subnet);
8466 if (address_in_subnet($clientip, $subnet)) {
8467 $inlist = true;
8468 break;
8471 return $inlist;
8475 * Returns most reliable client address
8477 * @param string $default If an address can't be determined, then return this
8478 * @return string The remote IP address
8480 function getremoteaddr($default='0.0.0.0') {
8481 global $CFG;
8483 if (empty($CFG->getremoteaddrconf)) {
8484 // This will happen, for example, before just after the upgrade, as the
8485 // user is redirected to the admin screen.
8486 $variablestoskip = 0;
8487 } else {
8488 $variablestoskip = $CFG->getremoteaddrconf;
8490 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8491 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8492 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8493 return $address ? $address : $default;
8496 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8497 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8498 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8499 $address = $forwardedaddresses[0];
8501 if (substr_count($address, ":") > 1) {
8502 // Remove port and brackets from IPv6.
8503 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8504 $address = $matches[1];
8506 } else {
8507 // Remove port from IPv4.
8508 if (substr_count($address, ":") == 1) {
8509 $parts = explode(":", $address);
8510 $address = $parts[0];
8514 $address = cleanremoteaddr($address);
8515 return $address ? $address : $default;
8518 if (!empty($_SERVER['REMOTE_ADDR'])) {
8519 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8520 return $address ? $address : $default;
8521 } else {
8522 return $default;
8527 * Cleans an ip address. Internal addresses are now allowed.
8528 * (Originally local addresses were not allowed.)
8530 * @param string $addr IPv4 or IPv6 address
8531 * @param bool $compress use IPv6 address compression
8532 * @return string normalised ip address string, null if error
8534 function cleanremoteaddr($addr, $compress=false) {
8535 $addr = trim($addr);
8537 // TODO: maybe add a separate function is_addr_public() or something like this.
8539 if (strpos($addr, ':') !== false) {
8540 // Can be only IPv6.
8541 $parts = explode(':', $addr);
8542 $count = count($parts);
8544 if (strpos($parts[$count-1], '.') !== false) {
8545 // Legacy ipv4 notation.
8546 $last = array_pop($parts);
8547 $ipv4 = cleanremoteaddr($last, true);
8548 if ($ipv4 === null) {
8549 return null;
8551 $bits = explode('.', $ipv4);
8552 $parts[] = dechex($bits[0]).dechex($bits[1]);
8553 $parts[] = dechex($bits[2]).dechex($bits[3]);
8554 $count = count($parts);
8555 $addr = implode(':', $parts);
8558 if ($count < 3 or $count > 8) {
8559 return null; // Severly malformed.
8562 if ($count != 8) {
8563 if (strpos($addr, '::') === false) {
8564 return null; // Malformed.
8566 // Uncompress.
8567 $insertat = array_search('', $parts, true);
8568 $missing = array_fill(0, 1 + 8 - $count, '0');
8569 array_splice($parts, $insertat, 1, $missing);
8570 foreach ($parts as $key => $part) {
8571 if ($part === '') {
8572 $parts[$key] = '0';
8577 $adr = implode(':', $parts);
8578 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8579 return null; // Incorrect format - sorry.
8582 // Normalise 0s and case.
8583 $parts = array_map('hexdec', $parts);
8584 $parts = array_map('dechex', $parts);
8586 $result = implode(':', $parts);
8588 if (!$compress) {
8589 return $result;
8592 if ($result === '0:0:0:0:0:0:0:0') {
8593 return '::'; // All addresses.
8596 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8597 if ($compressed !== $result) {
8598 return $compressed;
8601 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8602 if ($compressed !== $result) {
8603 return $compressed;
8606 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8607 if ($compressed !== $result) {
8608 return $compressed;
8611 return $result;
8614 // First get all things that look like IPv4 addresses.
8615 $parts = array();
8616 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8617 return null;
8619 unset($parts[0]);
8621 foreach ($parts as $key => $match) {
8622 if ($match > 255) {
8623 return null;
8625 $parts[$key] = (int)$match; // Normalise 0s.
8628 return implode('.', $parts);
8632 * This function will make a complete copy of anything it's given,
8633 * regardless of whether it's an object or not.
8635 * @param mixed $thing Something you want cloned
8636 * @return mixed What ever it is you passed it
8638 function fullclone($thing) {
8639 return unserialize(serialize($thing));
8643 * If new messages are waiting for the current user, then insert
8644 * JavaScript to pop up the messaging window into the page
8646 * @return void
8648 function message_popup_window() {
8649 global $USER, $DB, $PAGE, $CFG;
8651 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
8652 return;
8655 if (!isloggedin() || isguestuser()) {
8656 return;
8659 if (!isset($USER->message_lastpopup)) {
8660 $USER->message_lastpopup = 0;
8661 } else if ($USER->message_lastpopup > (time()-120)) {
8662 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8663 return;
8666 // A quick query to check whether the user has new messages.
8667 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
8668 if ($messagecount < 1) {
8669 return;
8672 // There are unread messages so now do a more complex but slower query.
8673 $messagesql = "SELECT m.id, c.blocked
8674 FROM {message} m
8675 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8676 JOIN {message_processors} p ON mw.processorid=p.id
8677 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8678 AND c.userid = m.useridto
8679 WHERE m.useridto = :userid
8680 AND p.name='popup'";
8682 // If the user was last notified over an hour ago we can re-notify them of old messages
8683 // so don't worry about when the new message was sent.
8684 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
8685 if (!$lastnotifiedlongago) {
8686 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8689 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
8691 $validmessages = 0;
8692 foreach ($waitingmessages as $messageinfo) {
8693 if ($messageinfo->blocked) {
8694 // Message is from a user who has since been blocked so just mark it read.
8695 // Get the full message to mark as read.
8696 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id));
8697 message_mark_message_read($messageobject, time());
8698 } else {
8699 $validmessages++;
8703 if ($validmessages > 0) {
8704 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8705 $strgomessage = get_string('gotomessages', 'message');
8706 $strstaymessage = get_string('ignore', 'admin');
8708 $notificationsound = null;
8709 $beep = get_user_preferences('message_beepnewmessage', '');
8710 if (!empty($beep)) {
8711 // Browsers will work down this list until they find something they support.
8712 $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
8713 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
8714 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8715 $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8717 $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8720 $url = $CFG->wwwroot.'/message/index.php';
8721 $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8722 html_writer::start_tag('div', array('id' => 'newmessagetext')).
8723 $strmessages.
8724 html_writer::end_tag('div').
8726 $notificationsound.
8727 html_writer::start_tag('div', array('id' => 'newmessagelinks')).
8728 html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
8729 html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
8730 html_writer::end_tag('div');
8731 html_writer::end_tag('div');
8733 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
8735 $USER->message_lastpopup = time();
8740 * Used to make sure that $min <= $value <= $max
8742 * Make sure that value is between min, and max
8744 * @param int $min The minimum value
8745 * @param int $value The value to check
8746 * @param int $max The maximum value
8747 * @return int
8749 function bounded_number($min, $value, $max) {
8750 if ($value < $min) {
8751 return $min;
8753 if ($value > $max) {
8754 return $max;
8756 return $value;
8760 * Check if there is a nested array within the passed array
8762 * @param array $array
8763 * @return bool true if there is a nested array false otherwise
8765 function array_is_nested($array) {
8766 foreach ($array as $value) {
8767 if (is_array($value)) {
8768 return true;
8771 return false;
8775 * get_performance_info() pairs up with init_performance_info()
8776 * loaded in setup.php. Returns an array with 'html' and 'txt'
8777 * values ready for use, and each of the individual stats provided
8778 * separately as well.
8780 * @return array
8782 function get_performance_info() {
8783 global $CFG, $PERF, $DB, $PAGE;
8785 $info = array();
8786 $info['html'] = ''; // Holds userfriendly HTML representation.
8787 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8789 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8791 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8792 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8794 if (function_exists('memory_get_usage')) {
8795 $info['memory_total'] = memory_get_usage();
8796 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8797 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8798 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8799 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8802 if (function_exists('memory_get_peak_usage')) {
8803 $info['memory_peak'] = memory_get_peak_usage();
8804 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8805 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8808 $inc = get_included_files();
8809 $info['includecount'] = count($inc);
8810 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8811 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8813 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8814 // We can not track more performance before installation or before PAGE init, sorry.
8815 return $info;
8818 $filtermanager = filter_manager::instance();
8819 if (method_exists($filtermanager, 'get_performance_summary')) {
8820 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8821 $info = array_merge($filterinfo, $info);
8822 foreach ($filterinfo as $key => $value) {
8823 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8824 $info['txt'] .= "$key: $value ";
8828 $stringmanager = get_string_manager();
8829 if (method_exists($stringmanager, 'get_performance_summary')) {
8830 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8831 $info = array_merge($filterinfo, $info);
8832 foreach ($filterinfo as $key => $value) {
8833 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8834 $info['txt'] .= "$key: $value ";
8838 if (!empty($PERF->logwrites)) {
8839 $info['logwrites'] = $PERF->logwrites;
8840 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8841 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8844 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
8845 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
8846 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8848 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
8849 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
8850 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
8852 if (function_exists('posix_times')) {
8853 $ptimes = posix_times();
8854 if (is_array($ptimes)) {
8855 foreach ($ptimes as $key => $val) {
8856 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
8858 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
8859 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8863 // Grab the load average for the last minute.
8864 // /proc will only work under some linux configurations
8865 // while uptime is there under MacOSX/Darwin and other unices.
8866 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
8867 list($serverload) = explode(' ', $loadavg[0]);
8868 unset($loadavg);
8869 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
8870 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
8871 $serverload = $matches[1];
8872 } else {
8873 trigger_error('Could not parse uptime output!');
8876 if (!empty($serverload)) {
8877 $info['serverload'] = $serverload;
8878 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
8879 $info['txt'] .= "serverload: {$info['serverload']} ";
8882 // Display size of session if session started.
8883 if ($si = \core\session\manager::get_performance_info()) {
8884 $info['sessionsize'] = $si['size'];
8885 $info['html'] .= $si['html'];
8886 $info['txt'] .= $si['txt'];
8889 if ($stats = cache_helper::get_stats()) {
8890 $html = '<span class="cachesused">';
8891 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
8892 $text = 'Caches used (hits/misses/sets): ';
8893 $hits = 0;
8894 $misses = 0;
8895 $sets = 0;
8896 foreach ($stats as $definition => $details) {
8897 switch ($details['mode']) {
8898 case cache_store::MODE_APPLICATION:
8899 $modeclass = 'application';
8900 $mode = ' <span title="application cache">[a]</span>';
8901 break;
8902 case cache_store::MODE_SESSION:
8903 $modeclass = 'session';
8904 $mode = ' <span title="session cache">[s]</span>';
8905 break;
8906 case cache_store::MODE_REQUEST:
8907 $modeclass = 'request';
8908 $mode = ' <span title="request cache">[r]</span>';
8909 break;
8911 $html .= '<span class="cache-definition-stats cache-mode-'.$modeclass.'">';
8912 $html .= '<span class="cache-definition-stats-heading">'.$definition.$mode.'</span>';
8913 $text .= "$definition {";
8914 foreach ($details['stores'] as $store => $data) {
8915 $hits += $data['hits'];
8916 $misses += $data['misses'];
8917 $sets += $data['sets'];
8918 if ($data['hits'] == 0 and $data['misses'] > 0) {
8919 $cachestoreclass = 'nohits';
8920 } else if ($data['hits'] < $data['misses']) {
8921 $cachestoreclass = 'lowhits';
8922 } else {
8923 $cachestoreclass = 'hihits';
8925 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
8926 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
8928 $html .= '</span>';
8929 $text .= '} ';
8931 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
8932 $html .= '</span> ';
8933 $info['cachesused'] = "$hits / $misses / $sets";
8934 $info['html'] .= $html;
8935 $info['txt'] .= $text.'. ';
8936 } else {
8937 $info['cachesused'] = '0 / 0 / 0';
8938 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
8939 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
8942 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
8943 return $info;
8947 * Legacy function.
8949 * @todo Document this function linux people
8951 function apd_get_profiling() {
8952 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
8956 * Delete directory or only its content
8958 * @param string $dir directory path
8959 * @param bool $contentonly
8960 * @return bool success, true also if dir does not exist
8962 function remove_dir($dir, $contentonly=false) {
8963 if (!file_exists($dir)) {
8964 // Nothing to do.
8965 return true;
8967 if (!$handle = opendir($dir)) {
8968 return false;
8970 $result = true;
8971 while (false!==($item = readdir($handle))) {
8972 if ($item != '.' && $item != '..') {
8973 if (is_dir($dir.'/'.$item)) {
8974 $result = remove_dir($dir.'/'.$item) && $result;
8975 } else {
8976 $result = unlink($dir.'/'.$item) && $result;
8980 closedir($handle);
8981 if ($contentonly) {
8982 clearstatcache(); // Make sure file stat cache is properly invalidated.
8983 return $result;
8985 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
8986 clearstatcache(); // Make sure file stat cache is properly invalidated.
8987 return $result;
8991 * Detect if an object or a class contains a given property
8992 * will take an actual object or the name of a class
8994 * @param mix $obj Name of class or real object to test
8995 * @param string $property name of property to find
8996 * @return bool true if property exists
8998 function object_property_exists( $obj, $property ) {
8999 if (is_string( $obj )) {
9000 $properties = get_class_vars( $obj );
9001 } else {
9002 $properties = get_object_vars( $obj );
9004 return array_key_exists( $property, $properties );
9008 * Converts an object into an associative array
9010 * This function converts an object into an associative array by iterating
9011 * over its public properties. Because this function uses the foreach
9012 * construct, Iterators are respected. It works recursively on arrays of objects.
9013 * Arrays and simple values are returned as is.
9015 * If class has magic properties, it can implement IteratorAggregate
9016 * and return all available properties in getIterator()
9018 * @param mixed $var
9019 * @return array
9021 function convert_to_array($var) {
9022 $result = array();
9024 // Loop over elements/properties.
9025 foreach ($var as $key => $value) {
9026 // Recursively convert objects.
9027 if (is_object($value) || is_array($value)) {
9028 $result[$key] = convert_to_array($value);
9029 } else {
9030 // Simple values are untouched.
9031 $result[$key] = $value;
9034 return $result;
9038 * Detect a custom script replacement in the data directory that will
9039 * replace an existing moodle script
9041 * @return string|bool full path name if a custom script exists, false if no custom script exists
9043 function custom_script_path() {
9044 global $CFG, $SCRIPT;
9046 if ($SCRIPT === null) {
9047 // Probably some weird external script.
9048 return false;
9051 $scriptpath = $CFG->customscripts . $SCRIPT;
9053 // Check the custom script exists.
9054 if (file_exists($scriptpath) and is_file($scriptpath)) {
9055 return $scriptpath;
9056 } else {
9057 return false;
9062 * Returns whether or not the user object is a remote MNET user. This function
9063 * is in moodlelib because it does not rely on loading any of the MNET code.
9065 * @param object $user A valid user object
9066 * @return bool True if the user is from a remote Moodle.
9068 function is_mnet_remote_user($user) {
9069 global $CFG;
9071 if (!isset($CFG->mnet_localhost_id)) {
9072 include_once($CFG->dirroot . '/mnet/lib.php');
9073 $env = new mnet_environment();
9074 $env->init();
9075 unset($env);
9078 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9082 * This function will search for browser prefereed languages, setting Moodle
9083 * to use the best one available if $SESSION->lang is undefined
9085 function setup_lang_from_browser() {
9086 global $CFG, $SESSION, $USER;
9088 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9089 // Lang is defined in session or user profile, nothing to do.
9090 return;
9093 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9094 return;
9097 // Extract and clean langs from headers.
9098 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9099 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9100 $rawlangs = explode(',', $rawlangs); // Convert to array.
9101 $langs = array();
9103 $order = 1.0;
9104 foreach ($rawlangs as $lang) {
9105 if (strpos($lang, ';') === false) {
9106 $langs[(string)$order] = $lang;
9107 $order = $order-0.01;
9108 } else {
9109 $parts = explode(';', $lang);
9110 $pos = strpos($parts[1], '=');
9111 $langs[substr($parts[1], $pos+1)] = $parts[0];
9114 krsort($langs, SORT_NUMERIC);
9116 // Look for such langs under standard locations.
9117 foreach ($langs as $lang) {
9118 // Clean it properly for include.
9119 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9120 if (get_string_manager()->translation_exists($lang, false)) {
9121 // Lang exists, set it in session.
9122 $SESSION->lang = $lang;
9123 // We have finished. Go out.
9124 break;
9127 return;
9131 * Check if $url matches anything in proxybypass list
9133 * Any errors just result in the proxy being used (least bad)
9135 * @param string $url url to check
9136 * @return boolean true if we should bypass the proxy
9138 function is_proxybypass( $url ) {
9139 global $CFG;
9141 // Sanity check.
9142 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9143 return false;
9146 // Get the host part out of the url.
9147 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9148 return false;
9151 // Get the possible bypass hosts into an array.
9152 $matches = explode( ',', $CFG->proxybypass );
9154 // Check for a match.
9155 // (IPs need to match the left hand side and hosts the right of the url,
9156 // but we can recklessly check both as there can't be a false +ve).
9157 foreach ($matches as $match) {
9158 $match = trim($match);
9160 // Try for IP match (Left side).
9161 $lhs = substr($host, 0, strlen($match));
9162 if (strcasecmp($match, $lhs)==0) {
9163 return true;
9166 // Try for host match (Right side).
9167 $rhs = substr($host, -strlen($match));
9168 if (strcasecmp($match, $rhs)==0) {
9169 return true;
9173 // Nothing matched.
9174 return false;
9178 * Check if the passed navigation is of the new style
9180 * @param mixed $navigation
9181 * @return bool true for yes false for no
9183 function is_newnav($navigation) {
9184 if (is_array($navigation) && !empty($navigation['newnav'])) {
9185 return true;
9186 } else {
9187 return false;
9192 * Checks whether the given variable name is defined as a variable within the given object.
9194 * This will NOT work with stdClass objects, which have no class variables.
9196 * @param string $var The variable name
9197 * @param object $object The object to check
9198 * @return boolean
9200 function in_object_vars($var, $object) {
9201 $classvars = get_class_vars(get_class($object));
9202 $classvars = array_keys($classvars);
9203 return in_array($var, $classvars);
9207 * Returns an array without repeated objects.
9208 * This function is similar to array_unique, but for arrays that have objects as values
9210 * @param array $array
9211 * @param bool $keepkeyassoc
9212 * @return array
9214 function object_array_unique($array, $keepkeyassoc = true) {
9215 $duplicatekeys = array();
9216 $tmp = array();
9218 foreach ($array as $key => $val) {
9219 // Convert objects to arrays, in_array() does not support objects.
9220 if (is_object($val)) {
9221 $val = (array)$val;
9224 if (!in_array($val, $tmp)) {
9225 $tmp[] = $val;
9226 } else {
9227 $duplicatekeys[] = $key;
9231 foreach ($duplicatekeys as $key) {
9232 unset($array[$key]);
9235 return $keepkeyassoc ? $array : array_values($array);
9239 * Is a userid the primary administrator?
9241 * @param int $userid int id of user to check
9242 * @return boolean
9244 function is_primary_admin($userid) {
9245 $primaryadmin = get_admin();
9247 if ($userid == $primaryadmin->id) {
9248 return true;
9249 } else {
9250 return false;
9255 * Returns the site identifier
9257 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9259 function get_site_identifier() {
9260 global $CFG;
9261 // Check to see if it is missing. If so, initialise it.
9262 if (empty($CFG->siteidentifier)) {
9263 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9265 // Return it.
9266 return $CFG->siteidentifier;
9270 * Check whether the given password has no more than the specified
9271 * number of consecutive identical characters.
9273 * @param string $password password to be checked against the password policy
9274 * @param integer $maxchars maximum number of consecutive identical characters
9275 * @return bool
9277 function check_consecutive_identical_characters($password, $maxchars) {
9279 if ($maxchars < 1) {
9280 return true; // Zero 0 is to disable this check.
9282 if (strlen($password) <= $maxchars) {
9283 return true; // Too short to fail this test.
9286 $previouschar = '';
9287 $consecutivecount = 1;
9288 foreach (str_split($password) as $char) {
9289 if ($char != $previouschar) {
9290 $consecutivecount = 1;
9291 } else {
9292 $consecutivecount++;
9293 if ($consecutivecount > $maxchars) {
9294 return false; // Check failed already.
9298 $previouschar = $char;
9301 return true;
9305 * Helper function to do partial function binding.
9306 * so we can use it for preg_replace_callback, for example
9307 * this works with php functions, user functions, static methods and class methods
9308 * it returns you a callback that you can pass on like so:
9310 * $callback = partial('somefunction', $arg1, $arg2);
9311 * or
9312 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9313 * or even
9314 * $obj = new someclass();
9315 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9317 * and then the arguments that are passed through at calltime are appended to the argument list.
9319 * @param mixed $function a php callback
9320 * @param mixed $arg1,... $argv arguments to partially bind with
9321 * @return array Array callback
9323 function partial() {
9324 if (!class_exists('partial')) {
9326 * Used to manage function binding.
9327 * @copyright 2009 Penny Leach
9328 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9330 class partial{
9331 /** @var array */
9332 public $values = array();
9333 /** @var string The function to call as a callback. */
9334 public $func;
9336 * Constructor
9337 * @param string $func
9338 * @param array $args
9340 public function __construct($func, $args) {
9341 $this->values = $args;
9342 $this->func = $func;
9345 * Calls the callback function.
9346 * @return mixed
9348 public function method() {
9349 $args = func_get_args();
9350 return call_user_func_array($this->func, array_merge($this->values, $args));
9354 $args = func_get_args();
9355 $func = array_shift($args);
9356 $p = new partial($func, $args);
9357 return array($p, 'method');
9361 * helper function to load up and initialise the mnet environment
9362 * this must be called before you use mnet functions.
9364 * @return mnet_environment the equivalent of old $MNET global
9366 function get_mnet_environment() {
9367 global $CFG;
9368 require_once($CFG->dirroot . '/mnet/lib.php');
9369 static $instance = null;
9370 if (empty($instance)) {
9371 $instance = new mnet_environment();
9372 $instance->init();
9374 return $instance;
9378 * during xmlrpc server code execution, any code wishing to access
9379 * information about the remote peer must use this to get it.
9381 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9383 function get_mnet_remote_client() {
9384 if (!defined('MNET_SERVER')) {
9385 debugging(get_string('notinxmlrpcserver', 'mnet'));
9386 return false;
9388 global $MNET_REMOTE_CLIENT;
9389 if (isset($MNET_REMOTE_CLIENT)) {
9390 return $MNET_REMOTE_CLIENT;
9392 return false;
9396 * during the xmlrpc server code execution, this will be called
9397 * to setup the object returned by {@link get_mnet_remote_client}
9399 * @param mnet_remote_client $client the client to set up
9400 * @throws moodle_exception
9402 function set_mnet_remote_client($client) {
9403 if (!defined('MNET_SERVER')) {
9404 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9406 global $MNET_REMOTE_CLIENT;
9407 $MNET_REMOTE_CLIENT = $client;
9411 * return the jump url for a given remote user
9412 * this is used for rewriting forum post links in emails, etc
9414 * @param stdclass $user the user to get the idp url for
9416 function mnet_get_idp_jump_url($user) {
9417 global $CFG;
9419 static $mnetjumps = array();
9420 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9421 $idp = mnet_get_peer_host($user->mnethostid);
9422 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9423 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9425 return $mnetjumps[$user->mnethostid];
9429 * Gets the homepage to use for the current user
9431 * @return int One of HOMEPAGE_*
9433 function get_home_page() {
9434 global $CFG;
9436 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9437 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9438 return HOMEPAGE_MY;
9439 } else {
9440 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9443 return HOMEPAGE_SITE;
9447 * Gets the name of a course to be displayed when showing a list of courses.
9448 * By default this is just $course->fullname but user can configure it. The
9449 * result of this function should be passed through print_string.
9450 * @param stdClass|course_in_list $course Moodle course object
9451 * @return string Display name of course (either fullname or short + fullname)
9453 function get_course_display_name_for_list($course) {
9454 global $CFG;
9455 if (!empty($CFG->courselistshortnames)) {
9456 if (!($course instanceof stdClass)) {
9457 $course = (object)convert_to_array($course);
9459 return get_string('courseextendednamedisplay', '', $course);
9460 } else {
9461 return $course->fullname;
9466 * The lang_string class
9468 * This special class is used to create an object representation of a string request.
9469 * It is special because processing doesn't occur until the object is first used.
9470 * The class was created especially to aid performance in areas where strings were
9471 * required to be generated but were not necessarily used.
9472 * As an example the admin tree when generated uses over 1500 strings, of which
9473 * normally only 1/3 are ever actually printed at any time.
9474 * The performance advantage is achieved by not actually processing strings that
9475 * arn't being used, as such reducing the processing required for the page.
9477 * How to use the lang_string class?
9478 * There are two methods of using the lang_string class, first through the
9479 * forth argument of the get_string function, and secondly directly.
9480 * The following are examples of both.
9481 * 1. Through get_string calls e.g.
9482 * $string = get_string($identifier, $component, $a, true);
9483 * $string = get_string('yes', 'moodle', null, true);
9484 * 2. Direct instantiation
9485 * $string = new lang_string($identifier, $component, $a, $lang);
9486 * $string = new lang_string('yes');
9488 * How do I use a lang_string object?
9489 * The lang_string object makes use of a magic __toString method so that you
9490 * are able to use the object exactly as you would use a string in most cases.
9491 * This means you are able to collect it into a variable and then directly
9492 * echo it, or concatenate it into another string, or similar.
9493 * The other thing you can do is manually get the string by calling the
9494 * lang_strings out method e.g.
9495 * $string = new lang_string('yes');
9496 * $string->out();
9497 * Also worth noting is that the out method can take one argument, $lang which
9498 * allows the developer to change the language on the fly.
9500 * When should I use a lang_string object?
9501 * The lang_string object is designed to be used in any situation where a
9502 * string may not be needed, but needs to be generated.
9503 * The admin tree is a good example of where lang_string objects should be
9504 * used.
9505 * A more practical example would be any class that requries strings that may
9506 * not be printed (after all classes get renderer by renderers and who knows
9507 * what they will do ;))
9509 * When should I not use a lang_string object?
9510 * Don't use lang_strings when you are going to use a string immediately.
9511 * There is no need as it will be processed immediately and there will be no
9512 * advantage, and in fact perhaps a negative hit as a class has to be
9513 * instantiated for a lang_string object, however get_string won't require
9514 * that.
9516 * Limitations:
9517 * 1. You cannot use a lang_string object as an array offset. Doing so will
9518 * result in PHP throwing an error. (You can use it as an object property!)
9520 * @package core
9521 * @category string
9522 * @copyright 2011 Sam Hemelryk
9523 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9525 class lang_string {
9527 /** @var string The strings identifier */
9528 protected $identifier;
9529 /** @var string The strings component. Default '' */
9530 protected $component = '';
9531 /** @var array|stdClass Any arguments required for the string. Default null */
9532 protected $a = null;
9533 /** @var string The language to use when processing the string. Default null */
9534 protected $lang = null;
9536 /** @var string The processed string (once processed) */
9537 protected $string = null;
9540 * A special boolean. If set to true then the object has been woken up and
9541 * cannot be regenerated. If this is set then $this->string MUST be used.
9542 * @var bool
9544 protected $forcedstring = false;
9547 * Constructs a lang_string object
9549 * This function should do as little processing as possible to ensure the best
9550 * performance for strings that won't be used.
9552 * @param string $identifier The strings identifier
9553 * @param string $component The strings component
9554 * @param stdClass|array $a Any arguments the string requires
9555 * @param string $lang The language to use when processing the string.
9556 * @throws coding_exception
9558 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9559 if (empty($component)) {
9560 $component = 'moodle';
9563 $this->identifier = $identifier;
9564 $this->component = $component;
9565 $this->lang = $lang;
9567 // We MUST duplicate $a to ensure that it if it changes by reference those
9568 // changes are not carried across.
9569 // To do this we always ensure $a or its properties/values are strings
9570 // and that any properties/values that arn't convertable are forgotten.
9571 if (!empty($a)) {
9572 if (is_scalar($a)) {
9573 $this->a = $a;
9574 } else if ($a instanceof lang_string) {
9575 $this->a = $a->out();
9576 } else if (is_object($a) or is_array($a)) {
9577 $a = (array)$a;
9578 $this->a = array();
9579 foreach ($a as $key => $value) {
9580 // Make sure conversion errors don't get displayed (results in '').
9581 if (is_array($value)) {
9582 $this->a[$key] = '';
9583 } else if (is_object($value)) {
9584 if (method_exists($value, '__toString')) {
9585 $this->a[$key] = $value->__toString();
9586 } else {
9587 $this->a[$key] = '';
9589 } else {
9590 $this->a[$key] = (string)$value;
9596 if (debugging(false, DEBUG_DEVELOPER)) {
9597 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9598 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9600 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9601 throw new coding_exception('Invalid string compontent. Please check your string definition');
9603 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9604 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9610 * Processes the string.
9612 * This function actually processes the string, stores it in the string property
9613 * and then returns it.
9614 * You will notice that this function is VERY similar to the get_string method.
9615 * That is because it is pretty much doing the same thing.
9616 * However as this function is an upgrade it isn't as tolerant to backwards
9617 * compatibility.
9619 * @return string
9620 * @throws coding_exception
9622 protected function get_string() {
9623 global $CFG;
9625 // Check if we need to process the string.
9626 if ($this->string === null) {
9627 // Check the quality of the identifier.
9628 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9629 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);
9632 // Process the string.
9633 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9634 // Debugging feature lets you display string identifier and component.
9635 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9636 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9639 // Return the string.
9640 return $this->string;
9644 * Returns the string
9646 * @param string $lang The langauge to use when processing the string
9647 * @return string
9649 public function out($lang = null) {
9650 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9651 if ($this->forcedstring) {
9652 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9653 return $this->get_string();
9655 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9656 return $translatedstring->out();
9658 return $this->get_string();
9662 * Magic __toString method for printing a string
9664 * @return string
9666 public function __toString() {
9667 return $this->get_string();
9671 * Magic __set_state method used for var_export
9673 * @return string
9675 public function __set_state() {
9676 return $this->get_string();
9680 * Prepares the lang_string for sleep and stores only the forcedstring and
9681 * string properties... the string cannot be regenerated so we need to ensure
9682 * it is generated for this.
9684 * @return string
9686 public function __sleep() {
9687 $this->get_string();
9688 $this->forcedstring = true;
9689 return array('forcedstring', 'string', 'lang');