Merge branch 'MDL-52763-30' of git://github.com/danpoltawski/moodle into MOODLE_30_STABLE
[moodle.git] / lib / moodlelib.php
blob7ca9188e2fb52485f4ecdd6197193fd512832061
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.'/tag/lib.php');
3905 require_once($CFG->dirroot.'/user/lib.php');
3907 // Make sure nobody sends bogus record type as parameter.
3908 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
3909 throw new coding_exception('Invalid $user parameter in delete_user() detected');
3912 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
3913 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
3914 debugging('Attempt to delete unknown user account.');
3915 return false;
3918 // There must be always exactly one guest record, originally the guest account was identified by username only,
3919 // now we use $CFG->siteguest for performance reasons.
3920 if ($user->username === 'guest' or isguestuser($user)) {
3921 debugging('Guest user account can not be deleted.');
3922 return false;
3925 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
3926 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
3927 if ($user->auth === 'manual' and is_siteadmin($user)) {
3928 debugging('Local administrator accounts can not be deleted.');
3929 return false;
3932 // Keep user record before updating it, as we have to pass this to user_deleted event.
3933 $olduser = clone $user;
3935 // Keep a copy of user context, we need it for event.
3936 $usercontext = context_user::instance($user->id);
3938 // Delete all grades - backup is kept in grade_grades_history table.
3939 grade_user_delete($user->id);
3941 // Move unread messages from this user to read.
3942 message_move_userfrom_unread2read($user->id);
3944 // TODO: remove from cohorts using standard API here.
3946 // Remove user tags.
3947 tag_set('user', $user->id, array(), 'core', $usercontext->id);
3949 // Unconditionally unenrol from all courses.
3950 enrol_user_delete($user);
3952 // Unenrol from all roles in all contexts.
3953 // This might be slow but it is really needed - modules might do some extra cleanup!
3954 role_unassign_all(array('userid' => $user->id));
3956 // Now do a brute force cleanup.
3958 // Remove from all cohorts.
3959 $DB->delete_records('cohort_members', array('userid' => $user->id));
3961 // Remove from all groups.
3962 $DB->delete_records('groups_members', array('userid' => $user->id));
3964 // Brute force unenrol from all courses.
3965 $DB->delete_records('user_enrolments', array('userid' => $user->id));
3967 // Purge user preferences.
3968 $DB->delete_records('user_preferences', array('userid' => $user->id));
3970 // Purge user extra profile info.
3971 $DB->delete_records('user_info_data', array('userid' => $user->id));
3973 // Purge log of previous password hashes.
3974 $DB->delete_records('user_password_history', array('userid' => $user->id));
3976 // Last course access not necessary either.
3977 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
3978 // Remove all user tokens.
3979 $DB->delete_records('external_tokens', array('userid' => $user->id));
3981 // Unauthorise the user for all services.
3982 $DB->delete_records('external_services_users', array('userid' => $user->id));
3984 // Remove users private keys.
3985 $DB->delete_records('user_private_key', array('userid' => $user->id));
3987 // Remove users customised pages.
3988 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
3990 // Force logout - may fail if file based sessions used, sorry.
3991 \core\session\manager::kill_user_sessions($user->id);
3993 // Generate username from email address, or a fake email.
3994 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
3995 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
3997 // Workaround for bulk deletes of users with the same email address.
3998 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
3999 $delname++;
4002 // Mark internal user record as "deleted".
4003 $updateuser = new stdClass();
4004 $updateuser->id = $user->id;
4005 $updateuser->deleted = 1;
4006 $updateuser->username = $delname; // Remember it just in case.
4007 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4008 $updateuser->idnumber = ''; // Clear this field to free it up.
4009 $updateuser->picture = 0;
4010 $updateuser->timemodified = time();
4012 // Don't trigger update event, as user is being deleted.
4013 user_update_user($updateuser, false, false);
4015 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4016 context_helper::delete_instance(CONTEXT_USER, $user->id);
4018 // Any plugin that needs to cleanup should register this event.
4019 // Trigger event.
4020 $event = \core\event\user_deleted::create(
4021 array(
4022 'objectid' => $user->id,
4023 'relateduserid' => $user->id,
4024 'context' => $usercontext,
4025 'other' => array(
4026 'username' => $user->username,
4027 'email' => $user->email,
4028 'idnumber' => $user->idnumber,
4029 'picture' => $user->picture,
4030 'mnethostid' => $user->mnethostid
4034 $event->add_record_snapshot('user', $olduser);
4035 $event->trigger();
4037 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4038 // should know about this updated property persisted to the user's table.
4039 $user->timemodified = $updateuser->timemodified;
4041 // Notify auth plugin - do not block the delete even when plugin fails.
4042 $authplugin = get_auth_plugin($user->auth);
4043 $authplugin->user_delete($user);
4045 return true;
4049 * Retrieve the guest user object.
4051 * @return stdClass A {@link $USER} object
4053 function guest_user() {
4054 global $CFG, $DB;
4056 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4057 $newuser->confirmed = 1;
4058 $newuser->lang = $CFG->lang;
4059 $newuser->lastip = getremoteaddr();
4062 return $newuser;
4066 * Authenticates a user against the chosen authentication mechanism
4068 * Given a username and password, this function looks them
4069 * up using the currently selected authentication mechanism,
4070 * and if the authentication is successful, it returns a
4071 * valid $user object from the 'user' table.
4073 * Uses auth_ functions from the currently active auth module
4075 * After authenticate_user_login() returns success, you will need to
4076 * log that the user has logged in, and call complete_user_login() to set
4077 * the session up.
4079 * Note: this function works only with non-mnet accounts!
4081 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4082 * @param string $password User's password
4083 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4084 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4085 * @return stdClass|false A {@link $USER} object or false if error
4087 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4088 global $CFG, $DB;
4089 require_once("$CFG->libdir/authlib.php");
4091 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4092 // we have found the user
4094 } else if (!empty($CFG->authloginviaemail)) {
4095 if ($email = clean_param($username, PARAM_EMAIL)) {
4096 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4097 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4098 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4099 if (count($users) === 1) {
4100 // Use email for login only if unique.
4101 $user = reset($users);
4102 $user = get_complete_user_data('id', $user->id);
4103 $username = $user->username;
4105 unset($users);
4109 $authsenabled = get_enabled_auth_plugins();
4111 if ($user) {
4112 // Use manual if auth not set.
4113 $auth = empty($user->auth) ? 'manual' : $user->auth;
4114 if (!empty($user->suspended)) {
4115 $failurereason = AUTH_LOGIN_SUSPENDED;
4117 // Trigger login failed event.
4118 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4119 'other' => array('username' => $username, 'reason' => $failurereason)));
4120 $event->trigger();
4121 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4122 return false;
4124 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4125 // Legacy way to suspend user.
4126 $failurereason = AUTH_LOGIN_SUSPENDED;
4128 // Trigger login failed event.
4129 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4130 'other' => array('username' => $username, 'reason' => $failurereason)));
4131 $event->trigger();
4132 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4133 return false;
4135 $auths = array($auth);
4137 } else {
4138 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4139 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4140 $failurereason = AUTH_LOGIN_NOUSER;
4142 // Trigger login failed event.
4143 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4144 'reason' => $failurereason)));
4145 $event->trigger();
4146 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4147 return false;
4150 // User does not exist.
4151 $auths = $authsenabled;
4152 $user = new stdClass();
4153 $user->id = 0;
4156 if ($ignorelockout) {
4157 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4158 // or this function is called from a SSO script.
4159 } else if ($user->id) {
4160 // Verify login lockout after other ways that may prevent user login.
4161 if (login_is_lockedout($user)) {
4162 $failurereason = AUTH_LOGIN_LOCKOUT;
4164 // Trigger login failed event.
4165 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4166 'other' => array('username' => $username, 'reason' => $failurereason)));
4167 $event->trigger();
4169 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4170 return false;
4172 } else {
4173 // We can not lockout non-existing accounts.
4176 foreach ($auths as $auth) {
4177 $authplugin = get_auth_plugin($auth);
4179 // On auth fail fall through to the next plugin.
4180 if (!$authplugin->user_login($username, $password)) {
4181 continue;
4184 // Successful authentication.
4185 if ($user->id) {
4186 // User already exists in database.
4187 if (empty($user->auth)) {
4188 // For some reason auth isn't set yet.
4189 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4190 $user->auth = $auth;
4193 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4194 // the current hash algorithm while we have access to the user's password.
4195 update_internal_user_password($user, $password);
4197 if ($authplugin->is_synchronised_with_external()) {
4198 // Update user record from external DB.
4199 $user = update_user_record_by_id($user->id);
4201 } else {
4202 // The user is authenticated but user creation may be disabled.
4203 if (!empty($CFG->authpreventaccountcreation)) {
4204 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4206 // Trigger login failed event.
4207 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4208 'reason' => $failurereason)));
4209 $event->trigger();
4211 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4212 $_SERVER['HTTP_USER_AGENT']);
4213 return false;
4214 } else {
4215 $user = create_user_record($username, $password, $auth);
4219 $authplugin->sync_roles($user);
4221 foreach ($authsenabled as $hau) {
4222 $hauth = get_auth_plugin($hau);
4223 $hauth->user_authenticated_hook($user, $username, $password);
4226 if (empty($user->id)) {
4227 $failurereason = AUTH_LOGIN_NOUSER;
4228 // Trigger login failed event.
4229 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4230 'reason' => $failurereason)));
4231 $event->trigger();
4232 return false;
4235 if (!empty($user->suspended)) {
4236 // Just in case some auth plugin suspended account.
4237 $failurereason = AUTH_LOGIN_SUSPENDED;
4238 // Trigger login failed event.
4239 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4240 'other' => array('username' => $username, 'reason' => $failurereason)));
4241 $event->trigger();
4242 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4243 return false;
4246 login_attempt_valid($user);
4247 $failurereason = AUTH_LOGIN_OK;
4248 return $user;
4251 // Failed if all the plugins have failed.
4252 if (debugging('', DEBUG_ALL)) {
4253 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4256 if ($user->id) {
4257 login_attempt_failed($user);
4258 $failurereason = AUTH_LOGIN_FAILED;
4259 // Trigger login failed event.
4260 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4261 'other' => array('username' => $username, 'reason' => $failurereason)));
4262 $event->trigger();
4263 } else {
4264 $failurereason = AUTH_LOGIN_NOUSER;
4265 // Trigger login failed event.
4266 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4267 'reason' => $failurereason)));
4268 $event->trigger();
4271 return false;
4275 * Call to complete the user login process after authenticate_user_login()
4276 * has succeeded. It will setup the $USER variable and other required bits
4277 * and pieces.
4279 * NOTE:
4280 * - It will NOT log anything -- up to the caller to decide what to log.
4281 * - this function does not set any cookies any more!
4283 * @param stdClass $user
4284 * @return stdClass A {@link $USER} object - BC only, do not use
4286 function complete_user_login($user) {
4287 global $CFG, $USER;
4289 \core\session\manager::login_user($user);
4291 // Reload preferences from DB.
4292 unset($USER->preference);
4293 check_user_preferences_loaded($USER);
4295 // Update login times.
4296 update_user_login_times();
4298 // Extra session prefs init.
4299 set_login_session_preferences();
4301 // Trigger login event.
4302 $event = \core\event\user_loggedin::create(
4303 array(
4304 'userid' => $USER->id,
4305 'objectid' => $USER->id,
4306 'other' => array('username' => $USER->username),
4309 $event->trigger();
4311 if (isguestuser()) {
4312 // No need to continue when user is THE guest.
4313 return $USER;
4316 if (CLI_SCRIPT) {
4317 // We can redirect to password change URL only in browser.
4318 return $USER;
4321 // Select password change url.
4322 $userauth = get_auth_plugin($USER->auth);
4324 // Check whether the user should be changing password.
4325 if (get_user_preferences('auth_forcepasswordchange', false)) {
4326 if ($userauth->can_change_password()) {
4327 if ($changeurl = $userauth->change_password_url()) {
4328 redirect($changeurl);
4329 } else {
4330 redirect($CFG->httpswwwroot.'/login/change_password.php');
4332 } else {
4333 print_error('nopasswordchangeforced', 'auth');
4336 return $USER;
4340 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4342 * @param string $password String to check.
4343 * @return boolean True if the $password matches the format of an md5 sum.
4345 function password_is_legacy_hash($password) {
4346 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4350 * Compare password against hash stored in user object to determine if it is valid.
4352 * If necessary it also updates the stored hash to the current format.
4354 * @param stdClass $user (Password property may be updated).
4355 * @param string $password Plain text password.
4356 * @return bool True if password is valid.
4358 function validate_internal_user_password($user, $password) {
4359 global $CFG;
4360 require_once($CFG->libdir.'/password_compat/lib/password.php');
4362 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4363 // Internal password is not used at all, it can not validate.
4364 return false;
4367 // If hash isn't a legacy (md5) hash, validate using the library function.
4368 if (!password_is_legacy_hash($user->password)) {
4369 return password_verify($password, $user->password);
4372 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4373 // is valid we can then update it to the new algorithm.
4375 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4376 $validated = false;
4378 if ($user->password === md5($password.$sitesalt)
4379 or $user->password === md5($password)
4380 or $user->password === md5(addslashes($password).$sitesalt)
4381 or $user->password === md5(addslashes($password))) {
4382 // Note: we are intentionally using the addslashes() here because we
4383 // need to accept old password hashes of passwords with magic quotes.
4384 $validated = true;
4386 } else {
4387 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4388 $alt = 'passwordsaltalt'.$i;
4389 if (!empty($CFG->$alt)) {
4390 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4391 $validated = true;
4392 break;
4398 if ($validated) {
4399 // If the password matches the existing md5 hash, update to the
4400 // current hash algorithm while we have access to the user's password.
4401 update_internal_user_password($user, $password);
4404 return $validated;
4408 * Calculate hash for a plain text password.
4410 * @param string $password Plain text password to be hashed.
4411 * @param bool $fasthash If true, use a low cost factor when generating the hash
4412 * This is much faster to generate but makes the hash
4413 * less secure. It is used when lots of hashes need to
4414 * be generated quickly.
4415 * @return string The hashed password.
4417 * @throws moodle_exception If a problem occurs while generating the hash.
4419 function hash_internal_user_password($password, $fasthash = false) {
4420 global $CFG;
4421 require_once($CFG->libdir.'/password_compat/lib/password.php');
4423 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4424 $options = ($fasthash) ? array('cost' => 4) : array();
4426 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4428 if ($generatedhash === false || $generatedhash === null) {
4429 throw new moodle_exception('Failed to generate password hash.');
4432 return $generatedhash;
4436 * Update password hash in user object (if necessary).
4438 * The password is updated if:
4439 * 1. The password has changed (the hash of $user->password is different
4440 * to the hash of $password).
4441 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4442 * md5 algorithm).
4444 * Updating the password will modify the $user object and the database
4445 * record to use the current hashing algorithm.
4447 * @param stdClass $user User object (password property may be updated).
4448 * @param string $password Plain text password.
4449 * @param bool $fasthash If true, use a low cost factor when generating the hash
4450 * This is much faster to generate but makes the hash
4451 * less secure. It is used when lots of hashes need to
4452 * be generated quickly.
4453 * @return bool Always returns true.
4455 function update_internal_user_password($user, $password, $fasthash = false) {
4456 global $CFG, $DB;
4457 require_once($CFG->libdir.'/password_compat/lib/password.php');
4459 // Figure out what the hashed password should be.
4460 if (!isset($user->auth)) {
4461 debugging('User record in update_internal_user_password() must include field auth',
4462 DEBUG_DEVELOPER);
4463 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4465 $authplugin = get_auth_plugin($user->auth);
4466 if ($authplugin->prevent_local_passwords()) {
4467 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4468 } else {
4469 $hashedpassword = hash_internal_user_password($password, $fasthash);
4472 $algorithmchanged = false;
4474 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4475 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4476 $passwordchanged = ($user->password !== $hashedpassword);
4478 } else if (isset($user->password)) {
4479 // If verification fails then it means the password has changed.
4480 $passwordchanged = !password_verify($password, $user->password);
4481 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4482 } else {
4483 // While creating new user, password in unset in $user object, to avoid
4484 // saving it with user_create()
4485 $passwordchanged = true;
4488 if ($passwordchanged || $algorithmchanged) {
4489 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4490 $user->password = $hashedpassword;
4492 // Trigger event.
4493 $user = $DB->get_record('user', array('id' => $user->id));
4494 \core\event\user_password_updated::create_from_user($user)->trigger();
4497 return true;
4501 * Get a complete user record, which includes all the info in the user record.
4503 * Intended for setting as $USER session variable
4505 * @param string $field The user field to be checked for a given value.
4506 * @param string $value The value to match for $field.
4507 * @param int $mnethostid
4508 * @return mixed False, or A {@link $USER} object.
4510 function get_complete_user_data($field, $value, $mnethostid = null) {
4511 global $CFG, $DB;
4513 if (!$field || !$value) {
4514 return false;
4517 // Build the WHERE clause for an SQL query.
4518 $params = array('fieldval' => $value);
4519 $constraints = "$field = :fieldval AND deleted <> 1";
4521 // If we are loading user data based on anything other than id,
4522 // we must also restrict our search based on mnet host.
4523 if ($field != 'id') {
4524 if (empty($mnethostid)) {
4525 // If empty, we restrict to local users.
4526 $mnethostid = $CFG->mnet_localhost_id;
4529 if (!empty($mnethostid)) {
4530 $params['mnethostid'] = $mnethostid;
4531 $constraints .= " AND mnethostid = :mnethostid";
4534 // Get all the basic user data.
4535 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4536 return false;
4539 // Get various settings and preferences.
4541 // Preload preference cache.
4542 check_user_preferences_loaded($user);
4544 // Load course enrolment related stuff.
4545 $user->lastcourseaccess = array(); // During last session.
4546 $user->currentcourseaccess = array(); // During current session.
4547 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4548 foreach ($lastaccesses as $lastaccess) {
4549 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4553 $sql = "SELECT g.id, g.courseid
4554 FROM {groups} g, {groups_members} gm
4555 WHERE gm.groupid=g.id AND gm.userid=?";
4557 // This is a special hack to speedup calendar display.
4558 $user->groupmember = array();
4559 if (!isguestuser($user)) {
4560 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4561 foreach ($groups as $group) {
4562 if (!array_key_exists($group->courseid, $user->groupmember)) {
4563 $user->groupmember[$group->courseid] = array();
4565 $user->groupmember[$group->courseid][$group->id] = $group->id;
4570 // Add the custom profile fields to the user record.
4571 $user->profile = array();
4572 if (!isguestuser($user)) {
4573 require_once($CFG->dirroot.'/user/profile/lib.php');
4574 profile_load_custom_fields($user);
4577 // Rewrite some variables if necessary.
4578 if (!empty($user->description)) {
4579 // No need to cart all of it around.
4580 $user->description = true;
4582 if (isguestuser($user)) {
4583 // Guest language always same as site.
4584 $user->lang = $CFG->lang;
4585 // Name always in current language.
4586 $user->firstname = get_string('guestuser');
4587 $user->lastname = ' ';
4590 return $user;
4594 * Validate a password against the configured password policy
4596 * @param string $password the password to be checked against the password policy
4597 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4598 * @return bool true if the password is valid according to the policy. false otherwise.
4600 function check_password_policy($password, &$errmsg) {
4601 global $CFG;
4603 if (empty($CFG->passwordpolicy)) {
4604 return true;
4607 $errmsg = '';
4608 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4609 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4612 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4613 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4616 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4617 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4620 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4621 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4624 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4625 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4627 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4628 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4631 if ($errmsg == '') {
4632 return true;
4633 } else {
4634 return false;
4640 * When logging in, this function is run to set certain preferences for the current SESSION.
4642 function set_login_session_preferences() {
4643 global $SESSION;
4645 $SESSION->justloggedin = true;
4647 unset($SESSION->lang);
4648 unset($SESSION->forcelang);
4649 unset($SESSION->load_navigation_admin);
4654 * Delete a course, including all related data from the database, and any associated files.
4656 * @param mixed $courseorid The id of the course or course object to delete.
4657 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4658 * @return bool true if all the removals succeeded. false if there were any failures. If this
4659 * method returns false, some of the removals will probably have succeeded, and others
4660 * failed, but you have no way of knowing which.
4662 function delete_course($courseorid, $showfeedback = true) {
4663 global $DB;
4665 if (is_object($courseorid)) {
4666 $courseid = $courseorid->id;
4667 $course = $courseorid;
4668 } else {
4669 $courseid = $courseorid;
4670 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4671 return false;
4674 $context = context_course::instance($courseid);
4676 // Frontpage course can not be deleted!!
4677 if ($courseid == SITEID) {
4678 return false;
4681 // Make the course completely empty.
4682 remove_course_contents($courseid, $showfeedback);
4684 // Delete the course and related context instance.
4685 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4687 $DB->delete_records("course", array("id" => $courseid));
4688 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4690 // Reset all course related caches here.
4691 if (class_exists('format_base', false)) {
4692 format_base::reset_course_cache($courseid);
4695 // Trigger a course deleted event.
4696 $event = \core\event\course_deleted::create(array(
4697 'objectid' => $course->id,
4698 'context' => $context,
4699 'other' => array(
4700 'shortname' => $course->shortname,
4701 'fullname' => $course->fullname,
4702 'idnumber' => $course->idnumber
4705 $event->add_record_snapshot('course', $course);
4706 $event->trigger();
4708 return true;
4712 * Clear a course out completely, deleting all content but don't delete the course itself.
4714 * This function does not verify any permissions.
4716 * Please note this function also deletes all user enrolments,
4717 * enrolment instances and role assignments by default.
4719 * $options:
4720 * - 'keep_roles_and_enrolments' - false by default
4721 * - 'keep_groups_and_groupings' - false by default
4723 * @param int $courseid The id of the course that is being deleted
4724 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4725 * @param array $options extra options
4726 * @return bool true if all the removals succeeded. false if there were any failures. If this
4727 * method returns false, some of the removals will probably have succeeded, and others
4728 * failed, but you have no way of knowing which.
4730 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4731 global $CFG, $DB, $OUTPUT;
4733 require_once($CFG->libdir.'/badgeslib.php');
4734 require_once($CFG->libdir.'/completionlib.php');
4735 require_once($CFG->libdir.'/questionlib.php');
4736 require_once($CFG->libdir.'/gradelib.php');
4737 require_once($CFG->dirroot.'/group/lib.php');
4738 require_once($CFG->dirroot.'/tag/lib.php');
4739 require_once($CFG->dirroot.'/comment/lib.php');
4740 require_once($CFG->dirroot.'/rating/lib.php');
4741 require_once($CFG->dirroot.'/notes/lib.php');
4743 // Handle course badges.
4744 badges_handle_course_deletion($courseid);
4746 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4747 $strdeleted = get_string('deleted').' - ';
4749 // Some crazy wishlist of stuff we should skip during purging of course content.
4750 $options = (array)$options;
4752 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4753 $coursecontext = context_course::instance($courseid);
4754 $fs = get_file_storage();
4756 // Delete course completion information, this has to be done before grades and enrols.
4757 $cc = new completion_info($course);
4758 $cc->clear_criteria();
4759 if ($showfeedback) {
4760 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4763 // Remove all data from gradebook - this needs to be done before course modules
4764 // because while deleting this information, the system may need to reference
4765 // the course modules that own the grades.
4766 remove_course_grades($courseid, $showfeedback);
4767 remove_grade_letters($coursecontext, $showfeedback);
4769 // Delete course blocks in any all child contexts,
4770 // they may depend on modules so delete them first.
4771 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4772 foreach ($childcontexts as $childcontext) {
4773 blocks_delete_all_for_context($childcontext->id);
4775 unset($childcontexts);
4776 blocks_delete_all_for_context($coursecontext->id);
4777 if ($showfeedback) {
4778 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4781 // Delete every instance of every module,
4782 // this has to be done before deleting of course level stuff.
4783 $locations = core_component::get_plugin_list('mod');
4784 foreach ($locations as $modname => $moddir) {
4785 if ($modname === 'NEWMODULE') {
4786 continue;
4788 if ($module = $DB->get_record('modules', array('name' => $modname))) {
4789 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
4790 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
4791 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
4793 if ($instances = $DB->get_records($modname, array('course' => $course->id))) {
4794 foreach ($instances as $instance) {
4795 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
4796 // Delete activity context questions and question categories.
4797 question_delete_activity($cm, $showfeedback);
4799 if (function_exists($moddelete)) {
4800 // This purges all module data in related tables, extra user prefs, settings, etc.
4801 $moddelete($instance->id);
4802 } else {
4803 // NOTE: we should not allow installation of modules with missing delete support!
4804 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4805 $DB->delete_records($modname, array('id' => $instance->id));
4808 if ($cm) {
4809 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
4810 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4811 $DB->delete_records('course_modules', array('id' => $cm->id));
4815 if (function_exists($moddeletecourse)) {
4816 // Execute ptional course cleanup callback.
4817 $moddeletecourse($course, $showfeedback);
4819 if ($instances and $showfeedback) {
4820 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4822 } else {
4823 // Ooops, this module is not properly installed, force-delete it in the next block.
4827 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
4829 // Remove all data from availability and completion tables that is associated
4830 // with course-modules belonging to this course. Note this is done even if the
4831 // features are not enabled now, in case they were enabled previously.
4832 $DB->delete_records_select('course_modules_completion',
4833 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4834 array($courseid));
4836 // Remove course-module data.
4837 $cms = $DB->get_records('course_modules', array('course' => $course->id));
4838 foreach ($cms as $cm) {
4839 if ($module = $DB->get_record('modules', array('id' => $cm->module))) {
4840 try {
4841 $DB->delete_records($module->name, array('id' => $cm->instance));
4842 } catch (Exception $e) {
4843 // Ignore weird or missing table problems.
4846 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4847 $DB->delete_records('course_modules', array('id' => $cm->id));
4850 if ($showfeedback) {
4851 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
4854 // Cleanup the rest of plugins.
4855 $cleanuplugintypes = array('report', 'coursereport', 'format');
4856 $callbacks = get_plugins_with_function('delete_course', 'lib.php');
4857 foreach ($cleanuplugintypes as $type) {
4858 if (!empty($callbacks[$type])) {
4859 foreach ($callbacks[$type] as $pluginfunction) {
4860 $pluginfunction($course->id, $showfeedback);
4863 if ($showfeedback) {
4864 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
4868 // Delete questions and question categories.
4869 question_delete_course($course, $showfeedback);
4870 if ($showfeedback) {
4871 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
4874 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
4875 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4876 foreach ($childcontexts as $childcontext) {
4877 $childcontext->delete();
4879 unset($childcontexts);
4881 // Remove all roles and enrolments by default.
4882 if (empty($options['keep_roles_and_enrolments'])) {
4883 // This hack is used in restore when deleting contents of existing course.
4884 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
4885 enrol_course_delete($course);
4886 if ($showfeedback) {
4887 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
4891 // Delete any groups, removing members and grouping/course links first.
4892 if (empty($options['keep_groups_and_groupings'])) {
4893 groups_delete_groupings($course->id, $showfeedback);
4894 groups_delete_groups($course->id, $showfeedback);
4897 // Filters be gone!
4898 filter_delete_all_for_context($coursecontext->id);
4900 // Notes, you shall not pass!
4901 note_delete_all($course->id);
4903 // Die comments!
4904 comment::delete_comments($coursecontext->id);
4906 // Ratings are history too.
4907 $delopt = new stdclass();
4908 $delopt->contextid = $coursecontext->id;
4909 $rm = new rating_manager();
4910 $rm->delete_ratings($delopt);
4912 // Delete course tags.
4913 tag_set('course', $course->id, array(), 'core', $coursecontext->id);
4915 // Delete calendar events.
4916 $DB->delete_records('event', array('courseid' => $course->id));
4917 $fs->delete_area_files($coursecontext->id, 'calendar');
4919 // Delete all related records in other core tables that may have a courseid
4920 // This array stores the tables that need to be cleared, as
4921 // table_name => column_name that contains the course id.
4922 $tablestoclear = array(
4923 'backup_courses' => 'courseid', // Scheduled backup stuff.
4924 'user_lastaccess' => 'courseid', // User access info.
4926 foreach ($tablestoclear as $table => $col) {
4927 $DB->delete_records($table, array($col => $course->id));
4930 // Delete all course backup files.
4931 $fs->delete_area_files($coursecontext->id, 'backup');
4933 // Cleanup course record - remove links to deleted stuff.
4934 $oldcourse = new stdClass();
4935 $oldcourse->id = $course->id;
4936 $oldcourse->summary = '';
4937 $oldcourse->cacherev = 0;
4938 $oldcourse->legacyfiles = 0;
4939 if (!empty($options['keep_groups_and_groupings'])) {
4940 $oldcourse->defaultgroupingid = 0;
4942 $DB->update_record('course', $oldcourse);
4944 // Delete course sections.
4945 $DB->delete_records('course_sections', array('course' => $course->id));
4947 // Delete legacy, section and any other course files.
4948 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
4950 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
4951 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
4952 // Easy, do not delete the context itself...
4953 $coursecontext->delete_content();
4954 } else {
4955 // Hack alert!!!!
4956 // We can not drop all context stuff because it would bork enrolments and roles,
4957 // there might be also files used by enrol plugins...
4960 // Delete legacy files - just in case some files are still left there after conversion to new file api,
4961 // also some non-standard unsupported plugins may try to store something there.
4962 fulldelete($CFG->dataroot.'/'.$course->id);
4964 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
4965 $cachemodinfo = cache::make('core', 'coursemodinfo');
4966 $cachemodinfo->delete($courseid);
4968 // Trigger a course content deleted event.
4969 $event = \core\event\course_content_deleted::create(array(
4970 'objectid' => $course->id,
4971 'context' => $coursecontext,
4972 'other' => array('shortname' => $course->shortname,
4973 'fullname' => $course->fullname,
4974 'options' => $options) // Passing this for legacy reasons.
4976 $event->add_record_snapshot('course', $course);
4977 $event->trigger();
4979 return true;
4983 * Change dates in module - used from course reset.
4985 * @param string $modname forum, assignment, etc
4986 * @param array $fields array of date fields from mod table
4987 * @param int $timeshift time difference
4988 * @param int $courseid
4989 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
4990 * @return bool success
4992 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
4993 global $CFG, $DB;
4994 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
4996 $return = true;
4997 $params = array($timeshift, $courseid);
4998 foreach ($fields as $field) {
4999 $updatesql = "UPDATE {".$modname."}
5000 SET $field = $field + ?
5001 WHERE course=? AND $field<>0";
5002 if ($modid) {
5003 $updatesql .= ' AND id=?';
5004 $params[] = $modid;
5006 $return = $DB->execute($updatesql, $params) && $return;
5009 $refreshfunction = $modname.'_refresh_events';
5010 if (function_exists($refreshfunction)) {
5011 $refreshfunction($courseid);
5014 return $return;
5018 * This function will empty a course of user data.
5019 * It will retain the activities and the structure of the course.
5021 * @param object $data an object containing all the settings including courseid (without magic quotes)
5022 * @return array status array of array component, item, error
5024 function reset_course_userdata($data) {
5025 global $CFG, $DB;
5026 require_once($CFG->libdir.'/gradelib.php');
5027 require_once($CFG->libdir.'/completionlib.php');
5028 require_once($CFG->dirroot.'/group/lib.php');
5030 $data->courseid = $data->id;
5031 $context = context_course::instance($data->courseid);
5033 $eventparams = array(
5034 'context' => $context,
5035 'courseid' => $data->id,
5036 'other' => array(
5037 'reset_options' => (array) $data
5040 $event = \core\event\course_reset_started::create($eventparams);
5041 $event->trigger();
5043 // Calculate the time shift of dates.
5044 if (!empty($data->reset_start_date)) {
5045 // Time part of course startdate should be zero.
5046 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5047 } else {
5048 $data->timeshift = 0;
5051 // Result array: component, item, error.
5052 $status = array();
5054 // Start the resetting.
5055 $componentstr = get_string('general');
5057 // Move the course start time.
5058 if (!empty($data->reset_start_date) and $data->timeshift) {
5059 // Change course start data.
5060 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5061 // Update all course and group events - do not move activity events.
5062 $updatesql = "UPDATE {event}
5063 SET timestart = timestart + ?
5064 WHERE courseid=? AND instance=0";
5065 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5067 // Update any date activity restrictions.
5068 if ($CFG->enableavailability) {
5069 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5072 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5075 if (!empty($data->reset_events)) {
5076 $DB->delete_records('event', array('courseid' => $data->courseid));
5077 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5080 if (!empty($data->reset_notes)) {
5081 require_once($CFG->dirroot.'/notes/lib.php');
5082 note_delete_all($data->courseid);
5083 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5086 if (!empty($data->delete_blog_associations)) {
5087 require_once($CFG->dirroot.'/blog/lib.php');
5088 blog_remove_associations_for_course($data->courseid);
5089 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5092 if (!empty($data->reset_completion)) {
5093 // Delete course and activity completion information.
5094 $course = $DB->get_record('course', array('id' => $data->courseid));
5095 $cc = new completion_info($course);
5096 $cc->delete_all_completion_data();
5097 $status[] = array('component' => $componentstr,
5098 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5101 $componentstr = get_string('roles');
5103 if (!empty($data->reset_roles_overrides)) {
5104 $children = $context->get_child_contexts();
5105 foreach ($children as $child) {
5106 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5108 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5109 // Force refresh for logged in users.
5110 $context->mark_dirty();
5111 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5114 if (!empty($data->reset_roles_local)) {
5115 $children = $context->get_child_contexts();
5116 foreach ($children as $child) {
5117 role_unassign_all(array('contextid' => $child->id));
5119 // Force refresh for logged in users.
5120 $context->mark_dirty();
5121 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5124 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5125 $data->unenrolled = array();
5126 if (!empty($data->unenrol_users)) {
5127 $plugins = enrol_get_plugins(true);
5128 $instances = enrol_get_instances($data->courseid, true);
5129 foreach ($instances as $key => $instance) {
5130 if (!isset($plugins[$instance->enrol])) {
5131 unset($instances[$key]);
5132 continue;
5136 foreach ($data->unenrol_users as $withroleid) {
5137 if ($withroleid) {
5138 $sql = "SELECT ue.*
5139 FROM {user_enrolments} ue
5140 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5141 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5142 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5143 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5145 } else {
5146 // Without any role assigned at course context.
5147 $sql = "SELECT ue.*
5148 FROM {user_enrolments} ue
5149 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5150 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5151 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5152 WHERE ra.id IS null";
5153 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5156 $rs = $DB->get_recordset_sql($sql, $params);
5157 foreach ($rs as $ue) {
5158 if (!isset($instances[$ue->enrolid])) {
5159 continue;
5161 $instance = $instances[$ue->enrolid];
5162 $plugin = $plugins[$instance->enrol];
5163 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5164 continue;
5167 $plugin->unenrol_user($instance, $ue->userid);
5168 $data->unenrolled[$ue->userid] = $ue->userid;
5170 $rs->close();
5173 if (!empty($data->unenrolled)) {
5174 $status[] = array(
5175 'component' => $componentstr,
5176 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5177 'error' => false
5181 $componentstr = get_string('groups');
5183 // Remove all group members.
5184 if (!empty($data->reset_groups_members)) {
5185 groups_delete_group_members($data->courseid);
5186 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5189 // Remove all groups.
5190 if (!empty($data->reset_groups_remove)) {
5191 groups_delete_groups($data->courseid, false);
5192 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5195 // Remove all grouping members.
5196 if (!empty($data->reset_groupings_members)) {
5197 groups_delete_groupings_groups($data->courseid, false);
5198 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5201 // Remove all groupings.
5202 if (!empty($data->reset_groupings_remove)) {
5203 groups_delete_groupings($data->courseid, false);
5204 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5207 // Look in every instance of every module for data to delete.
5208 $unsupportedmods = array();
5209 if ($allmods = $DB->get_records('modules') ) {
5210 foreach ($allmods as $mod) {
5211 $modname = $mod->name;
5212 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5213 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5214 if (file_exists($modfile)) {
5215 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5216 continue; // Skip mods with no instances.
5218 include_once($modfile);
5219 if (function_exists($moddeleteuserdata)) {
5220 $modstatus = $moddeleteuserdata($data);
5221 if (is_array($modstatus)) {
5222 $status = array_merge($status, $modstatus);
5223 } else {
5224 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5226 } else {
5227 $unsupportedmods[] = $mod;
5229 } else {
5230 debugging('Missing lib.php in '.$modname.' module!');
5235 // Mention unsupported mods.
5236 if (!empty($unsupportedmods)) {
5237 foreach ($unsupportedmods as $mod) {
5238 $status[] = array(
5239 'component' => get_string('modulenameplural', $mod->name),
5240 'item' => '',
5241 'error' => get_string('resetnotimplemented')
5246 $componentstr = get_string('gradebook', 'grades');
5247 // Reset gradebook,.
5248 if (!empty($data->reset_gradebook_items)) {
5249 remove_course_grades($data->courseid, false);
5250 grade_grab_course_grades($data->courseid);
5251 grade_regrade_final_grades($data->courseid);
5252 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5254 } else if (!empty($data->reset_gradebook_grades)) {
5255 grade_course_reset($data->courseid);
5256 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5258 // Reset comments.
5259 if (!empty($data->reset_comments)) {
5260 require_once($CFG->dirroot.'/comment/lib.php');
5261 comment::reset_course_page_comments($context);
5264 $event = \core\event\course_reset_ended::create($eventparams);
5265 $event->trigger();
5267 return $status;
5271 * Generate an email processing address.
5273 * @param int $modid
5274 * @param string $modargs
5275 * @return string Returns email processing address
5277 function generate_email_processing_address($modid, $modargs) {
5278 global $CFG;
5280 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5281 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5287 * @todo Finish documenting this function
5289 * @param string $modargs
5290 * @param string $body Currently unused
5292 function moodle_process_email($modargs, $body) {
5293 global $DB;
5295 // The first char should be an unencoded letter. We'll take this as an action.
5296 switch ($modargs{0}) {
5297 case 'B': { // Bounce.
5298 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5299 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5300 // Check the half md5 of their email.
5301 $md5check = substr(md5($user->email), 0, 16);
5302 if ($md5check == substr($modargs, -16)) {
5303 set_bounce_count($user);
5305 // Else maybe they've already changed it?
5308 break;
5309 // Maybe more later?
5313 // CORRESPONDENCE.
5316 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5318 * @param string $action 'get', 'buffer', 'close' or 'flush'
5319 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5321 function get_mailer($action='get') {
5322 global $CFG;
5324 /** @var moodle_phpmailer $mailer */
5325 static $mailer = null;
5326 static $counter = 0;
5328 if (!isset($CFG->smtpmaxbulk)) {
5329 $CFG->smtpmaxbulk = 1;
5332 if ($action == 'get') {
5333 $prevkeepalive = false;
5335 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5336 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5337 $counter++;
5338 // Reset the mailer.
5339 $mailer->Priority = 3;
5340 $mailer->CharSet = 'UTF-8'; // Our default.
5341 $mailer->ContentType = "text/plain";
5342 $mailer->Encoding = "8bit";
5343 $mailer->From = "root@localhost";
5344 $mailer->FromName = "Root User";
5345 $mailer->Sender = "";
5346 $mailer->Subject = "";
5347 $mailer->Body = "";
5348 $mailer->AltBody = "";
5349 $mailer->ConfirmReadingTo = "";
5351 $mailer->clearAllRecipients();
5352 $mailer->clearReplyTos();
5353 $mailer->clearAttachments();
5354 $mailer->clearCustomHeaders();
5355 return $mailer;
5358 $prevkeepalive = $mailer->SMTPKeepAlive;
5359 get_mailer('flush');
5362 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5363 $mailer = new moodle_phpmailer();
5365 $counter = 1;
5367 if ($CFG->smtphosts == 'qmail') {
5368 // Use Qmail system.
5369 $mailer->isQmail();
5371 } else if (empty($CFG->smtphosts)) {
5372 // Use PHP mail() = sendmail.
5373 $mailer->isMail();
5375 } else {
5376 // Use SMTP directly.
5377 $mailer->isSMTP();
5378 if (!empty($CFG->debugsmtp)) {
5379 $mailer->SMTPDebug = true;
5381 // Specify main and backup servers.
5382 $mailer->Host = $CFG->smtphosts;
5383 // Specify secure connection protocol.
5384 $mailer->SMTPSecure = $CFG->smtpsecure;
5385 // Use previous keepalive.
5386 $mailer->SMTPKeepAlive = $prevkeepalive;
5388 if ($CFG->smtpuser) {
5389 // Use SMTP authentication.
5390 $mailer->SMTPAuth = true;
5391 $mailer->Username = $CFG->smtpuser;
5392 $mailer->Password = $CFG->smtppass;
5396 return $mailer;
5399 $nothing = null;
5401 // Keep smtp session open after sending.
5402 if ($action == 'buffer') {
5403 if (!empty($CFG->smtpmaxbulk)) {
5404 get_mailer('flush');
5405 $m = get_mailer();
5406 if ($m->Mailer == 'smtp') {
5407 $m->SMTPKeepAlive = true;
5410 return $nothing;
5413 // Close smtp session, but continue buffering.
5414 if ($action == 'flush') {
5415 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5416 if (!empty($mailer->SMTPDebug)) {
5417 echo '<pre>'."\n";
5419 $mailer->SmtpClose();
5420 if (!empty($mailer->SMTPDebug)) {
5421 echo '</pre>';
5424 return $nothing;
5427 // Close smtp session, do not buffer anymore.
5428 if ($action == 'close') {
5429 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5430 get_mailer('flush');
5431 $mailer->SMTPKeepAlive = false;
5433 $mailer = null; // Better force new instance.
5434 return $nothing;
5439 * Send an email to a specified user
5441 * @param stdClass $user A {@link $USER} object
5442 * @param stdClass $from A {@link $USER} object
5443 * @param string $subject plain text subject line of the email
5444 * @param string $messagetext plain text version of the message
5445 * @param string $messagehtml complete html version of the message (optional)
5446 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5447 * @param string $attachname the name of the file (extension indicates MIME)
5448 * @param bool $usetrueaddress determines whether $from email address should
5449 * be sent out. Will be overruled by user profile setting for maildisplay
5450 * @param string $replyto Email address to reply to
5451 * @param string $replytoname Name of reply to recipient
5452 * @param int $wordwrapwidth custom word wrap width, default 79
5453 * @return bool Returns true if mail was sent OK and false if there was an error.
5455 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5456 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5458 global $CFG;
5460 if (empty($user) or empty($user->id)) {
5461 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5462 return false;
5465 if (empty($user->email)) {
5466 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5467 return false;
5470 if (!empty($user->deleted)) {
5471 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5472 return false;
5475 if (defined('BEHAT_SITE_RUNNING')) {
5476 // Fake email sending in behat.
5477 return true;
5480 if (!empty($CFG->noemailever)) {
5481 // Hidden setting for development sites, set in config.php if needed.
5482 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5483 return true;
5486 if (!empty($CFG->divertallemailsto)) {
5487 $subject = "[DIVERTED {$user->email}] $subject";
5488 $user = clone($user);
5489 $user->email = $CFG->divertallemailsto;
5492 // Skip mail to suspended users.
5493 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5494 return true;
5497 if (!validate_email($user->email)) {
5498 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5499 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5500 return false;
5503 if (over_bounce_threshold($user)) {
5504 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5505 return false;
5508 // TLD .invalid is specifically reserved for invalid domain names.
5509 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5510 if (substr($user->email, -8) == '.invalid') {
5511 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5512 return true; // This is not an error.
5515 // If the user is a remote mnet user, parse the email text for URL to the
5516 // wwwroot and modify the url to direct the user's browser to login at their
5517 // home site (identity provider - idp) before hitting the link itself.
5518 if (is_mnet_remote_user($user)) {
5519 require_once($CFG->dirroot.'/mnet/lib.php');
5521 $jumpurl = mnet_get_idp_jump_url($user);
5522 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5524 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5525 $callback,
5526 $messagetext);
5527 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5528 $callback,
5529 $messagehtml);
5531 $mail = get_mailer();
5533 if (!empty($mail->SMTPDebug)) {
5534 echo '<pre>' . "\n";
5537 $temprecipients = array();
5538 $tempreplyto = array();
5540 $supportuser = core_user::get_support_user();
5542 // Make up an email address for handling bounces.
5543 if (!empty($CFG->handlebounces)) {
5544 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5545 $mail->Sender = generate_email_processing_address(0, $modargs);
5546 } else {
5547 $mail->Sender = $supportuser->email;
5550 if (!empty($CFG->emailonlyfromnoreplyaddress)) {
5551 $usetrueaddress = false;
5552 if (empty($replyto) && $from->maildisplay) {
5553 $replyto = $from->email;
5554 $replytoname = fullname($from);
5558 if (is_string($from)) { // So we can pass whatever we want if there is need.
5559 $mail->From = $CFG->noreplyaddress;
5560 $mail->FromName = $from;
5561 } else if ($usetrueaddress and $from->maildisplay) {
5562 $mail->From = $from->email;
5563 $mail->FromName = fullname($from);
5564 } else {
5565 $mail->From = $CFG->noreplyaddress;
5566 $mail->FromName = fullname($from);
5567 if (empty($replyto)) {
5568 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5572 if (!empty($replyto)) {
5573 $tempreplyto[] = array($replyto, $replytoname);
5576 $mail->Subject = substr($subject, 0, 900);
5578 $temprecipients[] = array($user->email, fullname($user));
5580 // Set word wrap.
5581 $mail->WordWrap = $wordwrapwidth;
5583 if (!empty($from->customheaders)) {
5584 // Add custom headers.
5585 if (is_array($from->customheaders)) {
5586 foreach ($from->customheaders as $customheader) {
5587 $mail->addCustomHeader($customheader);
5589 } else {
5590 $mail->addCustomHeader($from->customheaders);
5594 if (!empty($from->priority)) {
5595 $mail->Priority = $from->priority;
5598 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5599 // Don't ever send HTML to users who don't want it.
5600 $mail->isHTML(true);
5601 $mail->Encoding = 'quoted-printable';
5602 $mail->Body = $messagehtml;
5603 $mail->AltBody = "\n$messagetext\n";
5604 } else {
5605 $mail->IsHTML(false);
5606 $mail->Body = "\n$messagetext\n";
5609 if ($attachment && $attachname) {
5610 if (preg_match( "~\\.\\.~" , $attachment )) {
5611 // Security check for ".." in dir path.
5612 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5613 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5614 } else {
5615 require_once($CFG->libdir.'/filelib.php');
5616 $mimetype = mimeinfo('type', $attachname);
5618 $attachmentpath = $attachment;
5620 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5621 $attachpath = str_replace('\\', '/', $attachmentpath);
5622 // Make sure both variables are normalised before comparing.
5623 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
5625 // If the attachment is a full path to a file in the tempdir, use it as is,
5626 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5627 if (strpos($attachpath, $temppath) !== 0) {
5628 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5631 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5635 // Check if the email should be sent in an other charset then the default UTF-8.
5636 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5638 // Use the defined site mail charset or eventually the one preferred by the recipient.
5639 $charset = $CFG->sitemailcharset;
5640 if (!empty($CFG->allowusermailcharset)) {
5641 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5642 $charset = $useremailcharset;
5646 // Convert all the necessary strings if the charset is supported.
5647 $charsets = get_list_of_charsets();
5648 unset($charsets['UTF-8']);
5649 if (in_array($charset, $charsets)) {
5650 $mail->CharSet = $charset;
5651 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5652 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5653 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5654 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5656 foreach ($temprecipients as $key => $values) {
5657 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5659 foreach ($tempreplyto as $key => $values) {
5660 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5665 foreach ($temprecipients as $values) {
5666 $mail->addAddress($values[0], $values[1]);
5668 foreach ($tempreplyto as $values) {
5669 $mail->addReplyTo($values[0], $values[1]);
5672 if ($mail->send()) {
5673 set_send_count($user);
5674 if (!empty($mail->SMTPDebug)) {
5675 echo '</pre>';
5677 return true;
5678 } else {
5679 // Trigger event for failing to send email.
5680 $event = \core\event\email_failed::create(array(
5681 'context' => context_system::instance(),
5682 'userid' => $from->id,
5683 'relateduserid' => $user->id,
5684 'other' => array(
5685 'subject' => $subject,
5686 'message' => $messagetext,
5687 'errorinfo' => $mail->ErrorInfo
5690 $event->trigger();
5691 if (CLI_SCRIPT) {
5692 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5694 if (!empty($mail->SMTPDebug)) {
5695 echo '</pre>';
5697 return false;
5702 * Generate a signoff for emails based on support settings
5704 * @return string
5706 function generate_email_signoff() {
5707 global $CFG;
5709 $signoff = "\n";
5710 if (!empty($CFG->supportname)) {
5711 $signoff .= $CFG->supportname."\n";
5713 if (!empty($CFG->supportemail)) {
5714 $signoff .= $CFG->supportemail."\n";
5716 if (!empty($CFG->supportpage)) {
5717 $signoff .= $CFG->supportpage."\n";
5719 return $signoff;
5723 * Sets specified user's password and send the new password to the user via email.
5725 * @param stdClass $user A {@link $USER} object
5726 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
5727 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
5729 function setnew_password_and_mail($user, $fasthash = false) {
5730 global $CFG, $DB;
5732 // We try to send the mail in language the user understands,
5733 // unfortunately the filter_string() does not support alternative langs yet
5734 // so multilang will not work properly for site->fullname.
5735 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
5737 $site = get_site();
5739 $supportuser = core_user::get_support_user();
5741 $newpassword = generate_password();
5743 update_internal_user_password($user, $newpassword, $fasthash);
5745 $a = new stdClass();
5746 $a->firstname = fullname($user, true);
5747 $a->sitename = format_string($site->fullname);
5748 $a->username = $user->username;
5749 $a->newpassword = $newpassword;
5750 $a->link = $CFG->wwwroot .'/login/';
5751 $a->signoff = generate_email_signoff();
5753 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
5755 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
5757 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5758 return email_to_user($user, $supportuser, $subject, $message);
5763 * Resets specified user's password and send the new password to the user via email.
5765 * @param stdClass $user A {@link $USER} object
5766 * @return bool Returns true if mail was sent OK and false if there was an error.
5768 function reset_password_and_mail($user) {
5769 global $CFG;
5771 $site = get_site();
5772 $supportuser = core_user::get_support_user();
5774 $userauth = get_auth_plugin($user->auth);
5775 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
5776 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
5777 return false;
5780 $newpassword = generate_password();
5782 if (!$userauth->user_update_password($user, $newpassword)) {
5783 print_error("cannotsetpassword");
5786 $a = new stdClass();
5787 $a->firstname = $user->firstname;
5788 $a->lastname = $user->lastname;
5789 $a->sitename = format_string($site->fullname);
5790 $a->username = $user->username;
5791 $a->newpassword = $newpassword;
5792 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
5793 $a->signoff = generate_email_signoff();
5795 $message = get_string('newpasswordtext', '', $a);
5797 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
5799 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
5801 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5802 return email_to_user($user, $supportuser, $subject, $message);
5806 * Send email to specified user with confirmation text and activation link.
5808 * @param stdClass $user A {@link $USER} object
5809 * @return bool Returns true if mail was sent OK and false if there was an error.
5811 function send_confirmation_email($user) {
5812 global $CFG;
5814 $site = get_site();
5815 $supportuser = core_user::get_support_user();
5817 $data = new stdClass();
5818 $data->firstname = fullname($user);
5819 $data->sitename = format_string($site->fullname);
5820 $data->admin = generate_email_signoff();
5822 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
5824 $username = urlencode($user->username);
5825 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
5826 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
5827 $message = get_string('emailconfirmation', '', $data);
5828 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
5830 $user->mailformat = 1; // Always send HTML version as well.
5832 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5833 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
5837 * Sends a password change confirmation email.
5839 * @param stdClass $user A {@link $USER} object
5840 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
5841 * @return bool Returns true if mail was sent OK and false if there was an error.
5843 function send_password_change_confirmation_email($user, $resetrecord) {
5844 global $CFG;
5846 $site = get_site();
5847 $supportuser = core_user::get_support_user();
5848 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
5850 $data = new stdClass();
5851 $data->firstname = $user->firstname;
5852 $data->lastname = $user->lastname;
5853 $data->username = $user->username;
5854 $data->sitename = format_string($site->fullname);
5855 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
5856 $data->admin = generate_email_signoff();
5857 $data->resetminutes = $pwresetmins;
5859 $message = get_string('emailresetconfirmation', '', $data);
5860 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
5862 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5863 return email_to_user($user, $supportuser, $subject, $message);
5868 * Sends an email containinginformation on how to change your password.
5870 * @param stdClass $user A {@link $USER} object
5871 * @return bool Returns true if mail was sent OK and false if there was an error.
5873 function send_password_change_info($user) {
5874 global $CFG;
5876 $site = get_site();
5877 $supportuser = core_user::get_support_user();
5878 $systemcontext = context_system::instance();
5880 $data = new stdClass();
5881 $data->firstname = $user->firstname;
5882 $data->lastname = $user->lastname;
5883 $data->sitename = format_string($site->fullname);
5884 $data->admin = generate_email_signoff();
5886 $userauth = get_auth_plugin($user->auth);
5888 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
5889 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
5890 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5891 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5892 return email_to_user($user, $supportuser, $subject, $message);
5895 if ($userauth->can_change_password() and $userauth->change_password_url()) {
5896 // We have some external url for password changing.
5897 $data->link .= $userauth->change_password_url();
5899 } else {
5900 // No way to change password, sorry.
5901 $data->link = '';
5904 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
5905 $message = get_string('emailpasswordchangeinfo', '', $data);
5906 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5907 } else {
5908 $message = get_string('emailpasswordchangeinfofail', '', $data);
5909 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5912 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5913 return email_to_user($user, $supportuser, $subject, $message);
5918 * Check that an email is allowed. It returns an error message if there was a problem.
5920 * @param string $email Content of email
5921 * @return string|false
5923 function email_is_not_allowed($email) {
5924 global $CFG;
5926 if (!empty($CFG->allowemailaddresses)) {
5927 $allowed = explode(' ', $CFG->allowemailaddresses);
5928 foreach ($allowed as $allowedpattern) {
5929 $allowedpattern = trim($allowedpattern);
5930 if (!$allowedpattern) {
5931 continue;
5933 if (strpos($allowedpattern, '.') === 0) {
5934 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
5935 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
5936 return false;
5939 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
5940 return false;
5943 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
5945 } else if (!empty($CFG->denyemailaddresses)) {
5946 $denied = explode(' ', $CFG->denyemailaddresses);
5947 foreach ($denied as $deniedpattern) {
5948 $deniedpattern = trim($deniedpattern);
5949 if (!$deniedpattern) {
5950 continue;
5952 if (strpos($deniedpattern, '.') === 0) {
5953 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
5954 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
5955 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
5958 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
5959 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
5964 return false;
5967 // FILE HANDLING.
5970 * Returns local file storage instance
5972 * @return file_storage
5974 function get_file_storage() {
5975 global $CFG;
5977 static $fs = null;
5979 if ($fs) {
5980 return $fs;
5983 require_once("$CFG->libdir/filelib.php");
5985 if (isset($CFG->filedir)) {
5986 $filedir = $CFG->filedir;
5987 } else {
5988 $filedir = $CFG->dataroot.'/filedir';
5991 if (isset($CFG->trashdir)) {
5992 $trashdirdir = $CFG->trashdir;
5993 } else {
5994 $trashdirdir = $CFG->dataroot.'/trashdir';
5997 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
5999 return $fs;
6003 * Returns local file storage instance
6005 * @return file_browser
6007 function get_file_browser() {
6008 global $CFG;
6010 static $fb = null;
6012 if ($fb) {
6013 return $fb;
6016 require_once("$CFG->libdir/filelib.php");
6018 $fb = new file_browser();
6020 return $fb;
6024 * Returns file packer
6026 * @param string $mimetype default application/zip
6027 * @return file_packer
6029 function get_file_packer($mimetype='application/zip') {
6030 global $CFG;
6032 static $fp = array();
6034 if (isset($fp[$mimetype])) {
6035 return $fp[$mimetype];
6038 switch ($mimetype) {
6039 case 'application/zip':
6040 case 'application/vnd.moodle.profiling':
6041 $classname = 'zip_packer';
6042 break;
6044 case 'application/x-gzip' :
6045 $classname = 'tgz_packer';
6046 break;
6048 case 'application/vnd.moodle.backup':
6049 $classname = 'mbz_packer';
6050 break;
6052 default:
6053 return false;
6056 require_once("$CFG->libdir/filestorage/$classname.php");
6057 $fp[$mimetype] = new $classname();
6059 return $fp[$mimetype];
6063 * Returns current name of file on disk if it exists.
6065 * @param string $newfile File to be verified
6066 * @return string Current name of file on disk if true
6068 function valid_uploaded_file($newfile) {
6069 if (empty($newfile)) {
6070 return '';
6072 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6073 return $newfile['tmp_name'];
6074 } else {
6075 return '';
6080 * Returns the maximum size for uploading files.
6082 * There are seven possible upload limits:
6083 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6084 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6085 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6086 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6087 * 5. by the Moodle admin in $CFG->maxbytes
6088 * 6. by the teacher in the current course $course->maxbytes
6089 * 7. by the teacher for the current module, eg $assignment->maxbytes
6091 * These last two are passed to this function as arguments (in bytes).
6092 * Anything defined as 0 is ignored.
6093 * The smallest of all the non-zero numbers is returned.
6095 * @todo Finish documenting this function
6097 * @param int $sitebytes Set maximum size
6098 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6099 * @param int $modulebytes Current module ->maxbytes (in bytes)
6100 * @return int The maximum size for uploading files.
6102 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6104 if (! $filesize = ini_get('upload_max_filesize')) {
6105 $filesize = '5M';
6107 $minimumsize = get_real_size($filesize);
6109 if ($postsize = ini_get('post_max_size')) {
6110 $postsize = get_real_size($postsize);
6111 if ($postsize < $minimumsize) {
6112 $minimumsize = $postsize;
6116 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6117 $minimumsize = $sitebytes;
6120 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6121 $minimumsize = $coursebytes;
6124 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6125 $minimumsize = $modulebytes;
6128 return $minimumsize;
6132 * Returns the maximum size for uploading files for the current user
6134 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6136 * @param context $context The context in which to check user capabilities
6137 * @param int $sitebytes Set maximum size
6138 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6139 * @param int $modulebytes Current module ->maxbytes (in bytes)
6140 * @param stdClass $user The user
6141 * @return int The maximum size for uploading files.
6143 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6144 global $USER;
6146 if (empty($user)) {
6147 $user = $USER;
6150 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6151 return get_max_upload_file_size(USER_CAN_IGNORE_FILE_SIZE_LIMITS);
6154 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6158 * Returns an array of possible sizes in local language
6160 * Related to {@link get_max_upload_file_size()} - this function returns an
6161 * array of possible sizes in an array, translated to the
6162 * local language.
6164 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6166 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6167 * with the value set to 0. This option will be the first in the list.
6169 * @uses SORT_NUMERIC
6170 * @param int $sitebytes Set maximum size
6171 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6172 * @param int $modulebytes Current module ->maxbytes (in bytes)
6173 * @param int|array $custombytes custom upload size/s which will be added to list,
6174 * Only value/s smaller then maxsize will be added to list.
6175 * @return array
6177 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6178 global $CFG;
6180 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6181 return array();
6184 if ($sitebytes == 0) {
6185 // Will get the minimum of upload_max_filesize or post_max_size.
6186 $sitebytes = get_max_upload_file_size();
6189 $filesize = array();
6190 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6191 5242880, 10485760, 20971520, 52428800, 104857600);
6193 // If custombytes is given and is valid then add it to the list.
6194 if (is_number($custombytes) and $custombytes > 0) {
6195 $custombytes = (int)$custombytes;
6196 if (!in_array($custombytes, $sizelist)) {
6197 $sizelist[] = $custombytes;
6199 } else if (is_array($custombytes)) {
6200 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6203 // Allow maxbytes to be selected if it falls outside the above boundaries.
6204 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6205 // Note: get_real_size() is used in order to prevent problems with invalid values.
6206 $sizelist[] = get_real_size($CFG->maxbytes);
6209 foreach ($sizelist as $sizebytes) {
6210 if ($sizebytes < $maxsize && $sizebytes > 0) {
6211 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6215 $limitlevel = '';
6216 $displaysize = '';
6217 if ($modulebytes &&
6218 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6219 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6220 $limitlevel = get_string('activity', 'core');
6221 $displaysize = display_size($modulebytes);
6222 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6224 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6225 $limitlevel = get_string('course', 'core');
6226 $displaysize = display_size($coursebytes);
6227 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6229 } else if ($sitebytes) {
6230 $limitlevel = get_string('site', 'core');
6231 $displaysize = display_size($sitebytes);
6232 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6235 krsort($filesize, SORT_NUMERIC);
6236 if ($limitlevel) {
6237 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6238 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6241 return $filesize;
6245 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6247 * If excludefiles is defined, then that file/directory is ignored
6248 * If getdirs is true, then (sub)directories are included in the output
6249 * If getfiles is true, then files are included in the output
6250 * (at least one of these must be true!)
6252 * @todo Finish documenting this function. Add examples of $excludefile usage.
6254 * @param string $rootdir A given root directory to start from
6255 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6256 * @param bool $descend If true then subdirectories are recursed as well
6257 * @param bool $getdirs If true then (sub)directories are included in the output
6258 * @param bool $getfiles If true then files are included in the output
6259 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6261 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6263 $dirs = array();
6265 if (!$getdirs and !$getfiles) { // Nothing to show.
6266 return $dirs;
6269 if (!is_dir($rootdir)) { // Must be a directory.
6270 return $dirs;
6273 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6274 return $dirs;
6277 if (!is_array($excludefiles)) {
6278 $excludefiles = array($excludefiles);
6281 while (false !== ($file = readdir($dir))) {
6282 $firstchar = substr($file, 0, 1);
6283 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6284 continue;
6286 $fullfile = $rootdir .'/'. $file;
6287 if (filetype($fullfile) == 'dir') {
6288 if ($getdirs) {
6289 $dirs[] = $file;
6291 if ($descend) {
6292 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6293 foreach ($subdirs as $subdir) {
6294 $dirs[] = $file .'/'. $subdir;
6297 } else if ($getfiles) {
6298 $dirs[] = $file;
6301 closedir($dir);
6303 asort($dirs);
6305 return $dirs;
6310 * Adds up all the files in a directory and works out the size.
6312 * @param string $rootdir The directory to start from
6313 * @param string $excludefile A file to exclude when summing directory size
6314 * @return int The summed size of all files and subfiles within the root directory
6316 function get_directory_size($rootdir, $excludefile='') {
6317 global $CFG;
6319 // Do it this way if we can, it's much faster.
6320 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6321 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6322 $output = null;
6323 $return = null;
6324 exec($command, $output, $return);
6325 if (is_array($output)) {
6326 // We told it to return k.
6327 return get_real_size(intval($output[0]).'k');
6331 if (!is_dir($rootdir)) {
6332 // Must be a directory.
6333 return 0;
6336 if (!$dir = @opendir($rootdir)) {
6337 // Can't open it for some reason.
6338 return 0;
6341 $size = 0;
6343 while (false !== ($file = readdir($dir))) {
6344 $firstchar = substr($file, 0, 1);
6345 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6346 continue;
6348 $fullfile = $rootdir .'/'. $file;
6349 if (filetype($fullfile) == 'dir') {
6350 $size += get_directory_size($fullfile, $excludefile);
6351 } else {
6352 $size += filesize($fullfile);
6355 closedir($dir);
6357 return $size;
6361 * Converts bytes into display form
6363 * @static string $gb Localized string for size in gigabytes
6364 * @static string $mb Localized string for size in megabytes
6365 * @static string $kb Localized string for size in kilobytes
6366 * @static string $b Localized string for size in bytes
6367 * @param int $size The size to convert to human readable form
6368 * @return string
6370 function display_size($size) {
6372 static $gb, $mb, $kb, $b;
6374 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6375 return get_string('unlimited');
6378 if (empty($gb)) {
6379 $gb = get_string('sizegb');
6380 $mb = get_string('sizemb');
6381 $kb = get_string('sizekb');
6382 $b = get_string('sizeb');
6385 if ($size >= 1073741824) {
6386 $size = round($size / 1073741824 * 10) / 10 . $gb;
6387 } else if ($size >= 1048576) {
6388 $size = round($size / 1048576 * 10) / 10 . $mb;
6389 } else if ($size >= 1024) {
6390 $size = round($size / 1024 * 10) / 10 . $kb;
6391 } else {
6392 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6394 return $size;
6398 * Cleans a given filename by removing suspicious or troublesome characters
6400 * @see clean_param()
6401 * @param string $string file name
6402 * @return string cleaned file name
6404 function clean_filename($string) {
6405 return clean_param($string, PARAM_FILE);
6409 // STRING TRANSLATION.
6412 * Returns the code for the current language
6414 * @category string
6415 * @return string
6417 function current_language() {
6418 global $CFG, $USER, $SESSION, $COURSE;
6420 if (!empty($SESSION->forcelang)) {
6421 // Allows overriding course-forced language (useful for admins to check
6422 // issues in courses whose language they don't understand).
6423 // Also used by some code to temporarily get language-related information in a
6424 // specific language (see force_current_language()).
6425 $return = $SESSION->forcelang;
6427 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6428 // Course language can override all other settings for this page.
6429 $return = $COURSE->lang;
6431 } else if (!empty($SESSION->lang)) {
6432 // Session language can override other settings.
6433 $return = $SESSION->lang;
6435 } else if (!empty($USER->lang)) {
6436 $return = $USER->lang;
6438 } else if (isset($CFG->lang)) {
6439 $return = $CFG->lang;
6441 } else {
6442 $return = 'en';
6445 // Just in case this slipped in from somewhere by accident.
6446 $return = str_replace('_utf8', '', $return);
6448 return $return;
6452 * Returns parent language of current active language if defined
6454 * @category string
6455 * @param string $lang null means current language
6456 * @return string
6458 function get_parent_language($lang=null) {
6460 // Let's hack around the current language.
6461 if (!empty($lang)) {
6462 $oldforcelang = force_current_language($lang);
6465 $parentlang = get_string('parentlanguage', 'langconfig');
6466 if ($parentlang === 'en') {
6467 $parentlang = '';
6470 // Let's hack around the current language.
6471 if (!empty($lang)) {
6472 force_current_language($oldforcelang);
6475 return $parentlang;
6479 * Force the current language to get strings and dates localised in the given language.
6481 * After calling this function, all strings will be provided in the given language
6482 * until this function is called again, or equivalent code is run.
6484 * @param string $language
6485 * @return string previous $SESSION->forcelang value
6487 function force_current_language($language) {
6488 global $SESSION;
6489 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6490 if ($language !== $sessionforcelang) {
6491 // Seting forcelang to null or an empty string disables it's effect.
6492 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6493 $SESSION->forcelang = $language;
6494 moodle_setlocale();
6497 return $sessionforcelang;
6501 * Returns current string_manager instance.
6503 * The param $forcereload is needed for CLI installer only where the string_manager instance
6504 * must be replaced during the install.php script life time.
6506 * @category string
6507 * @param bool $forcereload shall the singleton be released and new instance created instead?
6508 * @return core_string_manager
6510 function get_string_manager($forcereload=false) {
6511 global $CFG;
6513 static $singleton = null;
6515 if ($forcereload) {
6516 $singleton = null;
6518 if ($singleton === null) {
6519 if (empty($CFG->early_install_lang)) {
6521 if (empty($CFG->langlist)) {
6522 $translist = array();
6523 } else {
6524 $translist = explode(',', $CFG->langlist);
6527 if (!empty($CFG->config_php_settings['customstringmanager'])) {
6528 $classname = $CFG->config_php_settings['customstringmanager'];
6530 if (class_exists($classname)) {
6531 $implements = class_implements($classname);
6533 if (isset($implements['core_string_manager'])) {
6534 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
6535 return $singleton;
6537 } else {
6538 debugging('Unable to instantiate custom string manager: class '.$classname.
6539 ' does not implement the core_string_manager interface.');
6542 } else {
6543 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6547 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6549 } else {
6550 $singleton = new core_string_manager_install();
6554 return $singleton;
6558 * Returns a localized string.
6560 * Returns the translated string specified by $identifier as
6561 * for $module. Uses the same format files as STphp.
6562 * $a is an object, string or number that can be used
6563 * within translation strings
6565 * eg 'hello {$a->firstname} {$a->lastname}'
6566 * or 'hello {$a}'
6568 * If you would like to directly echo the localized string use
6569 * the function {@link print_string()}
6571 * Example usage of this function involves finding the string you would
6572 * like a local equivalent of and using its identifier and module information
6573 * to retrieve it.<br/>
6574 * If you open moodle/lang/en/moodle.php and look near line 278
6575 * you will find a string to prompt a user for their word for 'course'
6576 * <code>
6577 * $string['course'] = 'Course';
6578 * </code>
6579 * So if you want to display the string 'Course'
6580 * in any language that supports it on your site
6581 * you just need to use the identifier 'course'
6582 * <code>
6583 * $mystring = '<strong>'. get_string('course') .'</strong>';
6584 * or
6585 * </code>
6586 * If the string you want is in another file you'd take a slightly
6587 * different approach. Looking in moodle/lang/en/calendar.php you find
6588 * around line 75:
6589 * <code>
6590 * $string['typecourse'] = 'Course event';
6591 * </code>
6592 * If you want to display the string "Course event" in any language
6593 * supported you would use the identifier 'typecourse' and the module 'calendar'
6594 * (because it is in the file calendar.php):
6595 * <code>
6596 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6597 * </code>
6599 * As a last resort, should the identifier fail to map to a string
6600 * the returned string will be [[ $identifier ]]
6602 * In Moodle 2.3 there is a new argument to this function $lazyload.
6603 * Setting $lazyload to true causes get_string to return a lang_string object
6604 * rather than the string itself. The fetching of the string is then put off until
6605 * the string object is first used. The object can be used by calling it's out
6606 * method or by casting the object to a string, either directly e.g.
6607 * (string)$stringobject
6608 * or indirectly by using the string within another string or echoing it out e.g.
6609 * echo $stringobject
6610 * return "<p>{$stringobject}</p>";
6611 * It is worth noting that using $lazyload and attempting to use the string as an
6612 * array key will cause a fatal error as objects cannot be used as array keys.
6613 * But you should never do that anyway!
6614 * For more information {@link lang_string}
6616 * @category string
6617 * @param string $identifier The key identifier for the localized string
6618 * @param string $component The module where the key identifier is stored,
6619 * usually expressed as the filename in the language pack without the
6620 * .php on the end but can also be written as mod/forum or grade/export/xls.
6621 * If none is specified then moodle.php is used.
6622 * @param string|object|array $a An object, string or number that can be used
6623 * within translation strings
6624 * @param bool $lazyload If set to true a string object is returned instead of
6625 * the string itself. The string then isn't calculated until it is first used.
6626 * @return string The localized string.
6627 * @throws coding_exception
6629 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6630 global $CFG;
6632 // If the lazy load argument has been supplied return a lang_string object
6633 // instead.
6634 // We need to make sure it is true (and a bool) as you will see below there
6635 // used to be a forth argument at one point.
6636 if ($lazyload === true) {
6637 return new lang_string($identifier, $component, $a);
6640 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6641 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6644 // There is now a forth argument again, this time it is a boolean however so
6645 // we can still check for the old extralocations parameter.
6646 if (!is_bool($lazyload) && !empty($lazyload)) {
6647 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6650 if (strpos($component, '/') !== false) {
6651 debugging('The module name you passed to get_string is the deprecated format ' .
6652 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6653 $componentpath = explode('/', $component);
6655 switch ($componentpath[0]) {
6656 case 'mod':
6657 $component = $componentpath[1];
6658 break;
6659 case 'blocks':
6660 case 'block':
6661 $component = 'block_'.$componentpath[1];
6662 break;
6663 case 'enrol':
6664 $component = 'enrol_'.$componentpath[1];
6665 break;
6666 case 'format':
6667 $component = 'format_'.$componentpath[1];
6668 break;
6669 case 'grade':
6670 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6671 break;
6675 $result = get_string_manager()->get_string($identifier, $component, $a);
6677 // Debugging feature lets you display string identifier and component.
6678 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6679 $result .= ' {' . $identifier . '/' . $component . '}';
6681 return $result;
6685 * Converts an array of strings to their localized value.
6687 * @param array $array An array of strings
6688 * @param string $component The language module that these strings can be found in.
6689 * @return stdClass translated strings.
6691 function get_strings($array, $component = '') {
6692 $string = new stdClass;
6693 foreach ($array as $item) {
6694 $string->$item = get_string($item, $component);
6696 return $string;
6700 * Prints out a translated string.
6702 * Prints out a translated string using the return value from the {@link get_string()} function.
6704 * Example usage of this function when the string is in the moodle.php file:<br/>
6705 * <code>
6706 * echo '<strong>';
6707 * print_string('course');
6708 * echo '</strong>';
6709 * </code>
6711 * Example usage of this function when the string is not in the moodle.php file:<br/>
6712 * <code>
6713 * echo '<h1>';
6714 * print_string('typecourse', 'calendar');
6715 * echo '</h1>';
6716 * </code>
6718 * @category string
6719 * @param string $identifier The key identifier for the localized string
6720 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6721 * @param string|object|array $a An object, string or number that can be used within translation strings
6723 function print_string($identifier, $component = '', $a = null) {
6724 echo get_string($identifier, $component, $a);
6728 * Returns a list of charset codes
6730 * Returns a list of charset codes. It's hardcoded, so they should be added manually
6731 * (checking that such charset is supported by the texlib library!)
6733 * @return array And associative array with contents in the form of charset => charset
6735 function get_list_of_charsets() {
6737 $charsets = array(
6738 'EUC-JP' => 'EUC-JP',
6739 'ISO-2022-JP'=> 'ISO-2022-JP',
6740 'ISO-8859-1' => 'ISO-8859-1',
6741 'SHIFT-JIS' => 'SHIFT-JIS',
6742 'GB2312' => 'GB2312',
6743 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
6744 'UTF-8' => 'UTF-8');
6746 asort($charsets);
6748 return $charsets;
6752 * Returns a list of valid and compatible themes
6754 * @return array
6756 function get_list_of_themes() {
6757 global $CFG;
6759 $themes = array();
6761 if (!empty($CFG->themelist)) { // Use admin's list of themes.
6762 $themelist = explode(',', $CFG->themelist);
6763 } else {
6764 $themelist = array_keys(core_component::get_plugin_list("theme"));
6767 foreach ($themelist as $key => $themename) {
6768 $theme = theme_config::load($themename);
6769 $themes[$themename] = $theme;
6772 core_collator::asort_objects_by_method($themes, 'get_theme_name');
6774 return $themes;
6778 * Factory function for emoticon_manager
6780 * @return emoticon_manager singleton
6782 function get_emoticon_manager() {
6783 static $singleton = null;
6785 if (is_null($singleton)) {
6786 $singleton = new emoticon_manager();
6789 return $singleton;
6793 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
6795 * Whenever this manager mentiones 'emoticon object', the following data
6796 * structure is expected: stdClass with properties text, imagename, imagecomponent,
6797 * altidentifier and altcomponent
6799 * @see admin_setting_emoticons
6801 * @copyright 2010 David Mudrak
6802 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6804 class emoticon_manager {
6807 * Returns the currently enabled emoticons
6809 * @return array of emoticon objects
6811 public function get_emoticons() {
6812 global $CFG;
6814 if (empty($CFG->emoticons)) {
6815 return array();
6818 $emoticons = $this->decode_stored_config($CFG->emoticons);
6820 if (!is_array($emoticons)) {
6821 // Something is wrong with the format of stored setting.
6822 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
6823 return array();
6826 return $emoticons;
6830 * Converts emoticon object into renderable pix_emoticon object
6832 * @param stdClass $emoticon emoticon object
6833 * @param array $attributes explicit HTML attributes to set
6834 * @return pix_emoticon
6836 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
6837 $stringmanager = get_string_manager();
6838 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
6839 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
6840 } else {
6841 $alt = s($emoticon->text);
6843 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
6847 * Encodes the array of emoticon objects into a string storable in config table
6849 * @see self::decode_stored_config()
6850 * @param array $emoticons array of emtocion objects
6851 * @return string
6853 public function encode_stored_config(array $emoticons) {
6854 return json_encode($emoticons);
6858 * Decodes the string into an array of emoticon objects
6860 * @see self::encode_stored_config()
6861 * @param string $encoded
6862 * @return string|null
6864 public function decode_stored_config($encoded) {
6865 $decoded = json_decode($encoded);
6866 if (!is_array($decoded)) {
6867 return null;
6869 return $decoded;
6873 * Returns default set of emoticons supported by Moodle
6875 * @return array of sdtClasses
6877 public function default_emoticons() {
6878 return array(
6879 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
6880 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
6881 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
6882 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
6883 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
6884 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
6885 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
6886 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
6887 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
6888 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
6889 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
6890 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
6891 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
6892 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
6893 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
6894 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
6895 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
6896 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
6897 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
6898 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
6899 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
6900 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
6901 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
6902 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
6903 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
6904 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
6905 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
6906 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
6907 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
6908 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
6913 * Helper method preparing the stdClass with the emoticon properties
6915 * @param string|array $text or array of strings
6916 * @param string $imagename to be used by {@link pix_emoticon}
6917 * @param string $altidentifier alternative string identifier, null for no alt
6918 * @param string $altcomponent where the alternative string is defined
6919 * @param string $imagecomponent to be used by {@link pix_emoticon}
6920 * @return stdClass
6922 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
6923 $altcomponent = 'core_pix', $imagecomponent = 'core') {
6924 return (object)array(
6925 'text' => $text,
6926 'imagename' => $imagename,
6927 'imagecomponent' => $imagecomponent,
6928 'altidentifier' => $altidentifier,
6929 'altcomponent' => $altcomponent,
6934 // ENCRYPTION.
6937 * rc4encrypt
6939 * @param string $data Data to encrypt.
6940 * @return string The now encrypted data.
6942 function rc4encrypt($data) {
6943 return endecrypt(get_site_identifier(), $data, '');
6947 * rc4decrypt
6949 * @param string $data Data to decrypt.
6950 * @return string The now decrypted data.
6952 function rc4decrypt($data) {
6953 return endecrypt(get_site_identifier(), $data, 'de');
6957 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
6959 * @todo Finish documenting this function
6961 * @param string $pwd The password to use when encrypting or decrypting
6962 * @param string $data The data to be decrypted/encrypted
6963 * @param string $case Either 'de' for decrypt or '' for encrypt
6964 * @return string
6966 function endecrypt ($pwd, $data, $case) {
6968 if ($case == 'de') {
6969 $data = urldecode($data);
6972 $key[] = '';
6973 $box[] = '';
6974 $pwdlength = strlen($pwd);
6976 for ($i = 0; $i <= 255; $i++) {
6977 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
6978 $box[$i] = $i;
6981 $x = 0;
6983 for ($i = 0; $i <= 255; $i++) {
6984 $x = ($x + $box[$i] + $key[$i]) % 256;
6985 $tempswap = $box[$i];
6986 $box[$i] = $box[$x];
6987 $box[$x] = $tempswap;
6990 $cipher = '';
6992 $a = 0;
6993 $j = 0;
6995 for ($i = 0; $i < strlen($data); $i++) {
6996 $a = ($a + 1) % 256;
6997 $j = ($j + $box[$a]) % 256;
6998 $temp = $box[$a];
6999 $box[$a] = $box[$j];
7000 $box[$j] = $temp;
7001 $k = $box[(($box[$a] + $box[$j]) % 256)];
7002 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7003 $cipher .= chr($cipherby);
7006 if ($case == 'de') {
7007 $cipher = urldecode(urlencode($cipher));
7008 } else {
7009 $cipher = urlencode($cipher);
7012 return $cipher;
7015 // ENVIRONMENT CHECKING.
7018 * This method validates a plug name. It is much faster than calling clean_param.
7020 * @param string $name a string that might be a plugin name.
7021 * @return bool if this string is a valid plugin name.
7023 function is_valid_plugin_name($name) {
7024 // This does not work for 'mod', bad luck, use any other type.
7025 return core_component::is_valid_plugin_name('tool', $name);
7029 * Get a list of all the plugins of a given type that define a certain API function
7030 * in a certain file. The plugin component names and function names are returned.
7032 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7033 * @param string $function the part of the name of the function after the
7034 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7035 * names like report_courselist_hook.
7036 * @param string $file the name of file within the plugin that defines the
7037 * function. Defaults to lib.php.
7038 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7039 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7041 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7042 global $CFG;
7044 // We don't include here as all plugin types files would be included.
7045 $plugins = get_plugins_with_function($function, $file, false);
7047 if (empty($plugins[$plugintype])) {
7048 return array();
7051 $allplugins = core_component::get_plugin_list($plugintype);
7053 // Reformat the array and include the files.
7054 $pluginfunctions = array();
7055 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7057 // Check that it has not been removed and the file is still available.
7058 if (!empty($allplugins[$pluginname])) {
7060 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7061 if (file_exists($filepath)) {
7062 include_once($filepath);
7063 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7068 return $pluginfunctions;
7072 * Get a list of all the plugins that define a certain API function in a certain file.
7074 * @param string $function the part of the name of the function after the
7075 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7076 * names like report_courselist_hook.
7077 * @param string $file the name of file within the plugin that defines the
7078 * function. Defaults to lib.php.
7079 * @param bool $include Whether to include the files that contain the functions or not.
7080 * @return array with [plugintype][plugin] = functionname
7082 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7083 global $CFG;
7085 $cache = \cache::make('core', 'plugin_functions');
7087 // Including both although I doubt that we will find two functions definitions with the same name.
7088 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7089 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7091 if ($pluginfunctions = $cache->get($key)) {
7093 // Checking that the files are still available.
7094 foreach ($pluginfunctions as $plugintype => $plugins) {
7096 $allplugins = \core_component::get_plugin_list($plugintype);
7097 foreach ($plugins as $plugin => $fullpath) {
7099 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7100 if (empty($allplugins[$plugin])) {
7101 unset($pluginfunctions[$plugintype][$plugin]);
7102 continue;
7105 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7106 if ($include && $fileexists) {
7107 // Include the files if it was requested.
7108 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7109 } else if (!$fileexists) {
7110 // If the file is not available any more it should not be returned.
7111 unset($pluginfunctions[$plugintype][$plugin]);
7115 return $pluginfunctions;
7118 $pluginfunctions = array();
7120 // To fill the cached. Also, everything should continue working with cache disabled.
7121 $plugintypes = \core_component::get_plugin_types();
7122 foreach ($plugintypes as $plugintype => $unused) {
7124 // We need to include files here.
7125 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7126 foreach ($pluginswithfile as $plugin => $notused) {
7128 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7130 $pluginfunction = false;
7131 if (function_exists($fullfunction)) {
7132 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7133 $pluginfunction = $fullfunction;
7135 } else if ($plugintype === 'mod') {
7136 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7137 $shortfunction = $plugin . '_' . $function;
7138 if (function_exists($shortfunction)) {
7139 $pluginfunction = $shortfunction;
7143 if ($pluginfunction) {
7144 if (empty($pluginfunctions[$plugintype])) {
7145 $pluginfunctions[$plugintype] = array();
7147 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7152 $cache->set($key, $pluginfunctions);
7154 return $pluginfunctions;
7159 * Lists plugin-like directories within specified directory
7161 * This function was originally used for standard Moodle plugins, please use
7162 * new core_component::get_plugin_list() now.
7164 * This function is used for general directory listing and backwards compatility.
7166 * @param string $directory relative directory from root
7167 * @param string $exclude dir name to exclude from the list (defaults to none)
7168 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7169 * @return array Sorted array of directory names found under the requested parameters
7171 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7172 global $CFG;
7174 $plugins = array();
7176 if (empty($basedir)) {
7177 $basedir = $CFG->dirroot .'/'. $directory;
7179 } else {
7180 $basedir = $basedir .'/'. $directory;
7183 if ($CFG->debugdeveloper and empty($exclude)) {
7184 // Make sure devs do not use this to list normal plugins,
7185 // this is intended for general directories that are not plugins!
7187 $subtypes = core_component::get_plugin_types();
7188 if (in_array($basedir, $subtypes)) {
7189 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7191 unset($subtypes);
7194 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7195 if (!$dirhandle = opendir($basedir)) {
7196 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7197 return array();
7199 while (false !== ($dir = readdir($dirhandle))) {
7200 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7201 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7202 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7203 continue;
7205 if (filetype($basedir .'/'. $dir) != 'dir') {
7206 continue;
7208 $plugins[] = $dir;
7210 closedir($dirhandle);
7212 if ($plugins) {
7213 asort($plugins);
7215 return $plugins;
7219 * Invoke plugin's callback functions
7221 * @param string $type plugin type e.g. 'mod'
7222 * @param string $name plugin name
7223 * @param string $feature feature name
7224 * @param string $action feature's action
7225 * @param array $params parameters of callback function, should be an array
7226 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7227 * @return mixed
7229 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7231 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7232 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7236 * Invoke component's callback functions
7238 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7239 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7240 * @param array $params parameters of callback function
7241 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7242 * @return mixed
7244 function component_callback($component, $function, array $params = array(), $default = null) {
7246 $functionname = component_callback_exists($component, $function);
7248 if ($functionname) {
7249 // Function exists, so just return function result.
7250 $ret = call_user_func_array($functionname, $params);
7251 if (is_null($ret)) {
7252 return $default;
7253 } else {
7254 return $ret;
7257 return $default;
7261 * Determine if a component callback exists and return the function name to call. Note that this
7262 * function will include the required library files so that the functioname returned can be
7263 * called directly.
7265 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7266 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7267 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7268 * @throws coding_exception if invalid component specfied
7270 function component_callback_exists($component, $function) {
7271 global $CFG; // This is needed for the inclusions.
7273 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7274 if (empty($cleancomponent)) {
7275 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7277 $component = $cleancomponent;
7279 list($type, $name) = core_component::normalize_component($component);
7280 $component = $type . '_' . $name;
7282 $oldfunction = $name.'_'.$function;
7283 $function = $component.'_'.$function;
7285 $dir = core_component::get_component_directory($component);
7286 if (empty($dir)) {
7287 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7290 // Load library and look for function.
7291 if (file_exists($dir.'/lib.php')) {
7292 require_once($dir.'/lib.php');
7295 if (!function_exists($function) and function_exists($oldfunction)) {
7296 if ($type !== 'mod' and $type !== 'core') {
7297 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7299 $function = $oldfunction;
7302 if (function_exists($function)) {
7303 return $function;
7305 return false;
7309 * Checks whether a plugin supports a specified feature.
7311 * @param string $type Plugin type e.g. 'mod'
7312 * @param string $name Plugin name e.g. 'forum'
7313 * @param string $feature Feature code (FEATURE_xx constant)
7314 * @param mixed $default default value if feature support unknown
7315 * @return mixed Feature result (false if not supported, null if feature is unknown,
7316 * otherwise usually true but may have other feature-specific value such as array)
7317 * @throws coding_exception
7319 function plugin_supports($type, $name, $feature, $default = null) {
7320 global $CFG;
7322 if ($type === 'mod' and $name === 'NEWMODULE') {
7323 // Somebody forgot to rename the module template.
7324 return false;
7327 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7328 if (empty($component)) {
7329 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7332 $function = null;
7334 if ($type === 'mod') {
7335 // We need this special case because we support subplugins in modules,
7336 // otherwise it would end up in infinite loop.
7337 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7338 include_once("$CFG->dirroot/mod/$name/lib.php");
7339 $function = $component.'_supports';
7340 if (!function_exists($function)) {
7341 // Legacy non-frankenstyle function name.
7342 $function = $name.'_supports';
7346 } else {
7347 if (!$path = core_component::get_plugin_directory($type, $name)) {
7348 // Non existent plugin type.
7349 return false;
7351 if (file_exists("$path/lib.php")) {
7352 include_once("$path/lib.php");
7353 $function = $component.'_supports';
7357 if ($function and function_exists($function)) {
7358 $supports = $function($feature);
7359 if (is_null($supports)) {
7360 // Plugin does not know - use default.
7361 return $default;
7362 } else {
7363 return $supports;
7367 // Plugin does not care, so use default.
7368 return $default;
7372 * Returns true if the current version of PHP is greater that the specified one.
7374 * @todo Check PHP version being required here is it too low?
7376 * @param string $version The version of php being tested.
7377 * @return bool
7379 function check_php_version($version='5.2.4') {
7380 return (version_compare(phpversion(), $version) >= 0);
7384 * Determine if moodle installation requires update.
7386 * Checks version numbers of main code and all plugins to see
7387 * if there are any mismatches.
7389 * @return bool
7391 function moodle_needs_upgrading() {
7392 global $CFG;
7394 if (empty($CFG->version)) {
7395 return true;
7398 // There is no need to purge plugininfo caches here because
7399 // these caches are not used during upgrade and they are purged after
7400 // every upgrade.
7402 if (empty($CFG->allversionshash)) {
7403 return true;
7406 $hash = core_component::get_all_versions_hash();
7408 return ($hash !== $CFG->allversionshash);
7412 * Returns the major version of this site
7414 * Moodle version numbers consist of three numbers separated by a dot, for
7415 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7416 * called major version. This function extracts the major version from either
7417 * $CFG->release (default) or eventually from the $release variable defined in
7418 * the main version.php.
7420 * @param bool $fromdisk should the version if source code files be used
7421 * @return string|false the major version like '2.3', false if could not be determined
7423 function moodle_major_version($fromdisk = false) {
7424 global $CFG;
7426 if ($fromdisk) {
7427 $release = null;
7428 require($CFG->dirroot.'/version.php');
7429 if (empty($release)) {
7430 return false;
7433 } else {
7434 if (empty($CFG->release)) {
7435 return false;
7437 $release = $CFG->release;
7440 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7441 return $matches[0];
7442 } else {
7443 return false;
7447 // MISCELLANEOUS.
7450 * Sets the system locale
7452 * @category string
7453 * @param string $locale Can be used to force a locale
7455 function moodle_setlocale($locale='') {
7456 global $CFG;
7458 static $currentlocale = ''; // Last locale caching.
7460 $oldlocale = $currentlocale;
7462 // Fetch the correct locale based on ostype.
7463 if ($CFG->ostype == 'WINDOWS') {
7464 $stringtofetch = 'localewin';
7465 } else {
7466 $stringtofetch = 'locale';
7469 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7470 if (!empty($locale)) {
7471 $currentlocale = $locale;
7472 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7473 $currentlocale = $CFG->locale;
7474 } else {
7475 $currentlocale = get_string($stringtofetch, 'langconfig');
7478 // Do nothing if locale already set up.
7479 if ($oldlocale == $currentlocale) {
7480 return;
7483 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7484 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7485 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7487 // Get current values.
7488 $monetary= setlocale (LC_MONETARY, 0);
7489 $numeric = setlocale (LC_NUMERIC, 0);
7490 $ctype = setlocale (LC_CTYPE, 0);
7491 if ($CFG->ostype != 'WINDOWS') {
7492 $messages= setlocale (LC_MESSAGES, 0);
7494 // Set locale to all.
7495 $result = setlocale (LC_ALL, $currentlocale);
7496 // If setting of locale fails try the other utf8 or utf-8 variant,
7497 // some operating systems support both (Debian), others just one (OSX).
7498 if ($result === false) {
7499 if (stripos($currentlocale, '.UTF-8') !== false) {
7500 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7501 setlocale (LC_ALL, $newlocale);
7502 } else if (stripos($currentlocale, '.UTF8') !== false) {
7503 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7504 setlocale (LC_ALL, $newlocale);
7507 // Set old values.
7508 setlocale (LC_MONETARY, $monetary);
7509 setlocale (LC_NUMERIC, $numeric);
7510 if ($CFG->ostype != 'WINDOWS') {
7511 setlocale (LC_MESSAGES, $messages);
7513 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7514 // To workaround a well-known PHP problem with Turkish letter Ii.
7515 setlocale (LC_CTYPE, $ctype);
7520 * Count words in a string.
7522 * Words are defined as things between whitespace.
7524 * @category string
7525 * @param string $string The text to be searched for words.
7526 * @return int The count of words in the specified string
7528 function count_words($string) {
7529 $string = strip_tags($string);
7530 // Decode HTML entities.
7531 $string = html_entity_decode($string);
7532 // Replace underscores (which are classed as word characters) with spaces.
7533 $string = preg_replace('/_/u', ' ', $string);
7534 // Remove any characters that shouldn't be treated as word boundaries.
7535 $string = preg_replace('/[\'"’-]/u', '', $string);
7536 // Remove dots and commas from within numbers only.
7537 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7539 return count(preg_split('/\w\b/u', $string)) - 1;
7543 * Count letters in a string.
7545 * Letters are defined as chars not in tags and different from whitespace.
7547 * @category string
7548 * @param string $string The text to be searched for letters.
7549 * @return int The count of letters in the specified text.
7551 function count_letters($string) {
7552 $string = strip_tags($string); // Tags are out now.
7553 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7555 return core_text::strlen($string);
7559 * Generate and return a random string of the specified length.
7561 * @param int $length The length of the string to be created.
7562 * @return string
7564 function random_string($length=15) {
7565 $randombytes = random_bytes_emulate($length);
7566 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7567 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7568 $pool .= '0123456789';
7569 $poollen = strlen($pool);
7570 $string = '';
7571 for ($i = 0; $i < $length; $i++) {
7572 $rand = ord($randombytes[$i]);
7573 $string .= substr($pool, ($rand%($poollen)), 1);
7575 return $string;
7579 * Generate a complex random string (useful for md5 salts)
7581 * This function is based on the above {@link random_string()} however it uses a
7582 * larger pool of characters and generates a string between 24 and 32 characters
7584 * @param int $length Optional if set generates a string to exactly this length
7585 * @return string
7587 function complex_random_string($length=null) {
7588 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7589 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7590 $poollen = strlen($pool);
7591 if ($length===null) {
7592 $length = floor(rand(24, 32));
7594 $randombytes = random_bytes_emulate($length);
7595 $string = '';
7596 for ($i = 0; $i < $length; $i++) {
7597 $rand = ord($randombytes[$i]);
7598 $string .= $pool[($rand%$poollen)];
7600 return $string;
7604 * Try to generates cryptographically secure pseudo-random bytes.
7606 * Note this is achieved by fallbacking between:
7607 * - PHP 7 random_bytes().
7608 * - OpenSSL openssl_random_pseudo_bytes().
7609 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
7611 * @param int $length requested length in bytes
7612 * @return string binary data
7614 function random_bytes_emulate($length) {
7615 global $CFG;
7616 if ($length <= 0) {
7617 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
7618 return '';
7620 if (function_exists('random_bytes')) {
7621 // Use PHP 7 goodness.
7622 $hash = @random_bytes($length);
7623 if ($hash !== false) {
7624 return $hash;
7627 if (function_exists('openssl_random_pseudo_bytes')) {
7628 // For PHP 5.3 and later with openssl extension.
7629 $hash = openssl_random_pseudo_bytes($length);
7630 if ($hash !== false) {
7631 return $hash;
7635 // Bad luck, there is no reliable random generator, let's just hash some unique stuff that is hard to guess.
7636 $hash = sha1(serialize($CFG) . serialize($_SERVER) . microtime(true) . uniqid('', true), true);
7637 // NOTE: the last param in sha1() is true, this means we are getting 20 bytes, not 40 chars as usual.
7638 if ($length <= 20) {
7639 return substr($hash, 0, $length);
7641 return $hash . random_bytes_emulate($length - 20);
7645 * Given some text (which may contain HTML) and an ideal length,
7646 * this function truncates the text neatly on a word boundary if possible
7648 * @category string
7649 * @param string $text text to be shortened
7650 * @param int $ideal ideal string length
7651 * @param boolean $exact if false, $text will not be cut mid-word
7652 * @param string $ending The string to append if the passed string is truncated
7653 * @return string $truncate shortened string
7655 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7656 // If the plain text is shorter than the maximum length, return the whole text.
7657 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7658 return $text;
7661 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7662 // and only tag in its 'line'.
7663 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7665 $totallength = core_text::strlen($ending);
7666 $truncate = '';
7668 // This array stores information about open and close tags and their position
7669 // in the truncated string. Each item in the array is an object with fields
7670 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7671 // (byte position in truncated text).
7672 $tagdetails = array();
7674 foreach ($lines as $linematchings) {
7675 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7676 if (!empty($linematchings[1])) {
7677 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7678 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7679 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7680 // Record closing tag.
7681 $tagdetails[] = (object) array(
7682 'open' => false,
7683 'tag' => core_text::strtolower($tagmatchings[1]),
7684 'pos' => core_text::strlen($truncate),
7687 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7688 // Record opening tag.
7689 $tagdetails[] = (object) array(
7690 'open' => true,
7691 'tag' => core_text::strtolower($tagmatchings[1]),
7692 'pos' => core_text::strlen($truncate),
7694 } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
7695 $tagdetails[] = (object) array(
7696 'open' => true,
7697 'tag' => core_text::strtolower('if'),
7698 'pos' => core_text::strlen($truncate),
7700 } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
7701 $tagdetails[] = (object) array(
7702 'open' => false,
7703 'tag' => core_text::strtolower('if'),
7704 'pos' => core_text::strlen($truncate),
7708 // Add html-tag to $truncate'd text.
7709 $truncate .= $linematchings[1];
7712 // Calculate the length of the plain text part of the line; handle entities as one character.
7713 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7714 if ($totallength + $contentlength > $ideal) {
7715 // The number of characters which are left.
7716 $left = $ideal - $totallength;
7717 $entitieslength = 0;
7718 // Search for html entities.
7719 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)) {
7720 // Calculate the real length of all entities in the legal range.
7721 foreach ($entities[0] as $entity) {
7722 if ($entity[1]+1-$entitieslength <= $left) {
7723 $left--;
7724 $entitieslength += core_text::strlen($entity[0]);
7725 } else {
7726 // No more characters left.
7727 break;
7731 $breakpos = $left + $entitieslength;
7733 // If the words shouldn't be cut in the middle...
7734 if (!$exact) {
7735 // Search the last occurence of a space.
7736 for (; $breakpos > 0; $breakpos--) {
7737 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
7738 if ($char === '.' or $char === ' ') {
7739 $breakpos += 1;
7740 break;
7741 } else if (strlen($char) > 2) {
7742 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7743 $breakpos += 1;
7744 break;
7749 if ($breakpos == 0) {
7750 // This deals with the test_shorten_text_no_spaces case.
7751 $breakpos = $left + $entitieslength;
7752 } else if ($breakpos > $left + $entitieslength) {
7753 // This deals with the previous for loop breaking on the first char.
7754 $breakpos = $left + $entitieslength;
7757 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
7758 // Maximum length is reached, so get off the loop.
7759 break;
7760 } else {
7761 $truncate .= $linematchings[2];
7762 $totallength += $contentlength;
7765 // If the maximum length is reached, get off the loop.
7766 if ($totallength >= $ideal) {
7767 break;
7771 // Add the defined ending to the text.
7772 $truncate .= $ending;
7774 // Now calculate the list of open html tags based on the truncate position.
7775 $opentags = array();
7776 foreach ($tagdetails as $taginfo) {
7777 if ($taginfo->open) {
7778 // Add tag to the beginning of $opentags list.
7779 array_unshift($opentags, $taginfo->tag);
7780 } else {
7781 // Can have multiple exact same open tags, close the last one.
7782 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
7783 if ($pos !== false) {
7784 unset($opentags[$pos]);
7789 // Close all unclosed html-tags.
7790 foreach ($opentags as $tag) {
7791 if ($tag === 'if') {
7792 $truncate .= '<!--<![endif]-->';
7793 } else {
7794 $truncate .= '</' . $tag . '>';
7798 return $truncate;
7803 * Given dates in seconds, how many weeks is the date from startdate
7804 * The first week is 1, the second 2 etc ...
7806 * @param int $startdate Timestamp for the start date
7807 * @param int $thedate Timestamp for the end date
7808 * @return string
7810 function getweek ($startdate, $thedate) {
7811 if ($thedate < $startdate) {
7812 return 0;
7815 return floor(($thedate - $startdate) / WEEKSECS) + 1;
7819 * Returns a randomly generated password of length $maxlen. inspired by
7821 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
7822 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
7824 * @param int $maxlen The maximum size of the password being generated.
7825 * @return string
7827 function generate_password($maxlen=10) {
7828 global $CFG;
7830 if (empty($CFG->passwordpolicy)) {
7831 $fillers = PASSWORD_DIGITS;
7832 $wordlist = file($CFG->wordlist);
7833 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7834 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7835 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
7836 $password = $word1 . $filler1 . $word2;
7837 } else {
7838 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
7839 $digits = $CFG->minpassworddigits;
7840 $lower = $CFG->minpasswordlower;
7841 $upper = $CFG->minpasswordupper;
7842 $nonalphanum = $CFG->minpasswordnonalphanum;
7843 $total = $lower + $upper + $digits + $nonalphanum;
7844 // Var minlength should be the greater one of the two ( $minlen and $total ).
7845 $minlen = $minlen < $total ? $total : $minlen;
7846 // Var maxlen can never be smaller than minlen.
7847 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
7848 $additional = $maxlen - $total;
7850 // Make sure we have enough characters to fulfill
7851 // complexity requirements.
7852 $passworddigits = PASSWORD_DIGITS;
7853 while ($digits > strlen($passworddigits)) {
7854 $passworddigits .= PASSWORD_DIGITS;
7856 $passwordlower = PASSWORD_LOWER;
7857 while ($lower > strlen($passwordlower)) {
7858 $passwordlower .= PASSWORD_LOWER;
7860 $passwordupper = PASSWORD_UPPER;
7861 while ($upper > strlen($passwordupper)) {
7862 $passwordupper .= PASSWORD_UPPER;
7864 $passwordnonalphanum = PASSWORD_NONALPHANUM;
7865 while ($nonalphanum > strlen($passwordnonalphanum)) {
7866 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
7869 // Now mix and shuffle it all.
7870 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
7871 substr(str_shuffle ($passwordupper), 0, $upper) .
7872 substr(str_shuffle ($passworddigits), 0, $digits) .
7873 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
7874 substr(str_shuffle ($passwordlower .
7875 $passwordupper .
7876 $passworddigits .
7877 $passwordnonalphanum), 0 , $additional));
7880 return substr ($password, 0, $maxlen);
7884 * Given a float, prints it nicely.
7885 * Localized floats must not be used in calculations!
7887 * The stripzeros feature is intended for making numbers look nicer in small
7888 * areas where it is not necessary to indicate the degree of accuracy by showing
7889 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
7890 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
7892 * @param float $float The float to print
7893 * @param int $decimalpoints The number of decimal places to print.
7894 * @param bool $localized use localized decimal separator
7895 * @param bool $stripzeros If true, removes final zeros after decimal point
7896 * @return string locale float
7898 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
7899 if (is_null($float)) {
7900 return '';
7902 if ($localized) {
7903 $separator = get_string('decsep', 'langconfig');
7904 } else {
7905 $separator = '.';
7907 $result = number_format($float, $decimalpoints, $separator, '');
7908 if ($stripzeros) {
7909 // Remove zeros and final dot if not needed.
7910 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
7912 return $result;
7916 * Converts locale specific floating point/comma number back to standard PHP float value
7917 * Do NOT try to do any math operations before this conversion on any user submitted floats!
7919 * @param string $localefloat locale aware float representation
7920 * @param bool $strict If true, then check the input and return false if it is not a valid number.
7921 * @return mixed float|bool - false or the parsed float.
7923 function unformat_float($localefloat, $strict = false) {
7924 $localefloat = trim($localefloat);
7926 if ($localefloat == '') {
7927 return null;
7930 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
7931 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
7933 if ($strict && !is_numeric($localefloat)) {
7934 return false;
7937 return (float)$localefloat;
7941 * Given a simple array, this shuffles it up just like shuffle()
7942 * Unlike PHP's shuffle() this function works on any machine.
7944 * @param array $array The array to be rearranged
7945 * @return array
7947 function swapshuffle($array) {
7949 $last = count($array) - 1;
7950 for ($i = 0; $i <= $last; $i++) {
7951 $from = rand(0, $last);
7952 $curr = $array[$i];
7953 $array[$i] = $array[$from];
7954 $array[$from] = $curr;
7956 return $array;
7960 * Like {@link swapshuffle()}, but works on associative arrays
7962 * @param array $array The associative array to be rearranged
7963 * @return array
7965 function swapshuffle_assoc($array) {
7967 $newarray = array();
7968 $newkeys = swapshuffle(array_keys($array));
7970 foreach ($newkeys as $newkey) {
7971 $newarray[$newkey] = $array[$newkey];
7973 return $newarray;
7977 * Given an arbitrary array, and a number of draws,
7978 * this function returns an array with that amount
7979 * of items. The indexes are retained.
7981 * @todo Finish documenting this function
7983 * @param array $array
7984 * @param int $draws
7985 * @return array
7987 function draw_rand_array($array, $draws) {
7989 $return = array();
7991 $last = count($array);
7993 if ($draws > $last) {
7994 $draws = $last;
7997 while ($draws > 0) {
7998 $last--;
8000 $keys = array_keys($array);
8001 $rand = rand(0, $last);
8003 $return[$keys[$rand]] = $array[$keys[$rand]];
8004 unset($array[$keys[$rand]]);
8006 $draws--;
8009 return $return;
8013 * Calculate the difference between two microtimes
8015 * @param string $a The first Microtime
8016 * @param string $b The second Microtime
8017 * @return string
8019 function microtime_diff($a, $b) {
8020 list($adec, $asec) = explode(' ', $a);
8021 list($bdec, $bsec) = explode(' ', $b);
8022 return $bsec - $asec + $bdec - $adec;
8026 * Given a list (eg a,b,c,d,e) this function returns
8027 * an array of 1->a, 2->b, 3->c etc
8029 * @param string $list The string to explode into array bits
8030 * @param string $separator The separator used within the list string
8031 * @return array The now assembled array
8033 function make_menu_from_list($list, $separator=',') {
8035 $array = array_reverse(explode($separator, $list), true);
8036 foreach ($array as $key => $item) {
8037 $outarray[$key+1] = trim($item);
8039 return $outarray;
8043 * Creates an array that represents all the current grades that
8044 * can be chosen using the given grading type.
8046 * Negative numbers
8047 * are scales, zero is no grade, and positive numbers are maximum
8048 * grades.
8050 * @todo Finish documenting this function or better deprecated this completely!
8052 * @param int $gradingtype
8053 * @return array
8055 function make_grades_menu($gradingtype) {
8056 global $DB;
8058 $grades = array();
8059 if ($gradingtype < 0) {
8060 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8061 return make_menu_from_list($scale->scale);
8063 } else if ($gradingtype > 0) {
8064 for ($i=$gradingtype; $i>=0; $i--) {
8065 $grades[$i] = $i .' / '. $gradingtype;
8067 return $grades;
8069 return $grades;
8073 * This function returns the number of activities using the given scale in the given course.
8075 * @param int $courseid The course ID to check.
8076 * @param int $scaleid The scale ID to check
8077 * @return int
8079 function course_scale_used($courseid, $scaleid) {
8080 global $CFG, $DB;
8082 $return = 0;
8084 if (!empty($scaleid)) {
8085 if ($cms = get_course_mods($courseid)) {
8086 foreach ($cms as $cm) {
8087 // Check cm->name/lib.php exists.
8088 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
8089 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
8090 $functionname = $cm->modname.'_scale_used';
8091 if (function_exists($functionname)) {
8092 if ($functionname($cm->instance, $scaleid)) {
8093 $return++;
8100 // Check if any course grade item makes use of the scale.
8101 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8103 // Check if any outcome in the course makes use of the scale.
8104 $return += $DB->count_records_sql("SELECT COUNT('x')
8105 FROM {grade_outcomes_courses} goc,
8106 {grade_outcomes} go
8107 WHERE go.id = goc.outcomeid
8108 AND go.scaleid = ? AND goc.courseid = ?",
8109 array($scaleid, $courseid));
8111 return $return;
8115 * This function returns the number of activities using scaleid in the entire site
8117 * @param int $scaleid
8118 * @param array $courses
8119 * @return int
8121 function site_scale_used($scaleid, &$courses) {
8122 $return = 0;
8124 if (!is_array($courses) || count($courses) == 0) {
8125 $courses = get_courses("all", false, "c.id, c.shortname");
8128 if (!empty($scaleid)) {
8129 if (is_array($courses) && count($courses) > 0) {
8130 foreach ($courses as $course) {
8131 $return += course_scale_used($course->id, $scaleid);
8135 return $return;
8139 * make_unique_id_code
8141 * @todo Finish documenting this function
8143 * @uses $_SERVER
8144 * @param string $extra Extra string to append to the end of the code
8145 * @return string
8147 function make_unique_id_code($extra = '') {
8149 $hostname = 'unknownhost';
8150 if (!empty($_SERVER['HTTP_HOST'])) {
8151 $hostname = $_SERVER['HTTP_HOST'];
8152 } else if (!empty($_ENV['HTTP_HOST'])) {
8153 $hostname = $_ENV['HTTP_HOST'];
8154 } else if (!empty($_SERVER['SERVER_NAME'])) {
8155 $hostname = $_SERVER['SERVER_NAME'];
8156 } else if (!empty($_ENV['SERVER_NAME'])) {
8157 $hostname = $_ENV['SERVER_NAME'];
8160 $date = gmdate("ymdHis");
8162 $random = random_string(6);
8164 if ($extra) {
8165 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8166 } else {
8167 return $hostname .'+'. $date .'+'. $random;
8173 * Function to check the passed address is within the passed subnet
8175 * The parameter is a comma separated string of subnet definitions.
8176 * Subnet strings can be in one of three formats:
8177 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8178 * 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)
8179 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8180 * Code for type 1 modified from user posted comments by mediator at
8181 * {@link http://au.php.net/manual/en/function.ip2long.php}
8183 * @param string $addr The address you are checking
8184 * @param string $subnetstr The string of subnet addresses
8185 * @return bool
8187 function address_in_subnet($addr, $subnetstr) {
8189 if ($addr == '0.0.0.0') {
8190 return false;
8192 $subnets = explode(',', $subnetstr);
8193 $found = false;
8194 $addr = trim($addr);
8195 $addr = cleanremoteaddr($addr, false); // Normalise.
8196 if ($addr === null) {
8197 return false;
8199 $addrparts = explode(':', $addr);
8201 $ipv6 = strpos($addr, ':');
8203 foreach ($subnets as $subnet) {
8204 $subnet = trim($subnet);
8205 if ($subnet === '') {
8206 continue;
8209 if (strpos($subnet, '/') !== false) {
8210 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8211 list($ip, $mask) = explode('/', $subnet);
8212 $mask = trim($mask);
8213 if (!is_number($mask)) {
8214 continue; // Incorect mask number, eh?
8216 $ip = cleanremoteaddr($ip, false); // Normalise.
8217 if ($ip === null) {
8218 continue;
8220 if (strpos($ip, ':') !== false) {
8221 // IPv6.
8222 if (!$ipv6) {
8223 continue;
8225 if ($mask > 128 or $mask < 0) {
8226 continue; // Nonsense.
8228 if ($mask == 0) {
8229 return true; // Any address.
8231 if ($mask == 128) {
8232 if ($ip === $addr) {
8233 return true;
8235 continue;
8237 $ipparts = explode(':', $ip);
8238 $modulo = $mask % 16;
8239 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8240 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8241 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8242 if ($modulo == 0) {
8243 return true;
8245 $pos = ($mask-$modulo)/16;
8246 $ipnet = hexdec($ipparts[$pos]);
8247 $addrnet = hexdec($addrparts[$pos]);
8248 $mask = 0xffff << (16 - $modulo);
8249 if (($addrnet & $mask) == ($ipnet & $mask)) {
8250 return true;
8254 } else {
8255 // IPv4.
8256 if ($ipv6) {
8257 continue;
8259 if ($mask > 32 or $mask < 0) {
8260 continue; // Nonsense.
8262 if ($mask == 0) {
8263 return true;
8265 if ($mask == 32) {
8266 if ($ip === $addr) {
8267 return true;
8269 continue;
8271 $mask = 0xffffffff << (32 - $mask);
8272 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8273 return true;
8277 } else if (strpos($subnet, '-') !== false) {
8278 // 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.
8279 $parts = explode('-', $subnet);
8280 if (count($parts) != 2) {
8281 continue;
8284 if (strpos($subnet, ':') !== false) {
8285 // IPv6.
8286 if (!$ipv6) {
8287 continue;
8289 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8290 if ($ipstart === null) {
8291 continue;
8293 $ipparts = explode(':', $ipstart);
8294 $start = hexdec(array_pop($ipparts));
8295 $ipparts[] = trim($parts[1]);
8296 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8297 if ($ipend === null) {
8298 continue;
8300 $ipparts[7] = '';
8301 $ipnet = implode(':', $ipparts);
8302 if (strpos($addr, $ipnet) !== 0) {
8303 continue;
8305 $ipparts = explode(':', $ipend);
8306 $end = hexdec($ipparts[7]);
8308 $addrend = hexdec($addrparts[7]);
8310 if (($addrend >= $start) and ($addrend <= $end)) {
8311 return true;
8314 } else {
8315 // IPv4.
8316 if ($ipv6) {
8317 continue;
8319 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8320 if ($ipstart === null) {
8321 continue;
8323 $ipparts = explode('.', $ipstart);
8324 $ipparts[3] = trim($parts[1]);
8325 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8326 if ($ipend === null) {
8327 continue;
8330 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8331 return true;
8335 } else {
8336 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8337 if (strpos($subnet, ':') !== false) {
8338 // IPv6.
8339 if (!$ipv6) {
8340 continue;
8342 $parts = explode(':', $subnet);
8343 $count = count($parts);
8344 if ($parts[$count-1] === '') {
8345 unset($parts[$count-1]); // Trim trailing :'s.
8346 $count--;
8347 $subnet = implode('.', $parts);
8349 $isip = cleanremoteaddr($subnet, false); // Normalise.
8350 if ($isip !== null) {
8351 if ($isip === $addr) {
8352 return true;
8354 continue;
8355 } else if ($count > 8) {
8356 continue;
8358 $zeros = array_fill(0, 8-$count, '0');
8359 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8360 if (address_in_subnet($addr, $subnet)) {
8361 return true;
8364 } else {
8365 // IPv4.
8366 if ($ipv6) {
8367 continue;
8369 $parts = explode('.', $subnet);
8370 $count = count($parts);
8371 if ($parts[$count-1] === '') {
8372 unset($parts[$count-1]); // Trim trailing .
8373 $count--;
8374 $subnet = implode('.', $parts);
8376 if ($count == 4) {
8377 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8378 if ($subnet === $addr) {
8379 return true;
8381 continue;
8382 } else if ($count > 4) {
8383 continue;
8385 $zeros = array_fill(0, 4-$count, '0');
8386 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8387 if (address_in_subnet($addr, $subnet)) {
8388 return true;
8394 return false;
8398 * For outputting debugging info
8400 * @param string $string The string to write
8401 * @param string $eol The end of line char(s) to use
8402 * @param string $sleep Period to make the application sleep
8403 * This ensures any messages have time to display before redirect
8405 function mtrace($string, $eol="\n", $sleep=0) {
8407 if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
8408 fwrite(STDOUT, $string.$eol);
8409 } else {
8410 echo $string . $eol;
8413 flush();
8415 // Delay to keep message on user's screen in case of subsequent redirect.
8416 if ($sleep) {
8417 sleep($sleep);
8422 * Replace 1 or more slashes or backslashes to 1 slash
8424 * @param string $path The path to strip
8425 * @return string the path with double slashes removed
8427 function cleardoubleslashes ($path) {
8428 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8432 * Is current ip in give list?
8434 * @param string $list
8435 * @return bool
8437 function remoteip_in_list($list) {
8438 $inlist = false;
8439 $clientip = getremoteaddr(null);
8441 if (!$clientip) {
8442 // Ensure access on cli.
8443 return true;
8446 $list = explode("\n", $list);
8447 foreach ($list as $subnet) {
8448 $subnet = trim($subnet);
8449 if (address_in_subnet($clientip, $subnet)) {
8450 $inlist = true;
8451 break;
8454 return $inlist;
8458 * Returns most reliable client address
8460 * @param string $default If an address can't be determined, then return this
8461 * @return string The remote IP address
8463 function getremoteaddr($default='0.0.0.0') {
8464 global $CFG;
8466 if (empty($CFG->getremoteaddrconf)) {
8467 // This will happen, for example, before just after the upgrade, as the
8468 // user is redirected to the admin screen.
8469 $variablestoskip = 0;
8470 } else {
8471 $variablestoskip = $CFG->getremoteaddrconf;
8473 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8474 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8475 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8476 return $address ? $address : $default;
8479 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8480 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8481 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8482 $address = $forwardedaddresses[0];
8484 if (substr_count($address, ":") > 1) {
8485 // Remove port and brackets from IPv6.
8486 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8487 $address = $matches[1];
8489 } else {
8490 // Remove port from IPv4.
8491 if (substr_count($address, ":") == 1) {
8492 $parts = explode(":", $address);
8493 $address = $parts[0];
8497 $address = cleanremoteaddr($address);
8498 return $address ? $address : $default;
8501 if (!empty($_SERVER['REMOTE_ADDR'])) {
8502 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8503 return $address ? $address : $default;
8504 } else {
8505 return $default;
8510 * Cleans an ip address. Internal addresses are now allowed.
8511 * (Originally local addresses were not allowed.)
8513 * @param string $addr IPv4 or IPv6 address
8514 * @param bool $compress use IPv6 address compression
8515 * @return string normalised ip address string, null if error
8517 function cleanremoteaddr($addr, $compress=false) {
8518 $addr = trim($addr);
8520 // TODO: maybe add a separate function is_addr_public() or something like this.
8522 if (strpos($addr, ':') !== false) {
8523 // Can be only IPv6.
8524 $parts = explode(':', $addr);
8525 $count = count($parts);
8527 if (strpos($parts[$count-1], '.') !== false) {
8528 // Legacy ipv4 notation.
8529 $last = array_pop($parts);
8530 $ipv4 = cleanremoteaddr($last, true);
8531 if ($ipv4 === null) {
8532 return null;
8534 $bits = explode('.', $ipv4);
8535 $parts[] = dechex($bits[0]).dechex($bits[1]);
8536 $parts[] = dechex($bits[2]).dechex($bits[3]);
8537 $count = count($parts);
8538 $addr = implode(':', $parts);
8541 if ($count < 3 or $count > 8) {
8542 return null; // Severly malformed.
8545 if ($count != 8) {
8546 if (strpos($addr, '::') === false) {
8547 return null; // Malformed.
8549 // Uncompress.
8550 $insertat = array_search('', $parts, true);
8551 $missing = array_fill(0, 1 + 8 - $count, '0');
8552 array_splice($parts, $insertat, 1, $missing);
8553 foreach ($parts as $key => $part) {
8554 if ($part === '') {
8555 $parts[$key] = '0';
8560 $adr = implode(':', $parts);
8561 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8562 return null; // Incorrect format - sorry.
8565 // Normalise 0s and case.
8566 $parts = array_map('hexdec', $parts);
8567 $parts = array_map('dechex', $parts);
8569 $result = implode(':', $parts);
8571 if (!$compress) {
8572 return $result;
8575 if ($result === '0:0:0:0:0:0:0:0') {
8576 return '::'; // All addresses.
8579 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8580 if ($compressed !== $result) {
8581 return $compressed;
8584 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8585 if ($compressed !== $result) {
8586 return $compressed;
8589 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8590 if ($compressed !== $result) {
8591 return $compressed;
8594 return $result;
8597 // First get all things that look like IPv4 addresses.
8598 $parts = array();
8599 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8600 return null;
8602 unset($parts[0]);
8604 foreach ($parts as $key => $match) {
8605 if ($match > 255) {
8606 return null;
8608 $parts[$key] = (int)$match; // Normalise 0s.
8611 return implode('.', $parts);
8615 * This function will make a complete copy of anything it's given,
8616 * regardless of whether it's an object or not.
8618 * @param mixed $thing Something you want cloned
8619 * @return mixed What ever it is you passed it
8621 function fullclone($thing) {
8622 return unserialize(serialize($thing));
8626 * If new messages are waiting for the current user, then insert
8627 * JavaScript to pop up the messaging window into the page
8629 * @return void
8631 function message_popup_window() {
8632 global $USER, $DB, $PAGE, $CFG;
8634 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
8635 return;
8638 if (!isloggedin() || isguestuser()) {
8639 return;
8642 if (!isset($USER->message_lastpopup)) {
8643 $USER->message_lastpopup = 0;
8644 } else if ($USER->message_lastpopup > (time()-120)) {
8645 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8646 return;
8649 // A quick query to check whether the user has new messages.
8650 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
8651 if ($messagecount < 1) {
8652 return;
8655 // There are unread messages so now do a more complex but slower query.
8656 $messagesql = "SELECT m.id, c.blocked
8657 FROM {message} m
8658 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8659 JOIN {message_processors} p ON mw.processorid=p.id
8660 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8661 AND c.userid = m.useridto
8662 WHERE m.useridto = :userid
8663 AND p.name='popup'";
8665 // If the user was last notified over an hour ago we can re-notify them of old messages
8666 // so don't worry about when the new message was sent.
8667 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
8668 if (!$lastnotifiedlongago) {
8669 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8672 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
8674 $validmessages = 0;
8675 foreach ($waitingmessages as $messageinfo) {
8676 if ($messageinfo->blocked) {
8677 // Message is from a user who has since been blocked so just mark it read.
8678 // Get the full message to mark as read.
8679 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id));
8680 message_mark_message_read($messageobject, time());
8681 } else {
8682 $validmessages++;
8686 if ($validmessages > 0) {
8687 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8688 $strgomessage = get_string('gotomessages', 'message');
8689 $strstaymessage = get_string('ignore', 'admin');
8691 $notificationsound = null;
8692 $beep = get_user_preferences('message_beepnewmessage', '');
8693 if (!empty($beep)) {
8694 // Browsers will work down this list until they find something they support.
8695 $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
8696 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
8697 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8698 $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8700 $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8703 $url = $CFG->wwwroot.'/message/index.php';
8704 $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8705 html_writer::start_tag('div', array('id' => 'newmessagetext')).
8706 $strmessages.
8707 html_writer::end_tag('div').
8709 $notificationsound.
8710 html_writer::start_tag('div', array('id' => 'newmessagelinks')).
8711 html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
8712 html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
8713 html_writer::end_tag('div');
8714 html_writer::end_tag('div');
8716 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
8718 $USER->message_lastpopup = time();
8723 * Used to make sure that $min <= $value <= $max
8725 * Make sure that value is between min, and max
8727 * @param int $min The minimum value
8728 * @param int $value The value to check
8729 * @param int $max The maximum value
8730 * @return int
8732 function bounded_number($min, $value, $max) {
8733 if ($value < $min) {
8734 return $min;
8736 if ($value > $max) {
8737 return $max;
8739 return $value;
8743 * Check if there is a nested array within the passed array
8745 * @param array $array
8746 * @return bool true if there is a nested array false otherwise
8748 function array_is_nested($array) {
8749 foreach ($array as $value) {
8750 if (is_array($value)) {
8751 return true;
8754 return false;
8758 * get_performance_info() pairs up with init_performance_info()
8759 * loaded in setup.php. Returns an array with 'html' and 'txt'
8760 * values ready for use, and each of the individual stats provided
8761 * separately as well.
8763 * @return array
8765 function get_performance_info() {
8766 global $CFG, $PERF, $DB, $PAGE;
8768 $info = array();
8769 $info['html'] = ''; // Holds userfriendly HTML representation.
8770 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8772 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8774 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8775 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8777 if (function_exists('memory_get_usage')) {
8778 $info['memory_total'] = memory_get_usage();
8779 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8780 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8781 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8782 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8785 if (function_exists('memory_get_peak_usage')) {
8786 $info['memory_peak'] = memory_get_peak_usage();
8787 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8788 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8791 $inc = get_included_files();
8792 $info['includecount'] = count($inc);
8793 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8794 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8796 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8797 // We can not track more performance before installation or before PAGE init, sorry.
8798 return $info;
8801 $filtermanager = filter_manager::instance();
8802 if (method_exists($filtermanager, 'get_performance_summary')) {
8803 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8804 $info = array_merge($filterinfo, $info);
8805 foreach ($filterinfo as $key => $value) {
8806 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8807 $info['txt'] .= "$key: $value ";
8811 $stringmanager = get_string_manager();
8812 if (method_exists($stringmanager, 'get_performance_summary')) {
8813 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8814 $info = array_merge($filterinfo, $info);
8815 foreach ($filterinfo as $key => $value) {
8816 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8817 $info['txt'] .= "$key: $value ";
8821 if (!empty($PERF->logwrites)) {
8822 $info['logwrites'] = $PERF->logwrites;
8823 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8824 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8827 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
8828 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
8829 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8831 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
8832 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
8833 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
8835 if (function_exists('posix_times')) {
8836 $ptimes = posix_times();
8837 if (is_array($ptimes)) {
8838 foreach ($ptimes as $key => $val) {
8839 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
8841 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
8842 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8846 // Grab the load average for the last minute.
8847 // /proc will only work under some linux configurations
8848 // while uptime is there under MacOSX/Darwin and other unices.
8849 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
8850 list($serverload) = explode(' ', $loadavg[0]);
8851 unset($loadavg);
8852 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
8853 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
8854 $serverload = $matches[1];
8855 } else {
8856 trigger_error('Could not parse uptime output!');
8859 if (!empty($serverload)) {
8860 $info['serverload'] = $serverload;
8861 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
8862 $info['txt'] .= "serverload: {$info['serverload']} ";
8865 // Display size of session if session started.
8866 if ($si = \core\session\manager::get_performance_info()) {
8867 $info['sessionsize'] = $si['size'];
8868 $info['html'] .= $si['html'];
8869 $info['txt'] .= $si['txt'];
8872 if ($stats = cache_helper::get_stats()) {
8873 $html = '<span class="cachesused">';
8874 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
8875 $text = 'Caches used (hits/misses/sets): ';
8876 $hits = 0;
8877 $misses = 0;
8878 $sets = 0;
8879 foreach ($stats as $definition => $details) {
8880 switch ($details['mode']) {
8881 case cache_store::MODE_APPLICATION:
8882 $modeclass = 'application';
8883 $mode = ' <span title="application cache">[a]</span>';
8884 break;
8885 case cache_store::MODE_SESSION:
8886 $modeclass = 'session';
8887 $mode = ' <span title="session cache">[s]</span>';
8888 break;
8889 case cache_store::MODE_REQUEST:
8890 $modeclass = 'request';
8891 $mode = ' <span title="request cache">[r]</span>';
8892 break;
8894 $html .= '<span class="cache-definition-stats cache-mode-'.$modeclass.'">';
8895 $html .= '<span class="cache-definition-stats-heading">'.$definition.$mode.'</span>';
8896 $text .= "$definition {";
8897 foreach ($details['stores'] as $store => $data) {
8898 $hits += $data['hits'];
8899 $misses += $data['misses'];
8900 $sets += $data['sets'];
8901 if ($data['hits'] == 0 and $data['misses'] > 0) {
8902 $cachestoreclass = 'nohits';
8903 } else if ($data['hits'] < $data['misses']) {
8904 $cachestoreclass = 'lowhits';
8905 } else {
8906 $cachestoreclass = 'hihits';
8908 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
8909 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
8911 $html .= '</span>';
8912 $text .= '} ';
8914 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
8915 $html .= '</span> ';
8916 $info['cachesused'] = "$hits / $misses / $sets";
8917 $info['html'] .= $html;
8918 $info['txt'] .= $text.'. ';
8919 } else {
8920 $info['cachesused'] = '0 / 0 / 0';
8921 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
8922 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
8925 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
8926 return $info;
8930 * Legacy function.
8932 * @todo Document this function linux people
8934 function apd_get_profiling() {
8935 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
8939 * Delete directory or only its content
8941 * @param string $dir directory path
8942 * @param bool $contentonly
8943 * @return bool success, true also if dir does not exist
8945 function remove_dir($dir, $contentonly=false) {
8946 if (!file_exists($dir)) {
8947 // Nothing to do.
8948 return true;
8950 if (!$handle = opendir($dir)) {
8951 return false;
8953 $result = true;
8954 while (false!==($item = readdir($handle))) {
8955 if ($item != '.' && $item != '..') {
8956 if (is_dir($dir.'/'.$item)) {
8957 $result = remove_dir($dir.'/'.$item) && $result;
8958 } else {
8959 $result = unlink($dir.'/'.$item) && $result;
8963 closedir($handle);
8964 if ($contentonly) {
8965 clearstatcache(); // Make sure file stat cache is properly invalidated.
8966 return $result;
8968 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
8969 clearstatcache(); // Make sure file stat cache is properly invalidated.
8970 return $result;
8974 * Detect if an object or a class contains a given property
8975 * will take an actual object or the name of a class
8977 * @param mix $obj Name of class or real object to test
8978 * @param string $property name of property to find
8979 * @return bool true if property exists
8981 function object_property_exists( $obj, $property ) {
8982 if (is_string( $obj )) {
8983 $properties = get_class_vars( $obj );
8984 } else {
8985 $properties = get_object_vars( $obj );
8987 return array_key_exists( $property, $properties );
8991 * Converts an object into an associative array
8993 * This function converts an object into an associative array by iterating
8994 * over its public properties. Because this function uses the foreach
8995 * construct, Iterators are respected. It works recursively on arrays of objects.
8996 * Arrays and simple values are returned as is.
8998 * If class has magic properties, it can implement IteratorAggregate
8999 * and return all available properties in getIterator()
9001 * @param mixed $var
9002 * @return array
9004 function convert_to_array($var) {
9005 $result = array();
9007 // Loop over elements/properties.
9008 foreach ($var as $key => $value) {
9009 // Recursively convert objects.
9010 if (is_object($value) || is_array($value)) {
9011 $result[$key] = convert_to_array($value);
9012 } else {
9013 // Simple values are untouched.
9014 $result[$key] = $value;
9017 return $result;
9021 * Detect a custom script replacement in the data directory that will
9022 * replace an existing moodle script
9024 * @return string|bool full path name if a custom script exists, false if no custom script exists
9026 function custom_script_path() {
9027 global $CFG, $SCRIPT;
9029 if ($SCRIPT === null) {
9030 // Probably some weird external script.
9031 return false;
9034 $scriptpath = $CFG->customscripts . $SCRIPT;
9036 // Check the custom script exists.
9037 if (file_exists($scriptpath) and is_file($scriptpath)) {
9038 return $scriptpath;
9039 } else {
9040 return false;
9045 * Returns whether or not the user object is a remote MNET user. This function
9046 * is in moodlelib because it does not rely on loading any of the MNET code.
9048 * @param object $user A valid user object
9049 * @return bool True if the user is from a remote Moodle.
9051 function is_mnet_remote_user($user) {
9052 global $CFG;
9054 if (!isset($CFG->mnet_localhost_id)) {
9055 include_once($CFG->dirroot . '/mnet/lib.php');
9056 $env = new mnet_environment();
9057 $env->init();
9058 unset($env);
9061 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9065 * This function will search for browser prefereed languages, setting Moodle
9066 * to use the best one available if $SESSION->lang is undefined
9068 function setup_lang_from_browser() {
9069 global $CFG, $SESSION, $USER;
9071 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9072 // Lang is defined in session or user profile, nothing to do.
9073 return;
9076 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9077 return;
9080 // Extract and clean langs from headers.
9081 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9082 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9083 $rawlangs = explode(',', $rawlangs); // Convert to array.
9084 $langs = array();
9086 $order = 1.0;
9087 foreach ($rawlangs as $lang) {
9088 if (strpos($lang, ';') === false) {
9089 $langs[(string)$order] = $lang;
9090 $order = $order-0.01;
9091 } else {
9092 $parts = explode(';', $lang);
9093 $pos = strpos($parts[1], '=');
9094 $langs[substr($parts[1], $pos+1)] = $parts[0];
9097 krsort($langs, SORT_NUMERIC);
9099 // Look for such langs under standard locations.
9100 foreach ($langs as $lang) {
9101 // Clean it properly for include.
9102 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9103 if (get_string_manager()->translation_exists($lang, false)) {
9104 // Lang exists, set it in session.
9105 $SESSION->lang = $lang;
9106 // We have finished. Go out.
9107 break;
9110 return;
9114 * Check if $url matches anything in proxybypass list
9116 * Any errors just result in the proxy being used (least bad)
9118 * @param string $url url to check
9119 * @return boolean true if we should bypass the proxy
9121 function is_proxybypass( $url ) {
9122 global $CFG;
9124 // Sanity check.
9125 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9126 return false;
9129 // Get the host part out of the url.
9130 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9131 return false;
9134 // Get the possible bypass hosts into an array.
9135 $matches = explode( ',', $CFG->proxybypass );
9137 // Check for a match.
9138 // (IPs need to match the left hand side and hosts the right of the url,
9139 // but we can recklessly check both as there can't be a false +ve).
9140 foreach ($matches as $match) {
9141 $match = trim($match);
9143 // Try for IP match (Left side).
9144 $lhs = substr($host, 0, strlen($match));
9145 if (strcasecmp($match, $lhs)==0) {
9146 return true;
9149 // Try for host match (Right side).
9150 $rhs = substr($host, -strlen($match));
9151 if (strcasecmp($match, $rhs)==0) {
9152 return true;
9156 // Nothing matched.
9157 return false;
9161 * Check if the passed navigation is of the new style
9163 * @param mixed $navigation
9164 * @return bool true for yes false for no
9166 function is_newnav($navigation) {
9167 if (is_array($navigation) && !empty($navigation['newnav'])) {
9168 return true;
9169 } else {
9170 return false;
9175 * Checks whether the given variable name is defined as a variable within the given object.
9177 * This will NOT work with stdClass objects, which have no class variables.
9179 * @param string $var The variable name
9180 * @param object $object The object to check
9181 * @return boolean
9183 function in_object_vars($var, $object) {
9184 $classvars = get_class_vars(get_class($object));
9185 $classvars = array_keys($classvars);
9186 return in_array($var, $classvars);
9190 * Returns an array without repeated objects.
9191 * This function is similar to array_unique, but for arrays that have objects as values
9193 * @param array $array
9194 * @param bool $keepkeyassoc
9195 * @return array
9197 function object_array_unique($array, $keepkeyassoc = true) {
9198 $duplicatekeys = array();
9199 $tmp = array();
9201 foreach ($array as $key => $val) {
9202 // Convert objects to arrays, in_array() does not support objects.
9203 if (is_object($val)) {
9204 $val = (array)$val;
9207 if (!in_array($val, $tmp)) {
9208 $tmp[] = $val;
9209 } else {
9210 $duplicatekeys[] = $key;
9214 foreach ($duplicatekeys as $key) {
9215 unset($array[$key]);
9218 return $keepkeyassoc ? $array : array_values($array);
9222 * Is a userid the primary administrator?
9224 * @param int $userid int id of user to check
9225 * @return boolean
9227 function is_primary_admin($userid) {
9228 $primaryadmin = get_admin();
9230 if ($userid == $primaryadmin->id) {
9231 return true;
9232 } else {
9233 return false;
9238 * Returns the site identifier
9240 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9242 function get_site_identifier() {
9243 global $CFG;
9244 // Check to see if it is missing. If so, initialise it.
9245 if (empty($CFG->siteidentifier)) {
9246 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9248 // Return it.
9249 return $CFG->siteidentifier;
9253 * Check whether the given password has no more than the specified
9254 * number of consecutive identical characters.
9256 * @param string $password password to be checked against the password policy
9257 * @param integer $maxchars maximum number of consecutive identical characters
9258 * @return bool
9260 function check_consecutive_identical_characters($password, $maxchars) {
9262 if ($maxchars < 1) {
9263 return true; // Zero 0 is to disable this check.
9265 if (strlen($password) <= $maxchars) {
9266 return true; // Too short to fail this test.
9269 $previouschar = '';
9270 $consecutivecount = 1;
9271 foreach (str_split($password) as $char) {
9272 if ($char != $previouschar) {
9273 $consecutivecount = 1;
9274 } else {
9275 $consecutivecount++;
9276 if ($consecutivecount > $maxchars) {
9277 return false; // Check failed already.
9281 $previouschar = $char;
9284 return true;
9288 * Helper function to do partial function binding.
9289 * so we can use it for preg_replace_callback, for example
9290 * this works with php functions, user functions, static methods and class methods
9291 * it returns you a callback that you can pass on like so:
9293 * $callback = partial('somefunction', $arg1, $arg2);
9294 * or
9295 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9296 * or even
9297 * $obj = new someclass();
9298 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9300 * and then the arguments that are passed through at calltime are appended to the argument list.
9302 * @param mixed $function a php callback
9303 * @param mixed $arg1,... $argv arguments to partially bind with
9304 * @return array Array callback
9306 function partial() {
9307 if (!class_exists('partial')) {
9309 * Used to manage function binding.
9310 * @copyright 2009 Penny Leach
9311 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9313 class partial{
9314 /** @var array */
9315 public $values = array();
9316 /** @var string The function to call as a callback. */
9317 public $func;
9319 * Constructor
9320 * @param string $func
9321 * @param array $args
9323 public function __construct($func, $args) {
9324 $this->values = $args;
9325 $this->func = $func;
9328 * Calls the callback function.
9329 * @return mixed
9331 public function method() {
9332 $args = func_get_args();
9333 return call_user_func_array($this->func, array_merge($this->values, $args));
9337 $args = func_get_args();
9338 $func = array_shift($args);
9339 $p = new partial($func, $args);
9340 return array($p, 'method');
9344 * helper function to load up and initialise the mnet environment
9345 * this must be called before you use mnet functions.
9347 * @return mnet_environment the equivalent of old $MNET global
9349 function get_mnet_environment() {
9350 global $CFG;
9351 require_once($CFG->dirroot . '/mnet/lib.php');
9352 static $instance = null;
9353 if (empty($instance)) {
9354 $instance = new mnet_environment();
9355 $instance->init();
9357 return $instance;
9361 * during xmlrpc server code execution, any code wishing to access
9362 * information about the remote peer must use this to get it.
9364 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9366 function get_mnet_remote_client() {
9367 if (!defined('MNET_SERVER')) {
9368 debugging(get_string('notinxmlrpcserver', 'mnet'));
9369 return false;
9371 global $MNET_REMOTE_CLIENT;
9372 if (isset($MNET_REMOTE_CLIENT)) {
9373 return $MNET_REMOTE_CLIENT;
9375 return false;
9379 * during the xmlrpc server code execution, this will be called
9380 * to setup the object returned by {@link get_mnet_remote_client}
9382 * @param mnet_remote_client $client the client to set up
9383 * @throws moodle_exception
9385 function set_mnet_remote_client($client) {
9386 if (!defined('MNET_SERVER')) {
9387 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9389 global $MNET_REMOTE_CLIENT;
9390 $MNET_REMOTE_CLIENT = $client;
9394 * return the jump url for a given remote user
9395 * this is used for rewriting forum post links in emails, etc
9397 * @param stdclass $user the user to get the idp url for
9399 function mnet_get_idp_jump_url($user) {
9400 global $CFG;
9402 static $mnetjumps = array();
9403 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9404 $idp = mnet_get_peer_host($user->mnethostid);
9405 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9406 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9408 return $mnetjumps[$user->mnethostid];
9412 * Gets the homepage to use for the current user
9414 * @return int One of HOMEPAGE_*
9416 function get_home_page() {
9417 global $CFG;
9419 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9420 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9421 return HOMEPAGE_MY;
9422 } else {
9423 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9426 return HOMEPAGE_SITE;
9430 * Gets the name of a course to be displayed when showing a list of courses.
9431 * By default this is just $course->fullname but user can configure it. The
9432 * result of this function should be passed through print_string.
9433 * @param stdClass|course_in_list $course Moodle course object
9434 * @return string Display name of course (either fullname or short + fullname)
9436 function get_course_display_name_for_list($course) {
9437 global $CFG;
9438 if (!empty($CFG->courselistshortnames)) {
9439 if (!($course instanceof stdClass)) {
9440 $course = (object)convert_to_array($course);
9442 return get_string('courseextendednamedisplay', '', $course);
9443 } else {
9444 return $course->fullname;
9449 * The lang_string class
9451 * This special class is used to create an object representation of a string request.
9452 * It is special because processing doesn't occur until the object is first used.
9453 * The class was created especially to aid performance in areas where strings were
9454 * required to be generated but were not necessarily used.
9455 * As an example the admin tree when generated uses over 1500 strings, of which
9456 * normally only 1/3 are ever actually printed at any time.
9457 * The performance advantage is achieved by not actually processing strings that
9458 * arn't being used, as such reducing the processing required for the page.
9460 * How to use the lang_string class?
9461 * There are two methods of using the lang_string class, first through the
9462 * forth argument of the get_string function, and secondly directly.
9463 * The following are examples of both.
9464 * 1. Through get_string calls e.g.
9465 * $string = get_string($identifier, $component, $a, true);
9466 * $string = get_string('yes', 'moodle', null, true);
9467 * 2. Direct instantiation
9468 * $string = new lang_string($identifier, $component, $a, $lang);
9469 * $string = new lang_string('yes');
9471 * How do I use a lang_string object?
9472 * The lang_string object makes use of a magic __toString method so that you
9473 * are able to use the object exactly as you would use a string in most cases.
9474 * This means you are able to collect it into a variable and then directly
9475 * echo it, or concatenate it into another string, or similar.
9476 * The other thing you can do is manually get the string by calling the
9477 * lang_strings out method e.g.
9478 * $string = new lang_string('yes');
9479 * $string->out();
9480 * Also worth noting is that the out method can take one argument, $lang which
9481 * allows the developer to change the language on the fly.
9483 * When should I use a lang_string object?
9484 * The lang_string object is designed to be used in any situation where a
9485 * string may not be needed, but needs to be generated.
9486 * The admin tree is a good example of where lang_string objects should be
9487 * used.
9488 * A more practical example would be any class that requries strings that may
9489 * not be printed (after all classes get renderer by renderers and who knows
9490 * what they will do ;))
9492 * When should I not use a lang_string object?
9493 * Don't use lang_strings when you are going to use a string immediately.
9494 * There is no need as it will be processed immediately and there will be no
9495 * advantage, and in fact perhaps a negative hit as a class has to be
9496 * instantiated for a lang_string object, however get_string won't require
9497 * that.
9499 * Limitations:
9500 * 1. You cannot use a lang_string object as an array offset. Doing so will
9501 * result in PHP throwing an error. (You can use it as an object property!)
9503 * @package core
9504 * @category string
9505 * @copyright 2011 Sam Hemelryk
9506 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9508 class lang_string {
9510 /** @var string The strings identifier */
9511 protected $identifier;
9512 /** @var string The strings component. Default '' */
9513 protected $component = '';
9514 /** @var array|stdClass Any arguments required for the string. Default null */
9515 protected $a = null;
9516 /** @var string The language to use when processing the string. Default null */
9517 protected $lang = null;
9519 /** @var string The processed string (once processed) */
9520 protected $string = null;
9523 * A special boolean. If set to true then the object has been woken up and
9524 * cannot be regenerated. If this is set then $this->string MUST be used.
9525 * @var bool
9527 protected $forcedstring = false;
9530 * Constructs a lang_string object
9532 * This function should do as little processing as possible to ensure the best
9533 * performance for strings that won't be used.
9535 * @param string $identifier The strings identifier
9536 * @param string $component The strings component
9537 * @param stdClass|array $a Any arguments the string requires
9538 * @param string $lang The language to use when processing the string.
9539 * @throws coding_exception
9541 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9542 if (empty($component)) {
9543 $component = 'moodle';
9546 $this->identifier = $identifier;
9547 $this->component = $component;
9548 $this->lang = $lang;
9550 // We MUST duplicate $a to ensure that it if it changes by reference those
9551 // changes are not carried across.
9552 // To do this we always ensure $a or its properties/values are strings
9553 // and that any properties/values that arn't convertable are forgotten.
9554 if (!empty($a)) {
9555 if (is_scalar($a)) {
9556 $this->a = $a;
9557 } else if ($a instanceof lang_string) {
9558 $this->a = $a->out();
9559 } else if (is_object($a) or is_array($a)) {
9560 $a = (array)$a;
9561 $this->a = array();
9562 foreach ($a as $key => $value) {
9563 // Make sure conversion errors don't get displayed (results in '').
9564 if (is_array($value)) {
9565 $this->a[$key] = '';
9566 } else if (is_object($value)) {
9567 if (method_exists($value, '__toString')) {
9568 $this->a[$key] = $value->__toString();
9569 } else {
9570 $this->a[$key] = '';
9572 } else {
9573 $this->a[$key] = (string)$value;
9579 if (debugging(false, DEBUG_DEVELOPER)) {
9580 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9581 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9583 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9584 throw new coding_exception('Invalid string compontent. Please check your string definition');
9586 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9587 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9593 * Processes the string.
9595 * This function actually processes the string, stores it in the string property
9596 * and then returns it.
9597 * You will notice that this function is VERY similar to the get_string method.
9598 * That is because it is pretty much doing the same thing.
9599 * However as this function is an upgrade it isn't as tolerant to backwards
9600 * compatibility.
9602 * @return string
9603 * @throws coding_exception
9605 protected function get_string() {
9606 global $CFG;
9608 // Check if we need to process the string.
9609 if ($this->string === null) {
9610 // Check the quality of the identifier.
9611 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9612 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);
9615 // Process the string.
9616 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9617 // Debugging feature lets you display string identifier and component.
9618 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9619 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9622 // Return the string.
9623 return $this->string;
9627 * Returns the string
9629 * @param string $lang The langauge to use when processing the string
9630 * @return string
9632 public function out($lang = null) {
9633 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9634 if ($this->forcedstring) {
9635 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9636 return $this->get_string();
9638 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9639 return $translatedstring->out();
9641 return $this->get_string();
9645 * Magic __toString method for printing a string
9647 * @return string
9649 public function __toString() {
9650 return $this->get_string();
9654 * Magic __set_state method used for var_export
9656 * @return string
9658 public function __set_state() {
9659 return $this->get_string();
9663 * Prepares the lang_string for sleep and stores only the forcedstring and
9664 * string properties... the string cannot be regenerated so we need to ensure
9665 * it is generated for this.
9667 * @return string
9669 public function __sleep() {
9670 $this->get_string();
9671 $this->forcedstring = true;
9672 return array('forcedstring', 'string', 'lang');