2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
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.
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
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.
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
77 define('PARAM_ALPHA', 'alpha');
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');
86 * PARAM_ALPHANUM - expected numbers and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
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');
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);
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);
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
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
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];
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
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
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];
587 print_error('missingparam', '', '', $parname);
589 if (!is_array($param)) {
590 print_error('missingparam', '', '', $parname);
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);
599 $result[$key] = clean_param($value, $type);
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
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
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];
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
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
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];
675 if (!is_array($param)) {
676 debugging('optional_param_array() expects array parameters only: '.$parname);
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);
686 $result[$key] = clean_param($value, $type);
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
) {
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)) {
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);
736 * Makes sure array contains only the allowed types, this function does not validate array key names!
739 * $options = clean_param($options, PARAM_INT);
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
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)) {
754 $param[$key] = clean_param_array($value, $type, true);
756 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
759 $param[$key] = clean_param($value, $type);
766 * Used by {@link optional_param()} and {@link required_param()} to
767 * clean the variables and/or cast to specific types, based on
770 * $course->format = clean_param($course->format, PARAM_ALPHA);
771 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
774 * @param mixed $param the variable we are cleaning
775 * @param string $type expected format of param after cleaning.
777 * @throws coding_exception
779 function clean_param($param, $type) {
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();
788 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
794 // No cleaning at all.
795 $param = fix_utf8($param);
798 case PARAM_RAW_TRIMMED
:
799 // No cleaning, but strip leading and trailing whitespace.
800 $param = fix_utf8($param);
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)) {
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
);
821 // Convert to integer.
826 return (float)$param;
829 // Remove everything not `a-z`.
830 return preg_replace('/[^a-zA-Z]/i', '', $param);
833 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
834 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
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);
845 // Remove everything not `0-9,`.
846 return preg_replace('/[^0-9,]/i', '', $param);
849 // Convert to 1 or 0.
850 $tempstr = strtolower($param);
851 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
853 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
856 $param = empty($param) ?
0 : 1;
862 $param = fix_utf8($param);
863 return strip_tags($param);
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.
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)) {
878 foreach ($matches[0] as $match) {
879 if ($match === '</lang>') {
887 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
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)) {
905 foreach ($matches[0] as $match) {
906 if ($match === '</span>') {
914 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
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)) {
935 if (strpos($param, '__') !== false) {
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) {
948 // We do not want any guessing here, either the name is correct or not.
949 if (!is_valid_plugin_name($param)) {
955 // Remove everything not a-zA-Z0-9_- .
956 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
959 // Remove everything not a-zA-Z0-9/_- .
960 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
963 // Strip all suspicious characters from filename.
964 $param = fix_utf8($param);
965 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
966 if ($param === '.' ||
$param === '..') {
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.
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);
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.
1002 ||
$match[4] > 255 ) {
1003 // Hmmm, what kind of dotted quad is this?
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.
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.
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
) {
1038 } else if (!empty($CFG->loginhttps
) && $param === $httpswwwroot) {
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.
1047 // Relative - let's make sure there are no tricks.
1048 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1058 $param = trim($param);
1059 // PEM formatted strings may contain letters/numbers and the symbols:
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
);
1069 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1077 if (!empty($param)) {
1078 // PEM formatted strings may contain letters/numbers and the symbols
1082 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
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++
) {
1090 if (64 < strlen($lines[$i])) {
1096 if (64 != strlen($lines[$i])) {
1100 return implode("\n", $lines);
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
);
1117 $param = fix_utf8($param);
1118 $tags = explode(',', $param);
1120 foreach ($tags as $tag) {
1121 $res = clean_param($tag, PARAM_TAG
);
1127 return implode(',', $result);
1132 case PARAM_CAPABILITY
:
1133 if (get_capability_info($param)) {
1139 case PARAM_PERMISSION
:
1140 $param = (int)$param;
1141 if (in_array($param, array(CAP_INHERIT
, CAP_ALLOW
, CAP_PREVENT
, CAP_PROHIBIT
))) {
1148 $param = clean_param($param, PARAM_PLUGIN
);
1149 if (empty($param)) {
1151 } else if (exists_auth_plugin($param)) {
1158 $param = clean_param($param, PARAM_SAFEDIR
);
1159 if (get_string_manager()->translation_exists($param)) {
1162 // Specified language is not installed or param malformed.
1167 $param = clean_param($param, PARAM_PLUGIN
);
1168 if (empty($param)) {
1170 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1172 } else if (!empty($CFG->themedir
) and file_exists("$CFG->themedir/$param/config.php")) {
1175 // Specified theme is not installed.
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);
1193 $param = fix_utf8($param);
1194 if (validate_email($param)) {
1200 case PARAM_STRINGID
:
1201 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
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)) {
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 === '') {
1235 } else if (is_string($value)) {
1236 if ((string)(int)$value === $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€');
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);
1257 // Warn admins on admin/index.php page.
1262 $result = @iconv
('UTF-8', 'UTF-8//IGNORE', $value);
1267 } else if (is_array($value)) {
1268 foreach ($value as $k => $v) {
1269 $value[$k] = fix_utf8($v);
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);
1282 // This is some other type, no utf-8 here.
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)) {
1296 } else if (is_string($value)) {
1297 return ((string)(int)$value) === $value;
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);
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) {
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)) {
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));
1368 $DB->set_field('config', 'value', $value, array('name' => $name));
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');
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));
1388 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
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);
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) {
1427 static $siteidentifier = null;
1429 if ($plugin === 'moodle' ||
$plugin === 'core' ||
empty($plugin)) {
1430 $forced =& $CFG->config_php_settings
;
1434 if (array_key_exists($plugin, $CFG->forced_plugin_settings
)) {
1435 $forced =& $CFG->forced_plugin_settings
[$plugin];
1442 if ($siteidentifier === null) {
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;
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.
1468 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
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];
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]);
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) {
1512 if (empty($plugin)) {
1514 $DB->delete_records('config', array('name' => $name));
1515 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1517 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1518 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
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) {
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));
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@$') {
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@$') {
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;
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()}
1597 function purge_all_caches() {
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.
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) {
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";
1650 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1651 foreach ($flags as $flag) {
1652 $cf[$flag->name
] = $flag->value
;
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) {
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) {
1692 $timemodified = time();
1693 if ($expiry === null ||
$expiry < $timemodified) {
1694 $expiry = $timemodified +
24 * 60 * 60;
1696 $expiry = (int)$expiry;
1699 if ($value === null) {
1700 unset_cache_flag($type, $name);
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.
1710 $f->expiry
= $expiry;
1711 $f->timemodified
= $timemodified;
1712 $DB->update_record('cache_flags', $f);
1714 $f = new stdClass();
1715 $f->flagtype
= $type;
1718 $f->expiry
= $expiry;
1719 $f->timemodified
= $timemodified;
1720 $DB->insert_record('cache_flags', $f);
1726 * Removes a single volatile flag
1728 * @param string $type the "type" namespace for the key
1729 * @param string $name the key to set
1732 function unset_cache_flag($type, $name) {
1734 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1739 * Garbage-collect volatile flags
1741 * @return bool Always returns true
1743 function gc_cache_flags() {
1745 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
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.
1758 * @category preference
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
1765 function check_user_preferences_loaded(stdClass
$user, $cachelifetime = 120) {
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();
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.
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;
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.
1810 * @param integer $userid the user whose prefs were changed.
1812 function mark_user_preferences_changed($userid) {
1815 if (empty($userid) or isguestuser($userid)) {
1816 // No cache flags for guest and not-logged-in users.
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.
1829 * @category preference
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) {
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)) {
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);
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;
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.
1882 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id
));
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
);
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.
1907 * @category preference
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);
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.
1926 * @category preference
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) {
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)) {
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);
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]);
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
);
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,
1981 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1984 * @category preference
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) {
1996 if (is_null($name)) {
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)) {
2004 } else if (isset($user->id
)) {
2005 // Is a valid object.
2006 } else if (is_numeric($user)) {
2007 $user = (object)array('id' => (int)$user);
2009 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2012 check_user_preferences_loaded($user);
2016 return $user->preference
;
2017 } else if (isset($user->preference
[$name])) {
2018 // The single string value.
2019 return $user->preference
[$name];
2021 // Default value (null if not specified).
2026 // FUNCTIONS FOR HANDLING TIME.
2029 * Given date parts in user time produce a GMT timestamp.
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.
2054 $time +
= dst_offset_on($time, $timezone);
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
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);
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
;
2118 $oyears = $years .' '. $sy;
2121 $odays = $days .' '. $sd;
2124 $ohours = $hours .' '. $sh;
2127 $omins = $mins .' '. $sm;
2130 $osecs = $secs .' '. $ss;
2134 return trim($oyears .' '. $odays);
2137 return trim($odays .' '. $ohours);
2140 return trim($ohours .' '. $omins);
2143 return trim($omins .' '. $osecs);
2148 return get_string('now');
2152 * Returns a formatted string that represents a date in user 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) {
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');
2210 * Given a $time timestamp in GMT (seconds since epoch),
2211 * returns an array that represents the date in user 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();
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!
2236 * @param int $date Timestamp in GMT
2237 * @param float|int|string $timezone user timezone
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.
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
2272 * @param float|int|string $timezone user timezone
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
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) {
2298 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
2299 isset($USER->timezone
) ?
$USER->timezone
: 99,
2300 isset($CFG->timezone
) ?
$CFG->timezone
: 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.
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
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') {
2336 * Calculates when the day appears in specific month
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
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;
2383 $indexweekday = dayofweek($startday, $month, $year);
2385 $diff = $weekday - $indexweekday;
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
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
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
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
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() {
2436 $url = "$CFG->wwwroot/login/index.php";
2438 if (!empty($CFG->loginhttps
)) {
2439 $url = str_replace('http:', 'https:', $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
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
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;
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);
2497 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST
);
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
);
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!!
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();
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;
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();
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);
2605 // Use moodle internal method.
2606 if (empty($CFG->loginhttps
)) {
2607 redirect($CFG->wwwroot
.'/login/change_password.php');
2609 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot
);
2610 redirect($wwwroot .'/login/change_password.php');
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
.'&course='. SITEID
);
2629 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2632 // Do not bother admins with any formalities.
2633 if (is_siteadmin()) {
2634 // Set the global $COURSE.
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
);
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
);
2671 $cmcontext = context_module
::instance($cm->id
, MUST_EXIST
);
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.
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.
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.
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
.'/');
2727 if (is_role_switched($course->id
)) {
2728 // Ok, user had to be inside this course before the switch.
2731 } else if (is_viewing($coursecontext, $USER)) {
2732 // Ok, no need to mess with enrol.
2736 if (isset($USER->enrol
['enrolled'][$course->id
])) {
2737 if ($USER->enrol
['enrolled'][$course->id
] > time()) {
2739 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2740 unset($USER->enrol
['tempguest'][$course->id
]);
2741 remove_temp_course_roles($coursecontext);
2745 unset($USER->enrol
['enrolled'][$course->id
]);
2748 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2749 if ($USER->enrol
['tempguest'][$course->id
] == 0) {
2751 } else if ($USER->enrol
['tempguest'][$course->id
] > time()) {
2755 unset($USER->enrol
['tempguest'][$course->id
]);
2756 remove_temp_course_roles($coursecontext);
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.
2766 $until = ENROL_MAX_TIMESTAMP
;
2768 $USER->enrol
['enrolled'][$course->id
] = $until;
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
])) {
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) {
2784 $until = ENROL_MAX_TIMESTAMP
;
2786 $USER->enrol
['enrolled'][$course->id
] = $until;
2791 // If not enrolled yet try to gain temporary guest access.
2793 foreach ($instances as $instance) {
2794 if (!isset($enrols[$instance->enrol
])) {
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;
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
));
2829 $url = new moodle_url('/');
2831 redirect($url, get_string('activityiscurrentlyhidden'));
2834 // Set the global $COURSE.
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
2853 function require_logout() {
2856 if (!isloggedin()) {
2857 // This should not happen often, no need for hooks or events here.
2858 \core\session\manager
::terminate_current();
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(
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.
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
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
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;
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;
2950 $course = clone $SITE;
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');
2959 $PAGE->set_course($course);
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
);
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) {
2986 if (!NO_MOODLE_COOKIES
) {
2987 print_error('sessioncookiesdisable');
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) {
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
))) {
3052 $key->value
= md5($userid.'_'.time().random_string(40));
3054 $DB->insert_record('user_private_key', $key);
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
3065 function delete_user_key($script, $userid) {
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) {
3083 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3084 'instance' => $instance, 'iprestriction' => $iprestriction,
3085 'validuntil' => $validuntil))) {
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() {
3101 if (isguestuser()) {
3102 // Do not update guest access times/ips for performance.
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);
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
3137 function user_not_fully_set_up($user) {
3138 if (isguestuser($user)) {
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) {
3153 if (empty($CFG->handlebounces
)) {
3157 if (empty($user->id
)) {
3158 // No real (DB) user, nothing to do here.
3162 // Set sensible defaults.
3163 if (empty($CFG->minbounces
)) {
3164 $CFG->minbounces
= 10;
3166 if (empty($CFG->bounceratio
)) {
3167 $CFG->bounceratio
= .20;
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
3187 function set_send_count($user, $reset=false) {
3190 if (empty($user->id
)) {
3191 // No real (DB) user, nothing to do here.
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';
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) {
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';
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
3236 function ismoving($courseid) {
3239 if (!empty($USER->activitycopy
)) {
3240 return ($USER->activitycopycourse
== $courseid);
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
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.
3256 function fullname($user, $override=false) {
3257 global $CFG, $SESSION;
3259 if (!isset($user->firstname
) and !isset($user->lastname
)) {
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.
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
;
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.
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);
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);
3326 $displayname = str_replace($altname, $user->$altname, $displayname);
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.
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.
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.
3400 foreach ($alternatenames as $key => $altname) {
3401 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
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]);
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;
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()) {
3488 // Only users with permission get the extra fields.
3489 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3493 // Split showuseridentity on comma.
3494 if (empty($CFG->showuseridentity
)) {
3495 // Explode gives wrong result with empty string.
3498 $extra = explode(',', $CFG->showuseridentity
);
3501 foreach ($extra as $key => $field) {
3502 if (in_array($field, $already)) {
3503 unset($extra[$key]);
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);
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);
3529 // Add punctuation for alias.
3530 if ($alias !== '') {
3533 foreach ($fields as $field) {
3534 $result .= ', ' . $alias . $field;
3536 $result .= ' AS ' . $prefix . $field;
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.
3551 return get_string('phone');
3554 return get_string('webpage');
3557 return get_string('icqnumber');
3560 return get_string('skypeid');
3563 return get_string('aimid');
3566 return get_string('yahooid');
3569 return get_string('msnid');
3572 // Otherwise just use the same lang string.
3573 return get_string($field);
3577 * Returns whether a given authentication plugin exists.
3579 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3580 * @return boolean Whether the plugin is available.
3582 function exists_auth_plugin($auth) {
3585 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3586 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3592 * Checks if a given plugin is in the list of enabled authentication plugins.
3594 * @param string $auth Authentication plugin.
3595 * @return boolean Whether the plugin is enabled.
3597 function is_enabled_auth($auth) {
3602 $enabled = get_enabled_auth_plugins();
3604 return in_array($auth, $enabled);
3608 * Returns an authentication plugin instance.
3610 * @param string $auth name of authentication plugin
3611 * @return auth_plugin_base An instance of the required authentication plugin.
3613 function get_auth_plugin($auth) {
3616 // Check the plugin exists first.
3617 if (! exists_auth_plugin($auth)) {
3618 print_error('authpluginnotfound', 'debug', '', $auth);
3621 // Return auth plugin instance.
3622 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3623 $class = "auth_plugin_$auth";
3628 * Returns array of active auth plugins.
3630 * @param bool $fix fix $CFG->auth if needed
3633 function get_enabled_auth_plugins($fix=false) {
3636 $default = array('manual', 'nologin');
3638 if (empty($CFG->auth
)) {
3641 $auths = explode(',', $CFG->auth
);
3645 $auths = array_unique($auths);
3646 foreach ($auths as $k => $authname) {
3647 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3651 $newconfig = implode(',', $auths);
3652 if (!isset($CFG->auth
) or $newconfig != $CFG->auth
) {
3653 set_config('auth', $newconfig);
3657 return (array_merge($default, $auths));
3661 * Returns true if an internal authentication method is being used.
3662 * if method not specified then, global default is assumed
3664 * @param string $auth Form of authentication required
3667 function is_internal_auth($auth) {
3668 // Throws error if bad $auth.
3669 $authplugin = get_auth_plugin($auth);
3670 return $authplugin->is_internal();
3674 * Returns true if the user is a 'restored' one.
3676 * Used in the login process to inform the user and allow him/her to reset the password
3678 * @param string $username username to be checked
3681 function is_restored_user($username) {
3684 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'password' => 'restored'));
3688 * Returns an array of user fields
3690 * @return array User field/column names
3692 function get_user_fieldnames() {
3695 $fieldarray = $DB->get_columns('user');
3696 unset($fieldarray['id']);
3697 $fieldarray = array_keys($fieldarray);
3703 * Creates a bare-bones user record
3705 * @todo Outline auth types and provide code example
3707 * @param string $username New user's username to add to record
3708 * @param string $password New user's password to add to record
3709 * @param string $auth Form of authentication required
3710 * @return stdClass A complete user object
3712 function create_user_record($username, $password, $auth = 'manual') {
3714 require_once($CFG->dirroot
.'/user/profile/lib.php');
3715 require_once($CFG->dirroot
.'/user/lib.php');
3717 // Just in case check text case.
3718 $username = trim(core_text
::strtolower($username));
3720 $authplugin = get_auth_plugin($auth);
3721 $customfields = $authplugin->get_custom_user_profile_fields();
3722 $newuser = new stdClass();
3723 if ($newinfo = $authplugin->get_userinfo($username)) {
3724 $newinfo = truncate_userinfo($newinfo);
3725 foreach ($newinfo as $key => $value) {
3726 if (in_array($key, $authplugin->userfields
) ||
(in_array($key, $customfields))) {
3727 $newuser->$key = $value;
3732 if (!empty($newuser->email
)) {
3733 if (email_is_not_allowed($newuser->email
)) {
3734 unset($newuser->email
);
3738 if (!isset($newuser->city
)) {
3739 $newuser->city
= '';
3742 $newuser->auth
= $auth;
3743 $newuser->username
= $username;
3746 // user CFG lang for user if $newuser->lang is empty
3747 // or $user->lang is not an installed language.
3748 if (empty($newuser->lang
) ||
!get_string_manager()->translation_exists($newuser->lang
)) {
3749 $newuser->lang
= $CFG->lang
;
3751 $newuser->confirmed
= 1;
3752 $newuser->lastip
= getremoteaddr();
3753 $newuser->timecreated
= time();
3754 $newuser->timemodified
= $newuser->timecreated
;
3755 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
3757 $newuser->id
= user_create_user($newuser, false, false);
3759 // Save user profile data.
3760 profile_save_data($newuser);
3762 $user = get_complete_user_data('id', $newuser->id
);
3763 if (!empty($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'})) {
3764 set_user_preference('auth_forcepasswordchange', 1, $user);
3766 // Set the password.
3767 update_internal_user_password($user, $password);
3770 \core\event\user_created
::create_from_userid($newuser->id
)->trigger();
3776 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3778 * @param string $username user's username to update the record
3779 * @return stdClass A complete user object
3781 function update_user_record($username) {
3783 // Just in case check text case.
3784 $username = trim(core_text
::strtolower($username));
3786 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
), '*', MUST_EXIST
);
3787 return update_user_record_by_id($oldinfo->id
);
3791 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3793 * @param int $id user id
3794 * @return stdClass A complete user object
3796 function update_user_record_by_id($id) {
3798 require_once($CFG->dirroot
."/user/profile/lib.php");
3799 require_once($CFG->dirroot
.'/user/lib.php');
3801 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'id' => $id, 'deleted' => 0);
3802 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST
);
3805 $userauth = get_auth_plugin($oldinfo->auth
);
3807 if ($newinfo = $userauth->get_userinfo($oldinfo->username
)) {
3808 $newinfo = truncate_userinfo($newinfo);
3809 $customfields = $userauth->get_custom_user_profile_fields();
3811 foreach ($newinfo as $key => $value) {
3812 $key = strtolower($key);
3813 $iscustom = in_array($key, $customfields);
3814 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3815 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3816 // Unknown or must not be changed.
3819 $confval = $userauth->config
->{'field_updatelocal_' . $key};
3820 $lockval = $userauth->config
->{'field_lock_' . $key};
3821 if (empty($confval) ||
empty($lockval)) {
3824 if ($confval === 'onlogin') {
3825 // MDL-4207 Don't overwrite modified user profile values with
3826 // empty LDAP values when 'unlocked if empty' is set. The purpose
3827 // of the setting 'unlocked if empty' is to allow the user to fill
3828 // in a value for the selected field _if LDAP is giving
3829 // nothing_ for this field. Thus it makes sense to let this value
3830 // stand in until LDAP is giving a value for this field.
3831 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3832 if ($iscustom ||
(in_array($key, $userauth->userfields
) &&
3833 ((string)$oldinfo->$key !== (string)$value))) {
3834 $newuser[$key] = (string)$value;
3840 $newuser['id'] = $oldinfo->id
;
3841 $newuser['timemodified'] = time();
3842 user_update_user((object) $newuser, false, false);
3844 // Save user profile data.
3845 profile_save_data((object) $newuser);
3848 \core\event\user_updated
::create_from_userid($newuser['id'])->trigger();
3852 return get_complete_user_data('id', $oldinfo->id
);
3856 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
3858 * @param array $info Array of user properties to truncate if needed
3859 * @return array The now truncated information that was passed in
3861 function truncate_userinfo(array $info) {
3862 // Define the limits.
3872 'institution' => 255,
3873 'department' => 255,
3880 // Apply where needed.
3881 foreach (array_keys($info) as $key) {
3882 if (!empty($limit[$key])) {
3883 $info[$key] = trim(core_text
::substr($info[$key], 0, $limit[$key]));
3891 * Marks user deleted in internal user database and notifies the auth plugin.
3892 * Also unenrols user from all roles and does other cleanup.
3894 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3896 * @param stdClass $user full user object before delete
3897 * @return boolean success
3898 * @throws coding_exception if invalid $user parameter detected
3900 function delete_user(stdClass
$user) {
3902 require_once($CFG->libdir
.'/grouplib.php');
3903 require_once($CFG->libdir
.'/gradelib.php');
3904 require_once($CFG->dirroot
.'/message/lib.php');
3905 require_once($CFG->dirroot
.'/tag/lib.php');
3906 require_once($CFG->dirroot
.'/user/lib.php');
3908 // Make sure nobody sends bogus record type as parameter.
3909 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
3910 throw new coding_exception('Invalid $user parameter in delete_user() detected');
3913 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
3914 if (!$user = $DB->get_record('user', array('id' => $user->id
))) {
3915 debugging('Attempt to delete unknown user account.');
3919 // There must be always exactly one guest record, originally the guest account was identified by username only,
3920 // now we use $CFG->siteguest for performance reasons.
3921 if ($user->username
=== 'guest' or isguestuser($user)) {
3922 debugging('Guest user account can not be deleted.');
3926 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
3927 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
3928 if ($user->auth
=== 'manual' and is_siteadmin($user)) {
3929 debugging('Local administrator accounts can not be deleted.');
3933 // Keep user record before updating it, as we have to pass this to user_deleted event.
3934 $olduser = clone $user;
3936 // Keep a copy of user context, we need it for event.
3937 $usercontext = context_user
::instance($user->id
);
3939 // Delete all grades - backup is kept in grade_grades_history table.
3940 grade_user_delete($user->id
);
3942 // Move unread messages from this user to read.
3943 message_move_userfrom_unread2read($user->id
);
3945 // TODO: remove from cohorts using standard API here.
3947 // Remove user tags.
3948 tag_set('user', $user->id
, array(), 'core', $usercontext->id
);
3950 // Unconditionally unenrol from all courses.
3951 enrol_user_delete($user);
3953 // Unenrol from all roles in all contexts.
3954 // This might be slow but it is really needed - modules might do some extra cleanup!
3955 role_unassign_all(array('userid' => $user->id
));
3957 // Now do a brute force cleanup.
3959 // Remove from all cohorts.
3960 $DB->delete_records('cohort_members', array('userid' => $user->id
));
3962 // Remove from all groups.
3963 $DB->delete_records('groups_members', array('userid' => $user->id
));
3965 // Brute force unenrol from all courses.
3966 $DB->delete_records('user_enrolments', array('userid' => $user->id
));
3968 // Purge user preferences.
3969 $DB->delete_records('user_preferences', array('userid' => $user->id
));
3971 // Purge user extra profile info.
3972 $DB->delete_records('user_info_data', array('userid' => $user->id
));
3974 // Purge log of previous password hashes.
3975 $DB->delete_records('user_password_history', array('userid' => $user->id
));
3977 // Last course access not necessary either.
3978 $DB->delete_records('user_lastaccess', array('userid' => $user->id
));
3979 // Remove all user tokens.
3980 $DB->delete_records('external_tokens', array('userid' => $user->id
));
3982 // Unauthorise the user for all services.
3983 $DB->delete_records('external_services_users', array('userid' => $user->id
));
3985 // Remove users private keys.
3986 $DB->delete_records('user_private_key', array('userid' => $user->id
));
3988 // Remove users customised pages.
3989 $DB->delete_records('my_pages', array('userid' => $user->id
, 'private' => 1));
3991 // Force logout - may fail if file based sessions used, sorry.
3992 \core\session\manager
::kill_user_sessions($user->id
);
3994 // Generate username from email address, or a fake email.
3995 $delemail = !empty($user->email
) ?
$user->email
: $user->username
. '.' . $user->id
. '@unknownemail.invalid';
3996 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME
);
3998 // Workaround for bulk deletes of users with the same email address.
3999 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4003 // Mark internal user record as "deleted".
4004 $updateuser = new stdClass();
4005 $updateuser->id
= $user->id
;
4006 $updateuser->deleted
= 1;
4007 $updateuser->username
= $delname; // Remember it just in case.
4008 $updateuser->email
= md5($user->username
);// Store hash of username, useful importing/restoring users.
4009 $updateuser->idnumber
= ''; // Clear this field to free it up.
4010 $updateuser->picture
= 0;
4011 $updateuser->timemodified
= time();
4013 // Don't trigger update event, as user is being deleted.
4014 user_update_user($updateuser, false, false);
4016 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4017 context_helper
::delete_instance(CONTEXT_USER
, $user->id
);
4019 // Any plugin that needs to cleanup should register this event.
4021 $event = \core\event\user_deleted
::create(
4023 'objectid' => $user->id
,
4024 'relateduserid' => $user->id
,
4025 'context' => $usercontext,
4027 'username' => $user->username
,
4028 'email' => $user->email
,
4029 'idnumber' => $user->idnumber
,
4030 'picture' => $user->picture
,
4031 'mnethostid' => $user->mnethostid
4035 $event->add_record_snapshot('user', $olduser);
4038 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4039 // should know about this updated property persisted to the user's table.
4040 $user->timemodified
= $updateuser->timemodified
;
4042 // Notify auth plugin - do not block the delete even when plugin fails.
4043 $authplugin = get_auth_plugin($user->auth
);
4044 $authplugin->user_delete($user);
4050 * Retrieve the guest user object.
4052 * @return stdClass A {@link $USER} object
4054 function guest_user() {
4057 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest
))) {
4058 $newuser->confirmed
= 1;
4059 $newuser->lang
= $CFG->lang
;
4060 $newuser->lastip
= getremoteaddr();
4067 * Authenticates a user against the chosen authentication mechanism
4069 * Given a username and password, this function looks them
4070 * up using the currently selected authentication mechanism,
4071 * and if the authentication is successful, it returns a
4072 * valid $user object from the 'user' table.
4074 * Uses auth_ functions from the currently active auth module
4076 * After authenticate_user_login() returns success, you will need to
4077 * log that the user has logged in, and call complete_user_login() to set
4080 * Note: this function works only with non-mnet accounts!
4082 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4083 * @param string $password User's password
4084 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4085 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4086 * @return stdClass|false A {@link $USER} object or false if error
4088 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4090 require_once("$CFG->libdir/authlib.php");
4092 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id
)) {
4093 // we have found the user
4095 } else if (!empty($CFG->authloginviaemail
)) {
4096 if ($email = clean_param($username, PARAM_EMAIL
)) {
4097 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4098 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'email' => $email);
4099 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4100 if (count($users) === 1) {
4101 // Use email for login only if unique.
4102 $user = reset($users);
4103 $user = get_complete_user_data('id', $user->id
);
4104 $username = $user->username
;
4110 $authsenabled = get_enabled_auth_plugins();
4113 // Use manual if auth not set.
4114 $auth = empty($user->auth
) ?
'manual' : $user->auth
;
4115 if (!empty($user->suspended
)) {
4116 $failurereason = AUTH_LOGIN_SUSPENDED
;
4118 // Trigger login failed event.
4119 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4120 'other' => array('username' => $username, 'reason' => $failurereason)));
4122 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4125 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4126 // Legacy way to suspend user.
4127 $failurereason = AUTH_LOGIN_SUSPENDED
;
4129 // Trigger login failed event.
4130 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4131 'other' => array('username' => $username, 'reason' => $failurereason)));
4133 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4136 $auths = array($auth);
4139 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4140 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'deleted' => 1))) {
4141 $failurereason = AUTH_LOGIN_NOUSER
;
4143 // Trigger login failed event.
4144 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4145 'reason' => $failurereason)));
4147 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4151 // User does not exist.
4152 $auths = $authsenabled;
4153 $user = new stdClass();
4157 if ($ignorelockout) {
4158 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4159 // or this function is called from a SSO script.
4160 } else if ($user->id
) {
4161 // Verify login lockout after other ways that may prevent user login.
4162 if (login_is_lockedout($user)) {
4163 $failurereason = AUTH_LOGIN_LOCKOUT
;
4165 // Trigger login failed event.
4166 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4167 'other' => array('username' => $username, 'reason' => $failurereason)));
4170 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4174 // We can not lockout non-existing accounts.
4177 foreach ($auths as $auth) {
4178 $authplugin = get_auth_plugin($auth);
4180 // On auth fail fall through to the next plugin.
4181 if (!$authplugin->user_login($username, $password)) {
4185 // Successful authentication.
4187 // User already exists in database.
4188 if (empty($user->auth
)) {
4189 // For some reason auth isn't set yet.
4190 $DB->set_field('user', 'auth', $auth, array('id' => $user->id
));
4191 $user->auth
= $auth;
4194 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4195 // the current hash algorithm while we have access to the user's password.
4196 update_internal_user_password($user, $password);
4198 if ($authplugin->is_synchronised_with_external()) {
4199 // Update user record from external DB.
4200 $user = update_user_record_by_id($user->id
);
4203 // The user is authenticated but user creation may be disabled.
4204 if (!empty($CFG->authpreventaccountcreation
)) {
4205 $failurereason = AUTH_LOGIN_UNAUTHORISED
;
4207 // Trigger login failed event.
4208 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4209 'reason' => $failurereason)));
4212 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4213 $_SERVER['HTTP_USER_AGENT']);
4216 $user = create_user_record($username, $password, $auth);
4220 $authplugin->sync_roles($user);
4222 foreach ($authsenabled as $hau) {
4223 $hauth = get_auth_plugin($hau);
4224 $hauth->user_authenticated_hook($user, $username, $password);
4227 if (empty($user->id
)) {
4228 $failurereason = AUTH_LOGIN_NOUSER
;
4229 // Trigger login failed event.
4230 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4231 'reason' => $failurereason)));
4236 if (!empty($user->suspended
)) {
4237 // Just in case some auth plugin suspended account.
4238 $failurereason = AUTH_LOGIN_SUSPENDED
;
4239 // Trigger login failed event.
4240 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4241 'other' => array('username' => $username, 'reason' => $failurereason)));
4243 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4247 login_attempt_valid($user);
4248 $failurereason = AUTH_LOGIN_OK
;
4252 // Failed if all the plugins have failed.
4253 if (debugging('', DEBUG_ALL
)) {
4254 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4258 login_attempt_failed($user);
4259 $failurereason = AUTH_LOGIN_FAILED
;
4260 // Trigger login failed event.
4261 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4262 'other' => array('username' => $username, 'reason' => $failurereason)));
4265 $failurereason = AUTH_LOGIN_NOUSER
;
4266 // Trigger login failed event.
4267 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4268 'reason' => $failurereason)));
4276 * Call to complete the user login process after authenticate_user_login()
4277 * has succeeded. It will setup the $USER variable and other required bits
4281 * - It will NOT log anything -- up to the caller to decide what to log.
4282 * - this function does not set any cookies any more!
4284 * @param stdClass $user
4285 * @return stdClass A {@link $USER} object - BC only, do not use
4287 function complete_user_login($user) {
4290 \core\session\manager
::login_user($user);
4292 // Reload preferences from DB.
4293 unset($USER->preference
);
4294 check_user_preferences_loaded($USER);
4296 // Update login times.
4297 update_user_login_times();
4299 // Extra session prefs init.
4300 set_login_session_preferences();
4302 // Trigger login event.
4303 $event = \core\event\user_loggedin
::create(
4305 'userid' => $USER->id
,
4306 'objectid' => $USER->id
,
4307 'other' => array('username' => $USER->username
),
4312 if (isguestuser()) {
4313 // No need to continue when user is THE guest.
4318 // We can redirect to password change URL only in browser.
4322 // Select password change url.
4323 $userauth = get_auth_plugin($USER->auth
);
4325 // Check whether the user should be changing password.
4326 if (get_user_preferences('auth_forcepasswordchange', false)) {
4327 if ($userauth->can_change_password()) {
4328 if ($changeurl = $userauth->change_password_url()) {
4329 redirect($changeurl);
4331 redirect($CFG->httpswwwroot
.'/login/change_password.php');
4334 print_error('nopasswordchangeforced', 'auth');
4341 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4343 * @param string $password String to check.
4344 * @return boolean True if the $password matches the format of an md5 sum.
4346 function password_is_legacy_hash($password) {
4347 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4351 * Compare password against hash stored in user object to determine if it is valid.
4353 * If necessary it also updates the stored hash to the current format.
4355 * @param stdClass $user (Password property may be updated).
4356 * @param string $password Plain text password.
4357 * @return bool True if password is valid.
4359 function validate_internal_user_password($user, $password) {
4361 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4363 if ($user->password
=== AUTH_PASSWORD_NOT_CACHED
) {
4364 // Internal password is not used at all, it can not validate.
4368 // If hash isn't a legacy (md5) hash, validate using the library function.
4369 if (!password_is_legacy_hash($user->password
)) {
4370 return password_verify($password, $user->password
);
4373 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4374 // is valid we can then update it to the new algorithm.
4376 $sitesalt = isset($CFG->passwordsaltmain
) ?
$CFG->passwordsaltmain
: '';
4379 if ($user->password
=== md5($password.$sitesalt)
4380 or $user->password
=== md5($password)
4381 or $user->password
=== md5(addslashes($password).$sitesalt)
4382 or $user->password
=== md5(addslashes($password))) {
4383 // Note: we are intentionally using the addslashes() here because we
4384 // need to accept old password hashes of passwords with magic quotes.
4388 for ($i=1; $i<=20; $i++
) { // 20 alternative salts should be enough, right?
4389 $alt = 'passwordsaltalt'.$i;
4390 if (!empty($CFG->$alt)) {
4391 if ($user->password
=== md5($password.$CFG->$alt) or $user->password
=== md5(addslashes($password).$CFG->$alt)) {
4400 // If the password matches the existing md5 hash, update to the
4401 // current hash algorithm while we have access to the user's password.
4402 update_internal_user_password($user, $password);
4409 * Calculate hash for a plain text password.
4411 * @param string $password Plain text password to be hashed.
4412 * @param bool $fasthash If true, use a low cost factor when generating the hash
4413 * This is much faster to generate but makes the hash
4414 * less secure. It is used when lots of hashes need to
4415 * be generated quickly.
4416 * @return string The hashed password.
4418 * @throws moodle_exception If a problem occurs while generating the hash.
4420 function hash_internal_user_password($password, $fasthash = false) {
4422 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4424 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4425 $options = ($fasthash) ?
array('cost' => 4) : array();
4427 $generatedhash = password_hash($password, PASSWORD_DEFAULT
, $options);
4429 if ($generatedhash === false ||
$generatedhash === null) {
4430 throw new moodle_exception('Failed to generate password hash.');
4433 return $generatedhash;
4437 * Update password hash in user object (if necessary).
4439 * The password is updated if:
4440 * 1. The password has changed (the hash of $user->password is different
4441 * to the hash of $password).
4442 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4445 * Updating the password will modify the $user object and the database
4446 * record to use the current hashing algorithm.
4448 * @param stdClass $user User object (password property may be updated).
4449 * @param string $password Plain text password.
4450 * @param bool $fasthash If true, use a low cost factor when generating the hash
4451 * This is much faster to generate but makes the hash
4452 * less secure. It is used when lots of hashes need to
4453 * be generated quickly.
4454 * @return bool Always returns true.
4456 function update_internal_user_password($user, $password, $fasthash = false) {
4458 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4460 // Figure out what the hashed password should be.
4461 if (!isset($user->auth
)) {
4462 debugging('User record in update_internal_user_password() must include field auth',
4464 $user->auth
= $DB->get_field('user', 'auth', array('id' => $user->id
));
4466 $authplugin = get_auth_plugin($user->auth
);
4467 if ($authplugin->prevent_local_passwords()) {
4468 $hashedpassword = AUTH_PASSWORD_NOT_CACHED
;
4470 $hashedpassword = hash_internal_user_password($password, $fasthash);
4473 $algorithmchanged = false;
4475 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED
) {
4476 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4477 $passwordchanged = ($user->password
!== $hashedpassword);
4479 } else if (isset($user->password
)) {
4480 // If verification fails then it means the password has changed.
4481 $passwordchanged = !password_verify($password, $user->password
);
4482 $algorithmchanged = password_needs_rehash($user->password
, PASSWORD_DEFAULT
);
4484 // While creating new user, password in unset in $user object, to avoid
4485 // saving it with user_create()
4486 $passwordchanged = true;
4489 if ($passwordchanged ||
$algorithmchanged) {
4490 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id
));
4491 $user->password
= $hashedpassword;
4494 $user = $DB->get_record('user', array('id' => $user->id
));
4495 \core\event\user_password_updated
::create_from_user($user)->trigger();
4502 * Get a complete user record, which includes all the info in the user record.
4504 * Intended for setting as $USER session variable
4506 * @param string $field The user field to be checked for a given value.
4507 * @param string $value The value to match for $field.
4508 * @param int $mnethostid
4509 * @return mixed False, or A {@link $USER} object.
4511 function get_complete_user_data($field, $value, $mnethostid = null) {
4514 if (!$field ||
!$value) {
4518 // Build the WHERE clause for an SQL query.
4519 $params = array('fieldval' => $value);
4520 $constraints = "$field = :fieldval AND deleted <> 1";
4522 // If we are loading user data based on anything other than id,
4523 // we must also restrict our search based on mnet host.
4524 if ($field != 'id') {
4525 if (empty($mnethostid)) {
4526 // If empty, we restrict to local users.
4527 $mnethostid = $CFG->mnet_localhost_id
;
4530 if (!empty($mnethostid)) {
4531 $params['mnethostid'] = $mnethostid;
4532 $constraints .= " AND mnethostid = :mnethostid";
4535 // Get all the basic user data.
4536 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4540 // Get various settings and preferences.
4542 // Preload preference cache.
4543 check_user_preferences_loaded($user);
4545 // Load course enrolment related stuff.
4546 $user->lastcourseaccess
= array(); // During last session.
4547 $user->currentcourseaccess
= array(); // During current session.
4548 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id
))) {
4549 foreach ($lastaccesses as $lastaccess) {
4550 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
4554 $sql = "SELECT g.id, g.courseid
4555 FROM {groups} g, {groups_members} gm
4556 WHERE gm.groupid=g.id AND gm.userid=?";
4558 // This is a special hack to speedup calendar display.
4559 $user->groupmember
= array();
4560 if (!isguestuser($user)) {
4561 if ($groups = $DB->get_records_sql($sql, array($user->id
))) {
4562 foreach ($groups as $group) {
4563 if (!array_key_exists($group->courseid
, $user->groupmember
)) {
4564 $user->groupmember
[$group->courseid
] = array();
4566 $user->groupmember
[$group->courseid
][$group->id
] = $group->id
;
4571 // Add the custom profile fields to the user record.
4572 $user->profile
= array();
4573 if (!isguestuser($user)) {
4574 require_once($CFG->dirroot
.'/user/profile/lib.php');
4575 profile_load_custom_fields($user);
4578 // Rewrite some variables if necessary.
4579 if (!empty($user->description
)) {
4580 // No need to cart all of it around.
4581 $user->description
= true;
4583 if (isguestuser($user)) {
4584 // Guest language always same as site.
4585 $user->lang
= $CFG->lang
;
4586 // Name always in current language.
4587 $user->firstname
= get_string('guestuser');
4588 $user->lastname
= ' ';
4595 * Validate a password against the configured password policy
4597 * @param string $password the password to be checked against the password policy
4598 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4599 * @return bool true if the password is valid according to the policy. false otherwise.
4601 function check_password_policy($password, &$errmsg) {
4604 if (empty($CFG->passwordpolicy
)) {
4609 if (core_text
::strlen($password) < $CFG->minpasswordlength
) {
4610 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength
) .'</div>';
4613 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits
) {
4614 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits
) .'</div>';
4617 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower
) {
4618 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower
) .'</div>';
4621 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper
) {
4622 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper
) .'</div>';
4625 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum
) {
4626 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
) .'</div>';
4628 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars
)) {
4629 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars
) .'</div>';
4632 if ($errmsg == '') {
4641 * When logging in, this function is run to set certain preferences for the current SESSION.
4643 function set_login_session_preferences() {
4646 $SESSION->justloggedin
= true;
4648 unset($SESSION->lang
);
4649 unset($SESSION->forcelang
);
4650 unset($SESSION->load_navigation_admin
);
4655 * Delete a course, including all related data from the database, and any associated files.
4657 * @param mixed $courseorid The id of the course or course object to delete.
4658 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4659 * @return bool true if all the removals succeeded. false if there were any failures. If this
4660 * method returns false, some of the removals will probably have succeeded, and others
4661 * failed, but you have no way of knowing which.
4663 function delete_course($courseorid, $showfeedback = true) {
4666 if (is_object($courseorid)) {
4667 $courseid = $courseorid->id
;
4668 $course = $courseorid;
4670 $courseid = $courseorid;
4671 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4675 $context = context_course
::instance($courseid);
4677 // Frontpage course can not be deleted!!
4678 if ($courseid == SITEID
) {
4682 // Make the course completely empty.
4683 remove_course_contents($courseid, $showfeedback);
4685 // Delete the course and related context instance.
4686 context_helper
::delete_instance(CONTEXT_COURSE
, $courseid);
4688 $DB->delete_records("course", array("id" => $courseid));
4689 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4691 // Reset all course related caches here.
4692 if (class_exists('format_base', false)) {
4693 format_base
::reset_course_cache($courseid);
4696 // Trigger a course deleted event.
4697 $event = \core\event\course_deleted
::create(array(
4698 'objectid' => $course->id
,
4699 'context' => $context,
4701 'shortname' => $course->shortname
,
4702 'fullname' => $course->fullname
,
4703 'idnumber' => $course->idnumber
4706 $event->add_record_snapshot('course', $course);
4713 * Clear a course out completely, deleting all content but don't delete the course itself.
4715 * This function does not verify any permissions.
4717 * Please note this function also deletes all user enrolments,
4718 * enrolment instances and role assignments by default.
4721 * - 'keep_roles_and_enrolments' - false by default
4722 * - 'keep_groups_and_groupings' - false by default
4724 * @param int $courseid The id of the course that is being deleted
4725 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4726 * @param array $options extra options
4727 * @return bool true if all the removals succeeded. false if there were any failures. If this
4728 * method returns false, some of the removals will probably have succeeded, and others
4729 * failed, but you have no way of knowing which.
4731 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4732 global $CFG, $DB, $OUTPUT;
4734 require_once($CFG->libdir
.'/badgeslib.php');
4735 require_once($CFG->libdir
.'/completionlib.php');
4736 require_once($CFG->libdir
.'/questionlib.php');
4737 require_once($CFG->libdir
.'/gradelib.php');
4738 require_once($CFG->dirroot
.'/group/lib.php');
4739 require_once($CFG->dirroot
.'/tag/lib.php');
4740 require_once($CFG->dirroot
.'/comment/lib.php');
4741 require_once($CFG->dirroot
.'/rating/lib.php');
4742 require_once($CFG->dirroot
.'/notes/lib.php');
4744 // Handle course badges.
4745 badges_handle_course_deletion($courseid);
4747 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4748 $strdeleted = get_string('deleted').' - ';
4750 // Some crazy wishlist of stuff we should skip during purging of course content.
4751 $options = (array)$options;
4753 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST
);
4754 $coursecontext = context_course
::instance($courseid);
4755 $fs = get_file_storage();
4757 // Delete course completion information, this has to be done before grades and enrols.
4758 $cc = new completion_info($course);
4759 $cc->clear_criteria();
4760 if ($showfeedback) {
4761 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4764 // Remove all data from gradebook - this needs to be done before course modules
4765 // because while deleting this information, the system may need to reference
4766 // the course modules that own the grades.
4767 remove_course_grades($courseid, $showfeedback);
4768 remove_grade_letters($coursecontext, $showfeedback);
4770 // Delete course blocks in any all child contexts,
4771 // they may depend on modules so delete them first.
4772 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4773 foreach ($childcontexts as $childcontext) {
4774 blocks_delete_all_for_context($childcontext->id
);
4776 unset($childcontexts);
4777 blocks_delete_all_for_context($coursecontext->id
);
4778 if ($showfeedback) {
4779 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4782 // Delete every instance of every module,
4783 // this has to be done before deleting of course level stuff.
4784 $locations = core_component
::get_plugin_list('mod');
4785 foreach ($locations as $modname => $moddir) {
4786 if ($modname === 'NEWMODULE') {
4789 if ($module = $DB->get_record('modules', array('name' => $modname))) {
4790 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
4791 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
4792 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
4794 if ($instances = $DB->get_records($modname, array('course' => $course->id
))) {
4795 foreach ($instances as $instance) {
4796 if ($cm = get_coursemodule_from_instance($modname, $instance->id
, $course->id
)) {
4797 // Delete activity context questions and question categories.
4798 question_delete_activity($cm, $showfeedback);
4800 if (function_exists($moddelete)) {
4801 // This purges all module data in related tables, extra user prefs, settings, etc.
4802 $moddelete($instance->id
);
4804 // NOTE: we should not allow installation of modules with missing delete support!
4805 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4806 $DB->delete_records($modname, array('id' => $instance->id
));
4810 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
4811 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
4812 $DB->delete_records('course_modules', array('id' => $cm->id
));
4816 if (function_exists($moddeletecourse)) {
4817 // Execute ptional course cleanup callback.
4818 $moddeletecourse($course, $showfeedback);
4820 if ($instances and $showfeedback) {
4821 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4824 // Ooops, this module is not properly installed, force-delete it in the next block.
4828 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
4830 // Remove all data from availability and completion tables that is associated
4831 // with course-modules belonging to this course. Note this is done even if the
4832 // features are not enabled now, in case they were enabled previously.
4833 $DB->delete_records_select('course_modules_completion',
4834 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4837 // Remove course-module data.
4838 $cms = $DB->get_records('course_modules', array('course' => $course->id
));
4839 foreach ($cms as $cm) {
4840 if ($module = $DB->get_record('modules', array('id' => $cm->module
))) {
4842 $DB->delete_records($module->name
, array('id' => $cm->instance
));
4843 } catch (Exception
$e) {
4844 // Ignore weird or missing table problems.
4847 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
4848 $DB->delete_records('course_modules', array('id' => $cm->id
));
4851 if ($showfeedback) {
4852 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
4855 // Cleanup the rest of plugins.
4856 $cleanuplugintypes = array('report', 'coursereport', 'format');
4857 $callbacks = get_plugins_with_function('delete_course', 'lib.php');
4858 foreach ($cleanuplugintypes as $type) {
4859 if (!empty($callbacks[$type])) {
4860 foreach ($callbacks[$type] as $pluginfunction) {
4861 $pluginfunction($course->id
, $showfeedback);
4864 if ($showfeedback) {
4865 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
4869 // Delete questions and question categories.
4870 question_delete_course($course, $showfeedback);
4871 if ($showfeedback) {
4872 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
4875 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
4876 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4877 foreach ($childcontexts as $childcontext) {
4878 $childcontext->delete();
4880 unset($childcontexts);
4882 // Remove all roles and enrolments by default.
4883 if (empty($options['keep_roles_and_enrolments'])) {
4884 // This hack is used in restore when deleting contents of existing course.
4885 role_unassign_all(array('contextid' => $coursecontext->id
, 'component' => ''), true);
4886 enrol_course_delete($course);
4887 if ($showfeedback) {
4888 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
4892 // Delete any groups, removing members and grouping/course links first.
4893 if (empty($options['keep_groups_and_groupings'])) {
4894 groups_delete_groupings($course->id
, $showfeedback);
4895 groups_delete_groups($course->id
, $showfeedback);
4899 filter_delete_all_for_context($coursecontext->id
);
4901 // Notes, you shall not pass!
4902 note_delete_all($course->id
);
4905 comment
::delete_comments($coursecontext->id
);
4907 // Ratings are history too.
4908 $delopt = new stdclass();
4909 $delopt->contextid
= $coursecontext->id
;
4910 $rm = new rating_manager();
4911 $rm->delete_ratings($delopt);
4913 // Delete course tags.
4914 tag_set('course', $course->id
, array(), 'core', $coursecontext->id
);
4916 // Delete calendar events.
4917 $DB->delete_records('event', array('courseid' => $course->id
));
4918 $fs->delete_area_files($coursecontext->id
, 'calendar');
4920 // Delete all related records in other core tables that may have a courseid
4921 // This array stores the tables that need to be cleared, as
4922 // table_name => column_name that contains the course id.
4923 $tablestoclear = array(
4924 'backup_courses' => 'courseid', // Scheduled backup stuff.
4925 'user_lastaccess' => 'courseid', // User access info.
4927 foreach ($tablestoclear as $table => $col) {
4928 $DB->delete_records($table, array($col => $course->id
));
4931 // Delete all course backup files.
4932 $fs->delete_area_files($coursecontext->id
, 'backup');
4934 // Cleanup course record - remove links to deleted stuff.
4935 $oldcourse = new stdClass();
4936 $oldcourse->id
= $course->id
;
4937 $oldcourse->summary
= '';
4938 $oldcourse->cacherev
= 0;
4939 $oldcourse->legacyfiles
= 0;
4940 $oldcourse->enablecompletion
= 0;
4941 if (!empty($options['keep_groups_and_groupings'])) {
4942 $oldcourse->defaultgroupingid
= 0;
4944 $DB->update_record('course', $oldcourse);
4946 // Delete course sections.
4947 $DB->delete_records('course_sections', array('course' => $course->id
));
4949 // Delete legacy, section and any other course files.
4950 $fs->delete_area_files($coursecontext->id
, 'course'); // Files from summary and section.
4952 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
4953 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
4954 // Easy, do not delete the context itself...
4955 $coursecontext->delete_content();
4958 // We can not drop all context stuff because it would bork enrolments and roles,
4959 // there might be also files used by enrol plugins...
4962 // Delete legacy files - just in case some files are still left there after conversion to new file api,
4963 // also some non-standard unsupported plugins may try to store something there.
4964 fulldelete($CFG->dataroot
.'/'.$course->id
);
4966 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
4967 $cachemodinfo = cache
::make('core', 'coursemodinfo');
4968 $cachemodinfo->delete($courseid);
4970 // Trigger a course content deleted event.
4971 $event = \core\event\course_content_deleted
::create(array(
4972 'objectid' => $course->id
,
4973 'context' => $coursecontext,
4974 'other' => array('shortname' => $course->shortname
,
4975 'fullname' => $course->fullname
,
4976 'options' => $options) // Passing this for legacy reasons.
4978 $event->add_record_snapshot('course', $course);
4985 * Change dates in module - used from course reset.
4987 * @param string $modname forum, assignment, etc
4988 * @param array $fields array of date fields from mod table
4989 * @param int $timeshift time difference
4990 * @param int $courseid
4991 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
4992 * @return bool success
4994 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
4996 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
4999 $params = array($timeshift, $courseid);
5000 foreach ($fields as $field) {
5001 $updatesql = "UPDATE {".$modname."}
5002 SET $field = $field + ?
5003 WHERE course=? AND $field<>0";
5005 $updatesql .= ' AND id=?';
5008 $return = $DB->execute($updatesql, $params) && $return;
5011 $refreshfunction = $modname.'_refresh_events';
5012 if (function_exists($refreshfunction)) {
5013 $refreshfunction($courseid);
5020 * This function will empty a course of user data.
5021 * It will retain the activities and the structure of the course.
5023 * @param object $data an object containing all the settings including courseid (without magic quotes)
5024 * @return array status array of array component, item, error
5026 function reset_course_userdata($data) {
5028 require_once($CFG->libdir
.'/gradelib.php');
5029 require_once($CFG->libdir
.'/completionlib.php');
5030 require_once($CFG->dirroot
.'/group/lib.php');
5032 $data->courseid
= $data->id
;
5033 $context = context_course
::instance($data->courseid
);
5035 $eventparams = array(
5036 'context' => $context,
5037 'courseid' => $data->id
,
5039 'reset_options' => (array) $data
5042 $event = \core\event\course_reset_started
::create($eventparams);
5045 // Calculate the time shift of dates.
5046 if (!empty($data->reset_start_date
)) {
5047 // Time part of course startdate should be zero.
5048 $data->timeshift
= $data->reset_start_date
- usergetmidnight($data->reset_start_date_old
);
5050 $data->timeshift
= 0;
5053 // Result array: component, item, error.
5056 // Start the resetting.
5057 $componentstr = get_string('general');
5059 // Move the course start time.
5060 if (!empty($data->reset_start_date
) and $data->timeshift
) {
5061 // Change course start data.
5062 $DB->set_field('course', 'startdate', $data->reset_start_date
, array('id' => $data->courseid
));
5063 // Update all course and group events - do not move activity events.
5064 $updatesql = "UPDATE {event}
5065 SET timestart = timestart + ?
5066 WHERE courseid=? AND instance=0";
5067 $DB->execute($updatesql, array($data->timeshift
, $data->courseid
));
5069 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5072 if (!empty($data->reset_events
)) {
5073 $DB->delete_records('event', array('courseid' => $data->courseid
));
5074 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5077 if (!empty($data->reset_notes
)) {
5078 require_once($CFG->dirroot
.'/notes/lib.php');
5079 note_delete_all($data->courseid
);
5080 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5083 if (!empty($data->delete_blog_associations
)) {
5084 require_once($CFG->dirroot
.'/blog/lib.php');
5085 blog_remove_associations_for_course($data->courseid
);
5086 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5089 if (!empty($data->reset_completion
)) {
5090 // Delete course and activity completion information.
5091 $course = $DB->get_record('course', array('id' => $data->courseid
));
5092 $cc = new completion_info($course);
5093 $cc->delete_all_completion_data();
5094 $status[] = array('component' => $componentstr,
5095 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5098 $componentstr = get_string('roles');
5100 if (!empty($data->reset_roles_overrides
)) {
5101 $children = $context->get_child_contexts();
5102 foreach ($children as $child) {
5103 $DB->delete_records('role_capabilities', array('contextid' => $child->id
));
5105 $DB->delete_records('role_capabilities', array('contextid' => $context->id
));
5106 // Force refresh for logged in users.
5107 $context->mark_dirty();
5108 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5111 if (!empty($data->reset_roles_local
)) {
5112 $children = $context->get_child_contexts();
5113 foreach ($children as $child) {
5114 role_unassign_all(array('contextid' => $child->id
));
5116 // Force refresh for logged in users.
5117 $context->mark_dirty();
5118 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5121 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5122 $data->unenrolled
= array();
5123 if (!empty($data->unenrol_users
)) {
5124 $plugins = enrol_get_plugins(true);
5125 $instances = enrol_get_instances($data->courseid
, true);
5126 foreach ($instances as $key => $instance) {
5127 if (!isset($plugins[$instance->enrol
])) {
5128 unset($instances[$key]);
5133 foreach ($data->unenrol_users
as $withroleid) {
5136 FROM {user_enrolments} ue
5137 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5138 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5139 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5140 $params = array('courseid' => $data->courseid
, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE
);
5143 // Without any role assigned at course context.
5145 FROM {user_enrolments} ue
5146 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5147 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5148 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5149 WHERE ra.id IS null";
5150 $params = array('courseid' => $data->courseid
, 'courselevel' => CONTEXT_COURSE
);
5153 $rs = $DB->get_recordset_sql($sql, $params);
5154 foreach ($rs as $ue) {
5155 if (!isset($instances[$ue->enrolid
])) {
5158 $instance = $instances[$ue->enrolid
];
5159 $plugin = $plugins[$instance->enrol
];
5160 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5164 $plugin->unenrol_user($instance, $ue->userid
);
5165 $data->unenrolled
[$ue->userid
] = $ue->userid
;
5170 if (!empty($data->unenrolled
)) {
5172 'component' => $componentstr,
5173 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled
).')',
5178 $componentstr = get_string('groups');
5180 // Remove all group members.
5181 if (!empty($data->reset_groups_members
)) {
5182 groups_delete_group_members($data->courseid
);
5183 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5186 // Remove all groups.
5187 if (!empty($data->reset_groups_remove
)) {
5188 groups_delete_groups($data->courseid
, false);
5189 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5192 // Remove all grouping members.
5193 if (!empty($data->reset_groupings_members
)) {
5194 groups_delete_groupings_groups($data->courseid
, false);
5195 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5198 // Remove all groupings.
5199 if (!empty($data->reset_groupings_remove
)) {
5200 groups_delete_groupings($data->courseid
, false);
5201 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5204 // Look in every instance of every module for data to delete.
5205 $unsupportedmods = array();
5206 if ($allmods = $DB->get_records('modules') ) {
5207 foreach ($allmods as $mod) {
5208 $modname = $mod->name
;
5209 $modfile = $CFG->dirroot
.'/mod/'. $modname.'/lib.php';
5210 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5211 if (file_exists($modfile)) {
5212 if (!$DB->count_records($modname, array('course' => $data->courseid
))) {
5213 continue; // Skip mods with no instances.
5215 include_once($modfile);
5216 if (function_exists($moddeleteuserdata)) {
5217 $modstatus = $moddeleteuserdata($data);
5218 if (is_array($modstatus)) {
5219 $status = array_merge($status, $modstatus);
5221 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5224 $unsupportedmods[] = $mod;
5227 debugging('Missing lib.php in '.$modname.' module!');
5232 // Mention unsupported mods.
5233 if (!empty($unsupportedmods)) {
5234 foreach ($unsupportedmods as $mod) {
5236 'component' => get_string('modulenameplural', $mod->name
),
5238 'error' => get_string('resetnotimplemented')
5243 $componentstr = get_string('gradebook', 'grades');
5244 // Reset gradebook,.
5245 if (!empty($data->reset_gradebook_items
)) {
5246 remove_course_grades($data->courseid
, false);
5247 grade_grab_course_grades($data->courseid
);
5248 grade_regrade_final_grades($data->courseid
);
5249 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5251 } else if (!empty($data->reset_gradebook_grades
)) {
5252 grade_course_reset($data->courseid
);
5253 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5256 if (!empty($data->reset_comments
)) {
5257 require_once($CFG->dirroot
.'/comment/lib.php');
5258 comment
::reset_course_page_comments($context);
5261 $event = \core\event\course_reset_ended
::create($eventparams);
5268 * Generate an email processing address.
5271 * @param string $modargs
5272 * @return string Returns email processing address
5274 function generate_email_processing_address($modid, $modargs) {
5277 $header = $CFG->mailprefix
. substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5278 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain
;
5284 * @todo Finish documenting this function
5286 * @param string $modargs
5287 * @param string $body Currently unused
5289 function moodle_process_email($modargs, $body) {
5292 // The first char should be an unencoded letter. We'll take this as an action.
5293 switch ($modargs{0}) {
5294 case 'B': { // Bounce.
5295 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5296 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5297 // Check the half md5 of their email.
5298 $md5check = substr(md5($user->email
), 0, 16);
5299 if ($md5check == substr($modargs, -16)) {
5300 set_bounce_count($user);
5302 // Else maybe they've already changed it?
5306 // Maybe more later?
5313 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5315 * @param string $action 'get', 'buffer', 'close' or 'flush'
5316 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5318 function get_mailer($action='get') {
5321 /** @var moodle_phpmailer $mailer */
5322 static $mailer = null;
5323 static $counter = 0;
5325 if (!isset($CFG->smtpmaxbulk
)) {
5326 $CFG->smtpmaxbulk
= 1;
5329 if ($action == 'get') {
5330 $prevkeepalive = false;
5332 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5333 if ($counter < $CFG->smtpmaxbulk
and !$mailer->isError()) {
5335 // Reset the mailer.
5336 $mailer->Priority
= 3;
5337 $mailer->CharSet
= 'UTF-8'; // Our default.
5338 $mailer->ContentType
= "text/plain";
5339 $mailer->Encoding
= "8bit";
5340 $mailer->From
= "root@localhost";
5341 $mailer->FromName
= "Root User";
5342 $mailer->Sender
= "";
5343 $mailer->Subject
= "";
5345 $mailer->AltBody
= "";
5346 $mailer->ConfirmReadingTo
= "";
5348 $mailer->clearAllRecipients();
5349 $mailer->clearReplyTos();
5350 $mailer->clearAttachments();
5351 $mailer->clearCustomHeaders();
5355 $prevkeepalive = $mailer->SMTPKeepAlive
;
5356 get_mailer('flush');
5359 require_once($CFG->libdir
.'/phpmailer/moodle_phpmailer.php');
5360 $mailer = new moodle_phpmailer();
5364 if ($CFG->smtphosts
== 'qmail') {
5365 // Use Qmail system.
5368 } else if (empty($CFG->smtphosts
)) {
5369 // Use PHP mail() = sendmail.
5373 // Use SMTP directly.
5375 if (!empty($CFG->debugsmtp
)) {
5376 $mailer->SMTPDebug
= true;
5378 // Specify main and backup servers.
5379 $mailer->Host
= $CFG->smtphosts
;
5380 // Specify secure connection protocol.
5381 $mailer->SMTPSecure
= $CFG->smtpsecure
;
5382 // Use previous keepalive.
5383 $mailer->SMTPKeepAlive
= $prevkeepalive;
5385 if ($CFG->smtpuser
) {
5386 // Use SMTP authentication.
5387 $mailer->SMTPAuth
= true;
5388 $mailer->Username
= $CFG->smtpuser
;
5389 $mailer->Password
= $CFG->smtppass
;
5398 // Keep smtp session open after sending.
5399 if ($action == 'buffer') {
5400 if (!empty($CFG->smtpmaxbulk
)) {
5401 get_mailer('flush');
5403 if ($m->Mailer
== 'smtp') {
5404 $m->SMTPKeepAlive
= true;
5410 // Close smtp session, but continue buffering.
5411 if ($action == 'flush') {
5412 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5413 if (!empty($mailer->SMTPDebug
)) {
5416 $mailer->SmtpClose();
5417 if (!empty($mailer->SMTPDebug
)) {
5424 // Close smtp session, do not buffer anymore.
5425 if ($action == 'close') {
5426 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5427 get_mailer('flush');
5428 $mailer->SMTPKeepAlive
= false;
5430 $mailer = null; // Better force new instance.
5436 * Send an email to a specified user
5438 * @param stdClass $user A {@link $USER} object
5439 * @param stdClass $from A {@link $USER} object
5440 * @param string $subject plain text subject line of the email
5441 * @param string $messagetext plain text version of the message
5442 * @param string $messagehtml complete html version of the message (optional)
5443 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5444 * @param string $attachname the name of the file (extension indicates MIME)
5445 * @param bool $usetrueaddress determines whether $from email address should
5446 * be sent out. Will be overruled by user profile setting for maildisplay
5447 * @param string $replyto Email address to reply to
5448 * @param string $replytoname Name of reply to recipient
5449 * @param int $wordwrapwidth custom word wrap width, default 79
5450 * @return bool Returns true if mail was sent OK and false if there was an error.
5452 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5453 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5457 if (empty($user) or empty($user->id
)) {
5458 debugging('Can not send email to null user', DEBUG_DEVELOPER
);
5462 if (empty($user->email
)) {
5463 debugging('Can not send email to user without email: '.$user->id
, DEBUG_DEVELOPER
);
5467 if (!empty($user->deleted
)) {
5468 debugging('Can not send email to deleted user: '.$user->id
, DEBUG_DEVELOPER
);
5472 if (defined('BEHAT_SITE_RUNNING')) {
5473 // Fake email sending in behat.
5477 if (!empty($CFG->noemailever
)) {
5478 // Hidden setting for development sites, set in config.php if needed.
5479 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL
);
5483 if (!empty($CFG->divertallemailsto
)) {
5484 $subject = "[DIVERTED {$user->email}] $subject";
5485 $user = clone($user);
5486 $user->email
= $CFG->divertallemailsto
;
5489 // Skip mail to suspended users.
5490 if ((isset($user->auth
) && $user->auth
=='nologin') or (isset($user->suspended
) && $user->suspended
)) {
5494 if (!validate_email($user->email
)) {
5495 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5496 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5500 if (over_bounce_threshold($user)) {
5501 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5505 // TLD .invalid is specifically reserved for invalid domain names.
5506 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5507 if (substr($user->email
, -8) == '.invalid') {
5508 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5509 return true; // This is not an error.
5512 // If the user is a remote mnet user, parse the email text for URL to the
5513 // wwwroot and modify the url to direct the user's browser to login at their
5514 // home site (identity provider - idp) before hitting the link itself.
5515 if (is_mnet_remote_user($user)) {
5516 require_once($CFG->dirroot
.'/mnet/lib.php');
5518 $jumpurl = mnet_get_idp_jump_url($user);
5519 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5521 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5524 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5528 $mail = get_mailer();
5530 if (!empty($mail->SMTPDebug
)) {
5531 echo '<pre>' . "\n";
5534 $temprecipients = array();
5535 $tempreplyto = array();
5537 $supportuser = core_user
::get_support_user();
5539 // Make up an email address for handling bounces.
5540 if (!empty($CFG->handlebounces
)) {
5541 $modargs = 'B'.base64_encode(pack('V', $user->id
)).substr(md5($user->email
), 0, 16);
5542 $mail->Sender
= generate_email_processing_address(0, $modargs);
5544 $mail->Sender
= $supportuser->email
;
5547 if (!empty($CFG->emailonlyfromnoreplyaddress
)) {
5548 $usetrueaddress = false;
5549 if (empty($replyto) && $from->maildisplay
) {
5550 $replyto = $from->email
;
5551 $replytoname = fullname($from);
5555 if (is_string($from)) { // So we can pass whatever we want if there is need.
5556 $mail->From
= $CFG->noreplyaddress
;
5557 $mail->FromName
= $from;
5558 } else if ($usetrueaddress and $from->maildisplay
) {
5559 $mail->From
= $from->email
;
5560 $mail->FromName
= fullname($from);
5562 $mail->From
= $CFG->noreplyaddress
;
5563 $mail->FromName
= fullname($from);
5564 if (empty($replyto)) {
5565 $tempreplyto[] = array($CFG->noreplyaddress
, get_string('noreplyname'));
5569 if (!empty($replyto)) {
5570 $tempreplyto[] = array($replyto, $replytoname);
5573 $mail->Subject
= substr($subject, 0, 900);
5575 $temprecipients[] = array($user->email
, fullname($user));
5578 $mail->WordWrap
= $wordwrapwidth;
5580 if (!empty($from->customheaders
)) {
5581 // Add custom headers.
5582 if (is_array($from->customheaders
)) {
5583 foreach ($from->customheaders
as $customheader) {
5584 $mail->addCustomHeader($customheader);
5587 $mail->addCustomHeader($from->customheaders
);
5591 if (!empty($from->priority
)) {
5592 $mail->Priority
= $from->priority
;
5595 if ($messagehtml && !empty($user->mailformat
) && $user->mailformat
== 1) {
5596 // Don't ever send HTML to users who don't want it.
5597 $mail->isHTML(true);
5598 $mail->Encoding
= 'quoted-printable';
5599 $mail->Body
= $messagehtml;
5600 $mail->AltBody
= "\n$messagetext\n";
5602 $mail->IsHTML(false);
5603 $mail->Body
= "\n$messagetext\n";
5606 if ($attachment && $attachname) {
5607 if (preg_match( "~\\.\\.~" , $attachment )) {
5608 // Security check for ".." in dir path.
5609 $temprecipients[] = array($supportuser->email
, fullname($supportuser, true));
5610 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5612 require_once($CFG->libdir
.'/filelib.php');
5613 $mimetype = mimeinfo('type', $attachname);
5615 $attachmentpath = $attachment;
5617 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5618 $attachpath = str_replace('\\', '/', $attachmentpath);
5619 // Make sure both variables are normalised before comparing.
5620 $temppath = str_replace('\\', '/', realpath($CFG->tempdir
));
5622 // If the attachment is a full path to a file in the tempdir, use it as is,
5623 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5624 if (strpos($attachpath, $temppath) !== 0) {
5625 $attachmentpath = $CFG->dataroot
. '/' . $attachmentpath;
5628 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5632 // Check if the email should be sent in an other charset then the default UTF-8.
5633 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
5635 // Use the defined site mail charset or eventually the one preferred by the recipient.
5636 $charset = $CFG->sitemailcharset
;
5637 if (!empty($CFG->allowusermailcharset
)) {
5638 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
5639 $charset = $useremailcharset;
5643 // Convert all the necessary strings if the charset is supported.
5644 $charsets = get_list_of_charsets();
5645 unset($charsets['UTF-8']);
5646 if (in_array($charset, $charsets)) {
5647 $mail->CharSet
= $charset;
5648 $mail->FromName
= core_text
::convert($mail->FromName
, 'utf-8', strtolower($charset));
5649 $mail->Subject
= core_text
::convert($mail->Subject
, 'utf-8', strtolower($charset));
5650 $mail->Body
= core_text
::convert($mail->Body
, 'utf-8', strtolower($charset));
5651 $mail->AltBody
= core_text
::convert($mail->AltBody
, 'utf-8', strtolower($charset));
5653 foreach ($temprecipients as $key => $values) {
5654 $temprecipients[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
5656 foreach ($tempreplyto as $key => $values) {
5657 $tempreplyto[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
5662 foreach ($temprecipients as $values) {
5663 $mail->addAddress($values[0], $values[1]);
5665 foreach ($tempreplyto as $values) {
5666 $mail->addReplyTo($values[0], $values[1]);
5669 if ($mail->send()) {
5670 set_send_count($user);
5671 if (!empty($mail->SMTPDebug
)) {
5676 // Trigger event for failing to send email.
5677 $event = \core\event\email_failed
::create(array(
5678 'context' => context_system
::instance(),
5679 'userid' => $from->id
,
5680 'relateduserid' => $user->id
,
5682 'subject' => $subject,
5683 'message' => $messagetext,
5684 'errorinfo' => $mail->ErrorInfo
5689 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo
);
5691 if (!empty($mail->SMTPDebug
)) {
5699 * Generate a signoff for emails based on support settings
5703 function generate_email_signoff() {
5707 if (!empty($CFG->supportname
)) {
5708 $signoff .= $CFG->supportname
."\n";
5710 if (!empty($CFG->supportemail
)) {
5711 $signoff .= $CFG->supportemail
."\n";
5713 if (!empty($CFG->supportpage
)) {
5714 $signoff .= $CFG->supportpage
."\n";
5720 * Sets specified user's password and send the new password to the user via email.
5722 * @param stdClass $user A {@link $USER} object
5723 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
5724 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
5726 function setnew_password_and_mail($user, $fasthash = false) {
5729 // We try to send the mail in language the user understands,
5730 // unfortunately the filter_string() does not support alternative langs yet
5731 // so multilang will not work properly for site->fullname.
5732 $lang = empty($user->lang
) ?
$CFG->lang
: $user->lang
;
5736 $supportuser = core_user
::get_support_user();
5738 $newpassword = generate_password();
5740 update_internal_user_password($user, $newpassword, $fasthash);
5742 $a = new stdClass();
5743 $a->firstname
= fullname($user, true);
5744 $a->sitename
= format_string($site->fullname
);
5745 $a->username
= $user->username
;
5746 $a->newpassword
= $newpassword;
5747 $a->link
= $CFG->wwwroot
.'/login/';
5748 $a->signoff
= generate_email_signoff();
5750 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
5752 $subject = format_string($site->fullname
) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
5754 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5755 return email_to_user($user, $supportuser, $subject, $message);
5760 * Resets specified user's password and send the new password to the user via email.
5762 * @param stdClass $user A {@link $USER} object
5763 * @return bool Returns true if mail was sent OK and false if there was an error.
5765 function reset_password_and_mail($user) {
5769 $supportuser = core_user
::get_support_user();
5771 $userauth = get_auth_plugin($user->auth
);
5772 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth
)) {
5773 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
5777 $newpassword = generate_password();
5779 if (!$userauth->user_update_password($user, $newpassword)) {
5780 print_error("cannotsetpassword");
5783 $a = new stdClass();
5784 $a->firstname
= $user->firstname
;
5785 $a->lastname
= $user->lastname
;
5786 $a->sitename
= format_string($site->fullname
);
5787 $a->username
= $user->username
;
5788 $a->newpassword
= $newpassword;
5789 $a->link
= $CFG->httpswwwroot
.'/login/change_password.php';
5790 $a->signoff
= generate_email_signoff();
5792 $message = get_string('newpasswordtext', '', $a);
5794 $subject = format_string($site->fullname
) .': '. get_string('changedpassword');
5796 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
5798 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5799 return email_to_user($user, $supportuser, $subject, $message);
5803 * Send email to specified user with confirmation text and activation link.
5805 * @param stdClass $user A {@link $USER} object
5806 * @return bool Returns true if mail was sent OK and false if there was an error.
5808 function send_confirmation_email($user) {
5812 $supportuser = core_user
::get_support_user();
5814 $data = new stdClass();
5815 $data->firstname
= fullname($user);
5816 $data->sitename
= format_string($site->fullname
);
5817 $data->admin
= generate_email_signoff();
5819 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname
));
5821 $username = urlencode($user->username
);
5822 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
5823 $data->link
= $CFG->wwwroot
.'/login/confirm.php?data='. $user->secret
.'/'. $username;
5824 $message = get_string('emailconfirmation', '', $data);
5825 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
5827 $user->mailformat
= 1; // Always send HTML version as well.
5829 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5830 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
5834 * Sends a password change confirmation email.
5836 * @param stdClass $user A {@link $USER} object
5837 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
5838 * @return bool Returns true if mail was sent OK and false if there was an error.
5840 function send_password_change_confirmation_email($user, $resetrecord) {
5844 $supportuser = core_user
::get_support_user();
5845 $pwresetmins = isset($CFG->pwresettime
) ?
floor($CFG->pwresettime
/ MINSECS
) : 30;
5847 $data = new stdClass();
5848 $data->firstname
= $user->firstname
;
5849 $data->lastname
= $user->lastname
;
5850 $data->username
= $user->username
;
5851 $data->sitename
= format_string($site->fullname
);
5852 $data->link
= $CFG->httpswwwroot
.'/login/forgot_password.php?token='. $resetrecord->token
;
5853 $data->admin
= generate_email_signoff();
5854 $data->resetminutes
= $pwresetmins;
5856 $message = get_string('emailresetconfirmation', '', $data);
5857 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname
));
5859 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5860 return email_to_user($user, $supportuser, $subject, $message);
5865 * Sends an email containinginformation on how to change your password.
5867 * @param stdClass $user A {@link $USER} object
5868 * @return bool Returns true if mail was sent OK and false if there was an error.
5870 function send_password_change_info($user) {
5874 $supportuser = core_user
::get_support_user();
5875 $systemcontext = context_system
::instance();
5877 $data = new stdClass();
5878 $data->firstname
= $user->firstname
;
5879 $data->lastname
= $user->lastname
;
5880 $data->sitename
= format_string($site->fullname
);
5881 $data->admin
= generate_email_signoff();
5883 $userauth = get_auth_plugin($user->auth
);
5885 if (!is_enabled_auth($user->auth
) or $user->auth
== 'nologin') {
5886 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
5887 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
5888 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5889 return email_to_user($user, $supportuser, $subject, $message);
5892 if ($userauth->can_change_password() and $userauth->change_password_url()) {
5893 // We have some external url for password changing.
5894 $data->link
.= $userauth->change_password_url();
5897 // No way to change password, sorry.
5901 if (!empty($data->link
) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id
)) {
5902 $message = get_string('emailpasswordchangeinfo', '', $data);
5903 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
5905 $message = get_string('emailpasswordchangeinfofail', '', $data);
5906 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
5909 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5910 return email_to_user($user, $supportuser, $subject, $message);
5915 * Check that an email is allowed. It returns an error message if there was a problem.
5917 * @param string $email Content of email
5918 * @return string|false
5920 function email_is_not_allowed($email) {
5923 if (!empty($CFG->allowemailaddresses
)) {
5924 $allowed = explode(' ', $CFG->allowemailaddresses
);
5925 foreach ($allowed as $allowedpattern) {
5926 $allowedpattern = trim($allowedpattern);
5927 if (!$allowedpattern) {
5930 if (strpos($allowedpattern, '.') === 0) {
5931 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
5932 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
5936 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
5940 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
5942 } else if (!empty($CFG->denyemailaddresses
)) {
5943 $denied = explode(' ', $CFG->denyemailaddresses
);
5944 foreach ($denied as $deniedpattern) {
5945 $deniedpattern = trim($deniedpattern);
5946 if (!$deniedpattern) {
5949 if (strpos($deniedpattern, '.') === 0) {
5950 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
5951 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
5952 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
5955 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
5956 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
5967 * Returns local file storage instance
5969 * @return file_storage
5971 function get_file_storage() {
5980 require_once("$CFG->libdir/filelib.php");
5982 if (isset($CFG->filedir
)) {
5983 $filedir = $CFG->filedir
;
5985 $filedir = $CFG->dataroot
.'/filedir';
5988 if (isset($CFG->trashdir
)) {
5989 $trashdirdir = $CFG->trashdir
;
5991 $trashdirdir = $CFG->dataroot
.'/trashdir';
5994 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions
, $CFG->filepermissions
);
6000 * Returns local file storage instance
6002 * @return file_browser
6004 function get_file_browser() {
6013 require_once("$CFG->libdir/filelib.php");
6015 $fb = new file_browser();
6021 * Returns file packer
6023 * @param string $mimetype default application/zip
6024 * @return file_packer
6026 function get_file_packer($mimetype='application/zip') {
6029 static $fp = array();
6031 if (isset($fp[$mimetype])) {
6032 return $fp[$mimetype];
6035 switch ($mimetype) {
6036 case 'application/zip':
6037 case 'application/vnd.moodle.profiling':
6038 $classname = 'zip_packer';
6041 case 'application/x-gzip' :
6042 $classname = 'tgz_packer';
6045 case 'application/vnd.moodle.backup':
6046 $classname = 'mbz_packer';
6053 require_once("$CFG->libdir/filestorage/$classname.php");
6054 $fp[$mimetype] = new $classname();
6056 return $fp[$mimetype];
6060 * Returns current name of file on disk if it exists.
6062 * @param string $newfile File to be verified
6063 * @return string Current name of file on disk if true
6065 function valid_uploaded_file($newfile) {
6066 if (empty($newfile)) {
6069 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6070 return $newfile['tmp_name'];
6077 * Returns the maximum size for uploading files.
6079 * There are seven possible upload limits:
6080 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6081 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6082 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6083 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6084 * 5. by the Moodle admin in $CFG->maxbytes
6085 * 6. by the teacher in the current course $course->maxbytes
6086 * 7. by the teacher for the current module, eg $assignment->maxbytes
6088 * These last two are passed to this function as arguments (in bytes).
6089 * Anything defined as 0 is ignored.
6090 * The smallest of all the non-zero numbers is returned.
6092 * @todo Finish documenting this function
6094 * @param int $sitebytes Set maximum size
6095 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6096 * @param int $modulebytes Current module ->maxbytes (in bytes)
6097 * @return int The maximum size for uploading files.
6099 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6101 if (! $filesize = ini_get('upload_max_filesize')) {
6104 $minimumsize = get_real_size($filesize);
6106 if ($postsize = ini_get('post_max_size')) {
6107 $postsize = get_real_size($postsize);
6108 if ($postsize < $minimumsize) {
6109 $minimumsize = $postsize;
6113 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6114 $minimumsize = $sitebytes;
6117 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6118 $minimumsize = $coursebytes;
6121 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6122 $minimumsize = $modulebytes;
6125 return $minimumsize;
6129 * Returns the maximum size for uploading files for the current user
6131 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6133 * @param context $context The context in which to check user capabilities
6134 * @param int $sitebytes Set maximum size
6135 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6136 * @param int $modulebytes Current module ->maxbytes (in bytes)
6137 * @param stdClass $user The user
6138 * @return int The maximum size for uploading files.
6140 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6147 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6148 return USER_CAN_IGNORE_FILE_SIZE_LIMITS
;
6151 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6155 * Returns an array of possible sizes in local language
6157 * Related to {@link get_max_upload_file_size()} - this function returns an
6158 * array of possible sizes in an array, translated to the
6161 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6163 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6164 * with the value set to 0. This option will be the first in the list.
6166 * @uses SORT_NUMERIC
6167 * @param int $sitebytes Set maximum size
6168 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6169 * @param int $modulebytes Current module ->maxbytes (in bytes)
6170 * @param int|array $custombytes custom upload size/s which will be added to list,
6171 * Only value/s smaller then maxsize will be added to list.
6174 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6177 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6181 if ($sitebytes == 0) {
6182 // Will get the minimum of upload_max_filesize or post_max_size.
6183 $sitebytes = get_max_upload_file_size();
6186 $filesize = array();
6187 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6188 5242880, 10485760, 20971520, 52428800, 104857600);
6190 // If custombytes is given and is valid then add it to the list.
6191 if (is_number($custombytes) and $custombytes > 0) {
6192 $custombytes = (int)$custombytes;
6193 if (!in_array($custombytes, $sizelist)) {
6194 $sizelist[] = $custombytes;
6196 } else if (is_array($custombytes)) {
6197 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6200 // Allow maxbytes to be selected if it falls outside the above boundaries.
6201 if (isset($CFG->maxbytes
) && !in_array(get_real_size($CFG->maxbytes
), $sizelist)) {
6202 // Note: get_real_size() is used in order to prevent problems with invalid values.
6203 $sizelist[] = get_real_size($CFG->maxbytes
);
6206 foreach ($sizelist as $sizebytes) {
6207 if ($sizebytes < $maxsize && $sizebytes > 0) {
6208 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6215 (($modulebytes < $coursebytes ||
$coursebytes == 0) &&
6216 ($modulebytes < $sitebytes ||
$sitebytes == 0))) {
6217 $limitlevel = get_string('activity', 'core');
6218 $displaysize = display_size($modulebytes);
6219 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6221 } else if ($coursebytes && ($coursebytes < $sitebytes ||
$sitebytes == 0)) {
6222 $limitlevel = get_string('course', 'core');
6223 $displaysize = display_size($coursebytes);
6224 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6226 } else if ($sitebytes) {
6227 $limitlevel = get_string('site', 'core');
6228 $displaysize = display_size($sitebytes);
6229 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6232 krsort($filesize, SORT_NUMERIC
);
6234 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6235 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) +
$filesize;
6242 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6244 * If excludefiles is defined, then that file/directory is ignored
6245 * If getdirs is true, then (sub)directories are included in the output
6246 * If getfiles is true, then files are included in the output
6247 * (at least one of these must be true!)
6249 * @todo Finish documenting this function. Add examples of $excludefile usage.
6251 * @param string $rootdir A given root directory to start from
6252 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6253 * @param bool $descend If true then subdirectories are recursed as well
6254 * @param bool $getdirs If true then (sub)directories are included in the output
6255 * @param bool $getfiles If true then files are included in the output
6256 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6258 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6262 if (!$getdirs and !$getfiles) { // Nothing to show.
6266 if (!is_dir($rootdir)) { // Must be a directory.
6270 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6274 if (!is_array($excludefiles)) {
6275 $excludefiles = array($excludefiles);
6278 while (false !== ($file = readdir($dir))) {
6279 $firstchar = substr($file, 0, 1);
6280 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6283 $fullfile = $rootdir .'/'. $file;
6284 if (filetype($fullfile) == 'dir') {
6289 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6290 foreach ($subdirs as $subdir) {
6291 $dirs[] = $file .'/'. $subdir;
6294 } else if ($getfiles) {
6307 * Adds up all the files in a directory and works out the size.
6309 * @param string $rootdir The directory to start from
6310 * @param string $excludefile A file to exclude when summing directory size
6311 * @return int The summed size of all files and subfiles within the root directory
6313 function get_directory_size($rootdir, $excludefile='') {
6316 // Do it this way if we can, it's much faster.
6317 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
6318 $command = trim($CFG->pathtodu
).' -sk '.escapeshellarg($rootdir);
6321 exec($command, $output, $return);
6322 if (is_array($output)) {
6323 // We told it to return k.
6324 return get_real_size(intval($output[0]).'k');
6328 if (!is_dir($rootdir)) {
6329 // Must be a directory.
6333 if (!$dir = @opendir
($rootdir)) {
6334 // Can't open it for some reason.
6340 while (false !== ($file = readdir($dir))) {
6341 $firstchar = substr($file, 0, 1);
6342 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6345 $fullfile = $rootdir .'/'. $file;
6346 if (filetype($fullfile) == 'dir') {
6347 $size +
= get_directory_size($fullfile, $excludefile);
6349 $size +
= filesize($fullfile);
6358 * Converts bytes into display form
6360 * @static string $gb Localized string for size in gigabytes
6361 * @static string $mb Localized string for size in megabytes
6362 * @static string $kb Localized string for size in kilobytes
6363 * @static string $b Localized string for size in bytes
6364 * @param int $size The size to convert to human readable form
6367 function display_size($size) {
6369 static $gb, $mb, $kb, $b;
6371 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS
) {
6372 return get_string('unlimited');
6376 $gb = get_string('sizegb');
6377 $mb = get_string('sizemb');
6378 $kb = get_string('sizekb');
6379 $b = get_string('sizeb');
6382 if ($size >= 1073741824) {
6383 $size = round($size / 1073741824 * 10) / 10 . $gb;
6384 } else if ($size >= 1048576) {
6385 $size = round($size / 1048576 * 10) / 10 . $mb;
6386 } else if ($size >= 1024) {
6387 $size = round($size / 1024 * 10) / 10 . $kb;
6389 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6395 * Cleans a given filename by removing suspicious or troublesome characters
6397 * @see clean_param()
6398 * @param string $string file name
6399 * @return string cleaned file name
6401 function clean_filename($string) {
6402 return clean_param($string, PARAM_FILE
);
6406 // STRING TRANSLATION.
6409 * Returns the code for the current language
6414 function current_language() {
6415 global $CFG, $USER, $SESSION, $COURSE;
6417 if (!empty($SESSION->forcelang
)) {
6418 // Allows overriding course-forced language (useful for admins to check
6419 // issues in courses whose language they don't understand).
6420 // Also used by some code to temporarily get language-related information in a
6421 // specific language (see force_current_language()).
6422 $return = $SESSION->forcelang
;
6424 } else if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) {
6425 // Course language can override all other settings for this page.
6426 $return = $COURSE->lang
;
6428 } else if (!empty($SESSION->lang
)) {
6429 // Session language can override other settings.
6430 $return = $SESSION->lang
;
6432 } else if (!empty($USER->lang
)) {
6433 $return = $USER->lang
;
6435 } else if (isset($CFG->lang
)) {
6436 $return = $CFG->lang
;
6442 // Just in case this slipped in from somewhere by accident.
6443 $return = str_replace('_utf8', '', $return);
6449 * Returns parent language of current active language if defined
6452 * @param string $lang null means current language
6455 function get_parent_language($lang=null) {
6457 // Let's hack around the current language.
6458 if (!empty($lang)) {
6459 $oldforcelang = force_current_language($lang);
6462 $parentlang = get_string('parentlanguage', 'langconfig');
6463 if ($parentlang === 'en') {
6467 // Let's hack around the current language.
6468 if (!empty($lang)) {
6469 force_current_language($oldforcelang);
6476 * Force the current language to get strings and dates localised in the given language.
6478 * After calling this function, all strings will be provided in the given language
6479 * until this function is called again, or equivalent code is run.
6481 * @param string $language
6482 * @return string previous $SESSION->forcelang value
6484 function force_current_language($language) {
6486 $sessionforcelang = isset($SESSION->forcelang
) ?
$SESSION->forcelang
: '';
6487 if ($language !== $sessionforcelang) {
6488 // Seting forcelang to null or an empty string disables it's effect.
6489 if (empty($language) ||
get_string_manager()->translation_exists($language, false)) {
6490 $SESSION->forcelang
= $language;
6494 return $sessionforcelang;
6498 * Returns current string_manager instance.
6500 * The param $forcereload is needed for CLI installer only where the string_manager instance
6501 * must be replaced during the install.php script life time.
6504 * @param bool $forcereload shall the singleton be released and new instance created instead?
6505 * @return core_string_manager
6507 function get_string_manager($forcereload=false) {
6510 static $singleton = null;
6515 if ($singleton === null) {
6516 if (empty($CFG->early_install_lang
)) {
6518 if (empty($CFG->langlist
)) {
6519 $translist = array();
6521 $translist = explode(',', $CFG->langlist
);
6524 if (!empty($CFG->config_php_settings
['customstringmanager'])) {
6525 $classname = $CFG->config_php_settings
['customstringmanager'];
6527 if (class_exists($classname)) {
6528 $implements = class_implements($classname);
6530 if (isset($implements['core_string_manager'])) {
6531 $singleton = new $classname($CFG->langotherroot
, $CFG->langlocalroot
, $translist);
6535 debugging('Unable to instantiate custom string manager: class '.$classname.
6536 ' does not implement the core_string_manager interface.');
6540 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6544 $singleton = new core_string_manager_standard($CFG->langotherroot
, $CFG->langlocalroot
, $translist);
6547 $singleton = new core_string_manager_install();
6555 * Returns a localized string.
6557 * Returns the translated string specified by $identifier as
6558 * for $module. Uses the same format files as STphp.
6559 * $a is an object, string or number that can be used
6560 * within translation strings
6562 * eg 'hello {$a->firstname} {$a->lastname}'
6565 * If you would like to directly echo the localized string use
6566 * the function {@link print_string()}
6568 * Example usage of this function involves finding the string you would
6569 * like a local equivalent of and using its identifier and module information
6570 * to retrieve it.<br/>
6571 * If you open moodle/lang/en/moodle.php and look near line 278
6572 * you will find a string to prompt a user for their word for 'course'
6574 * $string['course'] = 'Course';
6576 * So if you want to display the string 'Course'
6577 * in any language that supports it on your site
6578 * you just need to use the identifier 'course'
6580 * $mystring = '<strong>'. get_string('course') .'</strong>';
6583 * If the string you want is in another file you'd take a slightly
6584 * different approach. Looking in moodle/lang/en/calendar.php you find
6587 * $string['typecourse'] = 'Course event';
6589 * If you want to display the string "Course event" in any language
6590 * supported you would use the identifier 'typecourse' and the module 'calendar'
6591 * (because it is in the file calendar.php):
6593 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6596 * As a last resort, should the identifier fail to map to a string
6597 * the returned string will be [[ $identifier ]]
6599 * In Moodle 2.3 there is a new argument to this function $lazyload.
6600 * Setting $lazyload to true causes get_string to return a lang_string object
6601 * rather than the string itself. The fetching of the string is then put off until
6602 * the string object is first used. The object can be used by calling it's out
6603 * method or by casting the object to a string, either directly e.g.
6604 * (string)$stringobject
6605 * or indirectly by using the string within another string or echoing it out e.g.
6606 * echo $stringobject
6607 * return "<p>{$stringobject}</p>";
6608 * It is worth noting that using $lazyload and attempting to use the string as an
6609 * array key will cause a fatal error as objects cannot be used as array keys.
6610 * But you should never do that anyway!
6611 * For more information {@link lang_string}
6614 * @param string $identifier The key identifier for the localized string
6615 * @param string $component The module where the key identifier is stored,
6616 * usually expressed as the filename in the language pack without the
6617 * .php on the end but can also be written as mod/forum or grade/export/xls.
6618 * If none is specified then moodle.php is used.
6619 * @param string|object|array $a An object, string or number that can be used
6620 * within translation strings
6621 * @param bool $lazyload If set to true a string object is returned instead of
6622 * the string itself. The string then isn't calculated until it is first used.
6623 * @return string The localized string.
6624 * @throws coding_exception
6626 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6629 // If the lazy load argument has been supplied return a lang_string object
6631 // We need to make sure it is true (and a bool) as you will see below there
6632 // used to be a forth argument at one point.
6633 if ($lazyload === true) {
6634 return new lang_string($identifier, $component, $a);
6637 if ($CFG->debugdeveloper
&& clean_param($identifier, PARAM_STRINGID
) === '') {
6638 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER
);
6641 // There is now a forth argument again, this time it is a boolean however so
6642 // we can still check for the old extralocations parameter.
6643 if (!is_bool($lazyload) && !empty($lazyload)) {
6644 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6647 if (strpos($component, '/') !== false) {
6648 debugging('The module name you passed to get_string is the deprecated format ' .
6649 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER
);
6650 $componentpath = explode('/', $component);
6652 switch ($componentpath[0]) {
6654 $component = $componentpath[1];
6658 $component = 'block_'.$componentpath[1];
6661 $component = 'enrol_'.$componentpath[1];
6664 $component = 'format_'.$componentpath[1];
6667 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6672 $result = get_string_manager()->get_string($identifier, $component, $a);
6674 // Debugging feature lets you display string identifier and component.
6675 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
6676 $result .= ' {' . $identifier . '/' . $component . '}';
6682 * Converts an array of strings to their localized value.
6684 * @param array $array An array of strings
6685 * @param string $component The language module that these strings can be found in.
6686 * @return stdClass translated strings.
6688 function get_strings($array, $component = '') {
6689 $string = new stdClass
;
6690 foreach ($array as $item) {
6691 $string->$item = get_string($item, $component);
6697 * Prints out a translated string.
6699 * Prints out a translated string using the return value from the {@link get_string()} function.
6701 * Example usage of this function when the string is in the moodle.php file:<br/>
6704 * print_string('course');
6708 * Example usage of this function when the string is not in the moodle.php file:<br/>
6711 * print_string('typecourse', 'calendar');
6716 * @param string $identifier The key identifier for the localized string
6717 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6718 * @param string|object|array $a An object, string or number that can be used within translation strings
6720 function print_string($identifier, $component = '', $a = null) {
6721 echo get_string($identifier, $component, $a);
6725 * Returns a list of charset codes
6727 * Returns a list of charset codes. It's hardcoded, so they should be added manually
6728 * (checking that such charset is supported by the texlib library!)
6730 * @return array And associative array with contents in the form of charset => charset
6732 function get_list_of_charsets() {
6735 'EUC-JP' => 'EUC-JP',
6736 'ISO-2022-JP'=> 'ISO-2022-JP',
6737 'ISO-8859-1' => 'ISO-8859-1',
6738 'SHIFT-JIS' => 'SHIFT-JIS',
6739 'GB2312' => 'GB2312',
6740 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
6741 'UTF-8' => 'UTF-8');
6749 * Returns a list of valid and compatible themes
6753 function get_list_of_themes() {
6758 if (!empty($CFG->themelist
)) { // Use admin's list of themes.
6759 $themelist = explode(',', $CFG->themelist
);
6761 $themelist = array_keys(core_component
::get_plugin_list("theme"));
6764 foreach ($themelist as $key => $themename) {
6765 $theme = theme_config
::load($themename);
6766 $themes[$themename] = $theme;
6769 core_collator
::asort_objects_by_method($themes, 'get_theme_name');
6775 * Factory function for emoticon_manager
6777 * @return emoticon_manager singleton
6779 function get_emoticon_manager() {
6780 static $singleton = null;
6782 if (is_null($singleton)) {
6783 $singleton = new emoticon_manager();
6790 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
6792 * Whenever this manager mentiones 'emoticon object', the following data
6793 * structure is expected: stdClass with properties text, imagename, imagecomponent,
6794 * altidentifier and altcomponent
6796 * @see admin_setting_emoticons
6798 * @copyright 2010 David Mudrak
6799 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6801 class emoticon_manager
{
6804 * Returns the currently enabled emoticons
6806 * @return array of emoticon objects
6808 public function get_emoticons() {
6811 if (empty($CFG->emoticons
)) {
6815 $emoticons = $this->decode_stored_config($CFG->emoticons
);
6817 if (!is_array($emoticons)) {
6818 // Something is wrong with the format of stored setting.
6819 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL
);
6827 * Converts emoticon object into renderable pix_emoticon object
6829 * @param stdClass $emoticon emoticon object
6830 * @param array $attributes explicit HTML attributes to set
6831 * @return pix_emoticon
6833 public function prepare_renderable_emoticon(stdClass
$emoticon, array $attributes = array()) {
6834 $stringmanager = get_string_manager();
6835 if ($stringmanager->string_exists($emoticon->altidentifier
, $emoticon->altcomponent
)) {
6836 $alt = get_string($emoticon->altidentifier
, $emoticon->altcomponent
);
6838 $alt = s($emoticon->text
);
6840 return new pix_emoticon($emoticon->imagename
, $alt, $emoticon->imagecomponent
, $attributes);
6844 * Encodes the array of emoticon objects into a string storable in config table
6846 * @see self::decode_stored_config()
6847 * @param array $emoticons array of emtocion objects
6850 public function encode_stored_config(array $emoticons) {
6851 return json_encode($emoticons);
6855 * Decodes the string into an array of emoticon objects
6857 * @see self::encode_stored_config()
6858 * @param string $encoded
6859 * @return string|null
6861 public function decode_stored_config($encoded) {
6862 $decoded = json_decode($encoded);
6863 if (!is_array($decoded)) {
6870 * Returns default set of emoticons supported by Moodle
6872 * @return array of sdtClasses
6874 public function default_emoticons() {
6876 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
6877 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
6878 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
6879 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
6880 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
6881 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
6882 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
6883 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
6884 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
6885 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
6886 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
6887 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
6888 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
6889 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
6890 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
6891 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
6892 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
6893 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
6894 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
6895 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
6896 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
6897 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
6898 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
6899 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
6900 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
6901 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
6902 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
6903 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
6904 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
6905 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
6910 * Helper method preparing the stdClass with the emoticon properties
6912 * @param string|array $text or array of strings
6913 * @param string $imagename to be used by {@link pix_emoticon}
6914 * @param string $altidentifier alternative string identifier, null for no alt
6915 * @param string $altcomponent where the alternative string is defined
6916 * @param string $imagecomponent to be used by {@link pix_emoticon}
6919 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
6920 $altcomponent = 'core_pix', $imagecomponent = 'core') {
6921 return (object)array(
6923 'imagename' => $imagename,
6924 'imagecomponent' => $imagecomponent,
6925 'altidentifier' => $altidentifier,
6926 'altcomponent' => $altcomponent,
6936 * @param string $data Data to encrypt.
6937 * @return string The now encrypted data.
6939 function rc4encrypt($data) {
6940 return endecrypt(get_site_identifier(), $data, '');
6946 * @param string $data Data to decrypt.
6947 * @return string The now decrypted data.
6949 function rc4decrypt($data) {
6950 return endecrypt(get_site_identifier(), $data, 'de');
6954 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
6956 * @todo Finish documenting this function
6958 * @param string $pwd The password to use when encrypting or decrypting
6959 * @param string $data The data to be decrypted/encrypted
6960 * @param string $case Either 'de' for decrypt or '' for encrypt
6963 function endecrypt ($pwd, $data, $case) {
6965 if ($case == 'de') {
6966 $data = urldecode($data);
6971 $pwdlength = strlen($pwd);
6973 for ($i = 0; $i <= 255; $i++
) {
6974 $key[$i] = ord(substr($pwd, ($i %
$pwdlength), 1));
6980 for ($i = 0; $i <= 255; $i++
) {
6981 $x = ($x +
$box[$i] +
$key[$i]) %
256;
6982 $tempswap = $box[$i];
6983 $box[$i] = $box[$x];
6984 $box[$x] = $tempswap;
6992 for ($i = 0; $i < strlen($data); $i++
) {
6993 $a = ($a +
1) %
256;
6994 $j = ($j +
$box[$a]) %
256;
6996 $box[$a] = $box[$j];
6998 $k = $box[(($box[$a] +
$box[$j]) %
256)];
6999 $cipherby = ord(substr($data, $i, 1)) ^
$k;
7000 $cipher .= chr($cipherby);
7003 if ($case == 'de') {
7004 $cipher = urldecode(urlencode($cipher));
7006 $cipher = urlencode($cipher);
7012 // ENVIRONMENT CHECKING.
7015 * This method validates a plug name. It is much faster than calling clean_param.
7017 * @param string $name a string that might be a plugin name.
7018 * @return bool if this string is a valid plugin name.
7020 function is_valid_plugin_name($name) {
7021 // This does not work for 'mod', bad luck, use any other type.
7022 return core_component
::is_valid_plugin_name('tool', $name);
7026 * Get a list of all the plugins of a given type that define a certain API function
7027 * in a certain file. The plugin component names and function names are returned.
7029 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7030 * @param string $function the part of the name of the function after the
7031 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7032 * names like report_courselist_hook.
7033 * @param string $file the name of file within the plugin that defines the
7034 * function. Defaults to lib.php.
7035 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7036 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7038 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7041 // We don't include here as all plugin types files would be included.
7042 $plugins = get_plugins_with_function($function, $file, false);
7044 if (empty($plugins[$plugintype])) {
7048 $allplugins = core_component
::get_plugin_list($plugintype);
7050 // Reformat the array and include the files.
7051 $pluginfunctions = array();
7052 foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7054 // Check that it has not been removed and the file is still available.
7055 if (!empty($allplugins[$pluginname])) {
7057 $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR
. $file;
7058 if (file_exists($filepath)) {
7059 include_once($filepath);
7060 $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7065 return $pluginfunctions;
7069 * Get a list of all the plugins that define a certain API function in a certain file.
7071 * @param string $function the part of the name of the function after the
7072 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7073 * names like report_courselist_hook.
7074 * @param string $file the name of file within the plugin that defines the
7075 * function. Defaults to lib.php.
7076 * @param bool $include Whether to include the files that contain the functions or not.
7077 * @return array with [plugintype][plugin] = functionname
7079 function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7082 $cache = \cache
::make('core', 'plugin_functions');
7084 // Including both although I doubt that we will find two functions definitions with the same name.
7085 // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7086 $key = $function . '_' . clean_param($file, PARAM_ALPHA
);
7088 if ($pluginfunctions = $cache->get($key)) {
7090 // Checking that the files are still available.
7091 foreach ($pluginfunctions as $plugintype => $plugins) {
7093 $allplugins = \core_component
::get_plugin_list($plugintype);
7094 foreach ($plugins as $plugin => $fullpath) {
7096 // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7097 if (empty($allplugins[$plugin])) {
7098 unset($pluginfunctions[$plugintype][$plugin]);
7102 $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR
. $file);
7103 if ($include && $fileexists) {
7104 // Include the files if it was requested.
7105 include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR
. $file);
7106 } else if (!$fileexists) {
7107 // If the file is not available any more it should not be returned.
7108 unset($pluginfunctions[$plugintype][$plugin]);
7112 return $pluginfunctions;
7115 $pluginfunctions = array();
7117 // To fill the cached. Also, everything should continue working with cache disabled.
7118 $plugintypes = \core_component
::get_plugin_types();
7119 foreach ($plugintypes as $plugintype => $unused) {
7121 // We need to include files here.
7122 $pluginswithfile = \core_component
::get_plugin_list_with_file($plugintype, $file, true);
7123 foreach ($pluginswithfile as $plugin => $notused) {
7125 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7127 $pluginfunction = false;
7128 if (function_exists($fullfunction)) {
7129 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7130 $pluginfunction = $fullfunction;
7132 } else if ($plugintype === 'mod') {
7133 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7134 $shortfunction = $plugin . '_' . $function;
7135 if (function_exists($shortfunction)) {
7136 $pluginfunction = $shortfunction;
7140 if ($pluginfunction) {
7141 if (empty($pluginfunctions[$plugintype])) {
7142 $pluginfunctions[$plugintype] = array();
7144 $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7149 $cache->set($key, $pluginfunctions);
7151 return $pluginfunctions;
7156 * Lists plugin-like directories within specified directory
7158 * This function was originally used for standard Moodle plugins, please use
7159 * new core_component::get_plugin_list() now.
7161 * This function is used for general directory listing and backwards compatility.
7163 * @param string $directory relative directory from root
7164 * @param string $exclude dir name to exclude from the list (defaults to none)
7165 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7166 * @return array Sorted array of directory names found under the requested parameters
7168 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7173 if (empty($basedir)) {
7174 $basedir = $CFG->dirroot
.'/'. $directory;
7177 $basedir = $basedir .'/'. $directory;
7180 if ($CFG->debugdeveloper
and empty($exclude)) {
7181 // Make sure devs do not use this to list normal plugins,
7182 // this is intended for general directories that are not plugins!
7184 $subtypes = core_component
::get_plugin_types();
7185 if (in_array($basedir, $subtypes)) {
7186 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER
);
7191 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7192 if (!$dirhandle = opendir($basedir)) {
7193 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER
);
7196 while (false !== ($dir = readdir($dirhandle))) {
7197 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7198 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7199 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7202 if (filetype($basedir .'/'. $dir) != 'dir') {
7207 closedir($dirhandle);
7216 * Invoke plugin's callback functions
7218 * @param string $type plugin type e.g. 'mod'
7219 * @param string $name plugin name
7220 * @param string $feature feature name
7221 * @param string $action feature's action
7222 * @param array $params parameters of callback function, should be an array
7223 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7226 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7228 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7229 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7233 * Invoke component's callback functions
7235 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7236 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7237 * @param array $params parameters of callback function
7238 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7241 function component_callback($component, $function, array $params = array(), $default = null) {
7243 $functionname = component_callback_exists($component, $function);
7245 if ($functionname) {
7246 // Function exists, so just return function result.
7247 $ret = call_user_func_array($functionname, $params);
7248 if (is_null($ret)) {
7258 * Determine if a component callback exists and return the function name to call. Note that this
7259 * function will include the required library files so that the functioname returned can be
7262 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7263 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7264 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7265 * @throws coding_exception if invalid component specfied
7267 function component_callback_exists($component, $function) {
7268 global $CFG; // This is needed for the inclusions.
7270 $cleancomponent = clean_param($component, PARAM_COMPONENT
);
7271 if (empty($cleancomponent)) {
7272 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7274 $component = $cleancomponent;
7276 list($type, $name) = core_component
::normalize_component($component);
7277 $component = $type . '_' . $name;
7279 $oldfunction = $name.'_'.$function;
7280 $function = $component.'_'.$function;
7282 $dir = core_component
::get_component_directory($component);
7284 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7287 // Load library and look for function.
7288 if (file_exists($dir.'/lib.php')) {
7289 require_once($dir.'/lib.php');
7292 if (!function_exists($function) and function_exists($oldfunction)) {
7293 if ($type !== 'mod' and $type !== 'core') {
7294 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER
);
7296 $function = $oldfunction;
7299 if (function_exists($function)) {
7306 * Checks whether a plugin supports a specified feature.
7308 * @param string $type Plugin type e.g. 'mod'
7309 * @param string $name Plugin name e.g. 'forum'
7310 * @param string $feature Feature code (FEATURE_xx constant)
7311 * @param mixed $default default value if feature support unknown
7312 * @return mixed Feature result (false if not supported, null if feature is unknown,
7313 * otherwise usually true but may have other feature-specific value such as array)
7314 * @throws coding_exception
7316 function plugin_supports($type, $name, $feature, $default = null) {
7319 if ($type === 'mod' and $name === 'NEWMODULE') {
7320 // Somebody forgot to rename the module template.
7324 $component = clean_param($type . '_' . $name, PARAM_COMPONENT
);
7325 if (empty($component)) {
7326 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7331 if ($type === 'mod') {
7332 // We need this special case because we support subplugins in modules,
7333 // otherwise it would end up in infinite loop.
7334 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7335 include_once("$CFG->dirroot/mod/$name/lib.php");
7336 $function = $component.'_supports';
7337 if (!function_exists($function)) {
7338 // Legacy non-frankenstyle function name.
7339 $function = $name.'_supports';
7344 if (!$path = core_component
::get_plugin_directory($type, $name)) {
7345 // Non existent plugin type.
7348 if (file_exists("$path/lib.php")) {
7349 include_once("$path/lib.php");
7350 $function = $component.'_supports';
7354 if ($function and function_exists($function)) {
7355 $supports = $function($feature);
7356 if (is_null($supports)) {
7357 // Plugin does not know - use default.
7364 // Plugin does not care, so use default.
7369 * Returns true if the current version of PHP is greater that the specified one.
7371 * @todo Check PHP version being required here is it too low?
7373 * @param string $version The version of php being tested.
7376 function check_php_version($version='5.2.4') {
7377 return (version_compare(phpversion(), $version) >= 0);
7381 * Determine if moodle installation requires update.
7383 * Checks version numbers of main code and all plugins to see
7384 * if there are any mismatches.
7388 function moodle_needs_upgrading() {
7391 if (empty($CFG->version
)) {
7395 // There is no need to purge plugininfo caches here because
7396 // these caches are not used during upgrade and they are purged after
7399 if (empty($CFG->allversionshash
)) {
7403 $hash = core_component
::get_all_versions_hash();
7405 return ($hash !== $CFG->allversionshash
);
7409 * Returns the major version of this site
7411 * Moodle version numbers consist of three numbers separated by a dot, for
7412 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7413 * called major version. This function extracts the major version from either
7414 * $CFG->release (default) or eventually from the $release variable defined in
7415 * the main version.php.
7417 * @param bool $fromdisk should the version if source code files be used
7418 * @return string|false the major version like '2.3', false if could not be determined
7420 function moodle_major_version($fromdisk = false) {
7425 require($CFG->dirroot
.'/version.php');
7426 if (empty($release)) {
7431 if (empty($CFG->release
)) {
7434 $release = $CFG->release
;
7437 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7447 * Sets the system locale
7450 * @param string $locale Can be used to force a locale
7452 function moodle_setlocale($locale='') {
7455 static $currentlocale = ''; // Last locale caching.
7457 $oldlocale = $currentlocale;
7459 // Fetch the correct locale based on ostype.
7460 if ($CFG->ostype
== 'WINDOWS') {
7461 $stringtofetch = 'localewin';
7463 $stringtofetch = 'locale';
7466 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7467 if (!empty($locale)) {
7468 $currentlocale = $locale;
7469 } else if (!empty($CFG->locale
)) { // Override locale for all language packs.
7470 $currentlocale = $CFG->locale
;
7472 $currentlocale = get_string($stringtofetch, 'langconfig');
7475 // Do nothing if locale already set up.
7476 if ($oldlocale == $currentlocale) {
7480 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7481 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7482 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7484 // Get current values.
7485 $monetary= setlocale (LC_MONETARY
, 0);
7486 $numeric = setlocale (LC_NUMERIC
, 0);
7487 $ctype = setlocale (LC_CTYPE
, 0);
7488 if ($CFG->ostype
!= 'WINDOWS') {
7489 $messages= setlocale (LC_MESSAGES
, 0);
7491 // Set locale to all.
7492 $result = setlocale (LC_ALL
, $currentlocale);
7493 // If setting of locale fails try the other utf8 or utf-8 variant,
7494 // some operating systems support both (Debian), others just one (OSX).
7495 if ($result === false) {
7496 if (stripos($currentlocale, '.UTF-8') !== false) {
7497 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7498 setlocale (LC_ALL
, $newlocale);
7499 } else if (stripos($currentlocale, '.UTF8') !== false) {
7500 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7501 setlocale (LC_ALL
, $newlocale);
7505 setlocale (LC_MONETARY
, $monetary);
7506 setlocale (LC_NUMERIC
, $numeric);
7507 if ($CFG->ostype
!= 'WINDOWS') {
7508 setlocale (LC_MESSAGES
, $messages);
7510 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7511 // To workaround a well-known PHP problem with Turkish letter Ii.
7512 setlocale (LC_CTYPE
, $ctype);
7517 * Count words in a string.
7519 * Words are defined as things between whitespace.
7522 * @param string $string The text to be searched for words.
7523 * @return int The count of words in the specified string
7525 function count_words($string) {
7526 $string = strip_tags($string);
7527 // Decode HTML entities.
7528 $string = html_entity_decode($string);
7529 // Replace underscores (which are classed as word characters) with spaces.
7530 $string = preg_replace('/_/u', ' ', $string);
7531 // Remove any characters that shouldn't be treated as word boundaries.
7532 $string = preg_replace('/[\'’-]/u', '', $string);
7533 // Remove dots and commas from within numbers only.
7534 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7536 return count(preg_split('/\w\b/u', $string)) - 1;
7540 * Count letters in a string.
7542 * Letters are defined as chars not in tags and different from whitespace.
7545 * @param string $string The text to be searched for letters.
7546 * @return int The count of letters in the specified text.
7548 function count_letters($string) {
7549 $string = strip_tags($string); // Tags are out now.
7550 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7552 return core_text
::strlen($string);
7556 * Generate and return a random string of the specified length.
7558 * @param int $length The length of the string to be created.
7561 function random_string($length=15) {
7562 $randombytes = random_bytes_emulate($length);
7563 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7564 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7565 $pool .= '0123456789';
7566 $poollen = strlen($pool);
7568 for ($i = 0; $i < $length; $i++
) {
7569 $rand = ord($randombytes[$i]);
7570 $string .= substr($pool, ($rand%
($poollen)), 1);
7576 * Generate a complex random string (useful for md5 salts)
7578 * This function is based on the above {@link random_string()} however it uses a
7579 * larger pool of characters and generates a string between 24 and 32 characters
7581 * @param int $length Optional if set generates a string to exactly this length
7584 function complex_random_string($length=null) {
7585 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7586 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7587 $poollen = strlen($pool);
7588 if ($length===null) {
7589 $length = floor(rand(24, 32));
7591 $randombytes = random_bytes_emulate($length);
7593 for ($i = 0; $i < $length; $i++
) {
7594 $rand = ord($randombytes[$i]);
7595 $string .= $pool[($rand%
$poollen)];
7601 * Try to generates cryptographically secure pseudo-random bytes.
7603 * Note this is achieved by fallbacking between:
7604 * - PHP 7 random_bytes().
7605 * - OpenSSL openssl_random_pseudo_bytes().
7606 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
7608 * @param int $length requested length in bytes
7609 * @return string binary data
7611 function random_bytes_emulate($length) {
7614 debugging('Invalid random bytes length', DEBUG_DEVELOPER
);
7617 if (function_exists('random_bytes')) {
7618 // Use PHP 7 goodness.
7619 $hash = @random_bytes
($length);
7620 if ($hash !== false) {
7624 if (function_exists('openssl_random_pseudo_bytes')) {
7625 // For PHP 5.3 and later with openssl extension.
7626 $hash = openssl_random_pseudo_bytes($length);
7627 if ($hash !== false) {
7632 // Bad luck, there is no reliable random generator, let's just hash some unique stuff that is hard to guess.
7633 $hash = sha1(serialize($CFG) . serialize($_SERVER) . microtime(true) . uniqid('', true), true);
7634 // NOTE: the last param in sha1() is true, this means we are getting 20 bytes, not 40 chars as usual.
7635 if ($length <= 20) {
7636 return substr($hash, 0, $length);
7638 return $hash . random_bytes_emulate($length - 20);
7642 * Given some text (which may contain HTML) and an ideal length,
7643 * this function truncates the text neatly on a word boundary if possible
7646 * @param string $text text to be shortened
7647 * @param int $ideal ideal string length
7648 * @param boolean $exact if false, $text will not be cut mid-word
7649 * @param string $ending The string to append if the passed string is truncated
7650 * @return string $truncate shortened string
7652 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7653 // If the plain text is shorter than the maximum length, return the whole text.
7654 if (core_text
::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7658 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7659 // and only tag in its 'line'.
7660 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER
);
7662 $totallength = core_text
::strlen($ending);
7665 // This array stores information about open and close tags and their position
7666 // in the truncated string. Each item in the array is an object with fields
7667 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7668 // (byte position in truncated text).
7669 $tagdetails = array();
7671 foreach ($lines as $linematchings) {
7672 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7673 if (!empty($linematchings[1])) {
7674 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7675 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7676 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7677 // Record closing tag.
7678 $tagdetails[] = (object) array(
7680 'tag' => core_text
::strtolower($tagmatchings[1]),
7681 'pos' => core_text
::strlen($truncate),
7684 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7685 // Record opening tag.
7686 $tagdetails[] = (object) array(
7688 'tag' => core_text
::strtolower($tagmatchings[1]),
7689 'pos' => core_text
::strlen($truncate),
7693 // Add html-tag to $truncate'd text.
7694 $truncate .= $linematchings[1];
7697 // Calculate the length of the plain text part of the line; handle entities as one character.
7698 $contentlength = core_text
::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7699 if ($totallength +
$contentlength > $ideal) {
7700 // The number of characters which are left.
7701 $left = $ideal - $totallength;
7702 $entitieslength = 0;
7703 // Search for html entities.
7704 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
)) {
7705 // Calculate the real length of all entities in the legal range.
7706 foreach ($entities[0] as $entity) {
7707 if ($entity[1]+
1-$entitieslength <= $left) {
7709 $entitieslength +
= core_text
::strlen($entity[0]);
7711 // No more characters left.
7716 $breakpos = $left +
$entitieslength;
7718 // If the words shouldn't be cut in the middle...
7720 // Search the last occurence of a space.
7721 for (; $breakpos > 0; $breakpos--) {
7722 if ($char = core_text
::substr($linematchings[2], $breakpos, 1)) {
7723 if ($char === '.' or $char === ' ') {
7726 } else if (strlen($char) > 2) {
7727 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7734 if ($breakpos == 0) {
7735 // This deals with the test_shorten_text_no_spaces case.
7736 $breakpos = $left +
$entitieslength;
7737 } else if ($breakpos > $left +
$entitieslength) {
7738 // This deals with the previous for loop breaking on the first char.
7739 $breakpos = $left +
$entitieslength;
7742 $truncate .= core_text
::substr($linematchings[2], 0, $breakpos);
7743 // Maximum length is reached, so get off the loop.
7746 $truncate .= $linematchings[2];
7747 $totallength +
= $contentlength;
7750 // If the maximum length is reached, get off the loop.
7751 if ($totallength >= $ideal) {
7756 // Add the defined ending to the text.
7757 $truncate .= $ending;
7759 // Now calculate the list of open html tags based on the truncate position.
7760 $opentags = array();
7761 foreach ($tagdetails as $taginfo) {
7762 if ($taginfo->open
) {
7763 // Add tag to the beginning of $opentags list.
7764 array_unshift($opentags, $taginfo->tag
);
7766 // Can have multiple exact same open tags, close the last one.
7767 $pos = array_search($taginfo->tag
, array_reverse($opentags, true));
7768 if ($pos !== false) {
7769 unset($opentags[$pos]);
7774 // Close all unclosed html-tags.
7775 foreach ($opentags as $tag) {
7776 $truncate .= '</' . $tag . '>';
7784 * Given dates in seconds, how many weeks is the date from startdate
7785 * The first week is 1, the second 2 etc ...
7787 * @param int $startdate Timestamp for the start date
7788 * @param int $thedate Timestamp for the end date
7791 function getweek ($startdate, $thedate) {
7792 if ($thedate < $startdate) {
7796 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
7800 * Returns a randomly generated password of length $maxlen. inspired by
7802 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
7803 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
7805 * @param int $maxlen The maximum size of the password being generated.
7808 function generate_password($maxlen=10) {
7811 if (empty($CFG->passwordpolicy
)) {
7812 $fillers = PASSWORD_DIGITS
;
7813 $wordlist = file($CFG->wordlist
);
7814 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7815 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7816 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
7817 $password = $word1 . $filler1 . $word2;
7819 $minlen = !empty($CFG->minpasswordlength
) ?
$CFG->minpasswordlength
: 0;
7820 $digits = $CFG->minpassworddigits
;
7821 $lower = $CFG->minpasswordlower
;
7822 $upper = $CFG->minpasswordupper
;
7823 $nonalphanum = $CFG->minpasswordnonalphanum
;
7824 $total = $lower +
$upper +
$digits +
$nonalphanum;
7825 // Var minlength should be the greater one of the two ( $minlen and $total ).
7826 $minlen = $minlen < $total ?
$total : $minlen;
7827 // Var maxlen can never be smaller than minlen.
7828 $maxlen = $minlen > $maxlen ?
$minlen : $maxlen;
7829 $additional = $maxlen - $total;
7831 // Make sure we have enough characters to fulfill
7832 // complexity requirements.
7833 $passworddigits = PASSWORD_DIGITS
;
7834 while ($digits > strlen($passworddigits)) {
7835 $passworddigits .= PASSWORD_DIGITS
;
7837 $passwordlower = PASSWORD_LOWER
;
7838 while ($lower > strlen($passwordlower)) {
7839 $passwordlower .= PASSWORD_LOWER
;
7841 $passwordupper = PASSWORD_UPPER
;
7842 while ($upper > strlen($passwordupper)) {
7843 $passwordupper .= PASSWORD_UPPER
;
7845 $passwordnonalphanum = PASSWORD_NONALPHANUM
;
7846 while ($nonalphanum > strlen($passwordnonalphanum)) {
7847 $passwordnonalphanum .= PASSWORD_NONALPHANUM
;
7850 // Now mix and shuffle it all.
7851 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
7852 substr(str_shuffle ($passwordupper), 0, $upper) .
7853 substr(str_shuffle ($passworddigits), 0, $digits) .
7854 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
7855 substr(str_shuffle ($passwordlower .
7858 $passwordnonalphanum), 0 , $additional));
7861 return substr ($password, 0, $maxlen);
7865 * Given a float, prints it nicely.
7866 * Localized floats must not be used in calculations!
7868 * The stripzeros feature is intended for making numbers look nicer in small
7869 * areas where it is not necessary to indicate the degree of accuracy by showing
7870 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
7871 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
7873 * @param float $float The float to print
7874 * @param int $decimalpoints The number of decimal places to print.
7875 * @param bool $localized use localized decimal separator
7876 * @param bool $stripzeros If true, removes final zeros after decimal point
7877 * @return string locale float
7879 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
7880 if (is_null($float)) {
7884 $separator = get_string('decsep', 'langconfig');
7888 $result = number_format($float, $decimalpoints, $separator, '');
7890 // Remove zeros and final dot if not needed.
7891 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
7897 * Converts locale specific floating point/comma number back to standard PHP float value
7898 * Do NOT try to do any math operations before this conversion on any user submitted floats!
7900 * @param string $localefloat locale aware float representation
7901 * @param bool $strict If true, then check the input and return false if it is not a valid number.
7902 * @return mixed float|bool - false or the parsed float.
7904 function unformat_float($localefloat, $strict = false) {
7905 $localefloat = trim($localefloat);
7907 if ($localefloat == '') {
7911 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
7912 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
7914 if ($strict && !is_numeric($localefloat)) {
7918 return (float)$localefloat;
7922 * Given a simple array, this shuffles it up just like shuffle()
7923 * Unlike PHP's shuffle() this function works on any machine.
7925 * @param array $array The array to be rearranged
7928 function swapshuffle($array) {
7930 $last = count($array) - 1;
7931 for ($i = 0; $i <= $last; $i++
) {
7932 $from = rand(0, $last);
7934 $array[$i] = $array[$from];
7935 $array[$from] = $curr;
7941 * Like {@link swapshuffle()}, but works on associative arrays
7943 * @param array $array The associative array to be rearranged
7946 function swapshuffle_assoc($array) {
7948 $newarray = array();
7949 $newkeys = swapshuffle(array_keys($array));
7951 foreach ($newkeys as $newkey) {
7952 $newarray[$newkey] = $array[$newkey];
7958 * Given an arbitrary array, and a number of draws,
7959 * this function returns an array with that amount
7960 * of items. The indexes are retained.
7962 * @todo Finish documenting this function
7964 * @param array $array
7968 function draw_rand_array($array, $draws) {
7972 $last = count($array);
7974 if ($draws > $last) {
7978 while ($draws > 0) {
7981 $keys = array_keys($array);
7982 $rand = rand(0, $last);
7984 $return[$keys[$rand]] = $array[$keys[$rand]];
7985 unset($array[$keys[$rand]]);
7994 * Calculate the difference between two microtimes
7996 * @param string $a The first Microtime
7997 * @param string $b The second Microtime
8000 function microtime_diff($a, $b) {
8001 list($adec, $asec) = explode(' ', $a);
8002 list($bdec, $bsec) = explode(' ', $b);
8003 return $bsec - $asec +
$bdec - $adec;
8007 * Given a list (eg a,b,c,d,e) this function returns
8008 * an array of 1->a, 2->b, 3->c etc
8010 * @param string $list The string to explode into array bits
8011 * @param string $separator The separator used within the list string
8012 * @return array The now assembled array
8014 function make_menu_from_list($list, $separator=',') {
8016 $array = array_reverse(explode($separator, $list), true);
8017 foreach ($array as $key => $item) {
8018 $outarray[$key+
1] = trim($item);
8024 * Creates an array that represents all the current grades that
8025 * can be chosen using the given grading type.
8028 * are scales, zero is no grade, and positive numbers are maximum
8031 * @todo Finish documenting this function or better deprecated this completely!
8033 * @param int $gradingtype
8036 function make_grades_menu($gradingtype) {
8040 if ($gradingtype < 0) {
8041 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8042 return make_menu_from_list($scale->scale
);
8044 } else if ($gradingtype > 0) {
8045 for ($i=$gradingtype; $i>=0; $i--) {
8046 $grades[$i] = $i .' / '. $gradingtype;
8054 * This function returns the number of activities using the given scale in the given course.
8056 * @param int $courseid The course ID to check.
8057 * @param int $scaleid The scale ID to check
8060 function course_scale_used($courseid, $scaleid) {
8065 if (!empty($scaleid)) {
8066 if ($cms = get_course_mods($courseid)) {
8067 foreach ($cms as $cm) {
8068 // Check cm->name/lib.php exists.
8069 if (file_exists($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php')) {
8070 include_once($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php');
8071 $functionname = $cm->modname
.'_scale_used';
8072 if (function_exists($functionname)) {
8073 if ($functionname($cm->instance
, $scaleid)) {
8081 // Check if any course grade item makes use of the scale.
8082 $return +
= $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8084 // Check if any outcome in the course makes use of the scale.
8085 $return +
= $DB->count_records_sql("SELECT COUNT('x')
8086 FROM {grade_outcomes_courses} goc,
8088 WHERE go.id = goc.outcomeid
8089 AND go.scaleid = ? AND goc.courseid = ?",
8090 array($scaleid, $courseid));
8096 * This function returns the number of activities using scaleid in the entire site
8098 * @param int $scaleid
8099 * @param array $courses
8102 function site_scale_used($scaleid, &$courses) {
8105 if (!is_array($courses) ||
count($courses) == 0) {
8106 $courses = get_courses("all", false, "c.id, c.shortname");
8109 if (!empty($scaleid)) {
8110 if (is_array($courses) && count($courses) > 0) {
8111 foreach ($courses as $course) {
8112 $return +
= course_scale_used($course->id
, $scaleid);
8120 * make_unique_id_code
8122 * @todo Finish documenting this function
8125 * @param string $extra Extra string to append to the end of the code
8128 function make_unique_id_code($extra = '') {
8130 $hostname = 'unknownhost';
8131 if (!empty($_SERVER['HTTP_HOST'])) {
8132 $hostname = $_SERVER['HTTP_HOST'];
8133 } else if (!empty($_ENV['HTTP_HOST'])) {
8134 $hostname = $_ENV['HTTP_HOST'];
8135 } else if (!empty($_SERVER['SERVER_NAME'])) {
8136 $hostname = $_SERVER['SERVER_NAME'];
8137 } else if (!empty($_ENV['SERVER_NAME'])) {
8138 $hostname = $_ENV['SERVER_NAME'];
8141 $date = gmdate("ymdHis");
8143 $random = random_string(6);
8146 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8148 return $hostname .'+'. $date .'+'. $random;
8154 * Function to check the passed address is within the passed subnet
8156 * The parameter is a comma separated string of subnet definitions.
8157 * Subnet strings can be in one of three formats:
8158 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8159 * 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)
8160 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8161 * Code for type 1 modified from user posted comments by mediator at
8162 * {@link http://au.php.net/manual/en/function.ip2long.php}
8164 * @param string $addr The address you are checking
8165 * @param string $subnetstr The string of subnet addresses
8168 function address_in_subnet($addr, $subnetstr) {
8170 if ($addr == '0.0.0.0') {
8173 $subnets = explode(',', $subnetstr);
8175 $addr = trim($addr);
8176 $addr = cleanremoteaddr($addr, false); // Normalise.
8177 if ($addr === null) {
8180 $addrparts = explode(':', $addr);
8182 $ipv6 = strpos($addr, ':');
8184 foreach ($subnets as $subnet) {
8185 $subnet = trim($subnet);
8186 if ($subnet === '') {
8190 if (strpos($subnet, '/') !== false) {
8191 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8192 list($ip, $mask) = explode('/', $subnet);
8193 $mask = trim($mask);
8194 if (!is_number($mask)) {
8195 continue; // Incorect mask number, eh?
8197 $ip = cleanremoteaddr($ip, false); // Normalise.
8201 if (strpos($ip, ':') !== false) {
8206 if ($mask > 128 or $mask < 0) {
8207 continue; // Nonsense.
8210 return true; // Any address.
8213 if ($ip === $addr) {
8218 $ipparts = explode(':', $ip);
8219 $modulo = $mask %
16;
8220 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8221 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8222 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8226 $pos = ($mask-$modulo)/16;
8227 $ipnet = hexdec($ipparts[$pos]);
8228 $addrnet = hexdec($addrparts[$pos]);
8229 $mask = 0xffff << (16 - $modulo);
8230 if (($addrnet & $mask) == ($ipnet & $mask)) {
8240 if ($mask > 32 or $mask < 0) {
8241 continue; // Nonsense.
8247 if ($ip === $addr) {
8252 $mask = 0xffffffff << (32 - $mask);
8253 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8258 } else if (strpos($subnet, '-') !== false) {
8259 // 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.
8260 $parts = explode('-', $subnet);
8261 if (count($parts) != 2) {
8265 if (strpos($subnet, ':') !== false) {
8270 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8271 if ($ipstart === null) {
8274 $ipparts = explode(':', $ipstart);
8275 $start = hexdec(array_pop($ipparts));
8276 $ipparts[] = trim($parts[1]);
8277 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8278 if ($ipend === null) {
8282 $ipnet = implode(':', $ipparts);
8283 if (strpos($addr, $ipnet) !== 0) {
8286 $ipparts = explode(':', $ipend);
8287 $end = hexdec($ipparts[7]);
8289 $addrend = hexdec($addrparts[7]);
8291 if (($addrend >= $start) and ($addrend <= $end)) {
8300 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8301 if ($ipstart === null) {
8304 $ipparts = explode('.', $ipstart);
8305 $ipparts[3] = trim($parts[1]);
8306 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8307 if ($ipend === null) {
8311 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8317 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8318 if (strpos($subnet, ':') !== false) {
8323 $parts = explode(':', $subnet);
8324 $count = count($parts);
8325 if ($parts[$count-1] === '') {
8326 unset($parts[$count-1]); // Trim trailing :'s.
8328 $subnet = implode('.', $parts);
8330 $isip = cleanremoteaddr($subnet, false); // Normalise.
8331 if ($isip !== null) {
8332 if ($isip === $addr) {
8336 } else if ($count > 8) {
8339 $zeros = array_fill(0, 8-$count, '0');
8340 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8341 if (address_in_subnet($addr, $subnet)) {
8350 $parts = explode('.', $subnet);
8351 $count = count($parts);
8352 if ($parts[$count-1] === '') {
8353 unset($parts[$count-1]); // Trim trailing .
8355 $subnet = implode('.', $parts);
8358 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8359 if ($subnet === $addr) {
8363 } else if ($count > 4) {
8366 $zeros = array_fill(0, 4-$count, '0');
8367 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8368 if (address_in_subnet($addr, $subnet)) {
8379 * For outputting debugging info
8381 * @param string $string The string to write
8382 * @param string $eol The end of line char(s) to use
8383 * @param string $sleep Period to make the application sleep
8384 * This ensures any messages have time to display before redirect
8386 function mtrace($string, $eol="\n", $sleep=0) {
8388 if (defined('STDOUT') and !PHPUNIT_TEST
) {
8389 fwrite(STDOUT
, $string.$eol);
8391 echo $string . $eol;
8396 // Delay to keep message on user's screen in case of subsequent redirect.
8403 * Replace 1 or more slashes or backslashes to 1 slash
8405 * @param string $path The path to strip
8406 * @return string the path with double slashes removed
8408 function cleardoubleslashes ($path) {
8409 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8413 * Is current ip in give list?
8415 * @param string $list
8418 function remoteip_in_list($list) {
8420 $clientip = getremoteaddr(null);
8423 // Ensure access on cli.
8427 $list = explode("\n", $list);
8428 foreach ($list as $subnet) {
8429 $subnet = trim($subnet);
8430 if (address_in_subnet($clientip, $subnet)) {
8439 * Returns most reliable client address
8441 * @param string $default If an address can't be determined, then return this
8442 * @return string The remote IP address
8444 function getremoteaddr($default='0.0.0.0') {
8447 if (empty($CFG->getremoteaddrconf
)) {
8448 // This will happen, for example, before just after the upgrade, as the
8449 // user is redirected to the admin screen.
8450 $variablestoskip = 0;
8452 $variablestoskip = $CFG->getremoteaddrconf
;
8454 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP
)) {
8455 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8456 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8457 return $address ?
$address : $default;
8460 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR
)) {
8461 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8462 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8463 $address = $forwardedaddresses[0];
8465 if (substr_count($address, ":") > 1) {
8466 // Remove port and brackets from IPv6.
8467 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8468 $address = $matches[1];
8471 // Remove port from IPv4.
8472 if (substr_count($address, ":") == 1) {
8473 $parts = explode(":", $address);
8474 $address = $parts[0];
8478 $address = cleanremoteaddr($address);
8479 return $address ?
$address : $default;
8482 if (!empty($_SERVER['REMOTE_ADDR'])) {
8483 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8484 return $address ?
$address : $default;
8491 * Cleans an ip address. Internal addresses are now allowed.
8492 * (Originally local addresses were not allowed.)
8494 * @param string $addr IPv4 or IPv6 address
8495 * @param bool $compress use IPv6 address compression
8496 * @return string normalised ip address string, null if error
8498 function cleanremoteaddr($addr, $compress=false) {
8499 $addr = trim($addr);
8501 // TODO: maybe add a separate function is_addr_public() or something like this.
8503 if (strpos($addr, ':') !== false) {
8504 // Can be only IPv6.
8505 $parts = explode(':', $addr);
8506 $count = count($parts);
8508 if (strpos($parts[$count-1], '.') !== false) {
8509 // Legacy ipv4 notation.
8510 $last = array_pop($parts);
8511 $ipv4 = cleanremoteaddr($last, true);
8512 if ($ipv4 === null) {
8515 $bits = explode('.', $ipv4);
8516 $parts[] = dechex($bits[0]).dechex($bits[1]);
8517 $parts[] = dechex($bits[2]).dechex($bits[3]);
8518 $count = count($parts);
8519 $addr = implode(':', $parts);
8522 if ($count < 3 or $count > 8) {
8523 return null; // Severly malformed.
8527 if (strpos($addr, '::') === false) {
8528 return null; // Malformed.
8531 $insertat = array_search('', $parts, true);
8532 $missing = array_fill(0, 1 +
8 - $count, '0');
8533 array_splice($parts, $insertat, 1, $missing);
8534 foreach ($parts as $key => $part) {
8541 $adr = implode(':', $parts);
8542 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8543 return null; // Incorrect format - sorry.
8546 // Normalise 0s and case.
8547 $parts = array_map('hexdec', $parts);
8548 $parts = array_map('dechex', $parts);
8550 $result = implode(':', $parts);
8556 if ($result === '0:0:0:0:0:0:0:0') {
8557 return '::'; // All addresses.
8560 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8561 if ($compressed !== $result) {
8565 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8566 if ($compressed !== $result) {
8570 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8571 if ($compressed !== $result) {
8578 // First get all things that look like IPv4 addresses.
8580 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8585 foreach ($parts as $key => $match) {
8589 $parts[$key] = (int)$match; // Normalise 0s.
8592 return implode('.', $parts);
8596 * This function will make a complete copy of anything it's given,
8597 * regardless of whether it's an object or not.
8599 * @param mixed $thing Something you want cloned
8600 * @return mixed What ever it is you passed it
8602 function fullclone($thing) {
8603 return unserialize(serialize($thing));
8607 * If new messages are waiting for the current user, then insert
8608 * JavaScript to pop up the messaging window into the page
8612 function message_popup_window() {
8613 global $USER, $DB, $PAGE, $CFG;
8615 if (!$PAGE->get_popup_notification_allowed() ||
empty($CFG->messaging
)) {
8619 if (!isloggedin() ||
isguestuser()) {
8623 if (!isset($USER->message_lastpopup
)) {
8624 $USER->message_lastpopup
= 0;
8625 } else if ($USER->message_lastpopup
> (time()-120)) {
8626 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8630 // A quick query to check whether the user has new messages.
8631 $messagecount = $DB->count_records('message', array('useridto' => $USER->id
));
8632 if ($messagecount < 1) {
8636 // There are unread messages so now do a more complex but slower query.
8637 $messagesql = "SELECT m.id, c.blocked
8639 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8640 JOIN {message_processors} p ON mw.processorid=p.id
8641 JOIN {user} u ON m.useridfrom=u.id
8642 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8643 AND c.userid = m.useridto
8644 WHERE m.useridto = :userid
8645 AND p.name='popup'";
8647 // If the user was last notified over an hour ago we can re-notify them of old messages
8648 // so don't worry about when the new message was sent.
8649 $lastnotifiedlongago = $USER->message_lastpopup
< (time()-3600);
8650 if (!$lastnotifiedlongago) {
8651 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8654 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id
, 'lastpopuptime' => $USER->message_lastpopup
));
8657 foreach ($waitingmessages as $messageinfo) {
8658 if ($messageinfo->blocked
) {
8659 // Message is from a user who has since been blocked so just mark it read.
8660 // Get the full message to mark as read.
8661 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id
));
8662 message_mark_message_read($messageobject, time());
8668 if ($validmessages > 0) {
8669 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8670 $strgomessage = get_string('gotomessages', 'message');
8671 $strstaymessage = get_string('ignore', 'admin');
8673 $notificationsound = null;
8674 $beep = get_user_preferences('message_beepnewmessage', '');
8675 if (!empty($beep)) {
8676 // Browsers will work down this list until they find something they support.
8677 $sourcetags = html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.wav', 'type' => 'audio/wav'));
8678 $sourcetags .= html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.ogg', 'type' => 'audio/ogg'));
8679 $sourcetags .= html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8680 $sourcetags .= html_writer
::empty_tag('embed', array('src' => $CFG->wwwroot
.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8682 $notificationsound = html_writer
::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8685 $url = $CFG->wwwroot
.'/message/index.php';
8686 $content = html_writer
::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8687 html_writer
::start_tag('div', array('id' => 'newmessagetext')).
8689 html_writer
::end_tag('div').
8692 html_writer
::start_tag('div', array('id' => 'newmessagelinks')).
8693 html_writer
::link($url, $strgomessage, array('id' => 'notificationyes')).' '.
8694 html_writer
::link('', $strstaymessage, array('id' => 'notificationno')).
8695 html_writer
::end_tag('div');
8696 html_writer
::end_tag('div');
8698 $PAGE->requires
->js_init_call('M.core_message.init_notification', array('', $content, $url));
8700 $USER->message_lastpopup
= time();
8705 * Used to make sure that $min <= $value <= $max
8707 * Make sure that value is between min, and max
8709 * @param int $min The minimum value
8710 * @param int $value The value to check
8711 * @param int $max The maximum value
8714 function bounded_number($min, $value, $max) {
8715 if ($value < $min) {
8718 if ($value > $max) {
8725 * Check if there is a nested array within the passed array
8727 * @param array $array
8728 * @return bool true if there is a nested array false otherwise
8730 function array_is_nested($array) {
8731 foreach ($array as $value) {
8732 if (is_array($value)) {
8740 * get_performance_info() pairs up with init_performance_info()
8741 * loaded in setup.php. Returns an array with 'html' and 'txt'
8742 * values ready for use, and each of the individual stats provided
8743 * separately as well.
8747 function get_performance_info() {
8748 global $CFG, $PERF, $DB, $PAGE;
8751 $info['html'] = ''; // Holds userfriendly HTML representation.
8752 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8754 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
8756 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8757 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8759 if (function_exists('memory_get_usage')) {
8760 $info['memory_total'] = memory_get_usage();
8761 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
8762 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8763 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8764 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8767 if (function_exists('memory_get_peak_usage')) {
8768 $info['memory_peak'] = memory_get_peak_usage();
8769 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8770 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8773 $inc = get_included_files();
8774 $info['includecount'] = count($inc);
8775 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8776 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8778 if (!empty($CFG->early_install_lang
) or empty($PAGE)) {
8779 // We can not track more performance before installation or before PAGE init, sorry.
8783 $filtermanager = filter_manager
::instance();
8784 if (method_exists($filtermanager, 'get_performance_summary')) {
8785 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8786 $info = array_merge($filterinfo, $info);
8787 foreach ($filterinfo as $key => $value) {
8788 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8789 $info['txt'] .= "$key: $value ";
8793 $stringmanager = get_string_manager();
8794 if (method_exists($stringmanager, 'get_performance_summary')) {
8795 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8796 $info = array_merge($filterinfo, $info);
8797 foreach ($filterinfo as $key => $value) {
8798 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8799 $info['txt'] .= "$key: $value ";
8803 if (!empty($PERF->logwrites
)) {
8804 $info['logwrites'] = $PERF->logwrites
;
8805 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8806 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8809 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites
);
8810 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
8811 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8813 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
8814 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
8815 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
8817 if (function_exists('posix_times')) {
8818 $ptimes = posix_times();
8819 if (is_array($ptimes)) {
8820 foreach ($ptimes as $key => $val) {
8821 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
8823 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
8824 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8828 // Grab the load average for the last minute.
8829 // /proc will only work under some linux configurations
8830 // while uptime is there under MacOSX/Darwin and other unices.
8831 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
8832 list($serverload) = explode(' ', $loadavg[0]);
8834 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
8835 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
8836 $serverload = $matches[1];
8838 trigger_error('Could not parse uptime output!');
8841 if (!empty($serverload)) {
8842 $info['serverload'] = $serverload;
8843 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
8844 $info['txt'] .= "serverload: {$info['serverload']} ";
8847 // Display size of session if session started.
8848 if ($si = \core\session\manager
::get_performance_info()) {
8849 $info['sessionsize'] = $si['size'];
8850 $info['html'] .= $si['html'];
8851 $info['txt'] .= $si['txt'];
8854 if ($stats = cache_helper
::get_stats()) {
8855 $html = '<span class="cachesused">';
8856 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
8857 $text = 'Caches used (hits/misses/sets): ';
8861 foreach ($stats as $definition => $details) {
8862 switch ($details['mode']) {
8863 case cache_store
::MODE_APPLICATION
:
8864 $modeclass = 'application';
8865 $mode = ' <span title="application cache">[a]</span>';
8867 case cache_store
::MODE_SESSION
:
8868 $modeclass = 'session';
8869 $mode = ' <span title="session cache">[s]</span>';
8871 case cache_store
::MODE_REQUEST
:
8872 $modeclass = 'request';
8873 $mode = ' <span title="request cache">[r]</span>';
8876 $html .= '<span class="cache-definition-stats cache-mode-'.$modeclass.'">';
8877 $html .= '<span class="cache-definition-stats-heading">'.$definition.$mode.'</span>';
8878 $text .= "$definition {";
8879 foreach ($details['stores'] as $store => $data) {
8880 $hits +
= $data['hits'];
8881 $misses +
= $data['misses'];
8882 $sets +
= $data['sets'];
8883 if ($data['hits'] == 0 and $data['misses'] > 0) {
8884 $cachestoreclass = 'nohits';
8885 } else if ($data['hits'] < $data['misses']) {
8886 $cachestoreclass = 'lowhits';
8888 $cachestoreclass = 'hihits';
8890 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
8891 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
8896 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
8897 $html .= '</span> ';
8898 $info['cachesused'] = "$hits / $misses / $sets";
8899 $info['html'] .= $html;
8900 $info['txt'] .= $text.'. ';
8902 $info['cachesused'] = '0 / 0 / 0';
8903 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
8904 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
8907 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
8914 * @todo Document this function linux people
8916 function apd_get_profiling() {
8917 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
8921 * Delete directory or only its content
8923 * @param string $dir directory path
8924 * @param bool $contentonly
8925 * @return bool success, true also if dir does not exist
8927 function remove_dir($dir, $contentonly=false) {
8928 if (!file_exists($dir)) {
8932 if (!$handle = opendir($dir)) {
8936 while (false!==($item = readdir($handle))) {
8937 if ($item != '.' && $item != '..') {
8938 if (is_dir($dir.'/'.$item)) {
8939 $result = remove_dir($dir.'/'.$item) && $result;
8941 $result = unlink($dir.'/'.$item) && $result;
8947 clearstatcache(); // Make sure file stat cache is properly invalidated.
8950 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
8951 clearstatcache(); // Make sure file stat cache is properly invalidated.
8956 * Detect if an object or a class contains a given property
8957 * will take an actual object or the name of a class
8959 * @param mix $obj Name of class or real object to test
8960 * @param string $property name of property to find
8961 * @return bool true if property exists
8963 function object_property_exists( $obj, $property ) {
8964 if (is_string( $obj )) {
8965 $properties = get_class_vars( $obj );
8967 $properties = get_object_vars( $obj );
8969 return array_key_exists( $property, $properties );
8973 * Converts an object into an associative array
8975 * This function converts an object into an associative array by iterating
8976 * over its public properties. Because this function uses the foreach
8977 * construct, Iterators are respected. It works recursively on arrays of objects.
8978 * Arrays and simple values are returned as is.
8980 * If class has magic properties, it can implement IteratorAggregate
8981 * and return all available properties in getIterator()
8986 function convert_to_array($var) {
8989 // Loop over elements/properties.
8990 foreach ($var as $key => $value) {
8991 // Recursively convert objects.
8992 if (is_object($value) ||
is_array($value)) {
8993 $result[$key] = convert_to_array($value);
8995 // Simple values are untouched.
8996 $result[$key] = $value;
9003 * Detect a custom script replacement in the data directory that will
9004 * replace an existing moodle script
9006 * @return string|bool full path name if a custom script exists, false if no custom script exists
9008 function custom_script_path() {
9009 global $CFG, $SCRIPT;
9011 if ($SCRIPT === null) {
9012 // Probably some weird external script.
9016 $scriptpath = $CFG->customscripts
. $SCRIPT;
9018 // Check the custom script exists.
9019 if (file_exists($scriptpath) and is_file($scriptpath)) {
9027 * Returns whether or not the user object is a remote MNET user. This function
9028 * is in moodlelib because it does not rely on loading any of the MNET code.
9030 * @param object $user A valid user object
9031 * @return bool True if the user is from a remote Moodle.
9033 function is_mnet_remote_user($user) {
9036 if (!isset($CFG->mnet_localhost_id
)) {
9037 include_once($CFG->dirroot
. '/mnet/lib.php');
9038 $env = new mnet_environment();
9043 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
9047 * This function will search for browser prefereed languages, setting Moodle
9048 * to use the best one available if $SESSION->lang is undefined
9050 function setup_lang_from_browser() {
9051 global $CFG, $SESSION, $USER;
9053 if (!empty($SESSION->lang
) or !empty($USER->lang
) or empty($CFG->autolang
)) {
9054 // Lang is defined in session or user profile, nothing to do.
9058 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9062 // Extract and clean langs from headers.
9063 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9064 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9065 $rawlangs = explode(',', $rawlangs); // Convert to array.
9069 foreach ($rawlangs as $lang) {
9070 if (strpos($lang, ';') === false) {
9071 $langs[(string)$order] = $lang;
9072 $order = $order-0.01;
9074 $parts = explode(';', $lang);
9075 $pos = strpos($parts[1], '=');
9076 $langs[substr($parts[1], $pos+
1)] = $parts[0];
9079 krsort($langs, SORT_NUMERIC
);
9081 // Look for such langs under standard locations.
9082 foreach ($langs as $lang) {
9083 // Clean it properly for include.
9084 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR
));
9085 if (get_string_manager()->translation_exists($lang, false)) {
9086 // Lang exists, set it in session.
9087 $SESSION->lang
= $lang;
9088 // We have finished. Go out.
9096 * Check if $url matches anything in proxybypass list
9098 * Any errors just result in the proxy being used (least bad)
9100 * @param string $url url to check
9101 * @return boolean true if we should bypass the proxy
9103 function is_proxybypass( $url ) {
9107 if (empty($CFG->proxyhost
) or empty($CFG->proxybypass
)) {
9111 // Get the host part out of the url.
9112 if (!$host = parse_url( $url, PHP_URL_HOST
)) {
9116 // Get the possible bypass hosts into an array.
9117 $matches = explode( ',', $CFG->proxybypass
);
9119 // Check for a match.
9120 // (IPs need to match the left hand side and hosts the right of the url,
9121 // but we can recklessly check both as there can't be a false +ve).
9122 foreach ($matches as $match) {
9123 $match = trim($match);
9125 // Try for IP match (Left side).
9126 $lhs = substr($host, 0, strlen($match));
9127 if (strcasecmp($match, $lhs)==0) {
9131 // Try for host match (Right side).
9132 $rhs = substr($host, -strlen($match));
9133 if (strcasecmp($match, $rhs)==0) {
9143 * Check if the passed navigation is of the new style
9145 * @param mixed $navigation
9146 * @return bool true for yes false for no
9148 function is_newnav($navigation) {
9149 if (is_array($navigation) && !empty($navigation['newnav'])) {
9157 * Checks whether the given variable name is defined as a variable within the given object.
9159 * This will NOT work with stdClass objects, which have no class variables.
9161 * @param string $var The variable name
9162 * @param object $object The object to check
9165 function in_object_vars($var, $object) {
9166 $classvars = get_class_vars(get_class($object));
9167 $classvars = array_keys($classvars);
9168 return in_array($var, $classvars);
9172 * Returns an array without repeated objects.
9173 * This function is similar to array_unique, but for arrays that have objects as values
9175 * @param array $array
9176 * @param bool $keepkeyassoc
9179 function object_array_unique($array, $keepkeyassoc = true) {
9180 $duplicatekeys = array();
9183 foreach ($array as $key => $val) {
9184 // Convert objects to arrays, in_array() does not support objects.
9185 if (is_object($val)) {
9189 if (!in_array($val, $tmp)) {
9192 $duplicatekeys[] = $key;
9196 foreach ($duplicatekeys as $key) {
9197 unset($array[$key]);
9200 return $keepkeyassoc ?
$array : array_values($array);
9204 * Is a userid the primary administrator?
9206 * @param int $userid int id of user to check
9209 function is_primary_admin($userid) {
9210 $primaryadmin = get_admin();
9212 if ($userid == $primaryadmin->id
) {
9220 * Returns the site identifier
9222 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9224 function get_site_identifier() {
9226 // Check to see if it is missing. If so, initialise it.
9227 if (empty($CFG->siteidentifier
)) {
9228 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9231 return $CFG->siteidentifier
;
9235 * Check whether the given password has no more than the specified
9236 * number of consecutive identical characters.
9238 * @param string $password password to be checked against the password policy
9239 * @param integer $maxchars maximum number of consecutive identical characters
9242 function check_consecutive_identical_characters($password, $maxchars) {
9244 if ($maxchars < 1) {
9245 return true; // Zero 0 is to disable this check.
9247 if (strlen($password) <= $maxchars) {
9248 return true; // Too short to fail this test.
9252 $consecutivecount = 1;
9253 foreach (str_split($password) as $char) {
9254 if ($char != $previouschar) {
9255 $consecutivecount = 1;
9257 $consecutivecount++
;
9258 if ($consecutivecount > $maxchars) {
9259 return false; // Check failed already.
9263 $previouschar = $char;
9270 * Helper function to do partial function binding.
9271 * so we can use it for preg_replace_callback, for example
9272 * this works with php functions, user functions, static methods and class methods
9273 * it returns you a callback that you can pass on like so:
9275 * $callback = partial('somefunction', $arg1, $arg2);
9277 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9279 * $obj = new someclass();
9280 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9282 * and then the arguments that are passed through at calltime are appended to the argument list.
9284 * @param mixed $function a php callback
9285 * @param mixed $arg1,... $argv arguments to partially bind with
9286 * @return array Array callback
9288 function partial() {
9289 if (!class_exists('partial')) {
9291 * Used to manage function binding.
9292 * @copyright 2009 Penny Leach
9293 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9297 public $values = array();
9298 /** @var string The function to call as a callback. */
9302 * @param string $func
9303 * @param array $args
9305 public function __construct($func, $args) {
9306 $this->values
= $args;
9307 $this->func
= $func;
9310 * Calls the callback function.
9313 public function method() {
9314 $args = func_get_args();
9315 return call_user_func_array($this->func
, array_merge($this->values
, $args));
9319 $args = func_get_args();
9320 $func = array_shift($args);
9321 $p = new partial($func, $args);
9322 return array($p, 'method');
9326 * helper function to load up and initialise the mnet environment
9327 * this must be called before you use mnet functions.
9329 * @return mnet_environment the equivalent of old $MNET global
9331 function get_mnet_environment() {
9333 require_once($CFG->dirroot
. '/mnet/lib.php');
9334 static $instance = null;
9335 if (empty($instance)) {
9336 $instance = new mnet_environment();
9343 * during xmlrpc server code execution, any code wishing to access
9344 * information about the remote peer must use this to get it.
9346 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9348 function get_mnet_remote_client() {
9349 if (!defined('MNET_SERVER')) {
9350 debugging(get_string('notinxmlrpcserver', 'mnet'));
9353 global $MNET_REMOTE_CLIENT;
9354 if (isset($MNET_REMOTE_CLIENT)) {
9355 return $MNET_REMOTE_CLIENT;
9361 * during the xmlrpc server code execution, this will be called
9362 * to setup the object returned by {@link get_mnet_remote_client}
9364 * @param mnet_remote_client $client the client to set up
9365 * @throws moodle_exception
9367 function set_mnet_remote_client($client) {
9368 if (!defined('MNET_SERVER')) {
9369 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9371 global $MNET_REMOTE_CLIENT;
9372 $MNET_REMOTE_CLIENT = $client;
9376 * return the jump url for a given remote user
9377 * this is used for rewriting forum post links in emails, etc
9379 * @param stdclass $user the user to get the idp url for
9381 function mnet_get_idp_jump_url($user) {
9384 static $mnetjumps = array();
9385 if (!array_key_exists($user->mnethostid
, $mnetjumps)) {
9386 $idp = mnet_get_peer_host($user->mnethostid
);
9387 $idpjumppath = mnet_get_app_jumppath($idp->applicationid
);
9388 $mnetjumps[$user->mnethostid
] = $idp->wwwroot
. $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot
. '&wantsurl=';
9390 return $mnetjumps[$user->mnethostid
];
9394 * Gets the homepage to use for the current user
9396 * @return int One of HOMEPAGE_*
9398 function get_home_page() {
9401 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage
)) {
9402 if ($CFG->defaulthomepage
== HOMEPAGE_MY
) {
9405 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY
);
9408 return HOMEPAGE_SITE
;
9412 * Gets the name of a course to be displayed when showing a list of courses.
9413 * By default this is just $course->fullname but user can configure it. The
9414 * result of this function should be passed through print_string.
9415 * @param stdClass|course_in_list $course Moodle course object
9416 * @return string Display name of course (either fullname or short + fullname)
9418 function get_course_display_name_for_list($course) {
9420 if (!empty($CFG->courselistshortnames
)) {
9421 if (!($course instanceof stdClass
)) {
9422 $course = (object)convert_to_array($course);
9424 return get_string('courseextendednamedisplay', '', $course);
9426 return $course->fullname
;
9431 * The lang_string class
9433 * This special class is used to create an object representation of a string request.
9434 * It is special because processing doesn't occur until the object is first used.
9435 * The class was created especially to aid performance in areas where strings were
9436 * required to be generated but were not necessarily used.
9437 * As an example the admin tree when generated uses over 1500 strings, of which
9438 * normally only 1/3 are ever actually printed at any time.
9439 * The performance advantage is achieved by not actually processing strings that
9440 * arn't being used, as such reducing the processing required for the page.
9442 * How to use the lang_string class?
9443 * There are two methods of using the lang_string class, first through the
9444 * forth argument of the get_string function, and secondly directly.
9445 * The following are examples of both.
9446 * 1. Through get_string calls e.g.
9447 * $string = get_string($identifier, $component, $a, true);
9448 * $string = get_string('yes', 'moodle', null, true);
9449 * 2. Direct instantiation
9450 * $string = new lang_string($identifier, $component, $a, $lang);
9451 * $string = new lang_string('yes');
9453 * How do I use a lang_string object?
9454 * The lang_string object makes use of a magic __toString method so that you
9455 * are able to use the object exactly as you would use a string in most cases.
9456 * This means you are able to collect it into a variable and then directly
9457 * echo it, or concatenate it into another string, or similar.
9458 * The other thing you can do is manually get the string by calling the
9459 * lang_strings out method e.g.
9460 * $string = new lang_string('yes');
9462 * Also worth noting is that the out method can take one argument, $lang which
9463 * allows the developer to change the language on the fly.
9465 * When should I use a lang_string object?
9466 * The lang_string object is designed to be used in any situation where a
9467 * string may not be needed, but needs to be generated.
9468 * The admin tree is a good example of where lang_string objects should be
9470 * A more practical example would be any class that requries strings that may
9471 * not be printed (after all classes get renderer by renderers and who knows
9472 * what they will do ;))
9474 * When should I not use a lang_string object?
9475 * Don't use lang_strings when you are going to use a string immediately.
9476 * There is no need as it will be processed immediately and there will be no
9477 * advantage, and in fact perhaps a negative hit as a class has to be
9478 * instantiated for a lang_string object, however get_string won't require
9482 * 1. You cannot use a lang_string object as an array offset. Doing so will
9483 * result in PHP throwing an error. (You can use it as an object property!)
9487 * @copyright 2011 Sam Hemelryk
9488 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9492 /** @var string The strings identifier */
9493 protected $identifier;
9494 /** @var string The strings component. Default '' */
9495 protected $component = '';
9496 /** @var array|stdClass Any arguments required for the string. Default null */
9497 protected $a = null;
9498 /** @var string The language to use when processing the string. Default null */
9499 protected $lang = null;
9501 /** @var string The processed string (once processed) */
9502 protected $string = null;
9505 * A special boolean. If set to true then the object has been woken up and
9506 * cannot be regenerated. If this is set then $this->string MUST be used.
9509 protected $forcedstring = false;
9512 * Constructs a lang_string object
9514 * This function should do as little processing as possible to ensure the best
9515 * performance for strings that won't be used.
9517 * @param string $identifier The strings identifier
9518 * @param string $component The strings component
9519 * @param stdClass|array $a Any arguments the string requires
9520 * @param string $lang The language to use when processing the string.
9521 * @throws coding_exception
9523 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9524 if (empty($component)) {
9525 $component = 'moodle';
9528 $this->identifier
= $identifier;
9529 $this->component
= $component;
9530 $this->lang
= $lang;
9532 // We MUST duplicate $a to ensure that it if it changes by reference those
9533 // changes are not carried across.
9534 // To do this we always ensure $a or its properties/values are strings
9535 // and that any properties/values that arn't convertable are forgotten.
9537 if (is_scalar($a)) {
9539 } else if ($a instanceof lang_string
) {
9540 $this->a
= $a->out();
9541 } else if (is_object($a) or is_array($a)) {
9544 foreach ($a as $key => $value) {
9545 // Make sure conversion errors don't get displayed (results in '').
9546 if (is_array($value)) {
9547 $this->a
[$key] = '';
9548 } else if (is_object($value)) {
9549 if (method_exists($value, '__toString')) {
9550 $this->a
[$key] = $value->__toString();
9552 $this->a
[$key] = '';
9555 $this->a
[$key] = (string)$value;
9561 if (debugging(false, DEBUG_DEVELOPER
)) {
9562 if (clean_param($this->identifier
, PARAM_STRINGID
) == '') {
9563 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9565 if (!empty($this->component
) && clean_param($this->component
, PARAM_COMPONENT
) == '') {
9566 throw new coding_exception('Invalid string compontent. Please check your string definition');
9568 if (!get_string_manager()->string_exists($this->identifier
, $this->component
)) {
9569 debugging('String does not exist. Please check your string definition for '.$this->identifier
.'/'.$this->component
, DEBUG_DEVELOPER
);
9575 * Processes the string.
9577 * This function actually processes the string, stores it in the string property
9578 * and then returns it.
9579 * You will notice that this function is VERY similar to the get_string method.
9580 * That is because it is pretty much doing the same thing.
9581 * However as this function is an upgrade it isn't as tolerant to backwards
9585 * @throws coding_exception
9587 protected function get_string() {
9590 // Check if we need to process the string.
9591 if ($this->string === null) {
9592 // Check the quality of the identifier.
9593 if ($CFG->debugdeveloper
&& clean_param($this->identifier
, PARAM_STRINGID
) === '') {
9594 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
);
9597 // Process the string.
9598 $this->string = get_string_manager()->get_string($this->identifier
, $this->component
, $this->a
, $this->lang
);
9599 // Debugging feature lets you display string identifier and component.
9600 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
9601 $this->string .= ' {' . $this->identifier
. '/' . $this->component
. '}';
9604 // Return the string.
9605 return $this->string;
9609 * Returns the string
9611 * @param string $lang The langauge to use when processing the string
9614 public function out($lang = null) {
9615 if ($lang !== null && $lang != $this->lang
&& ($this->lang
== null && $lang != current_language())) {
9616 if ($this->forcedstring
) {
9617 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang
.' used)', DEBUG_DEVELOPER
);
9618 return $this->get_string();
9620 $translatedstring = new lang_string($this->identifier
, $this->component
, $this->a
, $lang);
9621 return $translatedstring->out();
9623 return $this->get_string();
9627 * Magic __toString method for printing a string
9631 public function __toString() {
9632 return $this->get_string();
9636 * Magic __set_state method used for var_export
9640 public function __set_state() {
9641 return $this->get_string();
9645 * Prepares the lang_string for sleep and stores only the forcedstring and
9646 * string properties... the string cannot be regenerated so we need to ensure
9647 * it is generated for this.
9651 public function __sleep() {
9652 $this->get_string();
9653 $this->forcedstring
= true;
9654 return array('forcedstring', 'string', 'lang');