Merge branch 'wip-mdl-52007' of https://github.com/rajeshtaneja/moodle
[moodle.git] / lib / moodlelib.php
blobabb73c332d54bede9c862097986904843bc9cf3d
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 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 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 (!array_key_exists($allname, $user)) {
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 $oldcourse->enablecompletion = 0;
4940 if (!empty($options['keep_groups_and_groupings'])) {
4941 $oldcourse->defaultgroupingid = 0;
4943 $DB->update_record('course', $oldcourse);
4945 // Delete course sections.
4946 $DB->delete_records('course_sections', array('course' => $course->id));
4948 // Delete legacy, section and any other course files.
4949 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
4951 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
4952 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
4953 // Easy, do not delete the context itself...
4954 $coursecontext->delete_content();
4955 } else {
4956 // Hack alert!!!!
4957 // We can not drop all context stuff because it would bork enrolments and roles,
4958 // there might be also files used by enrol plugins...
4961 // Delete legacy files - just in case some files are still left there after conversion to new file api,
4962 // also some non-standard unsupported plugins may try to store something there.
4963 fulldelete($CFG->dataroot.'/'.$course->id);
4965 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
4966 $cachemodinfo = cache::make('core', 'coursemodinfo');
4967 $cachemodinfo->delete($courseid);
4969 // Trigger a course content deleted event.
4970 $event = \core\event\course_content_deleted::create(array(
4971 'objectid' => $course->id,
4972 'context' => $coursecontext,
4973 'other' => array('shortname' => $course->shortname,
4974 'fullname' => $course->fullname,
4975 'options' => $options) // Passing this for legacy reasons.
4977 $event->add_record_snapshot('course', $course);
4978 $event->trigger();
4980 return true;
4984 * Change dates in module - used from course reset.
4986 * @param string $modname forum, assignment, etc
4987 * @param array $fields array of date fields from mod table
4988 * @param int $timeshift time difference
4989 * @param int $courseid
4990 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
4991 * @return bool success
4993 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
4994 global $CFG, $DB;
4995 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
4997 $return = true;
4998 $params = array($timeshift, $courseid);
4999 foreach ($fields as $field) {
5000 $updatesql = "UPDATE {".$modname."}
5001 SET $field = $field + ?
5002 WHERE course=? AND $field<>0";
5003 if ($modid) {
5004 $updatesql .= ' AND id=?';
5005 $params[] = $modid;
5007 $return = $DB->execute($updatesql, $params) && $return;
5010 $refreshfunction = $modname.'_refresh_events';
5011 if (function_exists($refreshfunction)) {
5012 $refreshfunction($courseid);
5015 return $return;
5019 * This function will empty a course of user data.
5020 * It will retain the activities and the structure of the course.
5022 * @param object $data an object containing all the settings including courseid (without magic quotes)
5023 * @return array status array of array component, item, error
5025 function reset_course_userdata($data) {
5026 global $CFG, $DB;
5027 require_once($CFG->libdir.'/gradelib.php');
5028 require_once($CFG->libdir.'/completionlib.php');
5029 require_once($CFG->dirroot.'/group/lib.php');
5031 $data->courseid = $data->id;
5032 $context = context_course::instance($data->courseid);
5034 $eventparams = array(
5035 'context' => $context,
5036 'courseid' => $data->id,
5037 'other' => array(
5038 'reset_options' => (array) $data
5041 $event = \core\event\course_reset_started::create($eventparams);
5042 $event->trigger();
5044 // Calculate the time shift of dates.
5045 if (!empty($data->reset_start_date)) {
5046 // Time part of course startdate should be zero.
5047 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5048 } else {
5049 $data->timeshift = 0;
5052 // Result array: component, item, error.
5053 $status = array();
5055 // Start the resetting.
5056 $componentstr = get_string('general');
5058 // Move the course start time.
5059 if (!empty($data->reset_start_date) and $data->timeshift) {
5060 // Change course start data.
5061 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5062 // Update all course and group events - do not move activity events.
5063 $updatesql = "UPDATE {event}
5064 SET timestart = timestart + ?
5065 WHERE courseid=? AND instance=0";
5066 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5068 // Update any date activity restrictions.
5069 if ($CFG->enableavailability) {
5070 \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5073 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5076 if (!empty($data->reset_events)) {
5077 $DB->delete_records('event', array('courseid' => $data->courseid));
5078 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5081 if (!empty($data->reset_notes)) {
5082 require_once($CFG->dirroot.'/notes/lib.php');
5083 note_delete_all($data->courseid);
5084 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5087 if (!empty($data->delete_blog_associations)) {
5088 require_once($CFG->dirroot.'/blog/lib.php');
5089 blog_remove_associations_for_course($data->courseid);
5090 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5093 if (!empty($data->reset_completion)) {
5094 // Delete course and activity completion information.
5095 $course = $DB->get_record('course', array('id' => $data->courseid));
5096 $cc = new completion_info($course);
5097 $cc->delete_all_completion_data();
5098 $status[] = array('component' => $componentstr,
5099 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5102 $componentstr = get_string('roles');
5104 if (!empty($data->reset_roles_overrides)) {
5105 $children = $context->get_child_contexts();
5106 foreach ($children as $child) {
5107 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5109 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5110 // Force refresh for logged in users.
5111 $context->mark_dirty();
5112 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5115 if (!empty($data->reset_roles_local)) {
5116 $children = $context->get_child_contexts();
5117 foreach ($children as $child) {
5118 role_unassign_all(array('contextid' => $child->id));
5120 // Force refresh for logged in users.
5121 $context->mark_dirty();
5122 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5125 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5126 $data->unenrolled = array();
5127 if (!empty($data->unenrol_users)) {
5128 $plugins = enrol_get_plugins(true);
5129 $instances = enrol_get_instances($data->courseid, true);
5130 foreach ($instances as $key => $instance) {
5131 if (!isset($plugins[$instance->enrol])) {
5132 unset($instances[$key]);
5133 continue;
5137 foreach ($data->unenrol_users as $withroleid) {
5138 if ($withroleid) {
5139 $sql = "SELECT ue.*
5140 FROM {user_enrolments} ue
5141 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5142 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5143 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5144 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5146 } else {
5147 // Without any role assigned at course context.
5148 $sql = "SELECT ue.*
5149 FROM {user_enrolments} ue
5150 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5151 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5152 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5153 WHERE ra.id IS null";
5154 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5157 $rs = $DB->get_recordset_sql($sql, $params);
5158 foreach ($rs as $ue) {
5159 if (!isset($instances[$ue->enrolid])) {
5160 continue;
5162 $instance = $instances[$ue->enrolid];
5163 $plugin = $plugins[$instance->enrol];
5164 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5165 continue;
5168 $plugin->unenrol_user($instance, $ue->userid);
5169 $data->unenrolled[$ue->userid] = $ue->userid;
5171 $rs->close();
5174 if (!empty($data->unenrolled)) {
5175 $status[] = array(
5176 'component' => $componentstr,
5177 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5178 'error' => false
5182 $componentstr = get_string('groups');
5184 // Remove all group members.
5185 if (!empty($data->reset_groups_members)) {
5186 groups_delete_group_members($data->courseid);
5187 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5190 // Remove all groups.
5191 if (!empty($data->reset_groups_remove)) {
5192 groups_delete_groups($data->courseid, false);
5193 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5196 // Remove all grouping members.
5197 if (!empty($data->reset_groupings_members)) {
5198 groups_delete_groupings_groups($data->courseid, false);
5199 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5202 // Remove all groupings.
5203 if (!empty($data->reset_groupings_remove)) {
5204 groups_delete_groupings($data->courseid, false);
5205 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5208 // Look in every instance of every module for data to delete.
5209 $unsupportedmods = array();
5210 if ($allmods = $DB->get_records('modules') ) {
5211 foreach ($allmods as $mod) {
5212 $modname = $mod->name;
5213 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5214 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5215 if (file_exists($modfile)) {
5216 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5217 continue; // Skip mods with no instances.
5219 include_once($modfile);
5220 if (function_exists($moddeleteuserdata)) {
5221 $modstatus = $moddeleteuserdata($data);
5222 if (is_array($modstatus)) {
5223 $status = array_merge($status, $modstatus);
5224 } else {
5225 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5227 } else {
5228 $unsupportedmods[] = $mod;
5230 } else {
5231 debugging('Missing lib.php in '.$modname.' module!');
5236 // Mention unsupported mods.
5237 if (!empty($unsupportedmods)) {
5238 foreach ($unsupportedmods as $mod) {
5239 $status[] = array(
5240 'component' => get_string('modulenameplural', $mod->name),
5241 'item' => '',
5242 'error' => get_string('resetnotimplemented')
5247 $componentstr = get_string('gradebook', 'grades');
5248 // Reset gradebook,.
5249 if (!empty($data->reset_gradebook_items)) {
5250 remove_course_grades($data->courseid, false);
5251 grade_grab_course_grades($data->courseid);
5252 grade_regrade_final_grades($data->courseid);
5253 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5255 } else if (!empty($data->reset_gradebook_grades)) {
5256 grade_course_reset($data->courseid);
5257 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5259 // Reset comments.
5260 if (!empty($data->reset_comments)) {
5261 require_once($CFG->dirroot.'/comment/lib.php');
5262 comment::reset_course_page_comments($context);
5265 $event = \core\event\course_reset_ended::create($eventparams);
5266 $event->trigger();
5268 return $status;
5272 * Generate an email processing address.
5274 * @param int $modid
5275 * @param string $modargs
5276 * @return string Returns email processing address
5278 function generate_email_processing_address($modid, $modargs) {
5279 global $CFG;
5281 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5282 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5288 * @todo Finish documenting this function
5290 * @param string $modargs
5291 * @param string $body Currently unused
5293 function moodle_process_email($modargs, $body) {
5294 global $DB;
5296 // The first char should be an unencoded letter. We'll take this as an action.
5297 switch ($modargs{0}) {
5298 case 'B': { // Bounce.
5299 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5300 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5301 // Check the half md5 of their email.
5302 $md5check = substr(md5($user->email), 0, 16);
5303 if ($md5check == substr($modargs, -16)) {
5304 set_bounce_count($user);
5306 // Else maybe they've already changed it?
5309 break;
5310 // Maybe more later?
5314 // CORRESPONDENCE.
5317 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5319 * @param string $action 'get', 'buffer', 'close' or 'flush'
5320 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5322 function get_mailer($action='get') {
5323 global $CFG;
5325 /** @var moodle_phpmailer $mailer */
5326 static $mailer = null;
5327 static $counter = 0;
5329 if (!isset($CFG->smtpmaxbulk)) {
5330 $CFG->smtpmaxbulk = 1;
5333 if ($action == 'get') {
5334 $prevkeepalive = false;
5336 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5337 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5338 $counter++;
5339 // Reset the mailer.
5340 $mailer->Priority = 3;
5341 $mailer->CharSet = 'UTF-8'; // Our default.
5342 $mailer->ContentType = "text/plain";
5343 $mailer->Encoding = "8bit";
5344 $mailer->From = "root@localhost";
5345 $mailer->FromName = "Root User";
5346 $mailer->Sender = "";
5347 $mailer->Subject = "";
5348 $mailer->Body = "";
5349 $mailer->AltBody = "";
5350 $mailer->ConfirmReadingTo = "";
5352 $mailer->clearAllRecipients();
5353 $mailer->clearReplyTos();
5354 $mailer->clearAttachments();
5355 $mailer->clearCustomHeaders();
5356 return $mailer;
5359 $prevkeepalive = $mailer->SMTPKeepAlive;
5360 get_mailer('flush');
5363 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5364 $mailer = new moodle_phpmailer();
5366 $counter = 1;
5368 if ($CFG->smtphosts == 'qmail') {
5369 // Use Qmail system.
5370 $mailer->isQmail();
5372 } else if (empty($CFG->smtphosts)) {
5373 // Use PHP mail() = sendmail.
5374 $mailer->isMail();
5376 } else {
5377 // Use SMTP directly.
5378 $mailer->isSMTP();
5379 if (!empty($CFG->debugsmtp)) {
5380 $mailer->SMTPDebug = true;
5382 // Specify main and backup servers.
5383 $mailer->Host = $CFG->smtphosts;
5384 // Specify secure connection protocol.
5385 $mailer->SMTPSecure = $CFG->smtpsecure;
5386 // Use previous keepalive.
5387 $mailer->SMTPKeepAlive = $prevkeepalive;
5389 if ($CFG->smtpuser) {
5390 // Use SMTP authentication.
5391 $mailer->SMTPAuth = true;
5392 $mailer->Username = $CFG->smtpuser;
5393 $mailer->Password = $CFG->smtppass;
5397 return $mailer;
5400 $nothing = null;
5402 // Keep smtp session open after sending.
5403 if ($action == 'buffer') {
5404 if (!empty($CFG->smtpmaxbulk)) {
5405 get_mailer('flush');
5406 $m = get_mailer();
5407 if ($m->Mailer == 'smtp') {
5408 $m->SMTPKeepAlive = true;
5411 return $nothing;
5414 // Close smtp session, but continue buffering.
5415 if ($action == 'flush') {
5416 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5417 if (!empty($mailer->SMTPDebug)) {
5418 echo '<pre>'."\n";
5420 $mailer->SmtpClose();
5421 if (!empty($mailer->SMTPDebug)) {
5422 echo '</pre>';
5425 return $nothing;
5428 // Close smtp session, do not buffer anymore.
5429 if ($action == 'close') {
5430 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5431 get_mailer('flush');
5432 $mailer->SMTPKeepAlive = false;
5434 $mailer = null; // Better force new instance.
5435 return $nothing;
5440 * Send an email to a specified user
5442 * @param stdClass $user A {@link $USER} object
5443 * @param stdClass $from A {@link $USER} object
5444 * @param string $subject plain text subject line of the email
5445 * @param string $messagetext plain text version of the message
5446 * @param string $messagehtml complete html version of the message (optional)
5447 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5448 * @param string $attachname the name of the file (extension indicates MIME)
5449 * @param bool $usetrueaddress determines whether $from email address should
5450 * be sent out. Will be overruled by user profile setting for maildisplay
5451 * @param string $replyto Email address to reply to
5452 * @param string $replytoname Name of reply to recipient
5453 * @param int $wordwrapwidth custom word wrap width, default 79
5454 * @return bool Returns true if mail was sent OK and false if there was an error.
5456 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5457 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5459 global $CFG;
5461 if (empty($user) or empty($user->id)) {
5462 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5463 return false;
5466 if (empty($user->email)) {
5467 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5468 return false;
5471 if (!empty($user->deleted)) {
5472 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5473 return false;
5476 if (defined('BEHAT_SITE_RUNNING')) {
5477 // Fake email sending in behat.
5478 return true;
5481 if (!empty($CFG->noemailever)) {
5482 // Hidden setting for development sites, set in config.php if needed.
5483 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5484 return true;
5487 if (!empty($CFG->divertallemailsto)) {
5488 $subject = "[DIVERTED {$user->email}] $subject";
5489 $user = clone($user);
5490 $user->email = $CFG->divertallemailsto;
5493 // Skip mail to suspended users.
5494 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5495 return true;
5498 if (!validate_email($user->email)) {
5499 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5500 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5501 return false;
5504 if (over_bounce_threshold($user)) {
5505 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5506 return false;
5509 // TLD .invalid is specifically reserved for invalid domain names.
5510 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5511 if (substr($user->email, -8) == '.invalid') {
5512 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5513 return true; // This is not an error.
5516 // If the user is a remote mnet user, parse the email text for URL to the
5517 // wwwroot and modify the url to direct the user's browser to login at their
5518 // home site (identity provider - idp) before hitting the link itself.
5519 if (is_mnet_remote_user($user)) {
5520 require_once($CFG->dirroot.'/mnet/lib.php');
5522 $jumpurl = mnet_get_idp_jump_url($user);
5523 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5525 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5526 $callback,
5527 $messagetext);
5528 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5529 $callback,
5530 $messagehtml);
5532 $mail = get_mailer();
5534 if (!empty($mail->SMTPDebug)) {
5535 echo '<pre>' . "\n";
5538 $temprecipients = array();
5539 $tempreplyto = array();
5541 $supportuser = core_user::get_support_user();
5543 // Make up an email address for handling bounces.
5544 if (!empty($CFG->handlebounces)) {
5545 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5546 $mail->Sender = generate_email_processing_address(0, $modargs);
5547 } else {
5548 $mail->Sender = $supportuser->email;
5551 if (!empty($CFG->emailonlyfromnoreplyaddress)) {
5552 $usetrueaddress = false;
5553 if (empty($replyto) && $from->maildisplay) {
5554 $replyto = $from->email;
5555 $replytoname = fullname($from);
5559 if (is_string($from)) { // So we can pass whatever we want if there is need.
5560 $mail->From = $CFG->noreplyaddress;
5561 $mail->FromName = $from;
5562 } else if ($usetrueaddress and $from->maildisplay) {
5563 $mail->From = $from->email;
5564 $mail->FromName = fullname($from);
5565 } else {
5566 $mail->From = $CFG->noreplyaddress;
5567 $mail->FromName = fullname($from);
5568 if (empty($replyto)) {
5569 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5573 if (!empty($replyto)) {
5574 $tempreplyto[] = array($replyto, $replytoname);
5577 $mail->Subject = substr($subject, 0, 900);
5579 $temprecipients[] = array($user->email, fullname($user));
5581 // Set word wrap.
5582 $mail->WordWrap = $wordwrapwidth;
5584 if (!empty($from->customheaders)) {
5585 // Add custom headers.
5586 if (is_array($from->customheaders)) {
5587 foreach ($from->customheaders as $customheader) {
5588 $mail->addCustomHeader($customheader);
5590 } else {
5591 $mail->addCustomHeader($from->customheaders);
5595 if (!empty($from->priority)) {
5596 $mail->Priority = $from->priority;
5599 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5600 // Don't ever send HTML to users who don't want it.
5601 $mail->isHTML(true);
5602 $mail->Encoding = 'quoted-printable';
5603 $mail->Body = $messagehtml;
5604 $mail->AltBody = "\n$messagetext\n";
5605 } else {
5606 $mail->IsHTML(false);
5607 $mail->Body = "\n$messagetext\n";
5610 if ($attachment && $attachname) {
5611 if (preg_match( "~\\.\\.~" , $attachment )) {
5612 // Security check for ".." in dir path.
5613 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5614 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5615 } else {
5616 require_once($CFG->libdir.'/filelib.php');
5617 $mimetype = mimeinfo('type', $attachname);
5619 $attachmentpath = $attachment;
5621 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5622 $attachpath = str_replace('\\', '/', $attachmentpath);
5623 // Make sure both variables are normalised before comparing.
5624 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
5626 // If the attachment is a full path to a file in the tempdir, use it as is,
5627 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5628 if (strpos($attachpath, $temppath) !== 0) {
5629 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5632 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5636 // Check if the email should be sent in an other charset then the default UTF-8.
5637 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5639 // Use the defined site mail charset or eventually the one preferred by the recipient.
5640 $charset = $CFG->sitemailcharset;
5641 if (!empty($CFG->allowusermailcharset)) {
5642 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5643 $charset = $useremailcharset;
5647 // Convert all the necessary strings if the charset is supported.
5648 $charsets = get_list_of_charsets();
5649 unset($charsets['UTF-8']);
5650 if (in_array($charset, $charsets)) {
5651 $mail->CharSet = $charset;
5652 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5653 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5654 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5655 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5657 foreach ($temprecipients as $key => $values) {
5658 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5660 foreach ($tempreplyto as $key => $values) {
5661 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5666 foreach ($temprecipients as $values) {
5667 $mail->addAddress($values[0], $values[1]);
5669 foreach ($tempreplyto as $values) {
5670 $mail->addReplyTo($values[0], $values[1]);
5673 if ($mail->send()) {
5674 set_send_count($user);
5675 if (!empty($mail->SMTPDebug)) {
5676 echo '</pre>';
5678 return true;
5679 } else {
5680 // Trigger event for failing to send email.
5681 $event = \core\event\email_failed::create(array(
5682 'context' => context_system::instance(),
5683 'userid' => $from->id,
5684 'relateduserid' => $user->id,
5685 'other' => array(
5686 'subject' => $subject,
5687 'message' => $messagetext,
5688 'errorinfo' => $mail->ErrorInfo
5691 $event->trigger();
5692 if (CLI_SCRIPT) {
5693 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5695 if (!empty($mail->SMTPDebug)) {
5696 echo '</pre>';
5698 return false;
5703 * Generate a signoff for emails based on support settings
5705 * @return string
5707 function generate_email_signoff() {
5708 global $CFG;
5710 $signoff = "\n";
5711 if (!empty($CFG->supportname)) {
5712 $signoff .= $CFG->supportname."\n";
5714 if (!empty($CFG->supportemail)) {
5715 $signoff .= $CFG->supportemail."\n";
5717 if (!empty($CFG->supportpage)) {
5718 $signoff .= $CFG->supportpage."\n";
5720 return $signoff;
5724 * Sets specified user's password and send the new password to the user via email.
5726 * @param stdClass $user A {@link $USER} object
5727 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
5728 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
5730 function setnew_password_and_mail($user, $fasthash = false) {
5731 global $CFG, $DB;
5733 // We try to send the mail in language the user understands,
5734 // unfortunately the filter_string() does not support alternative langs yet
5735 // so multilang will not work properly for site->fullname.
5736 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
5738 $site = get_site();
5740 $supportuser = core_user::get_support_user();
5742 $newpassword = generate_password();
5744 update_internal_user_password($user, $newpassword, $fasthash);
5746 $a = new stdClass();
5747 $a->firstname = fullname($user, true);
5748 $a->sitename = format_string($site->fullname);
5749 $a->username = $user->username;
5750 $a->newpassword = $newpassword;
5751 $a->link = $CFG->wwwroot .'/login/';
5752 $a->signoff = generate_email_signoff();
5754 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
5756 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
5758 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5759 return email_to_user($user, $supportuser, $subject, $message);
5764 * Resets specified user's password and send the new password to the user via email.
5766 * @param stdClass $user A {@link $USER} object
5767 * @return bool Returns true if mail was sent OK and false if there was an error.
5769 function reset_password_and_mail($user) {
5770 global $CFG;
5772 $site = get_site();
5773 $supportuser = core_user::get_support_user();
5775 $userauth = get_auth_plugin($user->auth);
5776 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
5777 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
5778 return false;
5781 $newpassword = generate_password();
5783 if (!$userauth->user_update_password($user, $newpassword)) {
5784 print_error("cannotsetpassword");
5787 $a = new stdClass();
5788 $a->firstname = $user->firstname;
5789 $a->lastname = $user->lastname;
5790 $a->sitename = format_string($site->fullname);
5791 $a->username = $user->username;
5792 $a->newpassword = $newpassword;
5793 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
5794 $a->signoff = generate_email_signoff();
5796 $message = get_string('newpasswordtext', '', $a);
5798 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
5800 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
5802 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5803 return email_to_user($user, $supportuser, $subject, $message);
5807 * Send email to specified user with confirmation text and activation link.
5809 * @param stdClass $user A {@link $USER} object
5810 * @return bool Returns true if mail was sent OK and false if there was an error.
5812 function send_confirmation_email($user) {
5813 global $CFG;
5815 $site = get_site();
5816 $supportuser = core_user::get_support_user();
5818 $data = new stdClass();
5819 $data->firstname = fullname($user);
5820 $data->sitename = format_string($site->fullname);
5821 $data->admin = generate_email_signoff();
5823 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
5825 $username = urlencode($user->username);
5826 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
5827 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
5828 $message = get_string('emailconfirmation', '', $data);
5829 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
5831 $user->mailformat = 1; // Always send HTML version as well.
5833 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5834 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
5838 * Sends a password change confirmation email.
5840 * @param stdClass $user A {@link $USER} object
5841 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
5842 * @return bool Returns true if mail was sent OK and false if there was an error.
5844 function send_password_change_confirmation_email($user, $resetrecord) {
5845 global $CFG;
5847 $site = get_site();
5848 $supportuser = core_user::get_support_user();
5849 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
5851 $data = new stdClass();
5852 $data->firstname = $user->firstname;
5853 $data->lastname = $user->lastname;
5854 $data->username = $user->username;
5855 $data->sitename = format_string($site->fullname);
5856 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
5857 $data->admin = generate_email_signoff();
5858 $data->resetminutes = $pwresetmins;
5860 $message = get_string('emailresetconfirmation', '', $data);
5861 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
5863 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5864 return email_to_user($user, $supportuser, $subject, $message);
5869 * Sends an email containinginformation on how to change your password.
5871 * @param stdClass $user A {@link $USER} object
5872 * @return bool Returns true if mail was sent OK and false if there was an error.
5874 function send_password_change_info($user) {
5875 global $CFG;
5877 $site = get_site();
5878 $supportuser = core_user::get_support_user();
5879 $systemcontext = context_system::instance();
5881 $data = new stdClass();
5882 $data->firstname = $user->firstname;
5883 $data->lastname = $user->lastname;
5884 $data->sitename = format_string($site->fullname);
5885 $data->admin = generate_email_signoff();
5887 $userauth = get_auth_plugin($user->auth);
5889 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
5890 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
5891 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5892 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5893 return email_to_user($user, $supportuser, $subject, $message);
5896 if ($userauth->can_change_password() and $userauth->change_password_url()) {
5897 // We have some external url for password changing.
5898 $data->link .= $userauth->change_password_url();
5900 } else {
5901 // No way to change password, sorry.
5902 $data->link = '';
5905 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
5906 $message = get_string('emailpasswordchangeinfo', '', $data);
5907 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5908 } else {
5909 $message = get_string('emailpasswordchangeinfofail', '', $data);
5910 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5913 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5914 return email_to_user($user, $supportuser, $subject, $message);
5919 * Check that an email is allowed. It returns an error message if there was a problem.
5921 * @param string $email Content of email
5922 * @return string|false
5924 function email_is_not_allowed($email) {
5925 global $CFG;
5927 if (!empty($CFG->allowemailaddresses)) {
5928 $allowed = explode(' ', $CFG->allowemailaddresses);
5929 foreach ($allowed as $allowedpattern) {
5930 $allowedpattern = trim($allowedpattern);
5931 if (!$allowedpattern) {
5932 continue;
5934 if (strpos($allowedpattern, '.') === 0) {
5935 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
5936 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
5937 return false;
5940 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
5941 return false;
5944 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
5946 } else if (!empty($CFG->denyemailaddresses)) {
5947 $denied = explode(' ', $CFG->denyemailaddresses);
5948 foreach ($denied as $deniedpattern) {
5949 $deniedpattern = trim($deniedpattern);
5950 if (!$deniedpattern) {
5951 continue;
5953 if (strpos($deniedpattern, '.') === 0) {
5954 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
5955 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
5956 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
5959 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
5960 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
5965 return false;
5968 // FILE HANDLING.
5971 * Returns local file storage instance
5973 * @return file_storage
5975 function get_file_storage() {
5976 global $CFG;
5978 static $fs = null;
5980 if ($fs) {
5981 return $fs;
5984 require_once("$CFG->libdir/filelib.php");
5986 if (isset($CFG->filedir)) {
5987 $filedir = $CFG->filedir;
5988 } else {
5989 $filedir = $CFG->dataroot.'/filedir';
5992 if (isset($CFG->trashdir)) {
5993 $trashdirdir = $CFG->trashdir;
5994 } else {
5995 $trashdirdir = $CFG->dataroot.'/trashdir';
5998 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6000 return $fs;
6004 * Returns local file storage instance
6006 * @return file_browser
6008 function get_file_browser() {
6009 global $CFG;
6011 static $fb = null;
6013 if ($fb) {
6014 return $fb;
6017 require_once("$CFG->libdir/filelib.php");
6019 $fb = new file_browser();
6021 return $fb;
6025 * Returns file packer
6027 * @param string $mimetype default application/zip
6028 * @return file_packer
6030 function get_file_packer($mimetype='application/zip') {
6031 global $CFG;
6033 static $fp = array();
6035 if (isset($fp[$mimetype])) {
6036 return $fp[$mimetype];
6039 switch ($mimetype) {
6040 case 'application/zip':
6041 case 'application/vnd.moodle.profiling':
6042 $classname = 'zip_packer';
6043 break;
6045 case 'application/x-gzip' :
6046 $classname = 'tgz_packer';
6047 break;
6049 case 'application/vnd.moodle.backup':
6050 $classname = 'mbz_packer';
6051 break;
6053 default:
6054 return false;
6057 require_once("$CFG->libdir/filestorage/$classname.php");
6058 $fp[$mimetype] = new $classname();
6060 return $fp[$mimetype];
6064 * Returns current name of file on disk if it exists.
6066 * @param string $newfile File to be verified
6067 * @return string Current name of file on disk if true
6069 function valid_uploaded_file($newfile) {
6070 if (empty($newfile)) {
6071 return '';
6073 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6074 return $newfile['tmp_name'];
6075 } else {
6076 return '';
6081 * Returns the maximum size for uploading files.
6083 * There are seven possible upload limits:
6084 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6085 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6086 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6087 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6088 * 5. by the Moodle admin in $CFG->maxbytes
6089 * 6. by the teacher in the current course $course->maxbytes
6090 * 7. by the teacher for the current module, eg $assignment->maxbytes
6092 * These last two are passed to this function as arguments (in bytes).
6093 * Anything defined as 0 is ignored.
6094 * The smallest of all the non-zero numbers is returned.
6096 * @todo Finish documenting this function
6098 * @param int $sitebytes Set maximum size
6099 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6100 * @param int $modulebytes Current module ->maxbytes (in bytes)
6101 * @return int The maximum size for uploading files.
6103 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6105 if (! $filesize = ini_get('upload_max_filesize')) {
6106 $filesize = '5M';
6108 $minimumsize = get_real_size($filesize);
6110 if ($postsize = ini_get('post_max_size')) {
6111 $postsize = get_real_size($postsize);
6112 if ($postsize < $minimumsize) {
6113 $minimumsize = $postsize;
6117 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6118 $minimumsize = $sitebytes;
6121 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6122 $minimumsize = $coursebytes;
6125 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6126 $minimumsize = $modulebytes;
6129 return $minimumsize;
6133 * Returns the maximum size for uploading files for the current user
6135 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6137 * @param context $context The context in which to check user capabilities
6138 * @param int $sitebytes Set maximum size
6139 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6140 * @param int $modulebytes Current module ->maxbytes (in bytes)
6141 * @param stdClass $user The user
6142 * @return int The maximum size for uploading files.
6144 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6145 global $USER;
6147 if (empty($user)) {
6148 $user = $USER;
6151 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6152 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6155 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6159 * Returns an array of possible sizes in local language
6161 * Related to {@link get_max_upload_file_size()} - this function returns an
6162 * array of possible sizes in an array, translated to the
6163 * local language.
6165 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6167 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6168 * with the value set to 0. This option will be the first in the list.
6170 * @uses SORT_NUMERIC
6171 * @param int $sitebytes Set maximum size
6172 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6173 * @param int $modulebytes Current module ->maxbytes (in bytes)
6174 * @param int|array $custombytes custom upload size/s which will be added to list,
6175 * Only value/s smaller then maxsize will be added to list.
6176 * @return array
6178 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6179 global $CFG;
6181 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6182 return array();
6185 if ($sitebytes == 0) {
6186 // Will get the minimum of upload_max_filesize or post_max_size.
6187 $sitebytes = get_max_upload_file_size();
6190 $filesize = array();
6191 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6192 5242880, 10485760, 20971520, 52428800, 104857600);
6194 // If custombytes is given and is valid then add it to the list.
6195 if (is_number($custombytes) and $custombytes > 0) {
6196 $custombytes = (int)$custombytes;
6197 if (!in_array($custombytes, $sizelist)) {
6198 $sizelist[] = $custombytes;
6200 } else if (is_array($custombytes)) {
6201 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6204 // Allow maxbytes to be selected if it falls outside the above boundaries.
6205 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6206 // Note: get_real_size() is used in order to prevent problems with invalid values.
6207 $sizelist[] = get_real_size($CFG->maxbytes);
6210 foreach ($sizelist as $sizebytes) {
6211 if ($sizebytes < $maxsize && $sizebytes > 0) {
6212 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6216 $limitlevel = '';
6217 $displaysize = '';
6218 if ($modulebytes &&
6219 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6220 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6221 $limitlevel = get_string('activity', 'core');
6222 $displaysize = display_size($modulebytes);
6223 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6225 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6226 $limitlevel = get_string('course', 'core');
6227 $displaysize = display_size($coursebytes);
6228 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6230 } else if ($sitebytes) {
6231 $limitlevel = get_string('site', 'core');
6232 $displaysize = display_size($sitebytes);
6233 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6236 krsort($filesize, SORT_NUMERIC);
6237 if ($limitlevel) {
6238 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6239 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6242 return $filesize;
6246 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6248 * If excludefiles is defined, then that file/directory is ignored
6249 * If getdirs is true, then (sub)directories are included in the output
6250 * If getfiles is true, then files are included in the output
6251 * (at least one of these must be true!)
6253 * @todo Finish documenting this function. Add examples of $excludefile usage.
6255 * @param string $rootdir A given root directory to start from
6256 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6257 * @param bool $descend If true then subdirectories are recursed as well
6258 * @param bool $getdirs If true then (sub)directories are included in the output
6259 * @param bool $getfiles If true then files are included in the output
6260 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6262 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6264 $dirs = array();
6266 if (!$getdirs and !$getfiles) { // Nothing to show.
6267 return $dirs;
6270 if (!is_dir($rootdir)) { // Must be a directory.
6271 return $dirs;
6274 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6275 return $dirs;
6278 if (!is_array($excludefiles)) {
6279 $excludefiles = array($excludefiles);
6282 while (false !== ($file = readdir($dir))) {
6283 $firstchar = substr($file, 0, 1);
6284 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6285 continue;
6287 $fullfile = $rootdir .'/'. $file;
6288 if (filetype($fullfile) == 'dir') {
6289 if ($getdirs) {
6290 $dirs[] = $file;
6292 if ($descend) {
6293 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6294 foreach ($subdirs as $subdir) {
6295 $dirs[] = $file .'/'. $subdir;
6298 } else if ($getfiles) {
6299 $dirs[] = $file;
6302 closedir($dir);
6304 asort($dirs);
6306 return $dirs;
6311 * Adds up all the files in a directory and works out the size.
6313 * @param string $rootdir The directory to start from
6314 * @param string $excludefile A file to exclude when summing directory size
6315 * @return int The summed size of all files and subfiles within the root directory
6317 function get_directory_size($rootdir, $excludefile='') {
6318 global $CFG;
6320 // Do it this way if we can, it's much faster.
6321 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6322 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6323 $output = null;
6324 $return = null;
6325 exec($command, $output, $return);
6326 if (is_array($output)) {
6327 // We told it to return k.
6328 return get_real_size(intval($output[0]).'k');
6332 if (!is_dir($rootdir)) {
6333 // Must be a directory.
6334 return 0;
6337 if (!$dir = @opendir($rootdir)) {
6338 // Can't open it for some reason.
6339 return 0;
6342 $size = 0;
6344 while (false !== ($file = readdir($dir))) {
6345 $firstchar = substr($file, 0, 1);
6346 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6347 continue;
6349 $fullfile = $rootdir .'/'. $file;
6350 if (filetype($fullfile) == 'dir') {
6351 $size += get_directory_size($fullfile, $excludefile);
6352 } else {
6353 $size += filesize($fullfile);
6356 closedir($dir);
6358 return $size;
6362 * Converts bytes into display form
6364 * @static string $gb Localized string for size in gigabytes
6365 * @static string $mb Localized string for size in megabytes
6366 * @static string $kb Localized string for size in kilobytes
6367 * @static string $b Localized string for size in bytes
6368 * @param int $size The size to convert to human readable form
6369 * @return string
6371 function display_size($size) {
6373 static $gb, $mb, $kb, $b;
6375 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6376 return get_string('unlimited');
6379 if (empty($gb)) {
6380 $gb = get_string('sizegb');
6381 $mb = get_string('sizemb');
6382 $kb = get_string('sizekb');
6383 $b = get_string('sizeb');
6386 if ($size >= 1073741824) {
6387 $size = round($size / 1073741824 * 10) / 10 . $gb;
6388 } else if ($size >= 1048576) {
6389 $size = round($size / 1048576 * 10) / 10 . $mb;
6390 } else if ($size >= 1024) {
6391 $size = round($size / 1024 * 10) / 10 . $kb;
6392 } else {
6393 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6395 return $size;
6399 * Cleans a given filename by removing suspicious or troublesome characters
6401 * @see clean_param()
6402 * @param string $string file name
6403 * @return string cleaned file name
6405 function clean_filename($string) {
6406 return clean_param($string, PARAM_FILE);
6410 // STRING TRANSLATION.
6413 * Returns the code for the current language
6415 * @category string
6416 * @return string
6418 function current_language() {
6419 global $CFG, $USER, $SESSION, $COURSE;
6421 if (!empty($SESSION->forcelang)) {
6422 // Allows overriding course-forced language (useful for admins to check
6423 // issues in courses whose language they don't understand).
6424 // Also used by some code to temporarily get language-related information in a
6425 // specific language (see force_current_language()).
6426 $return = $SESSION->forcelang;
6428 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6429 // Course language can override all other settings for this page.
6430 $return = $COURSE->lang;
6432 } else if (!empty($SESSION->lang)) {
6433 // Session language can override other settings.
6434 $return = $SESSION->lang;
6436 } else if (!empty($USER->lang)) {
6437 $return = $USER->lang;
6439 } else if (isset($CFG->lang)) {
6440 $return = $CFG->lang;
6442 } else {
6443 $return = 'en';
6446 // Just in case this slipped in from somewhere by accident.
6447 $return = str_replace('_utf8', '', $return);
6449 return $return;
6453 * Returns parent language of current active language if defined
6455 * @category string
6456 * @param string $lang null means current language
6457 * @return string
6459 function get_parent_language($lang=null) {
6461 // Let's hack around the current language.
6462 if (!empty($lang)) {
6463 $oldforcelang = force_current_language($lang);
6466 $parentlang = get_string('parentlanguage', 'langconfig');
6467 if ($parentlang === 'en') {
6468 $parentlang = '';
6471 // Let's hack around the current language.
6472 if (!empty($lang)) {
6473 force_current_language($oldforcelang);
6476 return $parentlang;
6480 * Force the current language to get strings and dates localised in the given language.
6482 * After calling this function, all strings will be provided in the given language
6483 * until this function is called again, or equivalent code is run.
6485 * @param string $language
6486 * @return string previous $SESSION->forcelang value
6488 function force_current_language($language) {
6489 global $SESSION;
6490 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6491 if ($language !== $sessionforcelang) {
6492 // Seting forcelang to null or an empty string disables it's effect.
6493 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6494 $SESSION->forcelang = $language;
6495 moodle_setlocale();
6498 return $sessionforcelang;
6502 * Returns current string_manager instance.
6504 * The param $forcereload is needed for CLI installer only where the string_manager instance
6505 * must be replaced during the install.php script life time.
6507 * @category string
6508 * @param bool $forcereload shall the singleton be released and new instance created instead?
6509 * @return core_string_manager
6511 function get_string_manager($forcereload=false) {
6512 global $CFG;
6514 static $singleton = null;
6516 if ($forcereload) {
6517 $singleton = null;
6519 if ($singleton === null) {
6520 if (empty($CFG->early_install_lang)) {
6522 if (empty($CFG->langlist)) {
6523 $translist = array();
6524 } else {
6525 $translist = explode(',', $CFG->langlist);
6528 if (!empty($CFG->config_php_settings['customstringmanager'])) {
6529 $classname = $CFG->config_php_settings['customstringmanager'];
6531 if (class_exists($classname)) {
6532 $implements = class_implements($classname);
6534 if (isset($implements['core_string_manager'])) {
6535 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
6536 return $singleton;
6538 } else {
6539 debugging('Unable to instantiate custom string manager: class '.$classname.
6540 ' does not implement the core_string_manager interface.');
6543 } else {
6544 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6548 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6550 } else {
6551 $singleton = new core_string_manager_install();
6555 return $singleton;
6559 * Returns a localized string.
6561 * Returns the translated string specified by $identifier as
6562 * for $module. Uses the same format files as STphp.
6563 * $a is an object, string or number that can be used
6564 * within translation strings
6566 * eg 'hello {$a->firstname} {$a->lastname}'
6567 * or 'hello {$a}'
6569 * If you would like to directly echo the localized string use
6570 * the function {@link print_string()}
6572 * Example usage of this function involves finding the string you would
6573 * like a local equivalent of and using its identifier and module information
6574 * to retrieve it.<br/>
6575 * If you open moodle/lang/en/moodle.php and look near line 278
6576 * you will find a string to prompt a user for their word for 'course'
6577 * <code>
6578 * $string['course'] = 'Course';
6579 * </code>
6580 * So if you want to display the string 'Course'
6581 * in any language that supports it on your site
6582 * you just need to use the identifier 'course'
6583 * <code>
6584 * $mystring = '<strong>'. get_string('course') .'</strong>';
6585 * or
6586 * </code>
6587 * If the string you want is in another file you'd take a slightly
6588 * different approach. Looking in moodle/lang/en/calendar.php you find
6589 * around line 75:
6590 * <code>
6591 * $string['typecourse'] = 'Course event';
6592 * </code>
6593 * If you want to display the string "Course event" in any language
6594 * supported you would use the identifier 'typecourse' and the module 'calendar'
6595 * (because it is in the file calendar.php):
6596 * <code>
6597 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6598 * </code>
6600 * As a last resort, should the identifier fail to map to a string
6601 * the returned string will be [[ $identifier ]]
6603 * In Moodle 2.3 there is a new argument to this function $lazyload.
6604 * Setting $lazyload to true causes get_string to return a lang_string object
6605 * rather than the string itself. The fetching of the string is then put off until
6606 * the string object is first used. The object can be used by calling it's out
6607 * method or by casting the object to a string, either directly e.g.
6608 * (string)$stringobject
6609 * or indirectly by using the string within another string or echoing it out e.g.
6610 * echo $stringobject
6611 * return "<p>{$stringobject}</p>";
6612 * It is worth noting that using $lazyload and attempting to use the string as an
6613 * array key will cause a fatal error as objects cannot be used as array keys.
6614 * But you should never do that anyway!
6615 * For more information {@link lang_string}
6617 * @category string
6618 * @param string $identifier The key identifier for the localized string
6619 * @param string $component The module where the key identifier is stored,
6620 * usually expressed as the filename in the language pack without the
6621 * .php on the end but can also be written as mod/forum or grade/export/xls.
6622 * If none is specified then moodle.php is used.
6623 * @param string|object|array $a An object, string or number that can be used
6624 * within translation strings
6625 * @param bool $lazyload If set to true a string object is returned instead of
6626 * the string itself. The string then isn't calculated until it is first used.
6627 * @return string The localized string.
6628 * @throws coding_exception
6630 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6631 global $CFG;
6633 // If the lazy load argument has been supplied return a lang_string object
6634 // instead.
6635 // We need to make sure it is true (and a bool) as you will see below there
6636 // used to be a forth argument at one point.
6637 if ($lazyload === true) {
6638 return new lang_string($identifier, $component, $a);
6641 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6642 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6645 // There is now a forth argument again, this time it is a boolean however so
6646 // we can still check for the old extralocations parameter.
6647 if (!is_bool($lazyload) && !empty($lazyload)) {
6648 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6651 if (strpos($component, '/') !== false) {
6652 debugging('The module name you passed to get_string is the deprecated format ' .
6653 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6654 $componentpath = explode('/', $component);
6656 switch ($componentpath[0]) {
6657 case 'mod':
6658 $component = $componentpath[1];
6659 break;
6660 case 'blocks':
6661 case 'block':
6662 $component = 'block_'.$componentpath[1];
6663 break;
6664 case 'enrol':
6665 $component = 'enrol_'.$componentpath[1];
6666 break;
6667 case 'format':
6668 $component = 'format_'.$componentpath[1];
6669 break;
6670 case 'grade':
6671 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6672 break;
6676 $result = get_string_manager()->get_string($identifier, $component, $a);
6678 // Debugging feature lets you display string identifier and component.
6679 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6680 $result .= ' {' . $identifier . '/' . $component . '}';
6682 return $result;
6686 * Converts an array of strings to their localized value.
6688 * @param array $array An array of strings
6689 * @param string $component The language module that these strings can be found in.
6690 * @return stdClass translated strings.
6692 function get_strings($array, $component = '') {
6693 $string = new stdClass;
6694 foreach ($array as $item) {
6695 $string->$item = get_string($item, $component);
6697 return $string;
6701 * Prints out a translated string.
6703 * Prints out a translated string using the return value from the {@link get_string()} function.
6705 * Example usage of this function when the string is in the moodle.php file:<br/>
6706 * <code>
6707 * echo '<strong>';
6708 * print_string('course');
6709 * echo '</strong>';
6710 * </code>
6712 * Example usage of this function when the string is not in the moodle.php file:<br/>
6713 * <code>
6714 * echo '<h1>';
6715 * print_string('typecourse', 'calendar');
6716 * echo '</h1>';
6717 * </code>
6719 * @category string
6720 * @param string $identifier The key identifier for the localized string
6721 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6722 * @param string|object|array $a An object, string or number that can be used within translation strings
6724 function print_string($identifier, $component = '', $a = null) {
6725 echo get_string($identifier, $component, $a);
6729 * Returns a list of charset codes
6731 * Returns a list of charset codes. It's hardcoded, so they should be added manually
6732 * (checking that such charset is supported by the texlib library!)
6734 * @return array And associative array with contents in the form of charset => charset
6736 function get_list_of_charsets() {
6738 $charsets = array(
6739 'EUC-JP' => 'EUC-JP',
6740 'ISO-2022-JP'=> 'ISO-2022-JP',
6741 'ISO-8859-1' => 'ISO-8859-1',
6742 'SHIFT-JIS' => 'SHIFT-JIS',
6743 'GB2312' => 'GB2312',
6744 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
6745 'UTF-8' => 'UTF-8');
6747 asort($charsets);
6749 return $charsets;
6753 * Returns a list of valid and compatible themes
6755 * @return array
6757 function get_list_of_themes() {
6758 global $CFG;
6760 $themes = array();
6762 if (!empty($CFG->themelist)) { // Use admin's list of themes.
6763 $themelist = explode(',', $CFG->themelist);
6764 } else {
6765 $themelist = array_keys(core_component::get_plugin_list("theme"));
6768 foreach ($themelist as $key => $themename) {
6769 $theme = theme_config::load($themename);
6770 $themes[$themename] = $theme;
6773 core_collator::asort_objects_by_method($themes, 'get_theme_name');
6775 return $themes;
6779 * Factory function for emoticon_manager
6781 * @return emoticon_manager singleton
6783 function get_emoticon_manager() {
6784 static $singleton = null;
6786 if (is_null($singleton)) {
6787 $singleton = new emoticon_manager();
6790 return $singleton;
6794 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
6796 * Whenever this manager mentiones 'emoticon object', the following data
6797 * structure is expected: stdClass with properties text, imagename, imagecomponent,
6798 * altidentifier and altcomponent
6800 * @see admin_setting_emoticons
6802 * @copyright 2010 David Mudrak
6803 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6805 class emoticon_manager {
6808 * Returns the currently enabled emoticons
6810 * @return array of emoticon objects
6812 public function get_emoticons() {
6813 global $CFG;
6815 if (empty($CFG->emoticons)) {
6816 return array();
6819 $emoticons = $this->decode_stored_config($CFG->emoticons);
6821 if (!is_array($emoticons)) {
6822 // Something is wrong with the format of stored setting.
6823 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
6824 return array();
6827 return $emoticons;
6831 * Converts emoticon object into renderable pix_emoticon object
6833 * @param stdClass $emoticon emoticon object
6834 * @param array $attributes explicit HTML attributes to set
6835 * @return pix_emoticon
6837 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
6838 $stringmanager = get_string_manager();
6839 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
6840 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
6841 } else {
6842 $alt = s($emoticon->text);
6844 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
6848 * Encodes the array of emoticon objects into a string storable in config table
6850 * @see self::decode_stored_config()
6851 * @param array $emoticons array of emtocion objects
6852 * @return string
6854 public function encode_stored_config(array $emoticons) {
6855 return json_encode($emoticons);
6859 * Decodes the string into an array of emoticon objects
6861 * @see self::encode_stored_config()
6862 * @param string $encoded
6863 * @return string|null
6865 public function decode_stored_config($encoded) {
6866 $decoded = json_decode($encoded);
6867 if (!is_array($decoded)) {
6868 return null;
6870 return $decoded;
6874 * Returns default set of emoticons supported by Moodle
6876 * @return array of sdtClasses
6878 public function default_emoticons() {
6879 return array(
6880 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
6881 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
6882 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
6883 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
6884 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
6885 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
6886 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
6887 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
6888 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
6889 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
6890 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
6891 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
6892 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
6893 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
6894 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
6895 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
6896 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
6897 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
6898 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
6899 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
6900 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
6901 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
6902 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
6903 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
6904 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
6905 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
6906 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
6907 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
6908 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
6909 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
6914 * Helper method preparing the stdClass with the emoticon properties
6916 * @param string|array $text or array of strings
6917 * @param string $imagename to be used by {@link pix_emoticon}
6918 * @param string $altidentifier alternative string identifier, null for no alt
6919 * @param string $altcomponent where the alternative string is defined
6920 * @param string $imagecomponent to be used by {@link pix_emoticon}
6921 * @return stdClass
6923 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
6924 $altcomponent = 'core_pix', $imagecomponent = 'core') {
6925 return (object)array(
6926 'text' => $text,
6927 'imagename' => $imagename,
6928 'imagecomponent' => $imagecomponent,
6929 'altidentifier' => $altidentifier,
6930 'altcomponent' => $altcomponent,
6935 // ENCRYPTION.
6938 * rc4encrypt
6940 * @param string $data Data to encrypt.
6941 * @return string The now encrypted data.
6943 function rc4encrypt($data) {
6944 return endecrypt(get_site_identifier(), $data, '');
6948 * rc4decrypt
6950 * @param string $data Data to decrypt.
6951 * @return string The now decrypted data.
6953 function rc4decrypt($data) {
6954 return endecrypt(get_site_identifier(), $data, 'de');
6958 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
6960 * @todo Finish documenting this function
6962 * @param string $pwd The password to use when encrypting or decrypting
6963 * @param string $data The data to be decrypted/encrypted
6964 * @param string $case Either 'de' for decrypt or '' for encrypt
6965 * @return string
6967 function endecrypt ($pwd, $data, $case) {
6969 if ($case == 'de') {
6970 $data = urldecode($data);
6973 $key[] = '';
6974 $box[] = '';
6975 $pwdlength = strlen($pwd);
6977 for ($i = 0; $i <= 255; $i++) {
6978 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
6979 $box[$i] = $i;
6982 $x = 0;
6984 for ($i = 0; $i <= 255; $i++) {
6985 $x = ($x + $box[$i] + $key[$i]) % 256;
6986 $tempswap = $box[$i];
6987 $box[$i] = $box[$x];
6988 $box[$x] = $tempswap;
6991 $cipher = '';
6993 $a = 0;
6994 $j = 0;
6996 for ($i = 0; $i < strlen($data); $i++) {
6997 $a = ($a + 1) % 256;
6998 $j = ($j + $box[$a]) % 256;
6999 $temp = $box[$a];
7000 $box[$a] = $box[$j];
7001 $box[$j] = $temp;
7002 $k = $box[(($box[$a] + $box[$j]) % 256)];
7003 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7004 $cipher .= chr($cipherby);
7007 if ($case == 'de') {
7008 $cipher = urldecode(urlencode($cipher));
7009 } else {
7010 $cipher = urlencode($cipher);
7013 return $cipher;
7016 // ENVIRONMENT CHECKING.
7019 * This method validates a plug name. It is much faster than calling clean_param.
7021 * @param string $name a string that might be a plugin name.
7022 * @return bool if this string is a valid plugin name.
7024 function is_valid_plugin_name($name) {
7025 // This does not work for 'mod', bad luck, use any other type.
7026 return core_component::is_valid_plugin_name('tool', $name);
7030 * Get a list of all the plugins of a given type that define a certain API function
7031 * in a certain file. The plugin component names and function names are returned.
7033 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7034 * @param string $function the part of the name of the function after the
7035 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7036 * names like report_courselist_hook.
7037 * @param string $file the name of file within the plugin that defines the
7038 * function. Defaults to lib.php.
7039 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7040 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7042 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7043 global $CFG;
7045 // We don't include here as all plugin types files would be included.
7046 $plugins = get_plugins_with_function($function, $file, false);
7048 if (empty($plugins[$plugintype])) {
7049 return array();
7052 $allplugins = core_component::get_plugin_list($plugintype);
7054 // Reformat the array and include the files.
7055 $pluginfunctions = array();
7056 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7058 // Check that it has not been removed and the file is still available.
7059 if (!empty($allplugins[$pluginname])) {
7061 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7062 if (file_exists($filepath)) {
7063 include_once($filepath);
7064 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7069 return $pluginfunctions;
7073 * Get a list of all the plugins that define a certain API function in a certain file.
7075 * @param string $function the part of the name of the function after the
7076 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7077 * names like report_courselist_hook.
7078 * @param string $file the name of file within the plugin that defines the
7079 * function. Defaults to lib.php.
7080 * @param bool $include Whether to include the files that contain the functions or not.
7081 * @return array with [plugintype][plugin] = functionname
7083 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7084 global $CFG;
7086 $cache = \cache::make('core', 'plugin_functions');
7088 // Including both although I doubt that we will find two functions definitions with the same name.
7089 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7090 $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7092 if ($pluginfunctions = $cache->get($key)) {
7094 // Checking that the files are still available.
7095 foreach ($pluginfunctions as $plugintype => $plugins) {
7097 $allplugins = \core_component::get_plugin_list($plugintype);
7098 foreach ($plugins as $plugin => $fullpath) {
7100 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7101 if (empty($allplugins[$plugin])) {
7102 unset($pluginfunctions[$plugintype][$plugin]);
7103 continue;
7106 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7107 if ($include && $fileexists) {
7108 // Include the files if it was requested.
7109 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7110 } else if (!$fileexists) {
7111 // If the file is not available any more it should not be returned.
7112 unset($pluginfunctions[$plugintype][$plugin]);
7116 return $pluginfunctions;
7119 $pluginfunctions = array();
7121 // To fill the cached. Also, everything should continue working with cache disabled.
7122 $plugintypes = \core_component::get_plugin_types();
7123 foreach ($plugintypes as $plugintype => $unused) {
7125 // We need to include files here.
7126 $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7127 foreach ($pluginswithfile as $plugin => $notused) {
7129 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7131 $pluginfunction = false;
7132 if (function_exists($fullfunction)) {
7133 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7134 $pluginfunction = $fullfunction;
7136 } else if ($plugintype === 'mod') {
7137 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7138 $shortfunction = $plugin . '_' . $function;
7139 if (function_exists($shortfunction)) {
7140 $pluginfunction = $shortfunction;
7144 if ($pluginfunction) {
7145 if (empty($pluginfunctions[$plugintype])) {
7146 $pluginfunctions[$plugintype] = array();
7148 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7153 $cache->set($key, $pluginfunctions);
7155 return $pluginfunctions;
7160 * Lists plugin-like directories within specified directory
7162 * This function was originally used for standard Moodle plugins, please use
7163 * new core_component::get_plugin_list() now.
7165 * This function is used for general directory listing and backwards compatility.
7167 * @param string $directory relative directory from root
7168 * @param string $exclude dir name to exclude from the list (defaults to none)
7169 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7170 * @return array Sorted array of directory names found under the requested parameters
7172 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7173 global $CFG;
7175 $plugins = array();
7177 if (empty($basedir)) {
7178 $basedir = $CFG->dirroot .'/'. $directory;
7180 } else {
7181 $basedir = $basedir .'/'. $directory;
7184 if ($CFG->debugdeveloper and empty($exclude)) {
7185 // Make sure devs do not use this to list normal plugins,
7186 // this is intended for general directories that are not plugins!
7188 $subtypes = core_component::get_plugin_types();
7189 if (in_array($basedir, $subtypes)) {
7190 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7192 unset($subtypes);
7195 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7196 if (!$dirhandle = opendir($basedir)) {
7197 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7198 return array();
7200 while (false !== ($dir = readdir($dirhandle))) {
7201 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7202 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7203 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7204 continue;
7206 if (filetype($basedir .'/'. $dir) != 'dir') {
7207 continue;
7209 $plugins[] = $dir;
7211 closedir($dirhandle);
7213 if ($plugins) {
7214 asort($plugins);
7216 return $plugins;
7220 * Invoke plugin's callback functions
7222 * @param string $type plugin type e.g. 'mod'
7223 * @param string $name plugin name
7224 * @param string $feature feature name
7225 * @param string $action feature's action
7226 * @param array $params parameters of callback function, should be an array
7227 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7228 * @return mixed
7230 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7232 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7233 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7237 * Invoke component's callback functions
7239 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7240 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7241 * @param array $params parameters of callback function
7242 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7243 * @return mixed
7245 function component_callback($component, $function, array $params = array(), $default = null) {
7247 $functionname = component_callback_exists($component, $function);
7249 if ($functionname) {
7250 // Function exists, so just return function result.
7251 $ret = call_user_func_array($functionname, $params);
7252 if (is_null($ret)) {
7253 return $default;
7254 } else {
7255 return $ret;
7258 return $default;
7262 * Determine if a component callback exists and return the function name to call. Note that this
7263 * function will include the required library files so that the functioname returned can be
7264 * called directly.
7266 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7267 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7268 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7269 * @throws coding_exception if invalid component specfied
7271 function component_callback_exists($component, $function) {
7272 global $CFG; // This is needed for the inclusions.
7274 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7275 if (empty($cleancomponent)) {
7276 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7278 $component = $cleancomponent;
7280 list($type, $name) = core_component::normalize_component($component);
7281 $component = $type . '_' . $name;
7283 $oldfunction = $name.'_'.$function;
7284 $function = $component.'_'.$function;
7286 $dir = core_component::get_component_directory($component);
7287 if (empty($dir)) {
7288 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7291 // Load library and look for function.
7292 if (file_exists($dir.'/lib.php')) {
7293 require_once($dir.'/lib.php');
7296 if (!function_exists($function) and function_exists($oldfunction)) {
7297 if ($type !== 'mod' and $type !== 'core') {
7298 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7300 $function = $oldfunction;
7303 if (function_exists($function)) {
7304 return $function;
7306 return false;
7310 * Checks whether a plugin supports a specified feature.
7312 * @param string $type Plugin type e.g. 'mod'
7313 * @param string $name Plugin name e.g. 'forum'
7314 * @param string $feature Feature code (FEATURE_xx constant)
7315 * @param mixed $default default value if feature support unknown
7316 * @return mixed Feature result (false if not supported, null if feature is unknown,
7317 * otherwise usually true but may have other feature-specific value such as array)
7318 * @throws coding_exception
7320 function plugin_supports($type, $name, $feature, $default = null) {
7321 global $CFG;
7323 if ($type === 'mod' and $name === 'NEWMODULE') {
7324 // Somebody forgot to rename the module template.
7325 return false;
7328 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7329 if (empty($component)) {
7330 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7333 $function = null;
7335 if ($type === 'mod') {
7336 // We need this special case because we support subplugins in modules,
7337 // otherwise it would end up in infinite loop.
7338 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7339 include_once("$CFG->dirroot/mod/$name/lib.php");
7340 $function = $component.'_supports';
7341 if (!function_exists($function)) {
7342 // Legacy non-frankenstyle function name.
7343 $function = $name.'_supports';
7347 } else {
7348 if (!$path = core_component::get_plugin_directory($type, $name)) {
7349 // Non existent plugin type.
7350 return false;
7352 if (file_exists("$path/lib.php")) {
7353 include_once("$path/lib.php");
7354 $function = $component.'_supports';
7358 if ($function and function_exists($function)) {
7359 $supports = $function($feature);
7360 if (is_null($supports)) {
7361 // Plugin does not know - use default.
7362 return $default;
7363 } else {
7364 return $supports;
7368 // Plugin does not care, so use default.
7369 return $default;
7373 * Returns true if the current version of PHP is greater that the specified one.
7375 * @todo Check PHP version being required here is it too low?
7377 * @param string $version The version of php being tested.
7378 * @return bool
7380 function check_php_version($version='5.2.4') {
7381 return (version_compare(phpversion(), $version) >= 0);
7385 * Determine if moodle installation requires update.
7387 * Checks version numbers of main code and all plugins to see
7388 * if there are any mismatches.
7390 * @return bool
7392 function moodle_needs_upgrading() {
7393 global $CFG;
7395 if (empty($CFG->version)) {
7396 return true;
7399 // There is no need to purge plugininfo caches here because
7400 // these caches are not used during upgrade and they are purged after
7401 // every upgrade.
7403 if (empty($CFG->allversionshash)) {
7404 return true;
7407 $hash = core_component::get_all_versions_hash();
7409 return ($hash !== $CFG->allversionshash);
7413 * Returns the major version of this site
7415 * Moodle version numbers consist of three numbers separated by a dot, for
7416 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7417 * called major version. This function extracts the major version from either
7418 * $CFG->release (default) or eventually from the $release variable defined in
7419 * the main version.php.
7421 * @param bool $fromdisk should the version if source code files be used
7422 * @return string|false the major version like '2.3', false if could not be determined
7424 function moodle_major_version($fromdisk = false) {
7425 global $CFG;
7427 if ($fromdisk) {
7428 $release = null;
7429 require($CFG->dirroot.'/version.php');
7430 if (empty($release)) {
7431 return false;
7434 } else {
7435 if (empty($CFG->release)) {
7436 return false;
7438 $release = $CFG->release;
7441 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7442 return $matches[0];
7443 } else {
7444 return false;
7448 // MISCELLANEOUS.
7451 * Sets the system locale
7453 * @category string
7454 * @param string $locale Can be used to force a locale
7456 function moodle_setlocale($locale='') {
7457 global $CFG;
7459 static $currentlocale = ''; // Last locale caching.
7461 $oldlocale = $currentlocale;
7463 // Fetch the correct locale based on ostype.
7464 if ($CFG->ostype == 'WINDOWS') {
7465 $stringtofetch = 'localewin';
7466 } else {
7467 $stringtofetch = 'locale';
7470 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7471 if (!empty($locale)) {
7472 $currentlocale = $locale;
7473 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7474 $currentlocale = $CFG->locale;
7475 } else {
7476 $currentlocale = get_string($stringtofetch, 'langconfig');
7479 // Do nothing if locale already set up.
7480 if ($oldlocale == $currentlocale) {
7481 return;
7484 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7485 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7486 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7488 // Get current values.
7489 $monetary= setlocale (LC_MONETARY, 0);
7490 $numeric = setlocale (LC_NUMERIC, 0);
7491 $ctype = setlocale (LC_CTYPE, 0);
7492 if ($CFG->ostype != 'WINDOWS') {
7493 $messages= setlocale (LC_MESSAGES, 0);
7495 // Set locale to all.
7496 $result = setlocale (LC_ALL, $currentlocale);
7497 // If setting of locale fails try the other utf8 or utf-8 variant,
7498 // some operating systems support both (Debian), others just one (OSX).
7499 if ($result === false) {
7500 if (stripos($currentlocale, '.UTF-8') !== false) {
7501 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7502 setlocale (LC_ALL, $newlocale);
7503 } else if (stripos($currentlocale, '.UTF8') !== false) {
7504 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7505 setlocale (LC_ALL, $newlocale);
7508 // Set old values.
7509 setlocale (LC_MONETARY, $monetary);
7510 setlocale (LC_NUMERIC, $numeric);
7511 if ($CFG->ostype != 'WINDOWS') {
7512 setlocale (LC_MESSAGES, $messages);
7514 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7515 // To workaround a well-known PHP problem with Turkish letter Ii.
7516 setlocale (LC_CTYPE, $ctype);
7521 * Count words in a string.
7523 * Words are defined as things between whitespace.
7525 * @category string
7526 * @param string $string The text to be searched for words.
7527 * @return int The count of words in the specified string
7529 function count_words($string) {
7530 $string = strip_tags($string);
7531 // Decode HTML entities.
7532 $string = html_entity_decode($string);
7533 // Replace underscores (which are classed as word characters) with spaces.
7534 $string = preg_replace('/_/u', ' ', $string);
7535 // Remove any characters that shouldn't be treated as word boundaries.
7536 $string = preg_replace('/[\'’-]/u', '', $string);
7537 // Remove dots and commas from within numbers only.
7538 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7540 return count(preg_split('/\w\b/u', $string)) - 1;
7544 * Count letters in a string.
7546 * Letters are defined as chars not in tags and different from whitespace.
7548 * @category string
7549 * @param string $string The text to be searched for letters.
7550 * @return int The count of letters in the specified text.
7552 function count_letters($string) {
7553 $string = strip_tags($string); // Tags are out now.
7554 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7556 return core_text::strlen($string);
7560 * Generate and return a random string of the specified length.
7562 * @param int $length The length of the string to be created.
7563 * @return string
7565 function random_string($length=15) {
7566 $randombytes = random_bytes_emulate($length);
7567 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7568 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7569 $pool .= '0123456789';
7570 $poollen = strlen($pool);
7571 $string = '';
7572 for ($i = 0; $i < $length; $i++) {
7573 $rand = ord($randombytes[$i]);
7574 $string .= substr($pool, ($rand%($poollen)), 1);
7576 return $string;
7580 * Generate a complex random string (useful for md5 salts)
7582 * This function is based on the above {@link random_string()} however it uses a
7583 * larger pool of characters and generates a string between 24 and 32 characters
7585 * @param int $length Optional if set generates a string to exactly this length
7586 * @return string
7588 function complex_random_string($length=null) {
7589 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7590 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7591 $poollen = strlen($pool);
7592 if ($length===null) {
7593 $length = floor(rand(24, 32));
7595 $randombytes = random_bytes_emulate($length);
7596 $string = '';
7597 for ($i = 0; $i < $length; $i++) {
7598 $rand = ord($randombytes[$i]);
7599 $string .= $pool[($rand%$poollen)];
7601 return $string;
7605 * Try to generates cryptographically secure pseudo-random bytes.
7607 * Note this is achieved by fallbacking between:
7608 * - PHP 7 random_bytes().
7609 * - OpenSSL openssl_random_pseudo_bytes().
7610 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
7612 * @param int $length requested length in bytes
7613 * @return string binary data
7615 function random_bytes_emulate($length) {
7616 global $CFG;
7617 if ($length <= 0) {
7618 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
7619 return '';
7621 if (function_exists('random_bytes')) {
7622 // Use PHP 7 goodness.
7623 $hash = @random_bytes($length);
7624 if ($hash !== false) {
7625 return $hash;
7628 if (function_exists('openssl_random_pseudo_bytes')) {
7629 // For PHP 5.3 and later with openssl extension.
7630 $hash = openssl_random_pseudo_bytes($length);
7631 if ($hash !== false) {
7632 return $hash;
7636 // Bad luck, there is no reliable random generator, let's just hash some unique stuff that is hard to guess.
7637 $hash = sha1(serialize($CFG) . serialize($_SERVER) . microtime(true) . uniqid('', true), true);
7638 // NOTE: the last param in sha1() is true, this means we are getting 20 bytes, not 40 chars as usual.
7639 if ($length <= 20) {
7640 return substr($hash, 0, $length);
7642 return $hash . random_bytes_emulate($length - 20);
7646 * Given some text (which may contain HTML) and an ideal length,
7647 * this function truncates the text neatly on a word boundary if possible
7649 * @category string
7650 * @param string $text text to be shortened
7651 * @param int $ideal ideal string length
7652 * @param boolean $exact if false, $text will not be cut mid-word
7653 * @param string $ending The string to append if the passed string is truncated
7654 * @return string $truncate shortened string
7656 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7657 // If the plain text is shorter than the maximum length, return the whole text.
7658 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7659 return $text;
7662 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7663 // and only tag in its 'line'.
7664 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7666 $totallength = core_text::strlen($ending);
7667 $truncate = '';
7669 // This array stores information about open and close tags and their position
7670 // in the truncated string. Each item in the array is an object with fields
7671 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7672 // (byte position in truncated text).
7673 $tagdetails = array();
7675 foreach ($lines as $linematchings) {
7676 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7677 if (!empty($linematchings[1])) {
7678 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7679 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7680 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7681 // Record closing tag.
7682 $tagdetails[] = (object) array(
7683 'open' => false,
7684 'tag' => core_text::strtolower($tagmatchings[1]),
7685 'pos' => core_text::strlen($truncate),
7688 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7689 // Record opening tag.
7690 $tagdetails[] = (object) array(
7691 'open' => true,
7692 'tag' => core_text::strtolower($tagmatchings[1]),
7693 'pos' => core_text::strlen($truncate),
7697 // Add html-tag to $truncate'd text.
7698 $truncate .= $linematchings[1];
7701 // Calculate the length of the plain text part of the line; handle entities as one character.
7702 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7703 if ($totallength + $contentlength > $ideal) {
7704 // The number of characters which are left.
7705 $left = $ideal - $totallength;
7706 $entitieslength = 0;
7707 // Search for html entities.
7708 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)) {
7709 // Calculate the real length of all entities in the legal range.
7710 foreach ($entities[0] as $entity) {
7711 if ($entity[1]+1-$entitieslength <= $left) {
7712 $left--;
7713 $entitieslength += core_text::strlen($entity[0]);
7714 } else {
7715 // No more characters left.
7716 break;
7720 $breakpos = $left + $entitieslength;
7722 // If the words shouldn't be cut in the middle...
7723 if (!$exact) {
7724 // Search the last occurence of a space.
7725 for (; $breakpos > 0; $breakpos--) {
7726 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
7727 if ($char === '.' or $char === ' ') {
7728 $breakpos += 1;
7729 break;
7730 } else if (strlen($char) > 2) {
7731 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7732 $breakpos += 1;
7733 break;
7738 if ($breakpos == 0) {
7739 // This deals with the test_shorten_text_no_spaces case.
7740 $breakpos = $left + $entitieslength;
7741 } else if ($breakpos > $left + $entitieslength) {
7742 // This deals with the previous for loop breaking on the first char.
7743 $breakpos = $left + $entitieslength;
7746 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
7747 // Maximum length is reached, so get off the loop.
7748 break;
7749 } else {
7750 $truncate .= $linematchings[2];
7751 $totallength += $contentlength;
7754 // If the maximum length is reached, get off the loop.
7755 if ($totallength >= $ideal) {
7756 break;
7760 // Add the defined ending to the text.
7761 $truncate .= $ending;
7763 // Now calculate the list of open html tags based on the truncate position.
7764 $opentags = array();
7765 foreach ($tagdetails as $taginfo) {
7766 if ($taginfo->open) {
7767 // Add tag to the beginning of $opentags list.
7768 array_unshift($opentags, $taginfo->tag);
7769 } else {
7770 // Can have multiple exact same open tags, close the last one.
7771 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
7772 if ($pos !== false) {
7773 unset($opentags[$pos]);
7778 // Close all unclosed html-tags.
7779 foreach ($opentags as $tag) {
7780 $truncate .= '</' . $tag . '>';
7783 return $truncate;
7788 * Given dates in seconds, how many weeks is the date from startdate
7789 * The first week is 1, the second 2 etc ...
7791 * @param int $startdate Timestamp for the start date
7792 * @param int $thedate Timestamp for the end date
7793 * @return string
7795 function getweek ($startdate, $thedate) {
7796 if ($thedate < $startdate) {
7797 return 0;
7800 return floor(($thedate - $startdate) / WEEKSECS) + 1;
7804 * Returns a randomly generated password of length $maxlen. inspired by
7806 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
7807 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
7809 * @param int $maxlen The maximum size of the password being generated.
7810 * @return string
7812 function generate_password($maxlen=10) {
7813 global $CFG;
7815 if (empty($CFG->passwordpolicy)) {
7816 $fillers = PASSWORD_DIGITS;
7817 $wordlist = file($CFG->wordlist);
7818 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7819 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7820 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
7821 $password = $word1 . $filler1 . $word2;
7822 } else {
7823 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
7824 $digits = $CFG->minpassworddigits;
7825 $lower = $CFG->minpasswordlower;
7826 $upper = $CFG->minpasswordupper;
7827 $nonalphanum = $CFG->minpasswordnonalphanum;
7828 $total = $lower + $upper + $digits + $nonalphanum;
7829 // Var minlength should be the greater one of the two ( $minlen and $total ).
7830 $minlen = $minlen < $total ? $total : $minlen;
7831 // Var maxlen can never be smaller than minlen.
7832 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
7833 $additional = $maxlen - $total;
7835 // Make sure we have enough characters to fulfill
7836 // complexity requirements.
7837 $passworddigits = PASSWORD_DIGITS;
7838 while ($digits > strlen($passworddigits)) {
7839 $passworddigits .= PASSWORD_DIGITS;
7841 $passwordlower = PASSWORD_LOWER;
7842 while ($lower > strlen($passwordlower)) {
7843 $passwordlower .= PASSWORD_LOWER;
7845 $passwordupper = PASSWORD_UPPER;
7846 while ($upper > strlen($passwordupper)) {
7847 $passwordupper .= PASSWORD_UPPER;
7849 $passwordnonalphanum = PASSWORD_NONALPHANUM;
7850 while ($nonalphanum > strlen($passwordnonalphanum)) {
7851 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
7854 // Now mix and shuffle it all.
7855 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
7856 substr(str_shuffle ($passwordupper), 0, $upper) .
7857 substr(str_shuffle ($passworddigits), 0, $digits) .
7858 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
7859 substr(str_shuffle ($passwordlower .
7860 $passwordupper .
7861 $passworddigits .
7862 $passwordnonalphanum), 0 , $additional));
7865 return substr ($password, 0, $maxlen);
7869 * Given a float, prints it nicely.
7870 * Localized floats must not be used in calculations!
7872 * The stripzeros feature is intended for making numbers look nicer in small
7873 * areas where it is not necessary to indicate the degree of accuracy by showing
7874 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
7875 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
7877 * @param float $float The float to print
7878 * @param int $decimalpoints The number of decimal places to print.
7879 * @param bool $localized use localized decimal separator
7880 * @param bool $stripzeros If true, removes final zeros after decimal point
7881 * @return string locale float
7883 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
7884 if (is_null($float)) {
7885 return '';
7887 if ($localized) {
7888 $separator = get_string('decsep', 'langconfig');
7889 } else {
7890 $separator = '.';
7892 $result = number_format($float, $decimalpoints, $separator, '');
7893 if ($stripzeros) {
7894 // Remove zeros and final dot if not needed.
7895 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
7897 return $result;
7901 * Converts locale specific floating point/comma number back to standard PHP float value
7902 * Do NOT try to do any math operations before this conversion on any user submitted floats!
7904 * @param string $localefloat locale aware float representation
7905 * @param bool $strict If true, then check the input and return false if it is not a valid number.
7906 * @return mixed float|bool - false or the parsed float.
7908 function unformat_float($localefloat, $strict = false) {
7909 $localefloat = trim($localefloat);
7911 if ($localefloat == '') {
7912 return null;
7915 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
7916 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
7918 if ($strict && !is_numeric($localefloat)) {
7919 return false;
7922 return (float)$localefloat;
7926 * Given a simple array, this shuffles it up just like shuffle()
7927 * Unlike PHP's shuffle() this function works on any machine.
7929 * @param array $array The array to be rearranged
7930 * @return array
7932 function swapshuffle($array) {
7934 $last = count($array) - 1;
7935 for ($i = 0; $i <= $last; $i++) {
7936 $from = rand(0, $last);
7937 $curr = $array[$i];
7938 $array[$i] = $array[$from];
7939 $array[$from] = $curr;
7941 return $array;
7945 * Like {@link swapshuffle()}, but works on associative arrays
7947 * @param array $array The associative array to be rearranged
7948 * @return array
7950 function swapshuffle_assoc($array) {
7952 $newarray = array();
7953 $newkeys = swapshuffle(array_keys($array));
7955 foreach ($newkeys as $newkey) {
7956 $newarray[$newkey] = $array[$newkey];
7958 return $newarray;
7962 * Given an arbitrary array, and a number of draws,
7963 * this function returns an array with that amount
7964 * of items. The indexes are retained.
7966 * @todo Finish documenting this function
7968 * @param array $array
7969 * @param int $draws
7970 * @return array
7972 function draw_rand_array($array, $draws) {
7974 $return = array();
7976 $last = count($array);
7978 if ($draws > $last) {
7979 $draws = $last;
7982 while ($draws > 0) {
7983 $last--;
7985 $keys = array_keys($array);
7986 $rand = rand(0, $last);
7988 $return[$keys[$rand]] = $array[$keys[$rand]];
7989 unset($array[$keys[$rand]]);
7991 $draws--;
7994 return $return;
7998 * Calculate the difference between two microtimes
8000 * @param string $a The first Microtime
8001 * @param string $b The second Microtime
8002 * @return string
8004 function microtime_diff($a, $b) {
8005 list($adec, $asec) = explode(' ', $a);
8006 list($bdec, $bsec) = explode(' ', $b);
8007 return $bsec - $asec + $bdec - $adec;
8011 * Given a list (eg a,b,c,d,e) this function returns
8012 * an array of 1->a, 2->b, 3->c etc
8014 * @param string $list The string to explode into array bits
8015 * @param string $separator The separator used within the list string
8016 * @return array The now assembled array
8018 function make_menu_from_list($list, $separator=',') {
8020 $array = array_reverse(explode($separator, $list), true);
8021 foreach ($array as $key => $item) {
8022 $outarray[$key+1] = trim($item);
8024 return $outarray;
8028 * Creates an array that represents all the current grades that
8029 * can be chosen using the given grading type.
8031 * Negative numbers
8032 * are scales, zero is no grade, and positive numbers are maximum
8033 * grades.
8035 * @todo Finish documenting this function or better deprecated this completely!
8037 * @param int $gradingtype
8038 * @return array
8040 function make_grades_menu($gradingtype) {
8041 global $DB;
8043 $grades = array();
8044 if ($gradingtype < 0) {
8045 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8046 return make_menu_from_list($scale->scale);
8048 } else if ($gradingtype > 0) {
8049 for ($i=$gradingtype; $i>=0; $i--) {
8050 $grades[$i] = $i .' / '. $gradingtype;
8052 return $grades;
8054 return $grades;
8058 * This function returns the number of activities using the given scale in the given course.
8060 * @param int $courseid The course ID to check.
8061 * @param int $scaleid The scale ID to check
8062 * @return int
8064 function course_scale_used($courseid, $scaleid) {
8065 global $CFG, $DB;
8067 $return = 0;
8069 if (!empty($scaleid)) {
8070 if ($cms = get_course_mods($courseid)) {
8071 foreach ($cms as $cm) {
8072 // Check cm->name/lib.php exists.
8073 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
8074 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
8075 $functionname = $cm->modname.'_scale_used';
8076 if (function_exists($functionname)) {
8077 if ($functionname($cm->instance, $scaleid)) {
8078 $return++;
8085 // Check if any course grade item makes use of the scale.
8086 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8088 // Check if any outcome in the course makes use of the scale.
8089 $return += $DB->count_records_sql("SELECT COUNT('x')
8090 FROM {grade_outcomes_courses} goc,
8091 {grade_outcomes} go
8092 WHERE go.id = goc.outcomeid
8093 AND go.scaleid = ? AND goc.courseid = ?",
8094 array($scaleid, $courseid));
8096 return $return;
8100 * This function returns the number of activities using scaleid in the entire site
8102 * @param int $scaleid
8103 * @param array $courses
8104 * @return int
8106 function site_scale_used($scaleid, &$courses) {
8107 $return = 0;
8109 if (!is_array($courses) || count($courses) == 0) {
8110 $courses = get_courses("all", false, "c.id, c.shortname");
8113 if (!empty($scaleid)) {
8114 if (is_array($courses) && count($courses) > 0) {
8115 foreach ($courses as $course) {
8116 $return += course_scale_used($course->id, $scaleid);
8120 return $return;
8124 * make_unique_id_code
8126 * @todo Finish documenting this function
8128 * @uses $_SERVER
8129 * @param string $extra Extra string to append to the end of the code
8130 * @return string
8132 function make_unique_id_code($extra = '') {
8134 $hostname = 'unknownhost';
8135 if (!empty($_SERVER['HTTP_HOST'])) {
8136 $hostname = $_SERVER['HTTP_HOST'];
8137 } else if (!empty($_ENV['HTTP_HOST'])) {
8138 $hostname = $_ENV['HTTP_HOST'];
8139 } else if (!empty($_SERVER['SERVER_NAME'])) {
8140 $hostname = $_SERVER['SERVER_NAME'];
8141 } else if (!empty($_ENV['SERVER_NAME'])) {
8142 $hostname = $_ENV['SERVER_NAME'];
8145 $date = gmdate("ymdHis");
8147 $random = random_string(6);
8149 if ($extra) {
8150 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8151 } else {
8152 return $hostname .'+'. $date .'+'. $random;
8158 * Function to check the passed address is within the passed subnet
8160 * The parameter is a comma separated string of subnet definitions.
8161 * Subnet strings can be in one of three formats:
8162 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8163 * 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)
8164 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8165 * Code for type 1 modified from user posted comments by mediator at
8166 * {@link http://au.php.net/manual/en/function.ip2long.php}
8168 * @param string $addr The address you are checking
8169 * @param string $subnetstr The string of subnet addresses
8170 * @return bool
8172 function address_in_subnet($addr, $subnetstr) {
8174 if ($addr == '0.0.0.0') {
8175 return false;
8177 $subnets = explode(',', $subnetstr);
8178 $found = false;
8179 $addr = trim($addr);
8180 $addr = cleanremoteaddr($addr, false); // Normalise.
8181 if ($addr === null) {
8182 return false;
8184 $addrparts = explode(':', $addr);
8186 $ipv6 = strpos($addr, ':');
8188 foreach ($subnets as $subnet) {
8189 $subnet = trim($subnet);
8190 if ($subnet === '') {
8191 continue;
8194 if (strpos($subnet, '/') !== false) {
8195 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8196 list($ip, $mask) = explode('/', $subnet);
8197 $mask = trim($mask);
8198 if (!is_number($mask)) {
8199 continue; // Incorect mask number, eh?
8201 $ip = cleanremoteaddr($ip, false); // Normalise.
8202 if ($ip === null) {
8203 continue;
8205 if (strpos($ip, ':') !== false) {
8206 // IPv6.
8207 if (!$ipv6) {
8208 continue;
8210 if ($mask > 128 or $mask < 0) {
8211 continue; // Nonsense.
8213 if ($mask == 0) {
8214 return true; // Any address.
8216 if ($mask == 128) {
8217 if ($ip === $addr) {
8218 return true;
8220 continue;
8222 $ipparts = explode(':', $ip);
8223 $modulo = $mask % 16;
8224 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8225 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8226 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8227 if ($modulo == 0) {
8228 return true;
8230 $pos = ($mask-$modulo)/16;
8231 $ipnet = hexdec($ipparts[$pos]);
8232 $addrnet = hexdec($addrparts[$pos]);
8233 $mask = 0xffff << (16 - $modulo);
8234 if (($addrnet & $mask) == ($ipnet & $mask)) {
8235 return true;
8239 } else {
8240 // IPv4.
8241 if ($ipv6) {
8242 continue;
8244 if ($mask > 32 or $mask < 0) {
8245 continue; // Nonsense.
8247 if ($mask == 0) {
8248 return true;
8250 if ($mask == 32) {
8251 if ($ip === $addr) {
8252 return true;
8254 continue;
8256 $mask = 0xffffffff << (32 - $mask);
8257 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8258 return true;
8262 } else if (strpos($subnet, '-') !== false) {
8263 // 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.
8264 $parts = explode('-', $subnet);
8265 if (count($parts) != 2) {
8266 continue;
8269 if (strpos($subnet, ':') !== false) {
8270 // IPv6.
8271 if (!$ipv6) {
8272 continue;
8274 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8275 if ($ipstart === null) {
8276 continue;
8278 $ipparts = explode(':', $ipstart);
8279 $start = hexdec(array_pop($ipparts));
8280 $ipparts[] = trim($parts[1]);
8281 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8282 if ($ipend === null) {
8283 continue;
8285 $ipparts[7] = '';
8286 $ipnet = implode(':', $ipparts);
8287 if (strpos($addr, $ipnet) !== 0) {
8288 continue;
8290 $ipparts = explode(':', $ipend);
8291 $end = hexdec($ipparts[7]);
8293 $addrend = hexdec($addrparts[7]);
8295 if (($addrend >= $start) and ($addrend <= $end)) {
8296 return true;
8299 } else {
8300 // IPv4.
8301 if ($ipv6) {
8302 continue;
8304 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8305 if ($ipstart === null) {
8306 continue;
8308 $ipparts = explode('.', $ipstart);
8309 $ipparts[3] = trim($parts[1]);
8310 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8311 if ($ipend === null) {
8312 continue;
8315 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8316 return true;
8320 } else {
8321 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8322 if (strpos($subnet, ':') !== false) {
8323 // IPv6.
8324 if (!$ipv6) {
8325 continue;
8327 $parts = explode(':', $subnet);
8328 $count = count($parts);
8329 if ($parts[$count-1] === '') {
8330 unset($parts[$count-1]); // Trim trailing :'s.
8331 $count--;
8332 $subnet = implode('.', $parts);
8334 $isip = cleanremoteaddr($subnet, false); // Normalise.
8335 if ($isip !== null) {
8336 if ($isip === $addr) {
8337 return true;
8339 continue;
8340 } else if ($count > 8) {
8341 continue;
8343 $zeros = array_fill(0, 8-$count, '0');
8344 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8345 if (address_in_subnet($addr, $subnet)) {
8346 return true;
8349 } else {
8350 // IPv4.
8351 if ($ipv6) {
8352 continue;
8354 $parts = explode('.', $subnet);
8355 $count = count($parts);
8356 if ($parts[$count-1] === '') {
8357 unset($parts[$count-1]); // Trim trailing .
8358 $count--;
8359 $subnet = implode('.', $parts);
8361 if ($count == 4) {
8362 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8363 if ($subnet === $addr) {
8364 return true;
8366 continue;
8367 } else if ($count > 4) {
8368 continue;
8370 $zeros = array_fill(0, 4-$count, '0');
8371 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8372 if (address_in_subnet($addr, $subnet)) {
8373 return true;
8379 return false;
8383 * For outputting debugging info
8385 * @param string $string The string to write
8386 * @param string $eol The end of line char(s) to use
8387 * @param string $sleep Period to make the application sleep
8388 * This ensures any messages have time to display before redirect
8390 function mtrace($string, $eol="\n", $sleep=0) {
8392 if (defined('STDOUT') and !PHPUNIT_TEST) {
8393 fwrite(STDOUT, $string.$eol);
8394 } else {
8395 echo $string . $eol;
8398 flush();
8400 // Delay to keep message on user's screen in case of subsequent redirect.
8401 if ($sleep) {
8402 sleep($sleep);
8407 * Replace 1 or more slashes or backslashes to 1 slash
8409 * @param string $path The path to strip
8410 * @return string the path with double slashes removed
8412 function cleardoubleslashes ($path) {
8413 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8417 * Is current ip in give list?
8419 * @param string $list
8420 * @return bool
8422 function remoteip_in_list($list) {
8423 $inlist = false;
8424 $clientip = getremoteaddr(null);
8426 if (!$clientip) {
8427 // Ensure access on cli.
8428 return true;
8431 $list = explode("\n", $list);
8432 foreach ($list as $subnet) {
8433 $subnet = trim($subnet);
8434 if (address_in_subnet($clientip, $subnet)) {
8435 $inlist = true;
8436 break;
8439 return $inlist;
8443 * Returns most reliable client address
8445 * @param string $default If an address can't be determined, then return this
8446 * @return string The remote IP address
8448 function getremoteaddr($default='0.0.0.0') {
8449 global $CFG;
8451 if (empty($CFG->getremoteaddrconf)) {
8452 // This will happen, for example, before just after the upgrade, as the
8453 // user is redirected to the admin screen.
8454 $variablestoskip = 0;
8455 } else {
8456 $variablestoskip = $CFG->getremoteaddrconf;
8458 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8459 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8460 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8461 return $address ? $address : $default;
8464 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8465 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8466 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8467 $address = $forwardedaddresses[0];
8469 if (substr_count($address, ":") > 1) {
8470 // Remove port and brackets from IPv6.
8471 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8472 $address = $matches[1];
8474 } else {
8475 // Remove port from IPv4.
8476 if (substr_count($address, ":") == 1) {
8477 $parts = explode(":", $address);
8478 $address = $parts[0];
8482 $address = cleanremoteaddr($address);
8483 return $address ? $address : $default;
8486 if (!empty($_SERVER['REMOTE_ADDR'])) {
8487 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8488 return $address ? $address : $default;
8489 } else {
8490 return $default;
8495 * Cleans an ip address. Internal addresses are now allowed.
8496 * (Originally local addresses were not allowed.)
8498 * @param string $addr IPv4 or IPv6 address
8499 * @param bool $compress use IPv6 address compression
8500 * @return string normalised ip address string, null if error
8502 function cleanremoteaddr($addr, $compress=false) {
8503 $addr = trim($addr);
8505 // TODO: maybe add a separate function is_addr_public() or something like this.
8507 if (strpos($addr, ':') !== false) {
8508 // Can be only IPv6.
8509 $parts = explode(':', $addr);
8510 $count = count($parts);
8512 if (strpos($parts[$count-1], '.') !== false) {
8513 // Legacy ipv4 notation.
8514 $last = array_pop($parts);
8515 $ipv4 = cleanremoteaddr($last, true);
8516 if ($ipv4 === null) {
8517 return null;
8519 $bits = explode('.', $ipv4);
8520 $parts[] = dechex($bits[0]).dechex($bits[1]);
8521 $parts[] = dechex($bits[2]).dechex($bits[3]);
8522 $count = count($parts);
8523 $addr = implode(':', $parts);
8526 if ($count < 3 or $count > 8) {
8527 return null; // Severly malformed.
8530 if ($count != 8) {
8531 if (strpos($addr, '::') === false) {
8532 return null; // Malformed.
8534 // Uncompress.
8535 $insertat = array_search('', $parts, true);
8536 $missing = array_fill(0, 1 + 8 - $count, '0');
8537 array_splice($parts, $insertat, 1, $missing);
8538 foreach ($parts as $key => $part) {
8539 if ($part === '') {
8540 $parts[$key] = '0';
8545 $adr = implode(':', $parts);
8546 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8547 return null; // Incorrect format - sorry.
8550 // Normalise 0s and case.
8551 $parts = array_map('hexdec', $parts);
8552 $parts = array_map('dechex', $parts);
8554 $result = implode(':', $parts);
8556 if (!$compress) {
8557 return $result;
8560 if ($result === '0:0:0:0:0:0:0:0') {
8561 return '::'; // All addresses.
8564 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8565 if ($compressed !== $result) {
8566 return $compressed;
8569 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8570 if ($compressed !== $result) {
8571 return $compressed;
8574 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8575 if ($compressed !== $result) {
8576 return $compressed;
8579 return $result;
8582 // First get all things that look like IPv4 addresses.
8583 $parts = array();
8584 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8585 return null;
8587 unset($parts[0]);
8589 foreach ($parts as $key => $match) {
8590 if ($match > 255) {
8591 return null;
8593 $parts[$key] = (int)$match; // Normalise 0s.
8596 return implode('.', $parts);
8600 * This function will make a complete copy of anything it's given,
8601 * regardless of whether it's an object or not.
8603 * @param mixed $thing Something you want cloned
8604 * @return mixed What ever it is you passed it
8606 function fullclone($thing) {
8607 return unserialize(serialize($thing));
8611 * If new messages are waiting for the current user, then insert
8612 * JavaScript to pop up the messaging window into the page
8614 * @return void
8616 function message_popup_window() {
8617 global $USER, $DB, $PAGE, $CFG;
8619 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
8620 return;
8623 if (!isloggedin() || isguestuser()) {
8624 return;
8627 if (!isset($USER->message_lastpopup)) {
8628 $USER->message_lastpopup = 0;
8629 } else if ($USER->message_lastpopup > (time()-120)) {
8630 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8631 return;
8634 // A quick query to check whether the user has new messages.
8635 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
8636 if ($messagecount < 1) {
8637 return;
8640 // There are unread messages so now do a more complex but slower query.
8641 $messagesql = "SELECT m.id, c.blocked
8642 FROM {message} m
8643 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8644 JOIN {message_processors} p ON mw.processorid=p.id
8645 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8646 AND c.userid = m.useridto
8647 WHERE m.useridto = :userid
8648 AND p.name='popup'";
8650 // If the user was last notified over an hour ago we can re-notify them of old messages
8651 // so don't worry about when the new message was sent.
8652 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
8653 if (!$lastnotifiedlongago) {
8654 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8657 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
8659 $validmessages = 0;
8660 foreach ($waitingmessages as $messageinfo) {
8661 if ($messageinfo->blocked) {
8662 // Message is from a user who has since been blocked so just mark it read.
8663 // Get the full message to mark as read.
8664 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id));
8665 message_mark_message_read($messageobject, time());
8666 } else {
8667 $validmessages++;
8671 if ($validmessages > 0) {
8672 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8673 $strgomessage = get_string('gotomessages', 'message');
8674 $strstaymessage = get_string('ignore', 'admin');
8676 $notificationsound = null;
8677 $beep = get_user_preferences('message_beepnewmessage', '');
8678 if (!empty($beep)) {
8679 // Browsers will work down this list until they find something they support.
8680 $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
8681 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
8682 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8683 $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8685 $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8688 $url = $CFG->wwwroot.'/message/index.php';
8689 $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8690 html_writer::start_tag('div', array('id' => 'newmessagetext')).
8691 $strmessages.
8692 html_writer::end_tag('div').
8694 $notificationsound.
8695 html_writer::start_tag('div', array('id' => 'newmessagelinks')).
8696 html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
8697 html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
8698 html_writer::end_tag('div');
8699 html_writer::end_tag('div');
8701 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
8703 $USER->message_lastpopup = time();
8708 * Used to make sure that $min <= $value <= $max
8710 * Make sure that value is between min, and max
8712 * @param int $min The minimum value
8713 * @param int $value The value to check
8714 * @param int $max The maximum value
8715 * @return int
8717 function bounded_number($min, $value, $max) {
8718 if ($value < $min) {
8719 return $min;
8721 if ($value > $max) {
8722 return $max;
8724 return $value;
8728 * Check if there is a nested array within the passed array
8730 * @param array $array
8731 * @return bool true if there is a nested array false otherwise
8733 function array_is_nested($array) {
8734 foreach ($array as $value) {
8735 if (is_array($value)) {
8736 return true;
8739 return false;
8743 * get_performance_info() pairs up with init_performance_info()
8744 * loaded in setup.php. Returns an array with 'html' and 'txt'
8745 * values ready for use, and each of the individual stats provided
8746 * separately as well.
8748 * @return array
8750 function get_performance_info() {
8751 global $CFG, $PERF, $DB, $PAGE;
8753 $info = array();
8754 $info['html'] = ''; // Holds userfriendly HTML representation.
8755 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8757 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8759 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8760 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8762 if (function_exists('memory_get_usage')) {
8763 $info['memory_total'] = memory_get_usage();
8764 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8765 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8766 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8767 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8770 if (function_exists('memory_get_peak_usage')) {
8771 $info['memory_peak'] = memory_get_peak_usage();
8772 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8773 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8776 $inc = get_included_files();
8777 $info['includecount'] = count($inc);
8778 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8779 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8781 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8782 // We can not track more performance before installation or before PAGE init, sorry.
8783 return $info;
8786 $filtermanager = filter_manager::instance();
8787 if (method_exists($filtermanager, 'get_performance_summary')) {
8788 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8789 $info = array_merge($filterinfo, $info);
8790 foreach ($filterinfo as $key => $value) {
8791 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8792 $info['txt'] .= "$key: $value ";
8796 $stringmanager = get_string_manager();
8797 if (method_exists($stringmanager, 'get_performance_summary')) {
8798 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8799 $info = array_merge($filterinfo, $info);
8800 foreach ($filterinfo as $key => $value) {
8801 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8802 $info['txt'] .= "$key: $value ";
8806 if (!empty($PERF->logwrites)) {
8807 $info['logwrites'] = $PERF->logwrites;
8808 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8809 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8812 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
8813 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
8814 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8816 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
8817 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
8818 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
8820 if (function_exists('posix_times')) {
8821 $ptimes = posix_times();
8822 if (is_array($ptimes)) {
8823 foreach ($ptimes as $key => $val) {
8824 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
8826 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
8827 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8831 // Grab the load average for the last minute.
8832 // /proc will only work under some linux configurations
8833 // while uptime is there under MacOSX/Darwin and other unices.
8834 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
8835 list($serverload) = explode(' ', $loadavg[0]);
8836 unset($loadavg);
8837 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
8838 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
8839 $serverload = $matches[1];
8840 } else {
8841 trigger_error('Could not parse uptime output!');
8844 if (!empty($serverload)) {
8845 $info['serverload'] = $serverload;
8846 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
8847 $info['txt'] .= "serverload: {$info['serverload']} ";
8850 // Display size of session if session started.
8851 if ($si = \core\session\manager::get_performance_info()) {
8852 $info['sessionsize'] = $si['size'];
8853 $info['html'] .= $si['html'];
8854 $info['txt'] .= $si['txt'];
8857 if ($stats = cache_helper::get_stats()) {
8858 $html = '<span class="cachesused">';
8859 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
8860 $text = 'Caches used (hits/misses/sets): ';
8861 $hits = 0;
8862 $misses = 0;
8863 $sets = 0;
8864 foreach ($stats as $definition => $details) {
8865 switch ($details['mode']) {
8866 case cache_store::MODE_APPLICATION:
8867 $modeclass = 'application';
8868 $mode = ' <span title="application cache">[a]</span>';
8869 break;
8870 case cache_store::MODE_SESSION:
8871 $modeclass = 'session';
8872 $mode = ' <span title="session cache">[s]</span>';
8873 break;
8874 case cache_store::MODE_REQUEST:
8875 $modeclass = 'request';
8876 $mode = ' <span title="request cache">[r]</span>';
8877 break;
8879 $html .= '<span class="cache-definition-stats cache-mode-'.$modeclass.'">';
8880 $html .= '<span class="cache-definition-stats-heading">'.$definition.$mode.'</span>';
8881 $text .= "$definition {";
8882 foreach ($details['stores'] as $store => $data) {
8883 $hits += $data['hits'];
8884 $misses += $data['misses'];
8885 $sets += $data['sets'];
8886 if ($data['hits'] == 0 and $data['misses'] > 0) {
8887 $cachestoreclass = 'nohits';
8888 } else if ($data['hits'] < $data['misses']) {
8889 $cachestoreclass = 'lowhits';
8890 } else {
8891 $cachestoreclass = 'hihits';
8893 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
8894 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
8896 $html .= '</span>';
8897 $text .= '} ';
8899 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
8900 $html .= '</span> ';
8901 $info['cachesused'] = "$hits / $misses / $sets";
8902 $info['html'] .= $html;
8903 $info['txt'] .= $text.'. ';
8904 } else {
8905 $info['cachesused'] = '0 / 0 / 0';
8906 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
8907 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
8910 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
8911 return $info;
8915 * Legacy function.
8917 * @todo Document this function linux people
8919 function apd_get_profiling() {
8920 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
8924 * Delete directory or only its content
8926 * @param string $dir directory path
8927 * @param bool $contentonly
8928 * @return bool success, true also if dir does not exist
8930 function remove_dir($dir, $contentonly=false) {
8931 if (!file_exists($dir)) {
8932 // Nothing to do.
8933 return true;
8935 if (!$handle = opendir($dir)) {
8936 return false;
8938 $result = true;
8939 while (false!==($item = readdir($handle))) {
8940 if ($item != '.' && $item != '..') {
8941 if (is_dir($dir.'/'.$item)) {
8942 $result = remove_dir($dir.'/'.$item) && $result;
8943 } else {
8944 $result = unlink($dir.'/'.$item) && $result;
8948 closedir($handle);
8949 if ($contentonly) {
8950 clearstatcache(); // Make sure file stat cache is properly invalidated.
8951 return $result;
8953 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
8954 clearstatcache(); // Make sure file stat cache is properly invalidated.
8955 return $result;
8959 * Detect if an object or a class contains a given property
8960 * will take an actual object or the name of a class
8962 * @param mix $obj Name of class or real object to test
8963 * @param string $property name of property to find
8964 * @return bool true if property exists
8966 function object_property_exists( $obj, $property ) {
8967 if (is_string( $obj )) {
8968 $properties = get_class_vars( $obj );
8969 } else {
8970 $properties = get_object_vars( $obj );
8972 return array_key_exists( $property, $properties );
8976 * Converts an object into an associative array
8978 * This function converts an object into an associative array by iterating
8979 * over its public properties. Because this function uses the foreach
8980 * construct, Iterators are respected. It works recursively on arrays of objects.
8981 * Arrays and simple values are returned as is.
8983 * If class has magic properties, it can implement IteratorAggregate
8984 * and return all available properties in getIterator()
8986 * @param mixed $var
8987 * @return array
8989 function convert_to_array($var) {
8990 $result = array();
8992 // Loop over elements/properties.
8993 foreach ($var as $key => $value) {
8994 // Recursively convert objects.
8995 if (is_object($value) || is_array($value)) {
8996 $result[$key] = convert_to_array($value);
8997 } else {
8998 // Simple values are untouched.
8999 $result[$key] = $value;
9002 return $result;
9006 * Detect a custom script replacement in the data directory that will
9007 * replace an existing moodle script
9009 * @return string|bool full path name if a custom script exists, false if no custom script exists
9011 function custom_script_path() {
9012 global $CFG, $SCRIPT;
9014 if ($SCRIPT === null) {
9015 // Probably some weird external script.
9016 return false;
9019 $scriptpath = $CFG->customscripts . $SCRIPT;
9021 // Check the custom script exists.
9022 if (file_exists($scriptpath) and is_file($scriptpath)) {
9023 return $scriptpath;
9024 } else {
9025 return false;
9030 * Returns whether or not the user object is a remote MNET user. This function
9031 * is in moodlelib because it does not rely on loading any of the MNET code.
9033 * @param object $user A valid user object
9034 * @return bool True if the user is from a remote Moodle.
9036 function is_mnet_remote_user($user) {
9037 global $CFG;
9039 if (!isset($CFG->mnet_localhost_id)) {
9040 include_once($CFG->dirroot . '/mnet/lib.php');
9041 $env = new mnet_environment();
9042 $env->init();
9043 unset($env);
9046 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9050 * This function will search for browser prefereed languages, setting Moodle
9051 * to use the best one available if $SESSION->lang is undefined
9053 function setup_lang_from_browser() {
9054 global $CFG, $SESSION, $USER;
9056 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9057 // Lang is defined in session or user profile, nothing to do.
9058 return;
9061 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9062 return;
9065 // Extract and clean langs from headers.
9066 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9067 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9068 $rawlangs = explode(',', $rawlangs); // Convert to array.
9069 $langs = array();
9071 $order = 1.0;
9072 foreach ($rawlangs as $lang) {
9073 if (strpos($lang, ';') === false) {
9074 $langs[(string)$order] = $lang;
9075 $order = $order-0.01;
9076 } else {
9077 $parts = explode(';', $lang);
9078 $pos = strpos($parts[1], '=');
9079 $langs[substr($parts[1], $pos+1)] = $parts[0];
9082 krsort($langs, SORT_NUMERIC);
9084 // Look for such langs under standard locations.
9085 foreach ($langs as $lang) {
9086 // Clean it properly for include.
9087 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9088 if (get_string_manager()->translation_exists($lang, false)) {
9089 // Lang exists, set it in session.
9090 $SESSION->lang = $lang;
9091 // We have finished. Go out.
9092 break;
9095 return;
9099 * Check if $url matches anything in proxybypass list
9101 * Any errors just result in the proxy being used (least bad)
9103 * @param string $url url to check
9104 * @return boolean true if we should bypass the proxy
9106 function is_proxybypass( $url ) {
9107 global $CFG;
9109 // Sanity check.
9110 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9111 return false;
9114 // Get the host part out of the url.
9115 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9116 return false;
9119 // Get the possible bypass hosts into an array.
9120 $matches = explode( ',', $CFG->proxybypass );
9122 // Check for a match.
9123 // (IPs need to match the left hand side and hosts the right of the url,
9124 // but we can recklessly check both as there can't be a false +ve).
9125 foreach ($matches as $match) {
9126 $match = trim($match);
9128 // Try for IP match (Left side).
9129 $lhs = substr($host, 0, strlen($match));
9130 if (strcasecmp($match, $lhs)==0) {
9131 return true;
9134 // Try for host match (Right side).
9135 $rhs = substr($host, -strlen($match));
9136 if (strcasecmp($match, $rhs)==0) {
9137 return true;
9141 // Nothing matched.
9142 return false;
9146 * Check if the passed navigation is of the new style
9148 * @param mixed $navigation
9149 * @return bool true for yes false for no
9151 function is_newnav($navigation) {
9152 if (is_array($navigation) && !empty($navigation['newnav'])) {
9153 return true;
9154 } else {
9155 return false;
9160 * Checks whether the given variable name is defined as a variable within the given object.
9162 * This will NOT work with stdClass objects, which have no class variables.
9164 * @param string $var The variable name
9165 * @param object $object The object to check
9166 * @return boolean
9168 function in_object_vars($var, $object) {
9169 $classvars = get_class_vars(get_class($object));
9170 $classvars = array_keys($classvars);
9171 return in_array($var, $classvars);
9175 * Returns an array without repeated objects.
9176 * This function is similar to array_unique, but for arrays that have objects as values
9178 * @param array $array
9179 * @param bool $keepkeyassoc
9180 * @return array
9182 function object_array_unique($array, $keepkeyassoc = true) {
9183 $duplicatekeys = array();
9184 $tmp = array();
9186 foreach ($array as $key => $val) {
9187 // Convert objects to arrays, in_array() does not support objects.
9188 if (is_object($val)) {
9189 $val = (array)$val;
9192 if (!in_array($val, $tmp)) {
9193 $tmp[] = $val;
9194 } else {
9195 $duplicatekeys[] = $key;
9199 foreach ($duplicatekeys as $key) {
9200 unset($array[$key]);
9203 return $keepkeyassoc ? $array : array_values($array);
9207 * Is a userid the primary administrator?
9209 * @param int $userid int id of user to check
9210 * @return boolean
9212 function is_primary_admin($userid) {
9213 $primaryadmin = get_admin();
9215 if ($userid == $primaryadmin->id) {
9216 return true;
9217 } else {
9218 return false;
9223 * Returns the site identifier
9225 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9227 function get_site_identifier() {
9228 global $CFG;
9229 // Check to see if it is missing. If so, initialise it.
9230 if (empty($CFG->siteidentifier)) {
9231 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9233 // Return it.
9234 return $CFG->siteidentifier;
9238 * Check whether the given password has no more than the specified
9239 * number of consecutive identical characters.
9241 * @param string $password password to be checked against the password policy
9242 * @param integer $maxchars maximum number of consecutive identical characters
9243 * @return bool
9245 function check_consecutive_identical_characters($password, $maxchars) {
9247 if ($maxchars < 1) {
9248 return true; // Zero 0 is to disable this check.
9250 if (strlen($password) <= $maxchars) {
9251 return true; // Too short to fail this test.
9254 $previouschar = '';
9255 $consecutivecount = 1;
9256 foreach (str_split($password) as $char) {
9257 if ($char != $previouschar) {
9258 $consecutivecount = 1;
9259 } else {
9260 $consecutivecount++;
9261 if ($consecutivecount > $maxchars) {
9262 return false; // Check failed already.
9266 $previouschar = $char;
9269 return true;
9273 * Helper function to do partial function binding.
9274 * so we can use it for preg_replace_callback, for example
9275 * this works with php functions, user functions, static methods and class methods
9276 * it returns you a callback that you can pass on like so:
9278 * $callback = partial('somefunction', $arg1, $arg2);
9279 * or
9280 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9281 * or even
9282 * $obj = new someclass();
9283 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9285 * and then the arguments that are passed through at calltime are appended to the argument list.
9287 * @param mixed $function a php callback
9288 * @param mixed $arg1,... $argv arguments to partially bind with
9289 * @return array Array callback
9291 function partial() {
9292 if (!class_exists('partial')) {
9294 * Used to manage function binding.
9295 * @copyright 2009 Penny Leach
9296 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9298 class partial{
9299 /** @var array */
9300 public $values = array();
9301 /** @var string The function to call as a callback. */
9302 public $func;
9304 * Constructor
9305 * @param string $func
9306 * @param array $args
9308 public function __construct($func, $args) {
9309 $this->values = $args;
9310 $this->func = $func;
9313 * Calls the callback function.
9314 * @return mixed
9316 public function method() {
9317 $args = func_get_args();
9318 return call_user_func_array($this->func, array_merge($this->values, $args));
9322 $args = func_get_args();
9323 $func = array_shift($args);
9324 $p = new partial($func, $args);
9325 return array($p, 'method');
9329 * helper function to load up and initialise the mnet environment
9330 * this must be called before you use mnet functions.
9332 * @return mnet_environment the equivalent of old $MNET global
9334 function get_mnet_environment() {
9335 global $CFG;
9336 require_once($CFG->dirroot . '/mnet/lib.php');
9337 static $instance = null;
9338 if (empty($instance)) {
9339 $instance = new mnet_environment();
9340 $instance->init();
9342 return $instance;
9346 * during xmlrpc server code execution, any code wishing to access
9347 * information about the remote peer must use this to get it.
9349 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9351 function get_mnet_remote_client() {
9352 if (!defined('MNET_SERVER')) {
9353 debugging(get_string('notinxmlrpcserver', 'mnet'));
9354 return false;
9356 global $MNET_REMOTE_CLIENT;
9357 if (isset($MNET_REMOTE_CLIENT)) {
9358 return $MNET_REMOTE_CLIENT;
9360 return false;
9364 * during the xmlrpc server code execution, this will be called
9365 * to setup the object returned by {@link get_mnet_remote_client}
9367 * @param mnet_remote_client $client the client to set up
9368 * @throws moodle_exception
9370 function set_mnet_remote_client($client) {
9371 if (!defined('MNET_SERVER')) {
9372 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9374 global $MNET_REMOTE_CLIENT;
9375 $MNET_REMOTE_CLIENT = $client;
9379 * return the jump url for a given remote user
9380 * this is used for rewriting forum post links in emails, etc
9382 * @param stdclass $user the user to get the idp url for
9384 function mnet_get_idp_jump_url($user) {
9385 global $CFG;
9387 static $mnetjumps = array();
9388 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9389 $idp = mnet_get_peer_host($user->mnethostid);
9390 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9391 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9393 return $mnetjumps[$user->mnethostid];
9397 * Gets the homepage to use for the current user
9399 * @return int One of HOMEPAGE_*
9401 function get_home_page() {
9402 global $CFG;
9404 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9405 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9406 return HOMEPAGE_MY;
9407 } else {
9408 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9411 return HOMEPAGE_SITE;
9415 * Gets the name of a course to be displayed when showing a list of courses.
9416 * By default this is just $course->fullname but user can configure it. The
9417 * result of this function should be passed through print_string.
9418 * @param stdClass|course_in_list $course Moodle course object
9419 * @return string Display name of course (either fullname or short + fullname)
9421 function get_course_display_name_for_list($course) {
9422 global $CFG;
9423 if (!empty($CFG->courselistshortnames)) {
9424 if (!($course instanceof stdClass)) {
9425 $course = (object)convert_to_array($course);
9427 return get_string('courseextendednamedisplay', '', $course);
9428 } else {
9429 return $course->fullname;
9434 * The lang_string class
9436 * This special class is used to create an object representation of a string request.
9437 * It is special because processing doesn't occur until the object is first used.
9438 * The class was created especially to aid performance in areas where strings were
9439 * required to be generated but were not necessarily used.
9440 * As an example the admin tree when generated uses over 1500 strings, of which
9441 * normally only 1/3 are ever actually printed at any time.
9442 * The performance advantage is achieved by not actually processing strings that
9443 * arn't being used, as such reducing the processing required for the page.
9445 * How to use the lang_string class?
9446 * There are two methods of using the lang_string class, first through the
9447 * forth argument of the get_string function, and secondly directly.
9448 * The following are examples of both.
9449 * 1. Through get_string calls e.g.
9450 * $string = get_string($identifier, $component, $a, true);
9451 * $string = get_string('yes', 'moodle', null, true);
9452 * 2. Direct instantiation
9453 * $string = new lang_string($identifier, $component, $a, $lang);
9454 * $string = new lang_string('yes');
9456 * How do I use a lang_string object?
9457 * The lang_string object makes use of a magic __toString method so that you
9458 * are able to use the object exactly as you would use a string in most cases.
9459 * This means you are able to collect it into a variable and then directly
9460 * echo it, or concatenate it into another string, or similar.
9461 * The other thing you can do is manually get the string by calling the
9462 * lang_strings out method e.g.
9463 * $string = new lang_string('yes');
9464 * $string->out();
9465 * Also worth noting is that the out method can take one argument, $lang which
9466 * allows the developer to change the language on the fly.
9468 * When should I use a lang_string object?
9469 * The lang_string object is designed to be used in any situation where a
9470 * string may not be needed, but needs to be generated.
9471 * The admin tree is a good example of where lang_string objects should be
9472 * used.
9473 * A more practical example would be any class that requries strings that may
9474 * not be printed (after all classes get renderer by renderers and who knows
9475 * what they will do ;))
9477 * When should I not use a lang_string object?
9478 * Don't use lang_strings when you are going to use a string immediately.
9479 * There is no need as it will be processed immediately and there will be no
9480 * advantage, and in fact perhaps a negative hit as a class has to be
9481 * instantiated for a lang_string object, however get_string won't require
9482 * that.
9484 * Limitations:
9485 * 1. You cannot use a lang_string object as an array offset. Doing so will
9486 * result in PHP throwing an error. (You can use it as an object property!)
9488 * @package core
9489 * @category string
9490 * @copyright 2011 Sam Hemelryk
9491 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9493 class lang_string {
9495 /** @var string The strings identifier */
9496 protected $identifier;
9497 /** @var string The strings component. Default '' */
9498 protected $component = '';
9499 /** @var array|stdClass Any arguments required for the string. Default null */
9500 protected $a = null;
9501 /** @var string The language to use when processing the string. Default null */
9502 protected $lang = null;
9504 /** @var string The processed string (once processed) */
9505 protected $string = null;
9508 * A special boolean. If set to true then the object has been woken up and
9509 * cannot be regenerated. If this is set then $this->string MUST be used.
9510 * @var bool
9512 protected $forcedstring = false;
9515 * Constructs a lang_string object
9517 * This function should do as little processing as possible to ensure the best
9518 * performance for strings that won't be used.
9520 * @param string $identifier The strings identifier
9521 * @param string $component The strings component
9522 * @param stdClass|array $a Any arguments the string requires
9523 * @param string $lang The language to use when processing the string.
9524 * @throws coding_exception
9526 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9527 if (empty($component)) {
9528 $component = 'moodle';
9531 $this->identifier = $identifier;
9532 $this->component = $component;
9533 $this->lang = $lang;
9535 // We MUST duplicate $a to ensure that it if it changes by reference those
9536 // changes are not carried across.
9537 // To do this we always ensure $a or its properties/values are strings
9538 // and that any properties/values that arn't convertable are forgotten.
9539 if (!empty($a)) {
9540 if (is_scalar($a)) {
9541 $this->a = $a;
9542 } else if ($a instanceof lang_string) {
9543 $this->a = $a->out();
9544 } else if (is_object($a) or is_array($a)) {
9545 $a = (array)$a;
9546 $this->a = array();
9547 foreach ($a as $key => $value) {
9548 // Make sure conversion errors don't get displayed (results in '').
9549 if (is_array($value)) {
9550 $this->a[$key] = '';
9551 } else if (is_object($value)) {
9552 if (method_exists($value, '__toString')) {
9553 $this->a[$key] = $value->__toString();
9554 } else {
9555 $this->a[$key] = '';
9557 } else {
9558 $this->a[$key] = (string)$value;
9564 if (debugging(false, DEBUG_DEVELOPER)) {
9565 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9566 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9568 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9569 throw new coding_exception('Invalid string compontent. Please check your string definition');
9571 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9572 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9578 * Processes the string.
9580 * This function actually processes the string, stores it in the string property
9581 * and then returns it.
9582 * You will notice that this function is VERY similar to the get_string method.
9583 * That is because it is pretty much doing the same thing.
9584 * However as this function is an upgrade it isn't as tolerant to backwards
9585 * compatibility.
9587 * @return string
9588 * @throws coding_exception
9590 protected function get_string() {
9591 global $CFG;
9593 // Check if we need to process the string.
9594 if ($this->string === null) {
9595 // Check the quality of the identifier.
9596 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9597 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);
9600 // Process the string.
9601 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9602 // Debugging feature lets you display string identifier and component.
9603 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9604 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9607 // Return the string.
9608 return $this->string;
9612 * Returns the string
9614 * @param string $lang The langauge to use when processing the string
9615 * @return string
9617 public function out($lang = null) {
9618 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9619 if ($this->forcedstring) {
9620 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9621 return $this->get_string();
9623 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9624 return $translatedstring->out();
9626 return $this->get_string();
9630 * Magic __toString method for printing a string
9632 * @return string
9634 public function __toString() {
9635 return $this->get_string();
9639 * Magic __set_state method used for var_export
9641 * @return string
9643 public function __set_state() {
9644 return $this->get_string();
9648 * Prepares the lang_string for sleep and stores only the forcedstring and
9649 * string properties... the string cannot be regenerated so we need to ensure
9650 * it is generated for this.
9652 * @return string
9654 public function __sleep() {
9655 $this->get_string();
9656 $this->forcedstring = true;
9657 return array('forcedstring', 'string', 'lang');