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 if module supports outcomes */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
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.')');
626 if (!isset($default)) {
630 // POST has precedence.
631 if (isset($_POST[$parname])) {
632 $param = $_POST[$parname];
633 } else if (isset($_GET[$parname])) {
634 $param = $_GET[$parname];
639 if (is_array($param)) {
640 debugging('Invalid array parameter detected in required_param(): '.$parname);
641 // TODO: switch to $default in Moodle 2.3.
642 return optional_param_array($parname, $default, $type);
645 return clean_param($param, $type);
649 * Returns a particular array value for the named variable, taken from
650 * POST or GET, otherwise returning a given default.
652 * This function should be used to initialise all optional values
653 * in a script that are based on parameters. Usually it will be
655 * $ids = optional_param('id', array(), PARAM_INT);
657 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
659 * @param string $parname the name of the page parameter we want
660 * @param mixed $default the default value to return if nothing is found
661 * @param string $type expected type of parameter
663 * @throws coding_exception
665 function optional_param_array($parname, $default, $type) {
666 if (func_num_args() != 3 or empty($parname) or empty($type)) {
667 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
670 // POST has precedence.
671 if (isset($_POST[$parname])) {
672 $param = $_POST[$parname];
673 } else if (isset($_GET[$parname])) {
674 $param = $_GET[$parname];
678 if (!is_array($param)) {
679 debugging('optional_param_array() expects array parameters only: '.$parname);
684 foreach ($param as $key => $value) {
685 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
686 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
689 $result[$key] = clean_param($value, $type);
696 * Strict validation of parameter values, the values are only converted
697 * to requested PHP type. Internally it is using clean_param, the values
698 * before and after cleaning must be equal - otherwise
699 * an invalid_parameter_exception is thrown.
700 * Objects and classes are not accepted.
702 * @param mixed $param
703 * @param string $type PARAM_ constant
704 * @param bool $allownull are nulls valid value?
705 * @param string $debuginfo optional debug information
706 * @return mixed the $param value converted to PHP type
707 * @throws invalid_parameter_exception if $param is not of given type
709 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED
, $debuginfo='') {
710 if (is_null($param)) {
711 if ($allownull == NULL_ALLOWED
) {
714 throw new invalid_parameter_exception($debuginfo);
717 if (is_array($param) or is_object($param)) {
718 throw new invalid_parameter_exception($debuginfo);
721 $cleaned = clean_param($param, $type);
723 if ($type == PARAM_FLOAT
) {
724 // Do not detect precision loss here.
725 if (is_float($param) or is_int($param)) {
727 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
728 throw new invalid_parameter_exception($debuginfo);
730 } else if ((string)$param !== (string)$cleaned) {
731 // Conversion to string is usually lossless.
732 throw new invalid_parameter_exception($debuginfo);
739 * Makes sure array contains only the allowed types, this function does not validate array key names!
742 * $options = clean_param($options, PARAM_INT);
745 * @param array $param the variable array we are cleaning
746 * @param string $type expected format of param after cleaning.
747 * @param bool $recursive clean recursive arrays
749 * @throws coding_exception
751 function clean_param_array(array $param = null, $type, $recursive = false) {
752 // Convert null to empty array.
753 $param = (array)$param;
754 foreach ($param as $key => $value) {
755 if (is_array($value)) {
757 $param[$key] = clean_param_array($value, $type, true);
759 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
762 $param[$key] = clean_param($value, $type);
769 * Used by {@link optional_param()} and {@link required_param()} to
770 * clean the variables and/or cast to specific types, based on
773 * $course->format = clean_param($course->format, PARAM_ALPHA);
774 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
777 * @param mixed $param the variable we are cleaning
778 * @param string $type expected format of param after cleaning.
780 * @throws coding_exception
782 function clean_param($param, $type) {
785 if (is_array($param)) {
786 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
787 } else if (is_object($param)) {
788 if (method_exists($param, '__toString')) {
789 $param = $param->__toString();
791 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
797 // No cleaning at all.
798 $param = fix_utf8($param);
801 case PARAM_RAW_TRIMMED
:
802 // No cleaning, but strip leading and trailing whitespace.
803 $param = fix_utf8($param);
807 // General HTML cleaning, try to use more specific type if possible this is deprecated!
808 // Please use more specific type instead.
809 if (is_numeric($param)) {
812 $param = fix_utf8($param);
813 // Sweep for scripts, etc.
814 return clean_text($param);
816 case PARAM_CLEANHTML
:
817 // Clean html fragment.
818 $param = fix_utf8($param);
819 // Sweep for scripts, etc.
820 $param = clean_text($param, FORMAT_HTML
);
824 // Convert to integer.
829 return (float)$param;
832 // Remove everything not `a-z`.
833 return preg_replace('/[^a-zA-Z]/i', '', $param);
836 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
837 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
840 // Remove everything not `a-zA-Z0-9`.
841 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
843 case PARAM_ALPHANUMEXT
:
844 // Remove everything not `a-zA-Z0-9_-`.
845 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
848 // Remove everything not `0-9,`.
849 return preg_replace('/[^0-9,]/i', '', $param);
852 // Convert to 1 or 0.
853 $tempstr = strtolower($param);
854 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
856 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
859 $param = empty($param) ?
0 : 1;
865 $param = fix_utf8($param);
866 return strip_tags($param);
869 // Leave only tags needed for multilang.
870 $param = fix_utf8($param);
871 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
872 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
874 if (strpos($param, '</lang>') !== false) {
875 // Old and future mutilang syntax.
876 $param = strip_tags($param, '<lang>');
877 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
881 foreach ($matches[0] as $match) {
882 if ($match === '</lang>') {
890 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
901 } else if (strpos($param, '</span>') !== false) {
902 // Current problematic multilang syntax.
903 $param = strip_tags($param, '<span>');
904 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
908 foreach ($matches[0] as $match) {
909 if ($match === '</span>') {
917 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
929 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
930 return strip_tags($param);
932 case PARAM_COMPONENT
:
933 // We do not want any guessing here, either the name is correct or not
934 // please note only normalised component names are accepted.
935 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
938 if (strpos($param, '__') !== false) {
941 if (strpos($param, 'mod_') === 0) {
942 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
943 if (substr_count($param, '_') != 1) {
951 // We do not want any guessing here, either the name is correct or not.
952 if (!is_valid_plugin_name($param)) {
958 // Remove everything not a-zA-Z0-9_- .
959 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
962 // Remove everything not a-zA-Z0-9/_- .
963 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
966 // Strip all suspicious characters from filename.
967 $param = fix_utf8($param);
968 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
969 if ($param === '.' ||
$param === '..') {
975 // Strip all suspicious characters from file path.
976 $param = fix_utf8($param);
977 $param = str_replace('\\', '/', $param);
979 // Explode the path and clean each element using the PARAM_FILE rules.
980 $breadcrumb = explode('/', $param);
981 foreach ($breadcrumb as $key => $crumb) {
982 if ($crumb === '.' && $key === 0) {
983 // Special condition to allow for relative current path such as ./currentdirfile.txt.
985 $crumb = clean_param($crumb, PARAM_FILE
);
987 $breadcrumb[$key] = $crumb;
989 $param = implode('/', $breadcrumb);
991 // Remove multiple current path (./././) and multiple slashes (///).
992 $param = preg_replace('~//+~', '/', $param);
993 $param = preg_replace('~/(\./)+~', '/', $param);
997 // Allow FQDN or IPv4 dotted quad.
998 $param = preg_replace('/[^\.\d\w-]/', '', $param );
999 // Match ipv4 dotted quad.
1000 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1001 // Confirm values are ok.
1002 if ( $match[0] > 255
1005 ||
$match[4] > 255 ) {
1006 // Hmmm, what kind of dotted quad is this?
1009 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1010 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1011 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1013 // All is ok - $param is respected.
1020 case PARAM_URL
: // Allow safe ftp, http, mailto urls.
1021 $param = fix_utf8($param);
1022 include_once($CFG->dirroot
. '/lib/validateurlsyntax.php');
1023 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1024 // All is ok, param is respected.
1031 case PARAM_LOCALURL
:
1032 // Allow http absolute, root relative and relative URLs within wwwroot.
1033 $param = clean_param($param, PARAM_URL
);
1034 if (!empty($param)) {
1035 if (preg_match(':^/:', $param)) {
1036 // Root-relative, ok!
1037 } else if (preg_match('/^'.preg_quote($CFG->wwwroot
, '/').'/i', $param)) {
1038 // Absolute, and matches our wwwroot.
1040 // Relative - let's make sure there are no tricks.
1041 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1051 $param = trim($param);
1052 // PEM formatted strings may contain letters/numbers and the symbols:
1056 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1057 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1058 list($wholething, $body) = $matches;
1059 unset($wholething, $matches);
1060 $b64 = clean_param($body, PARAM_BASE64
);
1062 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1070 if (!empty($param)) {
1071 // PEM formatted strings may contain letters/numbers and the symbols
1075 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1078 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY
);
1079 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1080 // than (or equal to) 64 characters long.
1081 for ($i=0, $j=count($lines); $i < $j; $i++
) {
1083 if (64 < strlen($lines[$i])) {
1089 if (64 != strlen($lines[$i])) {
1093 return implode("\n", $lines);
1099 $param = fix_utf8($param);
1100 // Please note it is not safe to use the tag name directly anywhere,
1101 // it must be processed with s(), urlencode() before embedding anywhere.
1102 // Remove some nasties.
1103 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1104 // Convert many whitespace chars into one.
1105 $param = preg_replace('/\s+/', ' ', $param);
1106 $param = core_text
::substr(trim($param), 0, TAG_MAX_LENGTH
);
1110 $param = fix_utf8($param);
1111 $tags = explode(',', $param);
1113 foreach ($tags as $tag) {
1114 $res = clean_param($tag, PARAM_TAG
);
1120 return implode(',', $result);
1125 case PARAM_CAPABILITY
:
1126 if (get_capability_info($param)) {
1132 case PARAM_PERMISSION
:
1133 $param = (int)$param;
1134 if (in_array($param, array(CAP_INHERIT
, CAP_ALLOW
, CAP_PREVENT
, CAP_PROHIBIT
))) {
1141 $param = clean_param($param, PARAM_PLUGIN
);
1142 if (empty($param)) {
1144 } else if (exists_auth_plugin($param)) {
1151 $param = clean_param($param, PARAM_SAFEDIR
);
1152 if (get_string_manager()->translation_exists($param)) {
1155 // Specified language is not installed or param malformed.
1160 $param = clean_param($param, PARAM_PLUGIN
);
1161 if (empty($param)) {
1163 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1165 } else if (!empty($CFG->themedir
) and file_exists("$CFG->themedir/$param/config.php")) {
1168 // Specified theme is not installed.
1172 case PARAM_USERNAME
:
1173 $param = fix_utf8($param);
1174 $param = str_replace(" " , "", $param);
1175 // Convert uppercase to lowercase MDL-16919.
1176 $param = core_text
::strtolower($param);
1177 if (empty($CFG->extendedusernamechars
)) {
1178 // Regular expression, eliminate all chars EXCEPT:
1179 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1180 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1185 $param = fix_utf8($param);
1186 if (validate_email($param)) {
1192 case PARAM_STRINGID
:
1193 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1199 case PARAM_TIMEZONE
:
1200 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1201 $param = fix_utf8($param);
1202 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1203 if (preg_match($timezonepattern, $param)) {
1210 // Doh! throw error, switched parameters in optional_param or another serious problem.
1211 print_error("unknownparamtype", '', '', $type);
1216 * Makes sure the data is using valid utf8, invalid characters are discarded.
1218 * Note: this function is not intended for full objects with methods and private properties.
1220 * @param mixed $value
1221 * @return mixed with proper utf-8 encoding
1223 function fix_utf8($value) {
1224 if (is_null($value) or $value === '') {
1227 } else if (is_string($value)) {
1228 if ((string)(int)$value === $value) {
1232 // No null bytes expected in our data, so let's remove it.
1233 $value = str_replace("\0", '', $value);
1235 // Note: this duplicates min_fix_utf8() intentionally.
1236 static $buggyiconv = null;
1237 if ($buggyiconv === null) {
1238 $buggyiconv = (!function_exists('iconv') or @iconv
('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1242 if (function_exists('mb_convert_encoding')) {
1243 $subst = mb_substitute_character();
1244 mb_substitute_character('');
1245 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1246 mb_substitute_character($subst);
1249 // Warn admins on admin/index.php page.
1254 $result = @iconv
('UTF-8', 'UTF-8//IGNORE', $value);
1259 } else if (is_array($value)) {
1260 foreach ($value as $k => $v) {
1261 $value[$k] = fix_utf8($v);
1265 } else if (is_object($value)) {
1266 // Do not modify original.
1267 $value = clone($value);
1268 foreach ($value as $k => $v) {
1269 $value->$k = fix_utf8($v);
1274 // This is some other type, no utf-8 here.
1280 * Return true if given value is integer or string with integer value
1282 * @param mixed $value String or Int
1283 * @return bool true if number, false if not
1285 function is_number($value) {
1286 if (is_int($value)) {
1288 } else if (is_string($value)) {
1289 return ((string)(int)$value) === $value;
1296 * Returns host part from url.
1298 * @param string $url full url
1299 * @return string host, null if not found
1301 function get_host_from_url($url) {
1302 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1310 * Tests whether anything was returned by text editor
1312 * This function is useful for testing whether something you got back from
1313 * the HTML editor actually contains anything. Sometimes the HTML editor
1314 * appear to be empty, but actually you get back a <br> tag or something.
1316 * @param string $string a string containing HTML.
1317 * @return boolean does the string contain any actual content - that is text,
1318 * images, objects, etc.
1320 function html_is_blank($string) {
1321 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1325 * Set a key in global configuration
1327 * Set a key/value pair in both this session's {@link $CFG} global variable
1328 * and in the 'config' database table for future sessions.
1330 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1331 * In that case it doesn't affect $CFG.
1333 * A NULL value will delete the entry.
1335 * NOTE: this function is called from lib/db/upgrade.php
1337 * @param string $name the key to set
1338 * @param string $value the value to set (without magic quotes)
1339 * @param string $plugin (optional) the plugin scope, default null
1340 * @return bool true or exception
1342 function set_config($name, $value, $plugin=null) {
1345 if (empty($plugin)) {
1346 if (!array_key_exists($name, $CFG->config_php_settings
)) {
1347 // So it's defined for this invocation at least.
1348 if (is_null($value)) {
1351 // Settings from db are always strings.
1352 $CFG->$name = (string)$value;
1356 if ($DB->get_field('config', 'name', array('name' => $name))) {
1357 if ($value === null) {
1358 $DB->delete_records('config', array('name' => $name));
1360 $DB->set_field('config', 'value', $value, array('name' => $name));
1363 if ($value !== null) {
1364 $config = new stdClass();
1365 $config->name
= $name;
1366 $config->value
= $value;
1367 $DB->insert_record('config', $config, false);
1370 if ($name === 'siteidentifier') {
1371 cache_helper
::update_site_identifier($value);
1373 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1376 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1377 if ($value===null) {
1378 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1380 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1383 if ($value !== null) {
1384 $config = new stdClass();
1385 $config->plugin
= $plugin;
1386 $config->name
= $name;
1387 $config->value
= $value;
1388 $DB->insert_record('config_plugins', $config, false);
1391 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
1398 * Get configuration values from the global config table
1399 * or the config_plugins table.
1401 * If called with one parameter, it will load all the config
1402 * variables for one plugin, and return them as an object.
1404 * If called with 2 parameters it will return a string single
1405 * value or false if the value is not found.
1407 * NOTE: this function is called from lib/db/upgrade.php
1409 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1410 * that we need only fetch it once per request.
1411 * @param string $plugin full component name
1412 * @param string $name default null
1413 * @return mixed hash-like object or single value, return false no config found
1414 * @throws dml_exception
1416 function get_config($plugin, $name = null) {
1419 static $siteidentifier = null;
1421 if ($plugin === 'moodle' ||
$plugin === 'core' ||
empty($plugin)) {
1422 $forced =& $CFG->config_php_settings
;
1426 if (array_key_exists($plugin, $CFG->forced_plugin_settings
)) {
1427 $forced =& $CFG->forced_plugin_settings
[$plugin];
1434 if ($siteidentifier === null) {
1436 // This may fail during installation.
1437 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1438 // install the database.
1439 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1440 } catch (dml_exception
$ex) {
1441 // Set siteidentifier to false. We don't want to trip this continually.
1442 $siteidentifier = false;
1447 if (!empty($name)) {
1448 if (array_key_exists($name, $forced)) {
1449 return (string)$forced[$name];
1450 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1451 return $siteidentifier;
1455 $cache = cache
::make('core', 'config');
1456 $result = $cache->get($plugin);
1457 if ($result === false) {
1458 // The user is after a recordset.
1460 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1462 // This part is not really used any more, but anyway...
1463 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1465 $cache->set($plugin, $result);
1468 if (!empty($name)) {
1469 if (array_key_exists($name, $result)) {
1470 return $result[$name];
1475 if ($plugin === 'core') {
1476 $result['siteidentifier'] = $siteidentifier;
1479 foreach ($forced as $key => $value) {
1480 if (is_null($value) or is_array($value) or is_object($value)) {
1481 // We do not want any extra mess here, just real settings that could be saved in db.
1482 unset($result[$key]);
1484 // Convert to string as if it went through the DB.
1485 $result[$key] = (string)$value;
1489 return (object)$result;
1493 * Removes a key from global configuration.
1495 * NOTE: this function is called from lib/db/upgrade.php
1497 * @param string $name the key to set
1498 * @param string $plugin (optional) the plugin scope
1499 * @return boolean whether the operation succeeded.
1501 function unset_config($name, $plugin=null) {
1504 if (empty($plugin)) {
1506 $DB->delete_records('config', array('name' => $name));
1507 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1509 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1510 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
1517 * Remove all the config variables for a given plugin.
1519 * NOTE: this function is called from lib/db/upgrade.php
1521 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1522 * @return boolean whether the operation succeeded.
1524 function unset_all_config_for_plugin($plugin) {
1526 // Delete from the obvious config_plugins first.
1527 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1528 // Next delete any suspect settings from config.
1529 $like = $DB->sql_like('name', '?', true, true, false, '|');
1530 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1531 $DB->delete_records_select('config', $like, $params);
1532 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1533 cache_helper
::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1539 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1541 * All users are verified if they still have the necessary capability.
1543 * @param string $value the value of the config setting.
1544 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1545 * @param bool $includeadmins include administrators.
1546 * @return array of user objects.
1548 function get_users_from_config($value, $capability, $includeadmins = true) {
1549 if (empty($value) or $value === '$@NONE@$') {
1553 // We have to make sure that users still have the necessary capability,
1554 // it should be faster to fetch them all first and then test if they are present
1555 // instead of validating them one-by-one.
1556 $users = get_users_by_capability(context_system
::instance(), $capability);
1557 if ($includeadmins) {
1558 $admins = get_admins();
1559 foreach ($admins as $admin) {
1560 $users[$admin->id
] = $admin;
1564 if ($value === '$@ALL@$') {
1568 $result = array(); // Result in correct order.
1569 $allowed = explode(',', $value);
1570 foreach ($allowed as $uid) {
1571 if (isset($users[$uid])) {
1572 $user = $users[$uid];
1573 $result[$user->id
] = $user;
1582 * Invalidates browser caches and cached data in temp.
1584 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1585 * {@link phpunit_util::reset_dataroot()}
1589 function purge_all_caches() {
1592 reset_text_filters_cache();
1593 js_reset_all_caches();
1594 theme_reset_all_caches();
1595 get_string_manager()->reset_caches();
1596 core_text
::reset_caches();
1597 if (class_exists('core_plugin_manager')) {
1598 core_plugin_manager
::reset_caches();
1601 // Bump up cacherev field for all courses.
1603 increment_revision_number('course', 'cacherev', '');
1604 } catch (moodle_exception
$e) {
1605 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1608 $DB->reset_caches();
1609 cache_helper
::purge_all();
1611 // Purge all other caches: rss, simplepie, etc.
1612 remove_dir($CFG->cachedir
.'', true);
1614 // Make sure cache dir is writable, throws exception if not.
1615 make_cache_directory('');
1617 // This is the only place where we purge local caches, we are only adding files there.
1618 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1619 remove_dir($CFG->localcachedir
, true);
1620 set_config('localcachedirpurged', time());
1621 make_localcache_directory('', true);
1622 \core\task\manager
::clear_static_caches();
1626 * Get volatile flags
1628 * @param string $type
1629 * @param int $changedsince default null
1630 * @return array records array
1632 function get_cache_flags($type, $changedsince = null) {
1635 $params = array('type' => $type, 'expiry' => time());
1636 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1637 if ($changedsince !== null) {
1638 $params['changedsince'] = $changedsince;
1639 $sqlwhere .= " AND timemodified > :changedsince";
1642 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1643 foreach ($flags as $flag) {
1644 $cf[$flag->name
] = $flag->value
;
1651 * Get volatile flags
1653 * @param string $type
1654 * @param string $name
1655 * @param int $changedsince default null
1656 * @return string|false The cache flag value or false
1658 function get_cache_flag($type, $name, $changedsince=null) {
1661 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1663 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1664 if ($changedsince !== null) {
1665 $params['changedsince'] = $changedsince;
1666 $sqlwhere .= " AND timemodified > :changedsince";
1669 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1673 * Set a volatile flag
1675 * @param string $type the "type" namespace for the key
1676 * @param string $name the key to set
1677 * @param string $value the value to set (without magic quotes) - null will remove the flag
1678 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1679 * @return bool Always returns true
1681 function set_cache_flag($type, $name, $value, $expiry = null) {
1684 $timemodified = time();
1685 if ($expiry === null ||
$expiry < $timemodified) {
1686 $expiry = $timemodified +
24 * 60 * 60;
1688 $expiry = (int)$expiry;
1691 if ($value === null) {
1692 unset_cache_flag($type, $name);
1696 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE
)) {
1697 // This is a potential problem in DEBUG_DEVELOPER.
1698 if ($f->value
== $value and $f->expiry
== $expiry and $f->timemodified
== $timemodified) {
1699 return true; // No need to update.
1702 $f->expiry
= $expiry;
1703 $f->timemodified
= $timemodified;
1704 $DB->update_record('cache_flags', $f);
1706 $f = new stdClass();
1707 $f->flagtype
= $type;
1710 $f->expiry
= $expiry;
1711 $f->timemodified
= $timemodified;
1712 $DB->insert_record('cache_flags', $f);
1718 * Removes a single volatile flag
1720 * @param string $type the "type" namespace for the key
1721 * @param string $name the key to set
1724 function unset_cache_flag($type, $name) {
1726 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1731 * Garbage-collect volatile flags
1733 * @return bool Always returns true
1735 function gc_cache_flags() {
1737 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1741 // USER PREFERENCE API.
1744 * Refresh user preference cache. This is used most often for $USER
1745 * object that is stored in session, but it also helps with performance in cron script.
1747 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1750 * @category preference
1752 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1753 * @param int $cachelifetime Cache life time on the current page (in seconds)
1754 * @throws coding_exception
1757 function check_user_preferences_loaded(stdClass
$user, $cachelifetime = 120) {
1759 // Static cache, we need to check on each page load, not only every 2 minutes.
1760 static $loadedusers = array();
1762 if (!isset($user->id
)) {
1763 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1766 if (empty($user->id
) or isguestuser($user->id
)) {
1767 // No permanent storage for not-logged-in users and guest.
1768 if (!isset($user->preference
)) {
1769 $user->preference
= array();
1776 if (isset($loadedusers[$user->id
]) and isset($user->preference
) and isset($user->preference
['_lastloaded'])) {
1777 // Already loaded at least once on this page. Are we up to date?
1778 if ($user->preference
['_lastloaded'] +
$cachelifetime > $timenow) {
1779 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1782 } else if (!get_cache_flag('userpreferenceschanged', $user->id
, $user->preference
['_lastloaded'])) {
1783 // No change since the lastcheck on this page.
1784 $user->preference
['_lastloaded'] = $timenow;
1789 // OK, so we have to reload all preferences.
1790 $loadedusers[$user->id
] = true;
1791 $user->preference
= $DB->get_records_menu('user_preferences', array('userid' => $user->id
), '', 'name,value'); // All values.
1792 $user->preference
['_lastloaded'] = $timenow;
1796 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1798 * NOTE: internal function, do not call from other code.
1802 * @param integer $userid the user whose prefs were changed.
1804 function mark_user_preferences_changed($userid) {
1807 if (empty($userid) or isguestuser($userid)) {
1808 // No cache flags for guest and not-logged-in users.
1812 set_cache_flag('userpreferenceschanged', $userid, 1, time() +
$CFG->sessiontimeout
);
1816 * Sets a preference for the specified user.
1818 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1821 * @category preference
1823 * @param string $name The key to set as preference for the specified user
1824 * @param string $value The value to set for the $name key in the specified user's
1825 * record, null means delete current value.
1826 * @param stdClass|int|null $user A moodle user object or id, null means current user
1827 * @throws coding_exception
1828 * @return bool Always true or exception
1830 function set_user_preference($name, $value, $user = null) {
1833 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1834 throw new coding_exception('Invalid preference name in set_user_preference() call');
1837 if (is_null($value)) {
1838 // Null means delete current.
1839 return unset_user_preference($name, $user);
1840 } else if (is_object($value)) {
1841 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1842 } else if (is_array($value)) {
1843 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1845 // Value column maximum length is 1333 characters.
1846 $value = (string)$value;
1847 if (core_text
::strlen($value) > 1333) {
1848 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1851 if (is_null($user)) {
1853 } else if (isset($user->id
)) {
1854 // It is a valid object.
1855 } else if (is_numeric($user)) {
1856 $user = (object)array('id' => (int)$user);
1858 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1861 check_user_preferences_loaded($user);
1863 if (empty($user->id
) or isguestuser($user->id
)) {
1864 // No permanent storage for not-logged-in users and guest.
1865 $user->preference
[$name] = $value;
1869 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => $name))) {
1870 if ($preference->value
=== $value and isset($user->preference
[$name]) and $user->preference
[$name] === $value) {
1871 // Preference already set to this value.
1874 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id
));
1877 $preference = new stdClass();
1878 $preference->userid
= $user->id
;
1879 $preference->name
= $name;
1880 $preference->value
= $value;
1881 $DB->insert_record('user_preferences', $preference);
1884 // Update value in cache.
1885 $user->preference
[$name] = $value;
1887 // Set reload flag for other sessions.
1888 mark_user_preferences_changed($user->id
);
1894 * Sets a whole array of preferences for the current user
1896 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1899 * @category preference
1901 * @param array $prefarray An array of key/value pairs to be set
1902 * @param stdClass|int|null $user A moodle user object or id, null means current user
1903 * @return bool Always true or exception
1905 function set_user_preferences(array $prefarray, $user = null) {
1906 foreach ($prefarray as $name => $value) {
1907 set_user_preference($name, $value, $user);
1913 * Unsets a preference completely by deleting it from the database
1915 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1918 * @category preference
1920 * @param string $name The key to unset as preference for the specified user
1921 * @param stdClass|int|null $user A moodle user object or id, null means current user
1922 * @throws coding_exception
1923 * @return bool Always true or exception
1925 function unset_user_preference($name, $user = null) {
1928 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1929 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1932 if (is_null($user)) {
1934 } else if (isset($user->id
)) {
1935 // It is a valid object.
1936 } else if (is_numeric($user)) {
1937 $user = (object)array('id' => (int)$user);
1939 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1942 check_user_preferences_loaded($user);
1944 if (empty($user->id
) or isguestuser($user->id
)) {
1945 // No permanent storage for not-logged-in user and guest.
1946 unset($user->preference
[$name]);
1951 $DB->delete_records('user_preferences', array('userid' => $user->id
, 'name' => $name));
1953 // Delete the preference from cache.
1954 unset($user->preference
[$name]);
1956 // Set reload flag for other sessions.
1957 mark_user_preferences_changed($user->id
);
1963 * Used to fetch user preference(s)
1965 * If no arguments are supplied this function will return
1966 * all of the current user preferences as an array.
1968 * If a name is specified then this function
1969 * attempts to return that particular preference value. If
1970 * none is found, then the optional value $default is returned,
1973 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1976 * @category preference
1978 * @param string $name Name of the key to use in finding a preference value
1979 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1980 * @param stdClass|int|null $user A moodle user object or id, null means current user
1981 * @throws coding_exception
1982 * @return string|mixed|null A string containing the value of a single preference. An
1983 * array with all of the preferences or null
1985 function get_user_preferences($name = null, $default = null, $user = null) {
1988 if (is_null($name)) {
1990 } else if (is_numeric($name) or $name === '_lastloaded') {
1991 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1994 if (is_null($user)) {
1996 } else if (isset($user->id
)) {
1997 // Is a valid object.
1998 } else if (is_numeric($user)) {
1999 $user = (object)array('id' => (int)$user);
2001 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2004 check_user_preferences_loaded($user);
2008 return $user->preference
;
2009 } else if (isset($user->preference
[$name])) {
2010 // The single string value.
2011 return $user->preference
[$name];
2013 // Default value (null if not specified).
2018 // FUNCTIONS FOR HANDLING TIME.
2021 * Given date parts in user time produce a GMT timestamp.
2025 * @param int $year The year part to create timestamp of
2026 * @param int $month The month part to create timestamp of
2027 * @param int $day The day part to create timestamp of
2028 * @param int $hour The hour part to create timestamp of
2029 * @param int $minute The minute part to create timestamp of
2030 * @param int $second The second part to create timestamp of
2031 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2032 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2033 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2034 * applied only if timezone is 99 or string.
2035 * @return int GMT timestamp
2037 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2039 // Save input timezone, required for dst offset check.
2040 $passedtimezone = $timezone;
2042 $timezone = get_user_timezone_offset($timezone);
2044 if (abs($timezone) > 13) {
2046 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2048 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2049 $time = usertime($time, $timezone);
2051 // Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
2052 if ($applydst && ((99 == $passedtimezone) ||
!is_numeric($passedtimezone))) {
2053 $time -= dst_offset_on($time, $passedtimezone);
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 * This function does not do any calculation regarding the user preferences and should
2179 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2180 * to differentiate the use of server time or not (strftime() against gmstrftime()).
2182 * @param int $date the timestamp.
2183 * @param string $format strftime format.
2184 * @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2185 * @return string the formatted date/time.
2186 * @since Moodle 2.3.3
2188 function date_format_string($date, $format, $tz = 99) {
2191 $localewincharset = null;
2192 // Get the calendar type user is using.
2193 if ($CFG->ostype
== 'WINDOWS') {
2194 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2195 $localewincharset = $calendartype->locale_win_charset();
2198 if (abs($tz) > 13) {
2199 if ($localewincharset) {
2200 $format = core_text
::convert($format, 'utf-8', $localewincharset);
2201 $datestring = strftime($format, $date);
2202 $datestring = core_text
::convert($datestring, $localewincharset, 'utf-8');
2204 $datestring = strftime($format, $date);
2207 if ($localewincharset) {
2208 $format = core_text
::convert($format, 'utf-8', $localewincharset);
2209 $datestring = gmstrftime($format, $date);
2210 $datestring = core_text
::convert($datestring, $localewincharset, 'utf-8');
2212 $datestring = gmstrftime($format, $date);
2219 * Given a $time timestamp in GMT (seconds since epoch),
2220 * returns an array that represents the date in user time
2225 * @param int $time Timestamp in GMT
2226 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2227 * dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
2228 * @return array An array that represents the date in user time
2230 function usergetdate($time, $timezone=99) {
2232 // Save input timezone, required for dst offset check.
2233 $passedtimezone = $timezone;
2235 $timezone = get_user_timezone_offset($timezone);
2237 if (abs($timezone) > 13) {
2239 return getdate($time);
2242 // Add daylight saving offset for string timezones only, as we can't get dst for
2243 // float values. if timezone is 99 (user default timezone), then try update dst.
2244 if ($passedtimezone == 99 ||
!is_numeric($passedtimezone)) {
2245 $time +
= dst_offset_on($time, $passedtimezone);
2248 $time +
= intval((float)$timezone * HOURSECS
);
2250 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2252 // Be careful to ensure the returned array matches that produced by getdate() above.
2255 $getdate['weekday'],
2262 $getdate['minutes'],
2264 ) = explode('_', $datestring);
2266 // Set correct datatype to match with getdate().
2267 $getdate['seconds'] = (int)$getdate['seconds'];
2268 $getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
2269 $getdate['year'] = (int)$getdate['year'];
2270 $getdate['mon'] = (int)$getdate['mon'];
2271 $getdate['wday'] = (int)$getdate['wday'];
2272 $getdate['mday'] = (int)$getdate['mday'];
2273 $getdate['hours'] = (int)$getdate['hours'];
2274 $getdate['minutes'] = (int)$getdate['minutes'];
2279 * Given a GMT timestamp (seconds since epoch), offsets it by
2280 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2285 * @param int $date Timestamp in GMT
2286 * @param float|int|string $timezone timezone to calculate GMT time offset before
2287 * calculating user time, 99 is default user timezone
2288 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2291 function usertime($date, $timezone=99) {
2293 $timezone = get_user_timezone_offset($timezone);
2295 if (abs($timezone) > 13) {
2298 return $date - (int)($timezone * HOURSECS
);
2302 * Given a time, return the GMT timestamp of the most recent midnight
2303 * for the current user.
2307 * @param int $date Timestamp in GMT
2308 * @param float|int|string $timezone timezone to calculate GMT time offset before
2309 * calculating user midnight time, 99 is default user timezone
2310 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2311 * @return int Returns a GMT timestamp
2313 function usergetmidnight($date, $timezone=99) {
2315 $userdate = usergetdate($date, $timezone);
2317 // Time of midnight of this user's day, in GMT.
2318 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2323 * Returns a string that prints the user's timezone
2327 * @param float|int|string $timezone timezone to calculate GMT time offset before
2328 * calculating user timezone, 99 is default user timezone
2329 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2332 function usertimezone($timezone=99) {
2334 $tz = get_user_timezone($timezone);
2336 if (!is_float($tz)) {
2340 if (abs($tz) > 13) {
2342 return get_string('serverlocaltime');
2345 if ($tz == intval($tz)) {
2346 // Don't show .0 for whole hours.
2352 } else if ($tz > 0) {
2361 * Returns a float which represents the user's timezone difference from GMT in hours
2362 * Checks various settings and picks the most dominant of those which have a value
2366 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2367 * 99 is default user timezone
2368 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2371 function get_user_timezone_offset($tz = 99) {
2372 $tz = get_user_timezone($tz);
2374 if (is_float($tz)) {
2377 $tzrecord = get_timezone_record($tz);
2378 if (empty($tzrecord)) {
2381 return (float)$tzrecord->gmtoff
/ HOURMINS
;
2386 * Returns an int which represents the systems's timezone difference from GMT in seconds
2390 * @param float|int|string $tz timezone for which offset is required.
2391 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2392 * @return int|bool if found, false is timezone 99 or error
2394 function get_timezone_offset($tz) {
2399 if (is_numeric($tz)) {
2400 return intval($tz * 60*60);
2403 if (!$tzrecord = get_timezone_record($tz)) {
2406 return intval($tzrecord->gmtoff
* 60);
2410 * Returns a float or a string which denotes the user's timezone
2411 * 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)
2412 * means that for this timezone there are also DST rules to be taken into account
2413 * Checks various settings and picks the most dominant of those which have a value
2417 * @param float|int|string $tz timezone to calculate GMT time offset before
2418 * calculating user timezone, 99 is default user timezone
2419 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2420 * @return float|string
2422 function get_user_timezone($tz = 99) {
2427 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
2428 isset($USER->timezone
) ?
$USER->timezone
: 99,
2429 isset($CFG->timezone
) ?
$CFG->timezone
: 99,
2434 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2435 while (((empty($tz) && !is_numeric($tz)) ||
$tz == 99) && $next = each($timezones)) {
2436 $tz = $next['value'];
2438 return is_numeric($tz) ?
(float) $tz : $tz;
2442 * Returns cached timezone record for given $timezonename
2445 * @param string $timezonename name of the timezone
2446 * @return stdClass|bool timezonerecord or false
2448 function get_timezone_record($timezonename) {
2450 static $cache = null;
2452 if ($cache === null) {
2456 if (isset($cache[$timezonename])) {
2457 return $cache[$timezonename];
2460 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2461 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE
);
2465 * Build and store the users Daylight Saving Time (DST) table
2468 * @param int $fromyear Start year for the table, defaults to 1971
2469 * @param int $toyear End year for the table, defaults to 2035
2470 * @param int|float|string $strtimezone timezone to check if dst should be applied.
2473 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2474 global $SESSION, $DB;
2476 $usertz = get_user_timezone($strtimezone);
2478 if (is_float($usertz)) {
2479 // Trivial timezone, no DST.
2483 if (!empty($SESSION->dst_offsettz
) && $SESSION->dst_offsettz
!= $usertz) {
2484 // We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
2485 unset($SESSION->dst_offsets
);
2486 unset($SESSION->dst_range
);
2489 if (!empty($SESSION->dst_offsets
) && empty($fromyear) && empty($toyear)) {
2490 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
2491 // This will be the return path most of the time, pretty light computationally.
2495 // Reaching here means we either need to extend our table or create it from scratch.
2497 // Remember which TZ we calculated these changes for.
2498 $SESSION->dst_offsettz
= $usertz;
2500 if (empty($SESSION->dst_offsets
)) {
2501 // If we 're creating from scratch, put the two guard elements in there.
2502 $SESSION->dst_offsets
= array(1 => null, 0 => null);
2504 if (empty($SESSION->dst_range
)) {
2505 // If creating from scratch.
2506 $from = max((empty($fromyear) ?
intval(date('Y')) - 3 : $fromyear), 1971);
2507 $to = min((empty($toyear) ?
intval(date('Y')) +
3 : $toyear), 2035);
2509 // Fill in the array with the extra years we need to process.
2510 $yearstoprocess = array();
2511 for ($i = $from; $i <= $to; ++
$i) {
2512 $yearstoprocess[] = $i;
2515 // Take note of which years we have processed for future calls.
2516 $SESSION->dst_range
= array($from, $to);
2518 // If needing to extend the table, do the same.
2519 $yearstoprocess = array();
2521 $from = max((empty($fromyear) ?
$SESSION->dst_range
[0] : $fromyear), 1971);
2522 $to = min((empty($toyear) ?
$SESSION->dst_range
[1] : $toyear), 2035);
2524 if ($from < $SESSION->dst_range
[0]) {
2525 // Take note of which years we need to process and then note that we have processed them for future calls.
2526 for ($i = $from; $i < $SESSION->dst_range
[0]; ++
$i) {
2527 $yearstoprocess[] = $i;
2529 $SESSION->dst_range
[0] = $from;
2531 if ($to > $SESSION->dst_range
[1]) {
2532 // Take note of which years we need to process and then note that we have processed them for future calls.
2533 for ($i = $SESSION->dst_range
[1] +
1; $i <= $to; ++
$i) {
2534 $yearstoprocess[] = $i;
2536 $SESSION->dst_range
[1] = $to;
2540 if (empty($yearstoprocess)) {
2541 // This means that there was a call requesting a SMALLER range than we have already calculated.
2545 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2546 // Also, the array is sorted in descending timestamp order!
2550 static $presetscache = array();
2551 if (!isset($presetscache[$usertz])) {
2552 $presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
2553 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
2554 'std_startday, std_weekday, std_skipweeks, std_time');
2556 if (empty($presetscache[$usertz])) {
2560 // Remove ending guard (first element of the array).
2561 reset($SESSION->dst_offsets
);
2562 unset($SESSION->dst_offsets
[key($SESSION->dst_offsets
)]);
2564 // Add all required change timestamps.
2565 foreach ($yearstoprocess as $y) {
2566 // Find the record which is in effect for the year $y.
2567 foreach ($presetscache[$usertz] as $year => $preset) {
2573 $changes = dst_changes_for_year($y, $preset);
2575 if ($changes === null) {
2578 if ($changes['dst'] != 0) {
2579 $SESSION->dst_offsets
[$changes['dst']] = $preset->dstoff
* MINSECS
;
2581 if ($changes['std'] != 0) {
2582 $SESSION->dst_offsets
[$changes['std']] = 0;
2586 // Put in a guard element at the top.
2587 $maxtimestamp = max(array_keys($SESSION->dst_offsets
));
2588 $SESSION->dst_offsets
[($maxtimestamp + DAYSECS
)] = null; // DAYSECS is arbitrary, any "small" number will do.
2591 krsort($SESSION->dst_offsets
);
2597 * Calculates the required DST change and returns a Timestamp Array
2603 * @param int|string $year Int or String Year to focus on
2604 * @param object $timezone Instatiated Timezone object
2605 * @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
2607 function dst_changes_for_year($year, $timezone) {
2609 if ($timezone->dst_startday
== 0 && $timezone->dst_weekday
== 0 &&
2610 $timezone->std_startday
== 0 && $timezone->std_weekday
== 0) {
2614 $monthdaydst = find_day_in_month($timezone->dst_startday
, $timezone->dst_weekday
, $timezone->dst_month
, $year);
2615 $monthdaystd = find_day_in_month($timezone->std_startday
, $timezone->std_weekday
, $timezone->std_month
, $year);
2617 list($dsthour, $dstmin) = explode(':', $timezone->dst_time
);
2618 list($stdhour, $stdmin) = explode(':', $timezone->std_time
);
2620 $timedst = make_timestamp($year, $timezone->dst_month
, $monthdaydst, 0, 0, 0, 99, false);
2621 $timestd = make_timestamp($year, $timezone->std_month
, $monthdaystd, 0, 0, 0, 99, false);
2623 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2624 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2625 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2627 $timedst +
= $dsthour * HOURSECS +
$dstmin * MINSECS
;
2628 $timestd +
= $stdhour * HOURSECS +
$stdmin * MINSECS
;
2630 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2634 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2635 * - Note: Daylight saving only works for string timezones and not for float.
2639 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2640 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2641 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2644 function dst_offset_on($time, $strtimezone = null) {
2647 if (!calculate_user_dst_table(null, null, $strtimezone) ||
empty($SESSION->dst_offsets
)) {
2651 reset($SESSION->dst_offsets
);
2652 while (list($from, $offset) = each($SESSION->dst_offsets
)) {
2653 if ($from <= $time) {
2658 // This is the normal return path.
2659 if ($offset !== null) {
2663 // Reaching this point means we haven't calculated far enough, do it now:
2664 // Calculate extra DST changes if needed and recurse. The recursion always
2665 // moves toward the stopping condition, so will always end.
2668 // We need a year smaller than $SESSION->dst_range[0].
2669 if ($SESSION->dst_range
[0] == 1971) {
2672 calculate_user_dst_table($SESSION->dst_range
[0] - 5, null, $strtimezone);
2673 return dst_offset_on($time, $strtimezone);
2675 // We need a year larger than $SESSION->dst_range[1].
2676 if ($SESSION->dst_range
[1] == 2035) {
2679 calculate_user_dst_table(null, $SESSION->dst_range
[1] +
5, $strtimezone);
2680 return dst_offset_on($time, $strtimezone);
2685 * Calculates when the day appears in specific month
2689 * @param int $startday starting day of the month
2690 * @param int $weekday The day when week starts (normally taken from user preferences)
2691 * @param int $month The month whose day is sought
2692 * @param int $year The year of the month whose day is sought
2695 function find_day_in_month($startday, $weekday, $month, $year) {
2696 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2698 $daysinmonth = days_in_month($month, $year);
2699 $daysinweek = count($calendartype->get_weekdays());
2701 if ($weekday == -1) {
2702 // Don't care about weekday, so return:
2703 // abs($startday) if $startday != -1
2704 // $daysinmonth otherwise.
2705 return ($startday == -1) ?
$daysinmonth : abs($startday);
2708 // From now on we 're looking for a specific weekday.
2709 // Give "end of month" its actual value, since we know it.
2710 if ($startday == -1) {
2711 $startday = -1 * $daysinmonth;
2714 // Starting from day $startday, the sign is the direction.
2715 if ($startday < 1) {
2716 $startday = abs($startday);
2717 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2719 // This is the last such weekday of the month.
2720 $lastinmonth = $daysinmonth +
$weekday - $lastmonthweekday;
2721 if ($lastinmonth > $daysinmonth) {
2722 $lastinmonth -= $daysinweek;
2725 // Find the first such weekday <= $startday.
2726 while ($lastinmonth > $startday) {
2727 $lastinmonth -= $daysinweek;
2730 return $lastinmonth;
2732 $indexweekday = dayofweek($startday, $month, $year);
2734 $diff = $weekday - $indexweekday;
2736 $diff +
= $daysinweek;
2739 // This is the first such weekday of the month equal to or after $startday.
2740 $firstfromindex = $startday +
$diff;
2742 return $firstfromindex;
2747 * Calculate the number of days in a given month
2751 * @param int $month The month whose day count is sought
2752 * @param int $year The year of the month whose day count is sought
2755 function days_in_month($month, $year) {
2756 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2757 return $calendartype->get_num_days_in_month($year, $month);
2761 * Calculate the position in the week of a specific calendar day
2765 * @param int $day The day of the date whose position in the week is sought
2766 * @param int $month The month of the date whose position in the week is sought
2767 * @param int $year The year of the date whose position in the week is sought
2770 function dayofweek($day, $month, $year) {
2771 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2772 return $calendartype->get_weekday($year, $month, $day);
2775 // USER AUTHENTICATION AND LOGIN.
2778 * Returns full login url.
2780 * @return string login url
2782 function get_login_url() {
2785 $url = "$CFG->wwwroot/login/index.php";
2787 if (!empty($CFG->loginhttps
)) {
2788 $url = str_replace('http:', 'https:', $url);
2795 * This function checks that the current user is logged in and has the
2796 * required privileges
2798 * This function checks that the current user is logged in, and optionally
2799 * whether they are allowed to be in a particular course and view a particular
2801 * If they are not logged in, then it redirects them to the site login unless
2802 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2803 * case they are automatically logged in as guests.
2804 * If $courseid is given and the user is not enrolled in that course then the
2805 * user is redirected to the course enrolment page.
2806 * If $cm is given and the course module is hidden and the user is not a teacher
2807 * in the course then the user is redirected to the course home page.
2809 * When $cm parameter specified, this function sets page layout to 'module'.
2810 * You need to change it manually later if some other layout needed.
2812 * @package core_access
2815 * @param mixed $courseorid id of the course or course object
2816 * @param bool $autologinguest default true
2817 * @param object $cm course module object
2818 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2819 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2820 * in order to keep redirects working properly. MDL-14495
2821 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2822 * @return mixed Void, exit, and die depending on path
2823 * @throws coding_exception
2824 * @throws require_login_exception
2826 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2827 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2829 // Must not redirect when byteserving already started.
2830 if (!empty($_SERVER['HTTP_RANGE'])) {
2831 $preventredirect = true;
2834 // Setup global $COURSE, themes, language and locale.
2835 if (!empty($courseorid)) {
2836 if (is_object($courseorid)) {
2837 $course = $courseorid;
2838 } else if ($courseorid == SITEID
) {
2839 $course = clone($SITE);
2841 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST
);
2844 if ($cm->course
!= $course->id
) {
2845 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2847 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2848 if (!($cm instanceof cm_info
)) {
2849 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2850 // db queries so this is not really a performance concern, however it is obviously
2851 // better if you use get_fast_modinfo to get the cm before calling this.
2852 $modinfo = get_fast_modinfo($course);
2853 $cm = $modinfo->get_cm($cm->id
);
2855 $PAGE->set_cm($cm, $course); // Set's up global $COURSE.
2856 $PAGE->set_pagelayout('incourse');
2858 $PAGE->set_course($course); // Set's up global $COURSE.
2861 // Do not touch global $COURSE via $PAGE->set_course(),
2862 // the reasons is we need to be able to call require_login() at any time!!
2865 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2869 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2870 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2871 // risk leading the user back to the AJAX request URL.
2872 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT
) {
2873 $setwantsurltome = false;
2876 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2877 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out
) && !$preventredirect && !empty($CFG->dbsessions
)) {
2878 if ($setwantsurltome) {
2879 $SESSION->wantsurl
= qualified_me();
2881 redirect(get_login_url());
2884 // If the user is not even logged in yet then make sure they are.
2885 if (!isloggedin()) {
2886 if ($autologinguest and !empty($CFG->guestloginbutton
) and !empty($CFG->autologinguests
)) {
2887 if (!$guest = get_complete_user_data('id', $CFG->siteguest
)) {
2888 // Misconfigured site guest, just redirect to login page.
2889 redirect(get_login_url());
2890 exit; // Never reached.
2892 $lang = isset($SESSION->lang
) ?
$SESSION->lang
: $CFG->lang
;
2893 complete_user_login($guest);
2894 $USER->autologinguest
= true;
2895 $SESSION->lang
= $lang;
2897 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2898 if ($preventredirect) {
2899 throw new require_login_exception('You are not logged in');
2902 if ($setwantsurltome) {
2903 $SESSION->wantsurl
= qualified_me();
2905 if (!empty($_SERVER['HTTP_REFERER'])) {
2906 $SESSION->fromurl
= $_SERVER['HTTP_REFERER'];
2908 redirect(get_login_url());
2909 exit; // Never reached.
2913 // Loginas as redirection if needed.
2914 if ($course->id
!= SITEID
and \core\session\manager
::is_loggedinas()) {
2915 if ($USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
2916 if ($USER->loginascontext
->instanceid
!= $course->id
) {
2917 print_error('loginasonecourse', '', $CFG->wwwroot
.'/course/view.php?id='.$USER->loginascontext
->instanceid
);
2922 // Check whether the user should be changing password (but only if it is REALLY them).
2923 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager
::is_loggedinas()) {
2924 $userauth = get_auth_plugin($USER->auth
);
2925 if ($userauth->can_change_password() and !$preventredirect) {
2926 if ($setwantsurltome) {
2927 $SESSION->wantsurl
= qualified_me();
2929 if ($changeurl = $userauth->change_password_url()) {
2930 // Use plugin custom url.
2931 redirect($changeurl);
2933 // Use moodle internal method.
2934 if (empty($CFG->loginhttps
)) {
2935 redirect($CFG->wwwroot
.'/login/change_password.php');
2937 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot
);
2938 redirect($wwwroot .'/login/change_password.php');
2942 print_error('nopasswordchangeforced', 'auth');
2946 // Check that the user account is properly set up.
2947 if (user_not_fully_set_up($USER)) {
2948 if ($preventredirect) {
2949 throw new require_login_exception('User not fully set-up');
2951 if ($setwantsurltome) {
2952 $SESSION->wantsurl
= qualified_me();
2954 redirect($CFG->wwwroot
.'/user/edit.php?id='. $USER->id
.'&course='. SITEID
);
2957 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2960 // Do not bother admins with any formalities.
2961 if (is_siteadmin()) {
2962 // Set accesstime or the user will appear offline which messes up messaging.
2963 user_accesstime_log($course->id
);
2967 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2968 if (!$USER->policyagreed
and !is_siteadmin()) {
2969 if (!empty($CFG->sitepolicy
) and !isguestuser()) {
2970 if ($preventredirect) {
2971 throw new require_login_exception('Policy not agreed');
2973 if ($setwantsurltome) {
2974 $SESSION->wantsurl
= qualified_me();
2976 redirect($CFG->wwwroot
.'/user/policy.php');
2977 } else if (!empty($CFG->sitepolicyguest
) and isguestuser()) {
2978 if ($preventredirect) {
2979 throw new require_login_exception('Policy not agreed');
2981 if ($setwantsurltome) {
2982 $SESSION->wantsurl
= qualified_me();
2984 redirect($CFG->wwwroot
.'/user/policy.php');
2988 // Fetch the system context, the course context, and prefetch its child contexts.
2989 $sysctx = context_system
::instance();
2990 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
2992 $cmcontext = context_module
::instance($cm->id
, MUST_EXIST
);
2997 // If the site is currently under maintenance, then print a message.
2998 if (!empty($CFG->maintenance_enabled
) and !has_capability('moodle/site:config', $sysctx)) {
2999 if ($preventredirect) {
3000 throw new require_login_exception('Maintenance in progress');
3003 print_maintenance_message();
3006 // Make sure the course itself is not hidden.
3007 if ($course->id
== SITEID
) {
3008 // Frontpage can not be hidden.
3010 if (is_role_switched($course->id
)) {
3011 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
3013 if (!$course->visible
and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3014 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
3015 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
3016 if ($preventredirect) {
3017 throw new require_login_exception('Course is hidden');
3019 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3020 // the navigation will mess up when trying to find it.
3021 navigation_node
::override_active_url(new moodle_url('/'));
3022 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
3027 // Is the user enrolled?
3028 if ($course->id
== SITEID
) {
3029 // Everybody is enrolled on the frontpage.
3031 if (\core\session\manager
::is_loggedinas()) {
3032 // Make sure the REAL person can access this course first.
3033 $realuser = \core\session\manager
::get_realuser();
3034 if (!is_enrolled($coursecontext, $realuser->id
, '', true) and
3035 !is_viewing($coursecontext, $realuser->id
) and !is_siteadmin($realuser->id
)) {
3036 if ($preventredirect) {
3037 throw new require_login_exception('Invalid course login-as access');
3039 echo $OUTPUT->header();
3040 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot
.'/');
3046 if (is_role_switched($course->id
)) {
3047 // Ok, user had to be inside this course before the switch.
3050 } else if (is_viewing($coursecontext, $USER)) {
3051 // Ok, no need to mess with enrol.
3055 if (isset($USER->enrol
['enrolled'][$course->id
])) {
3056 if ($USER->enrol
['enrolled'][$course->id
] > time()) {
3058 if (isset($USER->enrol
['tempguest'][$course->id
])) {
3059 unset($USER->enrol
['tempguest'][$course->id
]);
3060 remove_temp_course_roles($coursecontext);
3064 unset($USER->enrol
['enrolled'][$course->id
]);
3067 if (isset($USER->enrol
['tempguest'][$course->id
])) {
3068 if ($USER->enrol
['tempguest'][$course->id
] == 0) {
3070 } else if ($USER->enrol
['tempguest'][$course->id
] > time()) {
3074 unset($USER->enrol
['tempguest'][$course->id
]);
3075 remove_temp_course_roles($coursecontext);
3081 $until = enrol_get_enrolment_end($coursecontext->instanceid
, $USER->id
);
3082 if ($until !== false) {
3083 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3085 $until = ENROL_MAX_TIMESTAMP
;
3087 $USER->enrol
['enrolled'][$course->id
] = $until;
3091 $params = array('courseid' => $course->id
, 'status' => ENROL_INSTANCE_ENABLED
);
3092 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3093 $enrols = enrol_get_plugins(true);
3094 // First ask all enabled enrol instances in course if they want to auto enrol user.
3095 foreach ($instances as $instance) {
3096 if (!isset($enrols[$instance->enrol
])) {
3099 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3100 $until = $enrols[$instance->enrol
]->try_autoenrol($instance);
3101 if ($until !== false) {
3103 $until = ENROL_MAX_TIMESTAMP
;
3105 $USER->enrol
['enrolled'][$course->id
] = $until;
3110 // If not enrolled yet try to gain temporary guest access.
3112 foreach ($instances as $instance) {
3113 if (!isset($enrols[$instance->enrol
])) {
3116 // Get a duration for the guest access, a timestamp in the future or false.
3117 $until = $enrols[$instance->enrol
]->try_guestaccess($instance);
3118 if ($until !== false and $until > time()) {
3119 $USER->enrol
['tempguest'][$course->id
] = $until;
3130 if ($preventredirect) {
3131 throw new require_login_exception('Not enrolled');
3133 if ($setwantsurltome) {
3134 $SESSION->wantsurl
= qualified_me();
3136 redirect($CFG->wwwroot
.'/enrol/index.php?id='. $course->id
);
3140 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3141 if ($cm && !$cm->uservisible
) {
3142 if ($preventredirect) {
3143 throw new require_login_exception('Activity is hidden');
3145 if ($course->id
!= SITEID
) {
3146 $url = new moodle_url('/course/view.php', array('id' => $course->id
));
3148 $url = new moodle_url('/');
3150 redirect($url, get_string('activityiscurrentlyhidden'));
3153 // Finally access granted, update lastaccess times.
3154 user_accesstime_log($course->id
);
3159 * This function just makes sure a user is logged out.
3161 * @package core_access
3164 function require_logout() {
3167 if (!isloggedin()) {
3168 // This should not happen often, no need for hooks or events here.
3169 \core\session\manager
::terminate_current();
3173 // Execute hooks before action.
3174 $authplugins = array();
3175 $authsequence = get_enabled_auth_plugins();
3176 foreach ($authsequence as $authname) {
3177 $authplugins[$authname] = get_auth_plugin($authname);
3178 $authplugins[$authname]->prelogout_hook();
3181 // Store info that gets removed during logout.
3182 $sid = session_id();
3183 $event = \core\event\user_loggedout
::create(
3185 'userid' => $USER->id
,
3186 'objectid' => $USER->id
,
3187 'other' => array('sessionid' => $sid),
3190 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3191 $event->add_record_snapshot('sessions', $session);
3194 // Clone of $USER object to be used by auth plugins.
3195 $user = fullclone($USER);
3197 // Delete session record and drop $_SESSION content.
3198 \core\session\manager
::terminate_current();
3200 // Trigger event AFTER action.
3203 // Hook to execute auth plugins redirection after event trigger.
3204 foreach ($authplugins as $authplugin) {
3205 $authplugin->postlogout_hook($user);
3210 * Weaker version of require_login()
3212 * This is a weaker version of {@link require_login()} which only requires login
3213 * when called from within a course rather than the site page, unless
3214 * the forcelogin option is turned on.
3215 * @see require_login()
3217 * @package core_access
3220 * @param mixed $courseorid The course object or id in question
3221 * @param bool $autologinguest Allow autologin guests if that is wanted
3222 * @param object $cm Course activity module if known
3223 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3224 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3225 * in order to keep redirects working properly. MDL-14495
3226 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3228 * @throws coding_exception
3230 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3231 global $CFG, $PAGE, $SITE;
3232 $issite = ((is_object($courseorid) and $courseorid->id
== SITEID
)
3233 or (!is_object($courseorid) and $courseorid == SITEID
));
3234 if ($issite && !empty($cm) && !($cm instanceof cm_info
)) {
3235 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3236 // db queries so this is not really a performance concern, however it is obviously
3237 // better if you use get_fast_modinfo to get the cm before calling this.
3238 if (is_object($courseorid)) {
3239 $course = $courseorid;
3241 $course = clone($SITE);
3243 $modinfo = get_fast_modinfo($course);
3244 $cm = $modinfo->get_cm($cm->id
);
3246 if (!empty($CFG->forcelogin
)) {
3247 // Login required for both SITE and courses.
3248 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3250 } else if ($issite && !empty($cm) and !$cm->uservisible
) {
3251 // Always login for hidden activities.
3252 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3254 } else if ($issite) {
3255 // Login for SITE not required.
3256 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3257 if (!empty($courseorid)) {
3258 if (is_object($courseorid)) {
3259 $course = $courseorid;
3261 $course = clone $SITE;
3264 if ($cm->course
!= $course->id
) {
3265 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3267 $PAGE->set_cm($cm, $course);
3268 $PAGE->set_pagelayout('incourse');
3270 $PAGE->set_course($course);
3273 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3274 $PAGE->set_course($PAGE->course
);
3276 user_accesstime_log(SITEID
);
3280 // Course login always required.
3281 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3286 * Require key login. Function terminates with error if key not found or incorrect.
3288 * @uses NO_MOODLE_COOKIES
3289 * @uses PARAM_ALPHANUM
3290 * @param string $script unique script identifier
3291 * @param int $instance optional instance id
3292 * @return int Instance ID
3294 function require_user_key_login($script, $instance=null) {
3297 if (!NO_MOODLE_COOKIES
) {
3298 print_error('sessioncookiesdisable');
3302 \core\session\manager
::write_close();
3304 $keyvalue = required_param('key', PARAM_ALPHANUM
);
3306 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3307 print_error('invalidkey');
3310 if (!empty($key->validuntil
) and $key->validuntil
< time()) {
3311 print_error('expiredkey');
3314 if ($key->iprestriction
) {
3315 $remoteaddr = getremoteaddr(null);
3316 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction
)) {
3317 print_error('ipmismatch');
3321 if (!$user = $DB->get_record('user', array('id' => $key->userid
))) {
3322 print_error('invaliduserid');
3325 // Emulate normal session.
3326 enrol_check_plugins($user);
3327 \core\session\manager
::set_user($user);
3329 // Note we are not using normal login.
3330 if (!defined('USER_KEY_LOGIN')) {
3331 define('USER_KEY_LOGIN', true);
3334 // Return instance id - it might be empty.
3335 return $key->instance
;
3339 * Creates a new private user access key.
3341 * @param string $script unique target identifier
3342 * @param int $userid
3343 * @param int $instance optional instance id
3344 * @param string $iprestriction optional ip restricted access
3345 * @param timestamp $validuntil key valid only until given data
3346 * @return string access key value
3348 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3351 $key = new stdClass();
3352 $key->script
= $script;
3353 $key->userid
= $userid;
3354 $key->instance
= $instance;
3355 $key->iprestriction
= $iprestriction;
3356 $key->validuntil
= $validuntil;
3357 $key->timecreated
= time();
3359 // Something long and unique.
3360 $key->value
= md5($userid.'_'.time().random_string(40));
3361 while ($DB->record_exists('user_private_key', array('value' => $key->value
))) {
3363 $key->value
= md5($userid.'_'.time().random_string(40));
3365 $DB->insert_record('user_private_key', $key);
3370 * Delete the user's new private user access keys for a particular script.
3372 * @param string $script unique target identifier
3373 * @param int $userid
3376 function delete_user_key($script, $userid) {
3378 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3382 * Gets a private user access key (and creates one if one doesn't exist).
3384 * @param string $script unique target identifier
3385 * @param int $userid
3386 * @param int $instance optional instance id
3387 * @param string $iprestriction optional ip restricted access
3388 * @param timestamp $validuntil key valid only until given data
3389 * @return string access key value
3391 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3394 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3395 'instance' => $instance, 'iprestriction' => $iprestriction,
3396 'validuntil' => $validuntil))) {
3399 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3405 * Modify the user table by setting the currently logged in user's last login to now.
3407 * @return bool Always returns true
3409 function update_user_login_times() {
3412 if (isguestuser()) {
3413 // Do not update guest access times/ips for performance.
3419 $user = new stdClass();
3420 $user->id
= $USER->id
;
3422 // Make sure all users that logged in have some firstaccess.
3423 if ($USER->firstaccess
== 0) {
3424 $USER->firstaccess
= $user->firstaccess
= $now;
3427 // Store the previous current as lastlogin.
3428 $USER->lastlogin
= $user->lastlogin
= $USER->currentlogin
;
3430 $USER->currentlogin
= $user->currentlogin
= $now;
3432 // Function user_accesstime_log() may not update immediately, better do it here.
3433 $USER->lastaccess
= $user->lastaccess
= $now;
3434 $USER->lastip
= $user->lastip
= getremoteaddr();
3436 // Note: do not call user_update_user() here because this is part of the login process,
3437 // the login event means that these fields were updated.
3438 $DB->update_record('user', $user);
3443 * Determines if a user has completed setting up their account.
3445 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3448 function user_not_fully_set_up($user) {
3449 if (isguestuser($user)) {
3452 return (empty($user->firstname
) or empty($user->lastname
) or empty($user->email
) or over_bounce_threshold($user));
3456 * Check whether the user has exceeded the bounce threshold
3458 * @param stdClass $user A {@link $USER} object
3459 * @return bool true => User has exceeded bounce threshold
3461 function over_bounce_threshold($user) {
3464 if (empty($CFG->handlebounces
)) {
3468 if (empty($user->id
)) {
3469 // No real (DB) user, nothing to do here.
3473 // Set sensible defaults.
3474 if (empty($CFG->minbounces
)) {
3475 $CFG->minbounces
= 10;
3477 if (empty($CFG->bounceratio
)) {
3478 $CFG->bounceratio
= .20;
3482 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3483 $bouncecount = $bounce->value
;
3485 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3486 $sendcount = $send->value
;
3488 return ($bouncecount >= $CFG->minbounces
&& $bouncecount/$sendcount >= $CFG->bounceratio
);
3492 * Used to increment or reset email sent count
3494 * @param stdClass $user object containing an id
3495 * @param bool $reset will reset the count to 0
3498 function set_send_count($user, $reset=false) {
3501 if (empty($user->id
)) {
3502 // No real (DB) user, nothing to do here.
3506 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3507 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3508 $DB->update_record('user_preferences', $pref);
3509 } else if (!empty($reset)) {
3510 // If it's not there and we're resetting, don't bother. Make a new one.
3511 $pref = new stdClass();
3512 $pref->name
= 'email_send_count';
3514 $pref->userid
= $user->id
;
3515 $DB->insert_record('user_preferences', $pref, false);
3520 * Increment or reset user's email bounce count
3522 * @param stdClass $user object containing an id
3523 * @param bool $reset will reset the count to 0
3525 function set_bounce_count($user, $reset=false) {
3528 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3529 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3530 $DB->update_record('user_preferences', $pref);
3531 } else if (!empty($reset)) {
3532 // If it's not there and we're resetting, don't bother. Make a new one.
3533 $pref = new stdClass();
3534 $pref->name
= 'email_bounce_count';
3536 $pref->userid
= $user->id
;
3537 $DB->insert_record('user_preferences', $pref, false);
3542 * Determines if the logged in user is currently moving an activity
3544 * @param int $courseid The id of the course being tested
3547 function ismoving($courseid) {
3550 if (!empty($USER->activitycopy
)) {
3551 return ($USER->activitycopycourse
== $courseid);
3557 * Returns a persons full name
3559 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3560 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3563 * @param stdClass $user A {@link $USER} object to get full name of.
3564 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3567 function fullname($user, $override=false) {
3568 global $CFG, $SESSION;
3570 if (!isset($user->firstname
) and !isset($user->lastname
)) {
3574 // Get all of the name fields.
3575 $allnames = get_all_user_name_fields();
3576 if ($CFG->debugdeveloper
) {
3577 foreach ($allnames as $allname) {
3578 if (!array_key_exists($allname, $user)) {
3579 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3580 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER
);
3581 // Message has been sent, no point in sending the message multiple times.
3588 if (!empty($CFG->forcefirstname
)) {
3589 $user->firstname
= $CFG->forcefirstname
;
3591 if (!empty($CFG->forcelastname
)) {
3592 $user->lastname
= $CFG->forcelastname
;
3596 if (!empty($SESSION->fullnamedisplay
)) {
3597 $CFG->fullnamedisplay
= $SESSION->fullnamedisplay
;
3601 // If the fullnamedisplay setting is available, set the template to that.
3602 if (isset($CFG->fullnamedisplay
)) {
3603 $template = $CFG->fullnamedisplay
;
3605 // If the template is empty, or set to language, return the language string.
3606 if ((empty($template) ||
$template == 'language') && !$override) {
3607 return get_string('fullnamedisplay', null, $user);
3610 $admindisplay = null;
3611 // Language isn't actually a valid value for alternativefullnameformat, but people might enter it in anyway.
3612 if (empty($CFG->alternativefullnameformat
) ||
$CFG->alternativefullnameformat
== 'language') {
3613 // Default to show all names if the setting is empty.
3614 $admindisplay = 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename';
3616 $admindisplay = $CFG->alternativefullnameformat
;
3619 // If the override is true, then change the template to use the complete name.
3620 $template = ($override) ?
$admindisplay : $template;
3622 $requirednames = array();
3623 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3624 foreach ($allnames as $allname) {
3625 if (strpos($template, $allname) !== false) {
3626 $requirednames[] = $allname;
3630 $displayname = $template;
3631 // Switch in the actual data into the template.
3632 foreach ($requirednames as $altname) {
3633 if (isset($user->$altname)) {
3634 // Using empty() on the below if statement causes breakages.
3635 if ((string)$user->$altname == '') {
3636 $displayname = str_replace($altname, 'EMPTY', $displayname);
3638 $displayname = str_replace($altname, $user->$altname, $displayname);
3641 $displayname = str_replace($altname, 'EMPTY', $displayname);
3644 // Tidy up any misc. characters (Not perfect, but gets most characters).
3645 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3646 // katakana and parenthesis.
3647 $patterns = array();
3648 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3649 // filled in by a user.
3650 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3651 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3652 // This regular expression is to remove any double spaces in the display name.
3653 $patterns[] = '/\s{2,}/u';
3654 foreach ($patterns as $pattern) {
3655 $displayname = preg_replace($pattern, ' ', $displayname);
3658 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3659 $displayname = trim($displayname);
3660 if (empty($displayname)) {
3661 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3662 // people in general feel is a good setting to fall back on.
3663 $displayname = $user->firstname
;
3665 return $displayname;
3669 * A centralised location for the all name fields. Returns an array / sql string snippet.
3671 * @param bool $returnsql True for an sql select field snippet.
3672 * @param string $tableprefix table query prefix to use in front of each field.
3673 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3674 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3675 * @return array|string All name fields.
3677 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null) {
3678 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3679 'lastnamephonetic' => 'lastnamephonetic',
3680 'middlename' => 'middlename',
3681 'alternatename' => 'alternatename',
3682 'firstname' => 'firstname',
3683 'lastname' => 'lastname');
3685 // Let's add a prefix to the array of user name fields if provided.
3687 foreach ($alternatenames as $key => $altname) {
3688 $alternatenames[$key] = $prefix . $altname;
3692 // Create an sql field snippet if requested.
3696 foreach ($alternatenames as $key => $altname) {
3697 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3700 foreach ($alternatenames as $key => $altname) {
3701 $alternatenames[$key] = $tableprefix . '.' . $altname;
3705 $alternatenames = implode(',', $alternatenames);
3707 return $alternatenames;
3711 * Reduces lines of duplicated code for getting user name fields.
3713 * See also {@link user_picture::unalias()}
3715 * @param object $addtoobject Object to add user name fields to.
3716 * @param object $secondobject Object that contains user name field information.
3717 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3718 * @param array $additionalfields Additional fields to be matched with data in the second object.
3719 * The key can be set to the user table field name.
3720 * @return object User name fields.
3722 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3723 $fields = get_all_user_name_fields(false, null, $prefix);
3724 if ($additionalfields) {
3725 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3726 // the key is a number and then sets the key to the array value.
3727 foreach ($additionalfields as $key => $value) {
3728 if (is_numeric($key)) {
3729 $additionalfields[$value] = $prefix . $value;
3730 unset($additionalfields[$key]);
3732 $additionalfields[$key] = $prefix . $value;
3735 $fields = array_merge($fields, $additionalfields);
3737 foreach ($fields as $key => $field) {
3738 // Important that we have all of the user name fields present in the object that we are sending back.
3739 $addtoobject->$key = '';
3740 if (isset($secondobject->$field)) {
3741 $addtoobject->$key = $secondobject->$field;
3744 return $addtoobject;
3748 * Returns an array of values in order of occurance in a provided string.
3749 * The key in the result is the character postion in the string.
3751 * @param array $values Values to be found in the string format
3752 * @param string $stringformat The string which may contain values being searched for.
3753 * @return array An array of values in order according to placement in the string format.
3755 function order_in_string($values, $stringformat) {
3756 $valuearray = array();
3757 foreach ($values as $value) {
3758 $pattern = "/$value\b/";
3759 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3760 if (preg_match($pattern, $stringformat)) {
3761 $replacement = "thing";
3762 // Replace the value with something more unique to ensure we get the right position when using strpos().
3763 $newformat = preg_replace($pattern, $replacement, $stringformat);
3764 $position = strpos($newformat, $replacement);
3765 $valuearray[$position] = $value;
3773 * Checks if current user is shown any extra fields when listing users.
3775 * @param object $context Context
3776 * @param array $already Array of fields that we're going to show anyway
3777 * so don't bother listing them
3778 * @return array Array of field names from user table, not including anything
3779 * listed in $already
3781 function get_extra_user_fields($context, $already = array()) {
3784 // Only users with permission get the extra fields.
3785 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3789 // Split showuseridentity on comma.
3790 if (empty($CFG->showuseridentity
)) {
3791 // Explode gives wrong result with empty string.
3794 $extra = explode(',', $CFG->showuseridentity
);
3797 foreach ($extra as $key => $field) {
3798 if (in_array($field, $already)) {
3799 unset($extra[$key]);
3804 // For consistency, if entries are removed from array, renumber it
3805 // so they are numbered as you would expect.
3806 $extra = array_merge($extra);
3812 * If the current user is to be shown extra user fields when listing or
3813 * selecting users, returns a string suitable for including in an SQL select
3814 * clause to retrieve those fields.
3816 * @param context $context Context
3817 * @param string $alias Alias of user table, e.g. 'u' (default none)
3818 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3819 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3820 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3822 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3823 $fields = get_extra_user_fields($context, $already);
3825 // Add punctuation for alias.
3826 if ($alias !== '') {
3829 foreach ($fields as $field) {
3830 $result .= ', ' . $alias . $field;
3832 $result .= ' AS ' . $prefix . $field;
3839 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3840 * @param string $field Field name, e.g. 'phone1'
3841 * @return string Text description taken from language file, e.g. 'Phone number'
3843 function get_user_field_name($field) {
3844 // Some fields have language strings which are not the same as field name.
3847 return get_string('phone');
3850 return get_string('webpage');
3853 return get_string('icqnumber');
3856 return get_string('skypeid');
3859 return get_string('aimid');
3862 return get_string('yahooid');
3865 return get_string('msnid');
3868 // Otherwise just use the same lang string.
3869 return get_string($field);
3873 * Returns whether a given authentication plugin exists.
3875 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3876 * @return boolean Whether the plugin is available.
3878 function exists_auth_plugin($auth) {
3881 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3882 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3888 * Checks if a given plugin is in the list of enabled authentication plugins.
3890 * @param string $auth Authentication plugin.
3891 * @return boolean Whether the plugin is enabled.
3893 function is_enabled_auth($auth) {
3898 $enabled = get_enabled_auth_plugins();
3900 return in_array($auth, $enabled);
3904 * Returns an authentication plugin instance.
3906 * @param string $auth name of authentication plugin
3907 * @return auth_plugin_base An instance of the required authentication plugin.
3909 function get_auth_plugin($auth) {
3912 // Check the plugin exists first.
3913 if (! exists_auth_plugin($auth)) {
3914 print_error('authpluginnotfound', 'debug', '', $auth);
3917 // Return auth plugin instance.
3918 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3919 $class = "auth_plugin_$auth";
3924 * Returns array of active auth plugins.
3926 * @param bool $fix fix $CFG->auth if needed
3929 function get_enabled_auth_plugins($fix=false) {
3932 $default = array('manual', 'nologin');
3934 if (empty($CFG->auth
)) {
3937 $auths = explode(',', $CFG->auth
);
3941 $auths = array_unique($auths);
3942 foreach ($auths as $k => $authname) {
3943 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3947 $newconfig = implode(',', $auths);
3948 if (!isset($CFG->auth
) or $newconfig != $CFG->auth
) {
3949 set_config('auth', $newconfig);
3953 return (array_merge($default, $auths));
3957 * Returns true if an internal authentication method is being used.
3958 * if method not specified then, global default is assumed
3960 * @param string $auth Form of authentication required
3963 function is_internal_auth($auth) {
3964 // Throws error if bad $auth.
3965 $authplugin = get_auth_plugin($auth);
3966 return $authplugin->is_internal();
3970 * Returns true if the user is a 'restored' one.
3972 * Used in the login process to inform the user and allow him/her to reset the password
3974 * @param string $username username to be checked
3977 function is_restored_user($username) {
3980 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'password' => 'restored'));
3984 * Returns an array of user fields
3986 * @return array User field/column names
3988 function get_user_fieldnames() {
3991 $fieldarray = $DB->get_columns('user');
3992 unset($fieldarray['id']);
3993 $fieldarray = array_keys($fieldarray);
3999 * Creates a bare-bones user record
4001 * @todo Outline auth types and provide code example
4003 * @param string $username New user's username to add to record
4004 * @param string $password New user's password to add to record
4005 * @param string $auth Form of authentication required
4006 * @return stdClass A complete user object
4008 function create_user_record($username, $password, $auth = 'manual') {
4010 require_once($CFG->dirroot
.'/user/profile/lib.php');
4011 require_once($CFG->dirroot
.'/user/lib.php');
4013 // Just in case check text case.
4014 $username = trim(core_text
::strtolower($username));
4016 $authplugin = get_auth_plugin($auth);
4017 $customfields = $authplugin->get_custom_user_profile_fields();
4018 $newuser = new stdClass();
4019 if ($newinfo = $authplugin->get_userinfo($username)) {
4020 $newinfo = truncate_userinfo($newinfo);
4021 foreach ($newinfo as $key => $value) {
4022 if (in_array($key, $authplugin->userfields
) ||
(in_array($key, $customfields))) {
4023 $newuser->$key = $value;
4028 if (!empty($newuser->email
)) {
4029 if (email_is_not_allowed($newuser->email
)) {
4030 unset($newuser->email
);
4034 if (!isset($newuser->city
)) {
4035 $newuser->city
= '';
4038 $newuser->auth
= $auth;
4039 $newuser->username
= $username;
4042 // user CFG lang for user if $newuser->lang is empty
4043 // or $user->lang is not an installed language.
4044 if (empty($newuser->lang
) ||
!get_string_manager()->translation_exists($newuser->lang
)) {
4045 $newuser->lang
= $CFG->lang
;
4047 $newuser->confirmed
= 1;
4048 $newuser->lastip
= getremoteaddr();
4049 $newuser->timecreated
= time();
4050 $newuser->timemodified
= $newuser->timecreated
;
4051 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
4053 $newuser->id
= user_create_user($newuser, false, false);
4055 // Save user profile data.
4056 profile_save_data($newuser);
4058 $user = get_complete_user_data('id', $newuser->id
);
4059 if (!empty($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'})) {
4060 set_user_preference('auth_forcepasswordchange', 1, $user);
4062 // Set the password.
4063 update_internal_user_password($user, $password);
4066 \core\event\user_created
::create_from_userid($newuser->id
)->trigger();
4072 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4074 * @param string $username user's username to update the record
4075 * @return stdClass A complete user object
4077 function update_user_record($username) {
4079 // Just in case check text case.
4080 $username = trim(core_text
::strtolower($username));
4082 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
), '*', MUST_EXIST
);
4083 return update_user_record_by_id($oldinfo->id
);
4087 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4089 * @param int $id user id
4090 * @return stdClass A complete user object
4092 function update_user_record_by_id($id) {
4094 require_once($CFG->dirroot
."/user/profile/lib.php");
4095 require_once($CFG->dirroot
.'/user/lib.php');
4097 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'id' => $id, 'deleted' => 0);
4098 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST
);
4101 $userauth = get_auth_plugin($oldinfo->auth
);
4103 if ($newinfo = $userauth->get_userinfo($oldinfo->username
)) {
4104 $newinfo = truncate_userinfo($newinfo);
4105 $customfields = $userauth->get_custom_user_profile_fields();
4107 foreach ($newinfo as $key => $value) {
4108 $key = strtolower($key);
4109 $iscustom = in_array($key, $customfields);
4110 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4111 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4112 // Unknown or must not be changed.
4115 $confval = $userauth->config
->{'field_updatelocal_' . $key};
4116 $lockval = $userauth->config
->{'field_lock_' . $key};
4117 if (empty($confval) ||
empty($lockval)) {
4120 if ($confval === 'onlogin') {
4121 // MDL-4207 Don't overwrite modified user profile values with
4122 // empty LDAP values when 'unlocked if empty' is set. The purpose
4123 // of the setting 'unlocked if empty' is to allow the user to fill
4124 // in a value for the selected field _if LDAP is giving
4125 // nothing_ for this field. Thus it makes sense to let this value
4126 // stand in until LDAP is giving a value for this field.
4127 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4128 if ($iscustom ||
(in_array($key, $userauth->userfields
) &&
4129 ((string)$oldinfo->$key !== (string)$value))) {
4130 $newuser[$key] = (string)$value;
4136 $newuser['id'] = $oldinfo->id
;
4137 $newuser['timemodified'] = time();
4138 user_update_user((object) $newuser, false, false);
4140 // Save user profile data.
4141 profile_save_data((object) $newuser);
4144 \core\event\user_updated
::create_from_userid($newuser['id'])->trigger();
4148 return get_complete_user_data('id', $oldinfo->id
);
4152 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4154 * @param array $info Array of user properties to truncate if needed
4155 * @return array The now truncated information that was passed in
4157 function truncate_userinfo(array $info) {
4158 // Define the limits.
4168 'institution' => 255,
4169 'department' => 255,
4176 // Apply where needed.
4177 foreach (array_keys($info) as $key) {
4178 if (!empty($limit[$key])) {
4179 $info[$key] = trim(core_text
::substr($info[$key], 0, $limit[$key]));
4187 * Marks user deleted in internal user database and notifies the auth plugin.
4188 * Also unenrols user from all roles and does other cleanup.
4190 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4192 * @param stdClass $user full user object before delete
4193 * @return boolean success
4194 * @throws coding_exception if invalid $user parameter detected
4196 function delete_user(stdClass
$user) {
4198 require_once($CFG->libdir
.'/grouplib.php');
4199 require_once($CFG->libdir
.'/gradelib.php');
4200 require_once($CFG->dirroot
.'/message/lib.php');
4201 require_once($CFG->dirroot
.'/tag/lib.php');
4202 require_once($CFG->dirroot
.'/user/lib.php');
4204 // Make sure nobody sends bogus record type as parameter.
4205 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4206 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4209 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4210 if (!$user = $DB->get_record('user', array('id' => $user->id
))) {
4211 debugging('Attempt to delete unknown user account.');
4215 // There must be always exactly one guest record, originally the guest account was identified by username only,
4216 // now we use $CFG->siteguest for performance reasons.
4217 if ($user->username
=== 'guest' or isguestuser($user)) {
4218 debugging('Guest user account can not be deleted.');
4222 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4223 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4224 if ($user->auth
=== 'manual' and is_siteadmin($user)) {
4225 debugging('Local administrator accounts can not be deleted.');
4229 // Keep user record before updating it, as we have to pass this to user_deleted event.
4230 $olduser = clone $user;
4232 // Keep a copy of user context, we need it for event.
4233 $usercontext = context_user
::instance($user->id
);
4235 // Delete all grades - backup is kept in grade_grades_history table.
4236 grade_user_delete($user->id
);
4238 // Move unread messages from this user to read.
4239 message_move_userfrom_unread2read($user->id
);
4241 // TODO: remove from cohorts using standard API here.
4243 // Remove user tags.
4244 tag_set('user', $user->id
, array(), 'core', $usercontext->id
);
4246 // Unconditionally unenrol from all courses.
4247 enrol_user_delete($user);
4249 // Unenrol from all roles in all contexts.
4250 // This might be slow but it is really needed - modules might do some extra cleanup!
4251 role_unassign_all(array('userid' => $user->id
));
4253 // Now do a brute force cleanup.
4255 // Remove from all cohorts.
4256 $DB->delete_records('cohort_members', array('userid' => $user->id
));
4258 // Remove from all groups.
4259 $DB->delete_records('groups_members', array('userid' => $user->id
));
4261 // Brute force unenrol from all courses.
4262 $DB->delete_records('user_enrolments', array('userid' => $user->id
));
4264 // Purge user preferences.
4265 $DB->delete_records('user_preferences', array('userid' => $user->id
));
4267 // Purge user extra profile info.
4268 $DB->delete_records('user_info_data', array('userid' => $user->id
));
4270 // Last course access not necessary either.
4271 $DB->delete_records('user_lastaccess', array('userid' => $user->id
));
4272 // Remove all user tokens.
4273 $DB->delete_records('external_tokens', array('userid' => $user->id
));
4275 // Unauthorise the user for all services.
4276 $DB->delete_records('external_services_users', array('userid' => $user->id
));
4278 // Remove users private keys.
4279 $DB->delete_records('user_private_key', array('userid' => $user->id
));
4281 // Remove users customised pages.
4282 $DB->delete_records('my_pages', array('userid' => $user->id
, 'private' => 1));
4284 // Force logout - may fail if file based sessions used, sorry.
4285 \core\session\manager
::kill_user_sessions($user->id
);
4287 // Workaround for bulk deletes of users with the same email address.
4288 $delname = clean_param($user->email
. "." . time(), PARAM_USERNAME
);
4289 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4293 // Mark internal user record as "deleted".
4294 $updateuser = new stdClass();
4295 $updateuser->id
= $user->id
;
4296 $updateuser->deleted
= 1;
4297 $updateuser->username
= $delname; // Remember it just in case.
4298 $updateuser->email
= md5($user->username
);// Store hash of username, useful importing/restoring users.
4299 $updateuser->idnumber
= ''; // Clear this field to free it up.
4300 $updateuser->picture
= 0;
4301 $updateuser->timemodified
= time();
4303 // Don't trigger update event, as user is being deleted.
4304 user_update_user($updateuser, false, false);
4306 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4307 context_helper
::delete_instance(CONTEXT_USER
, $user->id
);
4309 // Any plugin that needs to cleanup should register this event.
4311 $event = \core\event\user_deleted
::create(
4313 'objectid' => $user->id
,
4314 'relateduserid' => $user->id
,
4315 'context' => $usercontext,
4317 'username' => $user->username
,
4318 'email' => $user->email
,
4319 'idnumber' => $user->idnumber
,
4320 'picture' => $user->picture
,
4321 'mnethostid' => $user->mnethostid
4325 $event->add_record_snapshot('user', $olduser);
4328 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4329 // should know about this updated property persisted to the user's table.
4330 $user->timemodified
= $updateuser->timemodified
;
4332 // Notify auth plugin - do not block the delete even when plugin fails.
4333 $authplugin = get_auth_plugin($user->auth
);
4334 $authplugin->user_delete($user);
4340 * Retrieve the guest user object.
4342 * @return stdClass A {@link $USER} object
4344 function guest_user() {
4347 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest
))) {
4348 $newuser->confirmed
= 1;
4349 $newuser->lang
= $CFG->lang
;
4350 $newuser->lastip
= getremoteaddr();
4357 * Authenticates a user against the chosen authentication mechanism
4359 * Given a username and password, this function looks them
4360 * up using the currently selected authentication mechanism,
4361 * and if the authentication is successful, it returns a
4362 * valid $user object from the 'user' table.
4364 * Uses auth_ functions from the currently active auth module
4366 * After authenticate_user_login() returns success, you will need to
4367 * log that the user has logged in, and call complete_user_login() to set
4370 * Note: this function works only with non-mnet accounts!
4372 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4373 * @param string $password User's password
4374 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4375 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4376 * @return stdClass|false A {@link $USER} object or false if error
4378 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4380 require_once("$CFG->libdir/authlib.php");
4382 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id
)) {
4383 // we have found the user
4385 } else if (!empty($CFG->authloginviaemail
)) {
4386 if ($email = clean_param($username, PARAM_EMAIL
)) {
4387 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4388 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'email' => $email);
4389 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4390 if (count($users) === 1) {
4391 // Use email for login only if unique.
4392 $user = reset($users);
4393 $user = get_complete_user_data('id', $user->id
);
4394 $username = $user->username
;
4400 $authsenabled = get_enabled_auth_plugins();
4403 // Use manual if auth not set.
4404 $auth = empty($user->auth
) ?
'manual' : $user->auth
;
4405 if (!empty($user->suspended
)) {
4406 $failurereason = AUTH_LOGIN_SUSPENDED
;
4408 // Trigger login failed event.
4409 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4410 'other' => array('username' => $username, 'reason' => $failurereason)));
4412 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4415 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4416 // Legacy way to suspend user.
4417 $failurereason = AUTH_LOGIN_SUSPENDED
;
4419 // Trigger login failed event.
4420 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4421 'other' => array('username' => $username, 'reason' => $failurereason)));
4423 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4426 $auths = array($auth);
4429 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4430 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'deleted' => 1))) {
4431 $failurereason = AUTH_LOGIN_NOUSER
;
4433 // Trigger login failed event.
4434 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4435 'reason' => $failurereason)));
4437 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4441 // User does not exist.
4442 $auths = $authsenabled;
4443 $user = new stdClass();
4447 if ($ignorelockout) {
4448 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4449 // or this function is called from a SSO script.
4450 } else if ($user->id
) {
4451 // Verify login lockout after other ways that may prevent user login.
4452 if (login_is_lockedout($user)) {
4453 $failurereason = AUTH_LOGIN_LOCKOUT
;
4455 // Trigger login failed event.
4456 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4457 'other' => array('username' => $username, 'reason' => $failurereason)));
4460 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4464 // We can not lockout non-existing accounts.
4467 foreach ($auths as $auth) {
4468 $authplugin = get_auth_plugin($auth);
4470 // On auth fail fall through to the next plugin.
4471 if (!$authplugin->user_login($username, $password)) {
4475 // Successful authentication.
4477 // User already exists in database.
4478 if (empty($user->auth
)) {
4479 // For some reason auth isn't set yet.
4480 $DB->set_field('user', 'auth', $auth, array('id' => $user->id
));
4481 $user->auth
= $auth;
4484 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4485 // the current hash algorithm while we have access to the user's password.
4486 update_internal_user_password($user, $password);
4488 if ($authplugin->is_synchronised_with_external()) {
4489 // Update user record from external DB.
4490 $user = update_user_record_by_id($user->id
);
4493 // The user is authenticated but user creation may be disabled.
4494 if (!empty($CFG->authpreventaccountcreation
)) {
4495 $failurereason = AUTH_LOGIN_UNAUTHORISED
;
4497 // Trigger login failed event.
4498 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4499 'reason' => $failurereason)));
4502 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4503 $_SERVER['HTTP_USER_AGENT']);
4506 $user = create_user_record($username, $password, $auth);
4510 $authplugin->sync_roles($user);
4512 foreach ($authsenabled as $hau) {
4513 $hauth = get_auth_plugin($hau);
4514 $hauth->user_authenticated_hook($user, $username, $password);
4517 if (empty($user->id
)) {
4518 $failurereason = AUTH_LOGIN_NOUSER
;
4519 // Trigger login failed event.
4520 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4521 'reason' => $failurereason)));
4526 if (!empty($user->suspended
)) {
4527 // Just in case some auth plugin suspended account.
4528 $failurereason = AUTH_LOGIN_SUSPENDED
;
4529 // Trigger login failed event.
4530 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4531 'other' => array('username' => $username, 'reason' => $failurereason)));
4533 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4537 login_attempt_valid($user);
4538 $failurereason = AUTH_LOGIN_OK
;
4542 // Failed if all the plugins have failed.
4543 if (debugging('', DEBUG_ALL
)) {
4544 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4548 login_attempt_failed($user);
4549 $failurereason = AUTH_LOGIN_FAILED
;
4550 // Trigger login failed event.
4551 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4552 'other' => array('username' => $username, 'reason' => $failurereason)));
4555 $failurereason = AUTH_LOGIN_NOUSER
;
4556 // Trigger login failed event.
4557 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4558 'reason' => $failurereason)));
4566 * Call to complete the user login process after authenticate_user_login()
4567 * has succeeded. It will setup the $USER variable and other required bits
4571 * - It will NOT log anything -- up to the caller to decide what to log.
4572 * - this function does not set any cookies any more!
4574 * @param stdClass $user
4575 * @return stdClass A {@link $USER} object - BC only, do not use
4577 function complete_user_login($user) {
4580 \core\session\manager
::login_user($user);
4582 // Reload preferences from DB.
4583 unset($USER->preference
);
4584 check_user_preferences_loaded($USER);
4586 // Update login times.
4587 update_user_login_times();
4589 // Extra session prefs init.
4590 set_login_session_preferences();
4592 // Trigger login event.
4593 $event = \core\event\user_loggedin
::create(
4595 'userid' => $USER->id
,
4596 'objectid' => $USER->id
,
4597 'other' => array('username' => $USER->username
),
4602 if (isguestuser()) {
4603 // No need to continue when user is THE guest.
4608 // We can redirect to password change URL only in browser.
4612 // Select password change url.
4613 $userauth = get_auth_plugin($USER->auth
);
4615 // Check whether the user should be changing password.
4616 if (get_user_preferences('auth_forcepasswordchange', false)) {
4617 if ($userauth->can_change_password()) {
4618 if ($changeurl = $userauth->change_password_url()) {
4619 redirect($changeurl);
4621 redirect($CFG->httpswwwroot
.'/login/change_password.php');
4624 print_error('nopasswordchangeforced', 'auth');
4631 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4633 * @param string $password String to check.
4634 * @return boolean True if the $password matches the format of an md5 sum.
4636 function password_is_legacy_hash($password) {
4637 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4641 * Compare password against hash stored in user object to determine if it is valid.
4643 * If necessary it also updates the stored hash to the current format.
4645 * @param stdClass $user (Password property may be updated).
4646 * @param string $password Plain text password.
4647 * @return bool True if password is valid.
4649 function validate_internal_user_password($user, $password) {
4651 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4653 if ($user->password
=== AUTH_PASSWORD_NOT_CACHED
) {
4654 // Internal password is not used at all, it can not validate.
4658 // If hash isn't a legacy (md5) hash, validate using the library function.
4659 if (!password_is_legacy_hash($user->password
)) {
4660 return password_verify($password, $user->password
);
4663 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4664 // is valid we can then update it to the new algorithm.
4666 $sitesalt = isset($CFG->passwordsaltmain
) ?
$CFG->passwordsaltmain
: '';
4669 if ($user->password
=== md5($password.$sitesalt)
4670 or $user->password
=== md5($password)
4671 or $user->password
=== md5(addslashes($password).$sitesalt)
4672 or $user->password
=== md5(addslashes($password))) {
4673 // Note: we are intentionally using the addslashes() here because we
4674 // need to accept old password hashes of passwords with magic quotes.
4678 for ($i=1; $i<=20; $i++
) { // 20 alternative salts should be enough, right?
4679 $alt = 'passwordsaltalt'.$i;
4680 if (!empty($CFG->$alt)) {
4681 if ($user->password
=== md5($password.$CFG->$alt) or $user->password
=== md5(addslashes($password).$CFG->$alt)) {
4690 // If the password matches the existing md5 hash, update to the
4691 // current hash algorithm while we have access to the user's password.
4692 update_internal_user_password($user, $password);
4699 * Calculate hash for a plain text password.
4701 * @param string $password Plain text password to be hashed.
4702 * @param bool $fasthash If true, use a low cost factor when generating the hash
4703 * This is much faster to generate but makes the hash
4704 * less secure. It is used when lots of hashes need to
4705 * be generated quickly.
4706 * @return string The hashed password.
4708 * @throws moodle_exception If a problem occurs while generating the hash.
4710 function hash_internal_user_password($password, $fasthash = false) {
4712 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4714 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4715 $options = ($fasthash) ?
array('cost' => 4) : array();
4717 $generatedhash = password_hash($password, PASSWORD_DEFAULT
, $options);
4719 if ($generatedhash === false ||
$generatedhash === null) {
4720 throw new moodle_exception('Failed to generate password hash.');
4723 return $generatedhash;
4727 * Update password hash in user object (if necessary).
4729 * The password is updated if:
4730 * 1. The password has changed (the hash of $user->password is different
4731 * to the hash of $password).
4732 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4735 * Updating the password will modify the $user object and the database
4736 * record to use the current hashing algorithm.
4738 * @param stdClass $user User object (password property may be updated).
4739 * @param string $password Plain text password.
4740 * @param bool $fasthash If true, use a low cost factor when generating the hash
4741 * This is much faster to generate but makes the hash
4742 * less secure. It is used when lots of hashes need to
4743 * be generated quickly.
4744 * @return bool Always returns true.
4746 function update_internal_user_password($user, $password, $fasthash = false) {
4748 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4750 // Figure out what the hashed password should be.
4751 if (!isset($user->auth
)) {
4752 debugging('User record in update_internal_user_password() must include field auth',
4754 $user->auth
= $DB->get_field('user', 'auth', array('id' => $user->id
));
4756 $authplugin = get_auth_plugin($user->auth
);
4757 if ($authplugin->prevent_local_passwords()) {
4758 $hashedpassword = AUTH_PASSWORD_NOT_CACHED
;
4760 $hashedpassword = hash_internal_user_password($password, $fasthash);
4763 $algorithmchanged = false;
4765 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED
) {
4766 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4767 $passwordchanged = ($user->password
!== $hashedpassword);
4769 } else if (isset($user->password
)) {
4770 // If verification fails then it means the password has changed.
4771 $passwordchanged = !password_verify($password, $user->password
);
4772 $algorithmchanged = password_needs_rehash($user->password
, PASSWORD_DEFAULT
);
4774 // While creating new user, password in unset in $user object, to avoid
4775 // saving it with user_create()
4776 $passwordchanged = true;
4779 if ($passwordchanged ||
$algorithmchanged) {
4780 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id
));
4781 $user->password
= $hashedpassword;
4784 $user = $DB->get_record('user', array('id' => $user->id
));
4785 \core\event\user_password_updated
::create_from_user($user)->trigger();
4792 * Get a complete user record, which includes all the info in the user record.
4794 * Intended for setting as $USER session variable
4796 * @param string $field The user field to be checked for a given value.
4797 * @param string $value The value to match for $field.
4798 * @param int $mnethostid
4799 * @return mixed False, or A {@link $USER} object.
4801 function get_complete_user_data($field, $value, $mnethostid = null) {
4804 if (!$field ||
!$value) {
4808 // Build the WHERE clause for an SQL query.
4809 $params = array('fieldval' => $value);
4810 $constraints = "$field = :fieldval AND deleted <> 1";
4812 // If we are loading user data based on anything other than id,
4813 // we must also restrict our search based on mnet host.
4814 if ($field != 'id') {
4815 if (empty($mnethostid)) {
4816 // If empty, we restrict to local users.
4817 $mnethostid = $CFG->mnet_localhost_id
;
4820 if (!empty($mnethostid)) {
4821 $params['mnethostid'] = $mnethostid;
4822 $constraints .= " AND mnethostid = :mnethostid";
4825 // Get all the basic user data.
4826 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4830 // Get various settings and preferences.
4832 // Preload preference cache.
4833 check_user_preferences_loaded($user);
4835 // Load course enrolment related stuff.
4836 $user->lastcourseaccess
= array(); // During last session.
4837 $user->currentcourseaccess
= array(); // During current session.
4838 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id
))) {
4839 foreach ($lastaccesses as $lastaccess) {
4840 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
4844 $sql = "SELECT g.id, g.courseid
4845 FROM {groups} g, {groups_members} gm
4846 WHERE gm.groupid=g.id AND gm.userid=?";
4848 // This is a special hack to speedup calendar display.
4849 $user->groupmember
= array();
4850 if (!isguestuser($user)) {
4851 if ($groups = $DB->get_records_sql($sql, array($user->id
))) {
4852 foreach ($groups as $group) {
4853 if (!array_key_exists($group->courseid
, $user->groupmember
)) {
4854 $user->groupmember
[$group->courseid
] = array();
4856 $user->groupmember
[$group->courseid
][$group->id
] = $group->id
;
4861 // Add the custom profile fields to the user record.
4862 $user->profile
= array();
4863 if (!isguestuser($user)) {
4864 require_once($CFG->dirroot
.'/user/profile/lib.php');
4865 profile_load_custom_fields($user);
4868 // Rewrite some variables if necessary.
4869 if (!empty($user->description
)) {
4870 // No need to cart all of it around.
4871 $user->description
= true;
4873 if (isguestuser($user)) {
4874 // Guest language always same as site.
4875 $user->lang
= $CFG->lang
;
4876 // Name always in current language.
4877 $user->firstname
= get_string('guestuser');
4878 $user->lastname
= ' ';
4885 * Validate a password against the configured password policy
4887 * @param string $password the password to be checked against the password policy
4888 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4889 * @return bool true if the password is valid according to the policy. false otherwise.
4891 function check_password_policy($password, &$errmsg) {
4894 if (empty($CFG->passwordpolicy
)) {
4899 if (core_text
::strlen($password) < $CFG->minpasswordlength
) {
4900 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength
) .'</div>';
4903 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits
) {
4904 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits
) .'</div>';
4907 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower
) {
4908 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower
) .'</div>';
4911 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper
) {
4912 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper
) .'</div>';
4915 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum
) {
4916 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
) .'</div>';
4918 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars
)) {
4919 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars
) .'</div>';
4922 if ($errmsg == '') {
4931 * When logging in, this function is run to set certain preferences for the current SESSION.
4933 function set_login_session_preferences() {
4936 $SESSION->justloggedin
= true;
4938 unset($SESSION->lang
);
4939 unset($SESSION->forcelang
);
4940 unset($SESSION->load_navigation_admin
);
4945 * Delete a course, including all related data from the database, and any associated files.
4947 * @param mixed $courseorid The id of the course or course object to delete.
4948 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4949 * @return bool true if all the removals succeeded. false if there were any failures. If this
4950 * method returns false, some of the removals will probably have succeeded, and others
4951 * failed, but you have no way of knowing which.
4953 function delete_course($courseorid, $showfeedback = true) {
4956 if (is_object($courseorid)) {
4957 $courseid = $courseorid->id
;
4958 $course = $courseorid;
4960 $courseid = $courseorid;
4961 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4965 $context = context_course
::instance($courseid);
4967 // Frontpage course can not be deleted!!
4968 if ($courseid == SITEID
) {
4972 // Make the course completely empty.
4973 remove_course_contents($courseid, $showfeedback);
4975 // Delete the course and related context instance.
4976 context_helper
::delete_instance(CONTEXT_COURSE
, $courseid);
4978 $DB->delete_records("course", array("id" => $courseid));
4979 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4981 // Reset all course related caches here.
4982 if (class_exists('format_base', false)) {
4983 format_base
::reset_course_cache($courseid);
4986 // Trigger a course deleted event.
4987 $event = \core\event\course_deleted
::create(array(
4988 'objectid' => $course->id
,
4989 'context' => $context,
4991 'shortname' => $course->shortname
,
4992 'fullname' => $course->fullname
,
4993 'idnumber' => $course->idnumber
4996 $event->add_record_snapshot('course', $course);
5003 * Clear a course out completely, deleting all content but don't delete the course itself.
5005 * This function does not verify any permissions.
5007 * Please note this function also deletes all user enrolments,
5008 * enrolment instances and role assignments by default.
5011 * - 'keep_roles_and_enrolments' - false by default
5012 * - 'keep_groups_and_groupings' - false by default
5014 * @param int $courseid The id of the course that is being deleted
5015 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5016 * @param array $options extra options
5017 * @return bool true if all the removals succeeded. false if there were any failures. If this
5018 * method returns false, some of the removals will probably have succeeded, and others
5019 * failed, but you have no way of knowing which.
5021 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5022 global $CFG, $DB, $OUTPUT;
5024 require_once($CFG->libdir
.'/badgeslib.php');
5025 require_once($CFG->libdir
.'/completionlib.php');
5026 require_once($CFG->libdir
.'/questionlib.php');
5027 require_once($CFG->libdir
.'/gradelib.php');
5028 require_once($CFG->dirroot
.'/group/lib.php');
5029 require_once($CFG->dirroot
.'/tag/coursetagslib.php');
5030 require_once($CFG->dirroot
.'/comment/lib.php');
5031 require_once($CFG->dirroot
.'/rating/lib.php');
5032 require_once($CFG->dirroot
.'/notes/lib.php');
5034 // Handle course badges.
5035 badges_handle_course_deletion($courseid);
5037 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5038 $strdeleted = get_string('deleted').' - ';
5040 // Some crazy wishlist of stuff we should skip during purging of course content.
5041 $options = (array)$options;
5043 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST
);
5044 $coursecontext = context_course
::instance($courseid);
5045 $fs = get_file_storage();
5047 // Delete course completion information, this has to be done before grades and enrols.
5048 $cc = new completion_info($course);
5049 $cc->clear_criteria();
5050 if ($showfeedback) {
5051 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5054 // Remove all data from gradebook - this needs to be done before course modules
5055 // because while deleting this information, the system may need to reference
5056 // the course modules that own the grades.
5057 remove_course_grades($courseid, $showfeedback);
5058 remove_grade_letters($coursecontext, $showfeedback);
5060 // Delete course blocks in any all child contexts,
5061 // they may depend on modules so delete them first.
5062 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5063 foreach ($childcontexts as $childcontext) {
5064 blocks_delete_all_for_context($childcontext->id
);
5066 unset($childcontexts);
5067 blocks_delete_all_for_context($coursecontext->id
);
5068 if ($showfeedback) {
5069 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5072 // Delete every instance of every module,
5073 // this has to be done before deleting of course level stuff.
5074 $locations = core_component
::get_plugin_list('mod');
5075 foreach ($locations as $modname => $moddir) {
5076 if ($modname === 'NEWMODULE') {
5079 if ($module = $DB->get_record('modules', array('name' => $modname))) {
5080 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5081 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5082 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
5084 if ($instances = $DB->get_records($modname, array('course' => $course->id
))) {
5085 foreach ($instances as $instance) {
5086 if ($cm = get_coursemodule_from_instance($modname, $instance->id
, $course->id
)) {
5087 // Delete activity context questions and question categories.
5088 question_delete_activity($cm, $showfeedback);
5090 if (function_exists($moddelete)) {
5091 // This purges all module data in related tables, extra user prefs, settings, etc.
5092 $moddelete($instance->id
);
5094 // NOTE: we should not allow installation of modules with missing delete support!
5095 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5096 $DB->delete_records($modname, array('id' => $instance->id
));
5100 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5101 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5102 $DB->delete_records('course_modules', array('id' => $cm->id
));
5106 if (function_exists($moddeletecourse)) {
5107 // Execute ptional course cleanup callback.
5108 $moddeletecourse($course, $showfeedback);
5110 if ($instances and $showfeedback) {
5111 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5114 // Ooops, this module is not properly installed, force-delete it in the next block.
5118 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5120 // Remove all data from availability and completion tables that is associated
5121 // with course-modules belonging to this course. Note this is done even if the
5122 // features are not enabled now, in case they were enabled previously.
5123 $DB->delete_records_select('course_modules_completion',
5124 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5127 // Remove course-module data.
5128 $cms = $DB->get_records('course_modules', array('course' => $course->id
));
5129 foreach ($cms as $cm) {
5130 if ($module = $DB->get_record('modules', array('id' => $cm->module
))) {
5132 $DB->delete_records($module->name
, array('id' => $cm->instance
));
5133 } catch (Exception
$e) {
5134 // Ignore weird or missing table problems.
5137 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5138 $DB->delete_records('course_modules', array('id' => $cm->id
));
5141 if ($showfeedback) {
5142 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5145 // Cleanup the rest of plugins.
5146 $cleanuplugintypes = array('report', 'coursereport', 'format');
5147 foreach ($cleanuplugintypes as $type) {
5148 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
5149 foreach ($plugins as $plugin => $pluginfunction) {
5150 $pluginfunction($course->id
, $showfeedback);
5152 if ($showfeedback) {
5153 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5157 // Delete questions and question categories.
5158 question_delete_course($course, $showfeedback);
5159 if ($showfeedback) {
5160 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5163 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5164 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5165 foreach ($childcontexts as $childcontext) {
5166 $childcontext->delete();
5168 unset($childcontexts);
5170 // Remove all roles and enrolments by default.
5171 if (empty($options['keep_roles_and_enrolments'])) {
5172 // This hack is used in restore when deleting contents of existing course.
5173 role_unassign_all(array('contextid' => $coursecontext->id
, 'component' => ''), true);
5174 enrol_course_delete($course);
5175 if ($showfeedback) {
5176 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5180 // Delete any groups, removing members and grouping/course links first.
5181 if (empty($options['keep_groups_and_groupings'])) {
5182 groups_delete_groupings($course->id
, $showfeedback);
5183 groups_delete_groups($course->id
, $showfeedback);
5187 filter_delete_all_for_context($coursecontext->id
);
5189 // Notes, you shall not pass!
5190 note_delete_all($course->id
);
5193 comment
::delete_comments($coursecontext->id
);
5195 // Ratings are history too.
5196 $delopt = new stdclass();
5197 $delopt->contextid
= $coursecontext->id
;
5198 $rm = new rating_manager();
5199 $rm->delete_ratings($delopt);
5201 // Delete course tags.
5202 coursetag_delete_course_tags($course->id
, $showfeedback);
5204 // Delete calendar events.
5205 $DB->delete_records('event', array('courseid' => $course->id
));
5206 $fs->delete_area_files($coursecontext->id
, 'calendar');
5208 // Delete all related records in other core tables that may have a courseid
5209 // This array stores the tables that need to be cleared, as
5210 // table_name => column_name that contains the course id.
5211 $tablestoclear = array(
5212 'backup_courses' => 'courseid', // Scheduled backup stuff.
5213 'user_lastaccess' => 'courseid', // User access info.
5215 foreach ($tablestoclear as $table => $col) {
5216 $DB->delete_records($table, array($col => $course->id
));
5219 // Delete all course backup files.
5220 $fs->delete_area_files($coursecontext->id
, 'backup');
5222 // Cleanup course record - remove links to deleted stuff.
5223 $oldcourse = new stdClass();
5224 $oldcourse->id
= $course->id
;
5225 $oldcourse->summary
= '';
5226 $oldcourse->cacherev
= 0;
5227 $oldcourse->legacyfiles
= 0;
5228 $oldcourse->enablecompletion
= 0;
5229 if (!empty($options['keep_groups_and_groupings'])) {
5230 $oldcourse->defaultgroupingid
= 0;
5232 $DB->update_record('course', $oldcourse);
5234 // Delete course sections.
5235 $DB->delete_records('course_sections', array('course' => $course->id
));
5237 // Delete legacy, section and any other course files.
5238 $fs->delete_area_files($coursecontext->id
, 'course'); // Files from summary and section.
5240 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5241 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5242 // Easy, do not delete the context itself...
5243 $coursecontext->delete_content();
5246 // We can not drop all context stuff because it would bork enrolments and roles,
5247 // there might be also files used by enrol plugins...
5250 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5251 // also some non-standard unsupported plugins may try to store something there.
5252 fulldelete($CFG->dataroot
.'/'.$course->id
);
5254 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5255 $cachemodinfo = cache
::make('core', 'coursemodinfo');
5256 $cachemodinfo->delete($courseid);
5258 // Trigger a course content deleted event.
5259 $event = \core\event\course_content_deleted
::create(array(
5260 'objectid' => $course->id
,
5261 'context' => $coursecontext,
5262 'other' => array('shortname' => $course->shortname
,
5263 'fullname' => $course->fullname
,
5264 'options' => $options) // Passing this for legacy reasons.
5266 $event->add_record_snapshot('course', $course);
5273 * Change dates in module - used from course reset.
5275 * @param string $modname forum, assignment, etc
5276 * @param array $fields array of date fields from mod table
5277 * @param int $timeshift time difference
5278 * @param int $courseid
5279 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5280 * @return bool success
5282 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5284 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
5287 $params = array($timeshift, $courseid);
5288 foreach ($fields as $field) {
5289 $updatesql = "UPDATE {".$modname."}
5290 SET $field = $field + ?
5291 WHERE course=? AND $field<>0";
5293 $updatesql .= ' AND id=?';
5296 $return = $DB->execute($updatesql, $params) && $return;
5299 $refreshfunction = $modname.'_refresh_events';
5300 if (function_exists($refreshfunction)) {
5301 $refreshfunction($courseid);
5308 * This function will empty a course of user data.
5309 * It will retain the activities and the structure of the course.
5311 * @param object $data an object containing all the settings including courseid (without magic quotes)
5312 * @return array status array of array component, item, error
5314 function reset_course_userdata($data) {
5316 require_once($CFG->libdir
.'/gradelib.php');
5317 require_once($CFG->libdir
.'/completionlib.php');
5318 require_once($CFG->dirroot
.'/group/lib.php');
5320 $data->courseid
= $data->id
;
5321 $context = context_course
::instance($data->courseid
);
5323 $eventparams = array(
5324 'context' => $context,
5325 'courseid' => $data->id
,
5327 'reset_options' => (array) $data
5330 $event = \core\event\course_reset_started
::create($eventparams);
5333 // Calculate the time shift of dates.
5334 if (!empty($data->reset_start_date
)) {
5335 // Time part of course startdate should be zero.
5336 $data->timeshift
= $data->reset_start_date
- usergetmidnight($data->reset_start_date_old
);
5338 $data->timeshift
= 0;
5341 // Result array: component, item, error.
5344 // Start the resetting.
5345 $componentstr = get_string('general');
5347 // Move the course start time.
5348 if (!empty($data->reset_start_date
) and $data->timeshift
) {
5349 // Change course start data.
5350 $DB->set_field('course', 'startdate', $data->reset_start_date
, array('id' => $data->courseid
));
5351 // Update all course and group events - do not move activity events.
5352 $updatesql = "UPDATE {event}
5353 SET timestart = timestart + ?
5354 WHERE courseid=? AND instance=0";
5355 $DB->execute($updatesql, array($data->timeshift
, $data->courseid
));
5357 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5360 if (!empty($data->reset_events
)) {
5361 $DB->delete_records('event', array('courseid' => $data->courseid
));
5362 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5365 if (!empty($data->reset_notes
)) {
5366 require_once($CFG->dirroot
.'/notes/lib.php');
5367 note_delete_all($data->courseid
);
5368 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5371 if (!empty($data->delete_blog_associations
)) {
5372 require_once($CFG->dirroot
.'/blog/lib.php');
5373 blog_remove_associations_for_course($data->courseid
);
5374 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5377 if (!empty($data->reset_completion
)) {
5378 // Delete course and activity completion information.
5379 $course = $DB->get_record('course', array('id' => $data->courseid
));
5380 $cc = new completion_info($course);
5381 $cc->delete_all_completion_data();
5382 $status[] = array('component' => $componentstr,
5383 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5386 $componentstr = get_string('roles');
5388 if (!empty($data->reset_roles_overrides
)) {
5389 $children = $context->get_child_contexts();
5390 foreach ($children as $child) {
5391 $DB->delete_records('role_capabilities', array('contextid' => $child->id
));
5393 $DB->delete_records('role_capabilities', array('contextid' => $context->id
));
5394 // Force refresh for logged in users.
5395 $context->mark_dirty();
5396 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5399 if (!empty($data->reset_roles_local
)) {
5400 $children = $context->get_child_contexts();
5401 foreach ($children as $child) {
5402 role_unassign_all(array('contextid' => $child->id
));
5404 // Force refresh for logged in users.
5405 $context->mark_dirty();
5406 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5409 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5410 $data->unenrolled
= array();
5411 if (!empty($data->unenrol_users
)) {
5412 $plugins = enrol_get_plugins(true);
5413 $instances = enrol_get_instances($data->courseid
, true);
5414 foreach ($instances as $key => $instance) {
5415 if (!isset($plugins[$instance->enrol
])) {
5416 unset($instances[$key]);
5421 foreach ($data->unenrol_users
as $withroleid) {
5424 FROM {user_enrolments} ue
5425 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5426 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5427 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5428 $params = array('courseid' => $data->courseid
, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE
);
5431 // Without any role assigned at course context.
5433 FROM {user_enrolments} ue
5434 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5435 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5436 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5437 WHERE ra.id IS null";
5438 $params = array('courseid' => $data->courseid
, 'courselevel' => CONTEXT_COURSE
);
5441 $rs = $DB->get_recordset_sql($sql, $params);
5442 foreach ($rs as $ue) {
5443 if (!isset($instances[$ue->enrolid
])) {
5446 $instance = $instances[$ue->enrolid
];
5447 $plugin = $plugins[$instance->enrol
];
5448 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5452 $plugin->unenrol_user($instance, $ue->userid
);
5453 $data->unenrolled
[$ue->userid
] = $ue->userid
;
5458 if (!empty($data->unenrolled
)) {
5460 'component' => $componentstr,
5461 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled
).')',
5466 $componentstr = get_string('groups');
5468 // Remove all group members.
5469 if (!empty($data->reset_groups_members
)) {
5470 groups_delete_group_members($data->courseid
);
5471 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5474 // Remove all groups.
5475 if (!empty($data->reset_groups_remove
)) {
5476 groups_delete_groups($data->courseid
, false);
5477 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5480 // Remove all grouping members.
5481 if (!empty($data->reset_groupings_members
)) {
5482 groups_delete_groupings_groups($data->courseid
, false);
5483 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5486 // Remove all groupings.
5487 if (!empty($data->reset_groupings_remove
)) {
5488 groups_delete_groupings($data->courseid
, false);
5489 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5492 // Look in every instance of every module for data to delete.
5493 $unsupportedmods = array();
5494 if ($allmods = $DB->get_records('modules') ) {
5495 foreach ($allmods as $mod) {
5496 $modname = $mod->name
;
5497 $modfile = $CFG->dirroot
.'/mod/'. $modname.'/lib.php';
5498 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5499 if (file_exists($modfile)) {
5500 if (!$DB->count_records($modname, array('course' => $data->courseid
))) {
5501 continue; // Skip mods with no instances.
5503 include_once($modfile);
5504 if (function_exists($moddeleteuserdata)) {
5505 $modstatus = $moddeleteuserdata($data);
5506 if (is_array($modstatus)) {
5507 $status = array_merge($status, $modstatus);
5509 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5512 $unsupportedmods[] = $mod;
5515 debugging('Missing lib.php in '.$modname.' module!');
5520 // Mention unsupported mods.
5521 if (!empty($unsupportedmods)) {
5522 foreach ($unsupportedmods as $mod) {
5524 'component' => get_string('modulenameplural', $mod->name
),
5526 'error' => get_string('resetnotimplemented')
5531 $componentstr = get_string('gradebook', 'grades');
5532 // Reset gradebook,.
5533 if (!empty($data->reset_gradebook_items
)) {
5534 remove_course_grades($data->courseid
, false);
5535 grade_grab_course_grades($data->courseid
);
5536 grade_regrade_final_grades($data->courseid
);
5537 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5539 } else if (!empty($data->reset_gradebook_grades
)) {
5540 grade_course_reset($data->courseid
);
5541 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5544 if (!empty($data->reset_comments
)) {
5545 require_once($CFG->dirroot
.'/comment/lib.php');
5546 comment
::reset_course_page_comments($context);
5549 $event = \core\event\course_reset_ended
::create($eventparams);
5556 * Generate an email processing address.
5559 * @param string $modargs
5560 * @return string Returns email processing address
5562 function generate_email_processing_address($modid, $modargs) {
5565 $header = $CFG->mailprefix
. substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5566 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain
;
5572 * @todo Finish documenting this function
5574 * @param string $modargs
5575 * @param string $body Currently unused
5577 function moodle_process_email($modargs, $body) {
5580 // The first char should be an unencoded letter. We'll take this as an action.
5581 switch ($modargs{0}) {
5582 case 'B': { // Bounce.
5583 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5584 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5585 // Check the half md5 of their email.
5586 $md5check = substr(md5($user->email
), 0, 16);
5587 if ($md5check == substr($modargs, -16)) {
5588 set_bounce_count($user);
5590 // Else maybe they've already changed it?
5594 // Maybe more later?
5601 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5603 * @param string $action 'get', 'buffer', 'close' or 'flush'
5604 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5606 function get_mailer($action='get') {
5609 /** @var moodle_phpmailer $mailer */
5610 static $mailer = null;
5611 static $counter = 0;
5613 if (!isset($CFG->smtpmaxbulk
)) {
5614 $CFG->smtpmaxbulk
= 1;
5617 if ($action == 'get') {
5618 $prevkeepalive = false;
5620 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5621 if ($counter < $CFG->smtpmaxbulk
and !$mailer->isError()) {
5623 // Reset the mailer.
5624 $mailer->Priority
= 3;
5625 $mailer->CharSet
= 'UTF-8'; // Our default.
5626 $mailer->ContentType
= "text/plain";
5627 $mailer->Encoding
= "8bit";
5628 $mailer->From
= "root@localhost";
5629 $mailer->FromName
= "Root User";
5630 $mailer->Sender
= "";
5631 $mailer->Subject
= "";
5633 $mailer->AltBody
= "";
5634 $mailer->ConfirmReadingTo
= "";
5636 $mailer->clearAllRecipients();
5637 $mailer->clearReplyTos();
5638 $mailer->clearAttachments();
5639 $mailer->clearCustomHeaders();
5643 $prevkeepalive = $mailer->SMTPKeepAlive
;
5644 get_mailer('flush');
5647 require_once($CFG->libdir
.'/phpmailer/moodle_phpmailer.php');
5648 $mailer = new moodle_phpmailer();
5652 if ($CFG->smtphosts
== 'qmail') {
5653 // Use Qmail system.
5656 } else if (empty($CFG->smtphosts
)) {
5657 // Use PHP mail() = sendmail.
5661 // Use SMTP directly.
5663 if (!empty($CFG->debugsmtp
)) {
5664 $mailer->SMTPDebug
= true;
5666 // Specify main and backup servers.
5667 $mailer->Host
= $CFG->smtphosts
;
5668 // Specify secure connection protocol.
5669 $mailer->SMTPSecure
= $CFG->smtpsecure
;
5670 // Use previous keepalive.
5671 $mailer->SMTPKeepAlive
= $prevkeepalive;
5673 if ($CFG->smtpuser
) {
5674 // Use SMTP authentication.
5675 $mailer->SMTPAuth
= true;
5676 $mailer->Username
= $CFG->smtpuser
;
5677 $mailer->Password
= $CFG->smtppass
;
5686 // Keep smtp session open after sending.
5687 if ($action == 'buffer') {
5688 if (!empty($CFG->smtpmaxbulk
)) {
5689 get_mailer('flush');
5691 if ($m->Mailer
== 'smtp') {
5692 $m->SMTPKeepAlive
= true;
5698 // Close smtp session, but continue buffering.
5699 if ($action == 'flush') {
5700 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5701 if (!empty($mailer->SMTPDebug
)) {
5704 $mailer->SmtpClose();
5705 if (!empty($mailer->SMTPDebug
)) {
5712 // Close smtp session, do not buffer anymore.
5713 if ($action == 'close') {
5714 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5715 get_mailer('flush');
5716 $mailer->SMTPKeepAlive
= false;
5718 $mailer = null; // Better force new instance.
5724 * Send an email to a specified user
5726 * @param stdClass $user A {@link $USER} object
5727 * @param stdClass $from A {@link $USER} object
5728 * @param string $subject plain text subject line of the email
5729 * @param string $messagetext plain text version of the message
5730 * @param string $messagehtml complete html version of the message (optional)
5731 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
5732 * @param string $attachname the name of the file (extension indicates MIME)
5733 * @param bool $usetrueaddress determines whether $from email address should
5734 * be sent out. Will be overruled by user profile setting for maildisplay
5735 * @param string $replyto Email address to reply to
5736 * @param string $replytoname Name of reply to recipient
5737 * @param int $wordwrapwidth custom word wrap width, default 79
5738 * @return bool Returns true if mail was sent OK and false if there was an error.
5740 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5741 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5745 if (empty($user) or empty($user->id
)) {
5746 debugging('Can not send email to null user', DEBUG_DEVELOPER
);
5750 if (empty($user->email
)) {
5751 debugging('Can not send email to user without email: '.$user->id
, DEBUG_DEVELOPER
);
5755 if (!empty($user->deleted
)) {
5756 debugging('Can not send email to deleted user: '.$user->id
, DEBUG_DEVELOPER
);
5760 if (defined('BEHAT_SITE_RUNNING')) {
5761 // Fake email sending in behat.
5765 if (!empty($CFG->noemailever
)) {
5766 // Hidden setting for development sites, set in config.php if needed.
5767 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL
);
5771 if (!empty($CFG->divertallemailsto
)) {
5772 $subject = "[DIVERTED {$user->email}] $subject";
5773 $user = clone($user);
5774 $user->email
= $CFG->divertallemailsto
;
5777 // Skip mail to suspended users.
5778 if ((isset($user->auth
) && $user->auth
=='nologin') or (isset($user->suspended
) && $user->suspended
)) {
5782 if (!validate_email($user->email
)) {
5783 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5784 $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
5785 error_log($invalidemail);
5787 mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
5792 if (over_bounce_threshold($user)) {
5793 $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
5794 error_log($bouncemsg);
5796 mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
5801 // If the user is a remote mnet user, parse the email text for URL to the
5802 // wwwroot and modify the url to direct the user's browser to login at their
5803 // home site (identity provider - idp) before hitting the link itself.
5804 if (is_mnet_remote_user($user)) {
5805 require_once($CFG->dirroot
.'/mnet/lib.php');
5807 $jumpurl = mnet_get_idp_jump_url($user);
5808 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5810 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5813 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5817 $mail = get_mailer();
5819 if (!empty($mail->SMTPDebug
)) {
5820 echo '<pre>' . "\n";
5823 $temprecipients = array();
5824 $tempreplyto = array();
5826 $supportuser = core_user
::get_support_user();
5828 // Make up an email address for handling bounces.
5829 if (!empty($CFG->handlebounces
)) {
5830 $modargs = 'B'.base64_encode(pack('V', $user->id
)).substr(md5($user->email
), 0, 16);
5831 $mail->Sender
= generate_email_processing_address(0, $modargs);
5833 $mail->Sender
= $supportuser->email
;
5836 if (!empty($CFG->emailonlyfromnoreplyaddress
)) {
5837 $usetrueaddress = false;
5838 if (empty($replyto) && $from->maildisplay
) {
5839 $replyto = $from->email
;
5840 $replytoname = fullname($from);
5844 if (is_string($from)) { // So we can pass whatever we want if there is need.
5845 $mail->From
= $CFG->noreplyaddress
;
5846 $mail->FromName
= $from;
5847 } else if ($usetrueaddress and $from->maildisplay
) {
5848 $mail->From
= $from->email
;
5849 $mail->FromName
= fullname($from);
5851 $mail->From
= $CFG->noreplyaddress
;
5852 $mail->FromName
= fullname($from);
5853 if (empty($replyto)) {
5854 $tempreplyto[] = array($CFG->noreplyaddress
, get_string('noreplyname'));
5858 if (!empty($replyto)) {
5859 $tempreplyto[] = array($replyto, $replytoname);
5862 $mail->Subject
= substr($subject, 0, 900);
5864 $temprecipients[] = array($user->email
, fullname($user));
5867 $mail->WordWrap
= $wordwrapwidth;
5869 if (!empty($from->customheaders
)) {
5870 // Add custom headers.
5871 if (is_array($from->customheaders
)) {
5872 foreach ($from->customheaders
as $customheader) {
5873 $mail->addCustomHeader($customheader);
5876 $mail->addCustomHeader($from->customheaders
);
5880 if (!empty($from->priority
)) {
5881 $mail->Priority
= $from->priority
;
5884 if ($messagehtml && !empty($user->mailformat
) && $user->mailformat
== 1) {
5885 // Don't ever send HTML to users who don't want it.
5886 $mail->isHTML(true);
5887 $mail->Encoding
= 'quoted-printable';
5888 $mail->Body
= $messagehtml;
5889 $mail->AltBody
= "\n$messagetext\n";
5891 $mail->IsHTML(false);
5892 $mail->Body
= "\n$messagetext\n";
5895 if ($attachment && $attachname) {
5896 if (preg_match( "~\\.\\.~" , $attachment )) {
5897 // Security check for ".." in dir path.
5898 $temprecipients[] = array($supportuser->email
, fullname($supportuser, true));
5899 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5901 require_once($CFG->libdir
.'/filelib.php');
5902 $mimetype = mimeinfo('type', $attachname);
5903 $mail->addAttachment($CFG->dataroot
.'/'. $attachment, $attachname, 'base64', $mimetype);
5907 // Check if the email should be sent in an other charset then the default UTF-8.
5908 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
5910 // Use the defined site mail charset or eventually the one preferred by the recipient.
5911 $charset = $CFG->sitemailcharset
;
5912 if (!empty($CFG->allowusermailcharset
)) {
5913 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
5914 $charset = $useremailcharset;
5918 // Convert all the necessary strings if the charset is supported.
5919 $charsets = get_list_of_charsets();
5920 unset($charsets['UTF-8']);
5921 if (in_array($charset, $charsets)) {
5922 $mail->CharSet
= $charset;
5923 $mail->FromName
= core_text
::convert($mail->FromName
, 'utf-8', strtolower($charset));
5924 $mail->Subject
= core_text
::convert($mail->Subject
, 'utf-8', strtolower($charset));
5925 $mail->Body
= core_text
::convert($mail->Body
, 'utf-8', strtolower($charset));
5926 $mail->AltBody
= core_text
::convert($mail->AltBody
, 'utf-8', strtolower($charset));
5928 foreach ($temprecipients as $key => $values) {
5929 $temprecipients[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
5931 foreach ($tempreplyto as $key => $values) {
5932 $tempreplyto[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
5937 foreach ($temprecipients as $values) {
5938 $mail->addAddress($values[0], $values[1]);
5940 foreach ($tempreplyto as $values) {
5941 $mail->addReplyTo($values[0], $values[1]);
5944 if ($mail->send()) {
5945 set_send_count($user);
5946 if (!empty($mail->SMTPDebug
)) {
5951 // Trigger event for failing to send email.
5952 $event = \core\event\email_failed
::create(array(
5953 'context' => context_system
::instance(),
5954 'userid' => $from->id
,
5955 'relateduserid' => $user->id
,
5957 'subject' => $subject,
5958 'message' => $messagetext,
5959 'errorinfo' => $mail->ErrorInfo
5964 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo
);
5966 if (!empty($mail->SMTPDebug
)) {
5974 * Generate a signoff for emails based on support settings
5978 function generate_email_signoff() {
5982 if (!empty($CFG->supportname
)) {
5983 $signoff .= $CFG->supportname
."\n";
5985 if (!empty($CFG->supportemail
)) {
5986 $signoff .= $CFG->supportemail
."\n";
5988 if (!empty($CFG->supportpage
)) {
5989 $signoff .= $CFG->supportpage
."\n";
5995 * Sets specified user's password and send the new password to the user via email.
5997 * @param stdClass $user A {@link $USER} object
5998 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
5999 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6001 function setnew_password_and_mail($user, $fasthash = false) {
6004 // We try to send the mail in language the user understands,
6005 // unfortunately the filter_string() does not support alternative langs yet
6006 // so multilang will not work properly for site->fullname.
6007 $lang = empty($user->lang
) ?
$CFG->lang
: $user->lang
;
6011 $supportuser = core_user
::get_support_user();
6013 $newpassword = generate_password();
6015 update_internal_user_password($user, $newpassword, $fasthash);
6017 $a = new stdClass();
6018 $a->firstname
= fullname($user, true);
6019 $a->sitename
= format_string($site->fullname
);
6020 $a->username
= $user->username
;
6021 $a->newpassword
= $newpassword;
6022 $a->link
= $CFG->wwwroot
.'/login/';
6023 $a->signoff
= generate_email_signoff();
6025 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6027 $subject = format_string($site->fullname
) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6029 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6030 return email_to_user($user, $supportuser, $subject, $message);
6035 * Resets specified user's password and send the new password to the user via email.
6037 * @param stdClass $user A {@link $USER} object
6038 * @return bool Returns true if mail was sent OK and false if there was an error.
6040 function reset_password_and_mail($user) {
6044 $supportuser = core_user
::get_support_user();
6046 $userauth = get_auth_plugin($user->auth
);
6047 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth
)) {
6048 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6052 $newpassword = generate_password();
6054 if (!$userauth->user_update_password($user, $newpassword)) {
6055 print_error("cannotsetpassword");
6058 $a = new stdClass();
6059 $a->firstname
= $user->firstname
;
6060 $a->lastname
= $user->lastname
;
6061 $a->sitename
= format_string($site->fullname
);
6062 $a->username
= $user->username
;
6063 $a->newpassword
= $newpassword;
6064 $a->link
= $CFG->httpswwwroot
.'/login/change_password.php';
6065 $a->signoff
= generate_email_signoff();
6067 $message = get_string('newpasswordtext', '', $a);
6069 $subject = format_string($site->fullname
) .': '. get_string('changedpassword');
6071 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6073 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6074 return email_to_user($user, $supportuser, $subject, $message);
6078 * Send email to specified user with confirmation text and activation link.
6080 * @param stdClass $user A {@link $USER} object
6081 * @return bool Returns true if mail was sent OK and false if there was an error.
6083 function send_confirmation_email($user) {
6087 $supportuser = core_user
::get_support_user();
6089 $data = new stdClass();
6090 $data->firstname
= fullname($user);
6091 $data->sitename
= format_string($site->fullname
);
6092 $data->admin
= generate_email_signoff();
6094 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname
));
6096 $username = urlencode($user->username
);
6097 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
6098 $data->link
= $CFG->wwwroot
.'/login/confirm.php?data='. $user->secret
.'/'. $username;
6099 $message = get_string('emailconfirmation', '', $data);
6100 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6102 $user->mailformat
= 1; // Always send HTML version as well.
6104 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6105 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6109 * Sends a password change confirmation email.
6111 * @param stdClass $user A {@link $USER} object
6112 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6113 * @return bool Returns true if mail was sent OK and false if there was an error.
6115 function send_password_change_confirmation_email($user, $resetrecord) {
6119 $supportuser = core_user
::get_support_user();
6120 $pwresetmins = isset($CFG->pwresettime
) ?
floor($CFG->pwresettime
/ MINSECS
) : 30;
6122 $data = new stdClass();
6123 $data->firstname
= $user->firstname
;
6124 $data->lastname
= $user->lastname
;
6125 $data->username
= $user->username
;
6126 $data->sitename
= format_string($site->fullname
);
6127 $data->link
= $CFG->httpswwwroot
.'/login/forgot_password.php?token='. $resetrecord->token
;
6128 $data->admin
= generate_email_signoff();
6129 $data->resetminutes
= $pwresetmins;
6131 $message = get_string('emailresetconfirmation', '', $data);
6132 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname
));
6134 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6135 return email_to_user($user, $supportuser, $subject, $message);
6140 * Sends an email containinginformation on how to change your password.
6142 * @param stdClass $user A {@link $USER} object
6143 * @return bool Returns true if mail was sent OK and false if there was an error.
6145 function send_password_change_info($user) {
6149 $supportuser = core_user
::get_support_user();
6150 $systemcontext = context_system
::instance();
6152 $data = new stdClass();
6153 $data->firstname
= $user->firstname
;
6154 $data->lastname
= $user->lastname
;
6155 $data->sitename
= format_string($site->fullname
);
6156 $data->admin
= generate_email_signoff();
6158 $userauth = get_auth_plugin($user->auth
);
6160 if (!is_enabled_auth($user->auth
) or $user->auth
== 'nologin') {
6161 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6162 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6163 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6164 return email_to_user($user, $supportuser, $subject, $message);
6167 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6168 // We have some external url for password changing.
6169 $data->link
.= $userauth->change_password_url();
6172 // No way to change password, sorry.
6176 if (!empty($data->link
) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id
)) {
6177 $message = get_string('emailpasswordchangeinfo', '', $data);
6178 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6180 $message = get_string('emailpasswordchangeinfofail', '', $data);
6181 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6184 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6185 return email_to_user($user, $supportuser, $subject, $message);
6190 * Check that an email is allowed. It returns an error message if there was a problem.
6192 * @param string $email Content of email
6193 * @return string|false
6195 function email_is_not_allowed($email) {
6198 if (!empty($CFG->allowemailaddresses
)) {
6199 $allowed = explode(' ', $CFG->allowemailaddresses
);
6200 foreach ($allowed as $allowedpattern) {
6201 $allowedpattern = trim($allowedpattern);
6202 if (!$allowedpattern) {
6205 if (strpos($allowedpattern, '.') === 0) {
6206 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6207 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6211 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6215 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
6217 } else if (!empty($CFG->denyemailaddresses
)) {
6218 $denied = explode(' ', $CFG->denyemailaddresses
);
6219 foreach ($denied as $deniedpattern) {
6220 $deniedpattern = trim($deniedpattern);
6221 if (!$deniedpattern) {
6224 if (strpos($deniedpattern, '.') === 0) {
6225 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6226 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6227 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6230 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6231 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6242 * Returns local file storage instance
6244 * @return file_storage
6246 function get_file_storage() {
6255 require_once("$CFG->libdir/filelib.php");
6257 if (isset($CFG->filedir
)) {
6258 $filedir = $CFG->filedir
;
6260 $filedir = $CFG->dataroot
.'/filedir';
6263 if (isset($CFG->trashdir
)) {
6264 $trashdirdir = $CFG->trashdir
;
6266 $trashdirdir = $CFG->dataroot
.'/trashdir';
6269 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions
, $CFG->filepermissions
);
6275 * Returns local file storage instance
6277 * @return file_browser
6279 function get_file_browser() {
6288 require_once("$CFG->libdir/filelib.php");
6290 $fb = new file_browser();
6296 * Returns file packer
6298 * @param string $mimetype default application/zip
6299 * @return file_packer
6301 function get_file_packer($mimetype='application/zip') {
6304 static $fp = array();
6306 if (isset($fp[$mimetype])) {
6307 return $fp[$mimetype];
6310 switch ($mimetype) {
6311 case 'application/zip':
6312 case 'application/vnd.moodle.profiling':
6313 $classname = 'zip_packer';
6316 case 'application/x-gzip' :
6317 $classname = 'tgz_packer';
6320 case 'application/vnd.moodle.backup':
6321 $classname = 'mbz_packer';
6328 require_once("$CFG->libdir/filestorage/$classname.php");
6329 $fp[$mimetype] = new $classname();
6331 return $fp[$mimetype];
6335 * Returns current name of file on disk if it exists.
6337 * @param string $newfile File to be verified
6338 * @return string Current name of file on disk if true
6340 function valid_uploaded_file($newfile) {
6341 if (empty($newfile)) {
6344 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6345 return $newfile['tmp_name'];
6352 * Returns the maximum size for uploading files.
6354 * There are seven possible upload limits:
6355 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6356 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6357 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6358 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6359 * 5. by the Moodle admin in $CFG->maxbytes
6360 * 6. by the teacher in the current course $course->maxbytes
6361 * 7. by the teacher for the current module, eg $assignment->maxbytes
6363 * These last two are passed to this function as arguments (in bytes).
6364 * Anything defined as 0 is ignored.
6365 * The smallest of all the non-zero numbers is returned.
6367 * @todo Finish documenting this function
6369 * @param int $sitebytes Set maximum size
6370 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6371 * @param int $modulebytes Current module ->maxbytes (in bytes)
6372 * @return int The maximum size for uploading files.
6374 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6376 if (! $filesize = ini_get('upload_max_filesize')) {
6379 $minimumsize = get_real_size($filesize);
6381 if ($postsize = ini_get('post_max_size')) {
6382 $postsize = get_real_size($postsize);
6383 if ($postsize < $minimumsize) {
6384 $minimumsize = $postsize;
6388 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6389 $minimumsize = $sitebytes;
6392 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6393 $minimumsize = $coursebytes;
6396 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6397 $minimumsize = $modulebytes;
6400 return $minimumsize;
6404 * Returns the maximum size for uploading files for the current user
6406 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6408 * @param context $context The context in which to check user capabilities
6409 * @param int $sitebytes Set maximum size
6410 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6411 * @param int $modulebytes Current module ->maxbytes (in bytes)
6412 * @param stdClass $user The user
6413 * @return int The maximum size for uploading files.
6415 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6422 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6423 return USER_CAN_IGNORE_FILE_SIZE_LIMITS
;
6426 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6430 * Returns an array of possible sizes in local language
6432 * Related to {@link get_max_upload_file_size()} - this function returns an
6433 * array of possible sizes in an array, translated to the
6436 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6438 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6439 * with the value set to 0. This option will be the first in the list.
6441 * @uses SORT_NUMERIC
6442 * @param int $sitebytes Set maximum size
6443 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6444 * @param int $modulebytes Current module ->maxbytes (in bytes)
6445 * @param int|array $custombytes custom upload size/s which will be added to list,
6446 * Only value/s smaller then maxsize will be added to list.
6449 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6452 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6456 if ($sitebytes == 0) {
6457 // Will get the minimum of upload_max_filesize or post_max_size.
6458 $sitebytes = get_max_upload_file_size();
6461 $filesize = array();
6462 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6463 5242880, 10485760, 20971520, 52428800, 104857600);
6465 // If custombytes is given and is valid then add it to the list.
6466 if (is_number($custombytes) and $custombytes > 0) {
6467 $custombytes = (int)$custombytes;
6468 if (!in_array($custombytes, $sizelist)) {
6469 $sizelist[] = $custombytes;
6471 } else if (is_array($custombytes)) {
6472 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6475 // Allow maxbytes to be selected if it falls outside the above boundaries.
6476 if (isset($CFG->maxbytes
) && !in_array(get_real_size($CFG->maxbytes
), $sizelist)) {
6477 // Note: get_real_size() is used in order to prevent problems with invalid values.
6478 $sizelist[] = get_real_size($CFG->maxbytes
);
6481 foreach ($sizelist as $sizebytes) {
6482 if ($sizebytes < $maxsize && $sizebytes > 0) {
6483 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6490 (($modulebytes < $coursebytes ||
$coursebytes == 0) &&
6491 ($modulebytes < $sitebytes ||
$sitebytes == 0))) {
6492 $limitlevel = get_string('activity', 'core');
6493 $displaysize = display_size($modulebytes);
6494 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6496 } else if ($coursebytes && ($coursebytes < $sitebytes ||
$sitebytes == 0)) {
6497 $limitlevel = get_string('course', 'core');
6498 $displaysize = display_size($coursebytes);
6499 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6501 } else if ($sitebytes) {
6502 $limitlevel = get_string('site', 'core');
6503 $displaysize = display_size($sitebytes);
6504 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6507 krsort($filesize, SORT_NUMERIC
);
6509 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6510 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) +
$filesize;
6517 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6519 * If excludefiles is defined, then that file/directory is ignored
6520 * If getdirs is true, then (sub)directories are included in the output
6521 * If getfiles is true, then files are included in the output
6522 * (at least one of these must be true!)
6524 * @todo Finish documenting this function. Add examples of $excludefile usage.
6526 * @param string $rootdir A given root directory to start from
6527 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6528 * @param bool $descend If true then subdirectories are recursed as well
6529 * @param bool $getdirs If true then (sub)directories are included in the output
6530 * @param bool $getfiles If true then files are included in the output
6531 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6533 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6537 if (!$getdirs and !$getfiles) { // Nothing to show.
6541 if (!is_dir($rootdir)) { // Must be a directory.
6545 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6549 if (!is_array($excludefiles)) {
6550 $excludefiles = array($excludefiles);
6553 while (false !== ($file = readdir($dir))) {
6554 $firstchar = substr($file, 0, 1);
6555 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6558 $fullfile = $rootdir .'/'. $file;
6559 if (filetype($fullfile) == 'dir') {
6564 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6565 foreach ($subdirs as $subdir) {
6566 $dirs[] = $file .'/'. $subdir;
6569 } else if ($getfiles) {
6582 * Adds up all the files in a directory and works out the size.
6584 * @param string $rootdir The directory to start from
6585 * @param string $excludefile A file to exclude when summing directory size
6586 * @return int The summed size of all files and subfiles within the root directory
6588 function get_directory_size($rootdir, $excludefile='') {
6591 // Do it this way if we can, it's much faster.
6592 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
6593 $command = trim($CFG->pathtodu
).' -sk '.escapeshellarg($rootdir);
6596 exec($command, $output, $return);
6597 if (is_array($output)) {
6598 // We told it to return k.
6599 return get_real_size(intval($output[0]).'k');
6603 if (!is_dir($rootdir)) {
6604 // Must be a directory.
6608 if (!$dir = @opendir
($rootdir)) {
6609 // Can't open it for some reason.
6615 while (false !== ($file = readdir($dir))) {
6616 $firstchar = substr($file, 0, 1);
6617 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6620 $fullfile = $rootdir .'/'. $file;
6621 if (filetype($fullfile) == 'dir') {
6622 $size +
= get_directory_size($fullfile, $excludefile);
6624 $size +
= filesize($fullfile);
6633 * Converts bytes into display form
6635 * @static string $gb Localized string for size in gigabytes
6636 * @static string $mb Localized string for size in megabytes
6637 * @static string $kb Localized string for size in kilobytes
6638 * @static string $b Localized string for size in bytes
6639 * @param int $size The size to convert to human readable form
6642 function display_size($size) {
6644 static $gb, $mb, $kb, $b;
6646 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS
) {
6647 return get_string('unlimited');
6651 $gb = get_string('sizegb');
6652 $mb = get_string('sizemb');
6653 $kb = get_string('sizekb');
6654 $b = get_string('sizeb');
6657 if ($size >= 1073741824) {
6658 $size = round($size / 1073741824 * 10) / 10 . $gb;
6659 } else if ($size >= 1048576) {
6660 $size = round($size / 1048576 * 10) / 10 . $mb;
6661 } else if ($size >= 1024) {
6662 $size = round($size / 1024 * 10) / 10 . $kb;
6664 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6670 * Cleans a given filename by removing suspicious or troublesome characters
6672 * @see clean_param()
6673 * @param string $string file name
6674 * @return string cleaned file name
6676 function clean_filename($string) {
6677 return clean_param($string, PARAM_FILE
);
6681 // STRING TRANSLATION.
6684 * Returns the code for the current language
6689 function current_language() {
6690 global $CFG, $USER, $SESSION, $COURSE;
6692 if (!empty($SESSION->forcelang
)) {
6693 // Allows overriding course-forced language (useful for admins to check
6694 // issues in courses whose language they don't understand).
6695 // Also used by some code to temporarily get language-related information in a
6696 // specific language (see force_current_language()).
6697 $return = $SESSION->forcelang
;
6699 } else if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) {
6700 // Course language can override all other settings for this page.
6701 $return = $COURSE->lang
;
6703 } else if (!empty($SESSION->lang
)) {
6704 // Session language can override other settings.
6705 $return = $SESSION->lang
;
6707 } else if (!empty($USER->lang
)) {
6708 $return = $USER->lang
;
6710 } else if (isset($CFG->lang
)) {
6711 $return = $CFG->lang
;
6717 // Just in case this slipped in from somewhere by accident.
6718 $return = str_replace('_utf8', '', $return);
6724 * Returns parent language of current active language if defined
6727 * @param string $lang null means current language
6730 function get_parent_language($lang=null) {
6732 // Let's hack around the current language.
6733 if (!empty($lang)) {
6734 $oldforcelang = force_current_language($lang);
6737 $parentlang = get_string('parentlanguage', 'langconfig');
6738 if ($parentlang === 'en') {
6742 // Let's hack around the current language.
6743 if (!empty($lang)) {
6744 force_current_language($oldforcelang);
6751 * Force the current language to get strings and dates localised in the given language.
6753 * After calling this function, all strings will be provided in the given language
6754 * until this function is called again, or equivalent code is run.
6756 * @param string $language
6757 * @return string previous $SESSION->forcelang value
6759 function force_current_language($language) {
6761 $sessionforcelang = isset($SESSION->forcelang
) ?
$SESSION->forcelang
: '';
6762 if ($language !== $sessionforcelang) {
6763 // Seting forcelang to null or an empty string disables it's effect.
6764 if (empty($language) ||
get_string_manager()->translation_exists($language, false)) {
6765 $SESSION->forcelang
= $language;
6769 return $sessionforcelang;
6773 * Returns current string_manager instance.
6775 * The param $forcereload is needed for CLI installer only where the string_manager instance
6776 * must be replaced during the install.php script life time.
6779 * @param bool $forcereload shall the singleton be released and new instance created instead?
6780 * @return core_string_manager
6782 function get_string_manager($forcereload=false) {
6785 static $singleton = null;
6790 if ($singleton === null) {
6791 if (empty($CFG->early_install_lang
)) {
6793 if (empty($CFG->langlist
)) {
6794 $translist = array();
6796 $translist = explode(',', $CFG->langlist
);
6799 $singleton = new core_string_manager_standard($CFG->langotherroot
, $CFG->langlocalroot
, $translist);
6802 $singleton = new core_string_manager_install();
6810 * Returns a localized string.
6812 * Returns the translated string specified by $identifier as
6813 * for $module. Uses the same format files as STphp.
6814 * $a is an object, string or number that can be used
6815 * within translation strings
6817 * eg 'hello {$a->firstname} {$a->lastname}'
6820 * If you would like to directly echo the localized string use
6821 * the function {@link print_string()}
6823 * Example usage of this function involves finding the string you would
6824 * like a local equivalent of and using its identifier and module information
6825 * to retrieve it.<br/>
6826 * If you open moodle/lang/en/moodle.php and look near line 278
6827 * you will find a string to prompt a user for their word for 'course'
6829 * $string['course'] = 'Course';
6831 * So if you want to display the string 'Course'
6832 * in any language that supports it on your site
6833 * you just need to use the identifier 'course'
6835 * $mystring = '<strong>'. get_string('course') .'</strong>';
6838 * If the string you want is in another file you'd take a slightly
6839 * different approach. Looking in moodle/lang/en/calendar.php you find
6842 * $string['typecourse'] = 'Course event';
6844 * If you want to display the string "Course event" in any language
6845 * supported you would use the identifier 'typecourse' and the module 'calendar'
6846 * (because it is in the file calendar.php):
6848 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6851 * As a last resort, should the identifier fail to map to a string
6852 * the returned string will be [[ $identifier ]]
6854 * In Moodle 2.3 there is a new argument to this function $lazyload.
6855 * Setting $lazyload to true causes get_string to return a lang_string object
6856 * rather than the string itself. The fetching of the string is then put off until
6857 * the string object is first used. The object can be used by calling it's out
6858 * method or by casting the object to a string, either directly e.g.
6859 * (string)$stringobject
6860 * or indirectly by using the string within another string or echoing it out e.g.
6861 * echo $stringobject
6862 * return "<p>{$stringobject}</p>";
6863 * It is worth noting that using $lazyload and attempting to use the string as an
6864 * array key will cause a fatal error as objects cannot be used as array keys.
6865 * But you should never do that anyway!
6866 * For more information {@link lang_string}
6869 * @param string $identifier The key identifier for the localized string
6870 * @param string $component The module where the key identifier is stored,
6871 * usually expressed as the filename in the language pack without the
6872 * .php on the end but can also be written as mod/forum or grade/export/xls.
6873 * If none is specified then moodle.php is used.
6874 * @param string|object|array $a An object, string or number that can be used
6875 * within translation strings
6876 * @param bool $lazyload If set to true a string object is returned instead of
6877 * the string itself. The string then isn't calculated until it is first used.
6878 * @return string The localized string.
6879 * @throws coding_exception
6881 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6884 // If the lazy load argument has been supplied return a lang_string object
6886 // We need to make sure it is true (and a bool) as you will see below there
6887 // used to be a forth argument at one point.
6888 if ($lazyload === true) {
6889 return new lang_string($identifier, $component, $a);
6892 if ($CFG->debugdeveloper
&& clean_param($identifier, PARAM_STRINGID
) === '') {
6893 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER
);
6896 // There is now a forth argument again, this time it is a boolean however so
6897 // we can still check for the old extralocations parameter.
6898 if (!is_bool($lazyload) && !empty($lazyload)) {
6899 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6902 if (strpos($component, '/') !== false) {
6903 debugging('The module name you passed to get_string is the deprecated format ' .
6904 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER
);
6905 $componentpath = explode('/', $component);
6907 switch ($componentpath[0]) {
6909 $component = $componentpath[1];
6913 $component = 'block_'.$componentpath[1];
6916 $component = 'enrol_'.$componentpath[1];
6919 $component = 'format_'.$componentpath[1];
6922 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6927 $result = get_string_manager()->get_string($identifier, $component, $a);
6929 // Debugging feature lets you display string identifier and component.
6930 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
6931 $result .= ' {' . $identifier . '/' . $component . '}';
6937 * Converts an array of strings to their localized value.
6939 * @param array $array An array of strings
6940 * @param string $component The language module that these strings can be found in.
6941 * @return stdClass translated strings.
6943 function get_strings($array, $component = '') {
6944 $string = new stdClass
;
6945 foreach ($array as $item) {
6946 $string->$item = get_string($item, $component);
6952 * Prints out a translated string.
6954 * Prints out a translated string using the return value from the {@link get_string()} function.
6956 * Example usage of this function when the string is in the moodle.php file:<br/>
6959 * print_string('course');
6963 * Example usage of this function when the string is not in the moodle.php file:<br/>
6966 * print_string('typecourse', 'calendar');
6971 * @param string $identifier The key identifier for the localized string
6972 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6973 * @param string|object|array $a An object, string or number that can be used within translation strings
6975 function print_string($identifier, $component = '', $a = null) {
6976 echo get_string($identifier, $component, $a);
6980 * Returns a list of charset codes
6982 * Returns a list of charset codes. It's hardcoded, so they should be added manually
6983 * (checking that such charset is supported by the texlib library!)
6985 * @return array And associative array with contents in the form of charset => charset
6987 function get_list_of_charsets() {
6990 'EUC-JP' => 'EUC-JP',
6991 'ISO-2022-JP'=> 'ISO-2022-JP',
6992 'ISO-8859-1' => 'ISO-8859-1',
6993 'SHIFT-JIS' => 'SHIFT-JIS',
6994 'GB2312' => 'GB2312',
6995 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
6996 'UTF-8' => 'UTF-8');
7004 * Returns a list of valid and compatible themes
7008 function get_list_of_themes() {
7013 if (!empty($CFG->themelist
)) { // Use admin's list of themes.
7014 $themelist = explode(',', $CFG->themelist
);
7016 $themelist = array_keys(core_component
::get_plugin_list("theme"));
7019 foreach ($themelist as $key => $themename) {
7020 $theme = theme_config
::load($themename);
7021 $themes[$themename] = $theme;
7024 core_collator
::asort_objects_by_method($themes, 'get_theme_name');
7030 * Returns a list of timezones in the current language
7034 function get_list_of_timezones() {
7039 if (!empty($timezones)) { // This function has been called recently.
7043 $timezones = array();
7045 if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
7046 foreach ($rawtimezones as $timezone) {
7047 if (!empty($timezone->name
)) {
7048 if (get_string_manager()->string_exists(strtolower($timezone->name
), 'timezones')) {
7049 $timezones[$timezone->name
] = get_string(strtolower($timezone->name
), 'timezones');
7051 $timezones[$timezone->name
] = $timezone->name
;
7053 if (substr($timezones[$timezone->name
], 0, 1) == '[') { // No translation found.
7054 $timezones[$timezone->name
] = $timezone->name
;
7062 for ($i = -13; $i <= 13; $i +
= .5) {
7065 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
7066 } else if ($i > 0) {
7067 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
7069 $timezones[sprintf("%.1f", $i)] = $tzstring;
7077 * Factory function for emoticon_manager
7079 * @return emoticon_manager singleton
7081 function get_emoticon_manager() {
7082 static $singleton = null;
7084 if (is_null($singleton)) {
7085 $singleton = new emoticon_manager();
7092 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7094 * Whenever this manager mentiones 'emoticon object', the following data
7095 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7096 * altidentifier and altcomponent
7098 * @see admin_setting_emoticons
7100 * @copyright 2010 David Mudrak
7101 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7103 class emoticon_manager
{
7106 * Returns the currently enabled emoticons
7108 * @return array of emoticon objects
7110 public function get_emoticons() {
7113 if (empty($CFG->emoticons
)) {
7117 $emoticons = $this->decode_stored_config($CFG->emoticons
);
7119 if (!is_array($emoticons)) {
7120 // Something is wrong with the format of stored setting.
7121 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL
);
7129 * Converts emoticon object into renderable pix_emoticon object
7131 * @param stdClass $emoticon emoticon object
7132 * @param array $attributes explicit HTML attributes to set
7133 * @return pix_emoticon
7135 public function prepare_renderable_emoticon(stdClass
$emoticon, array $attributes = array()) {
7136 $stringmanager = get_string_manager();
7137 if ($stringmanager->string_exists($emoticon->altidentifier
, $emoticon->altcomponent
)) {
7138 $alt = get_string($emoticon->altidentifier
, $emoticon->altcomponent
);
7140 $alt = s($emoticon->text
);
7142 return new pix_emoticon($emoticon->imagename
, $alt, $emoticon->imagecomponent
, $attributes);
7146 * Encodes the array of emoticon objects into a string storable in config table
7148 * @see self::decode_stored_config()
7149 * @param array $emoticons array of emtocion objects
7152 public function encode_stored_config(array $emoticons) {
7153 return json_encode($emoticons);
7157 * Decodes the string into an array of emoticon objects
7159 * @see self::encode_stored_config()
7160 * @param string $encoded
7161 * @return string|null
7163 public function decode_stored_config($encoded) {
7164 $decoded = json_decode($encoded);
7165 if (!is_array($decoded)) {
7172 * Returns default set of emoticons supported by Moodle
7174 * @return array of sdtClasses
7176 public function default_emoticons() {
7178 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7179 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7180 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7181 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7182 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7183 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7184 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7185 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7186 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7187 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7188 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7189 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7190 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7191 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7192 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7193 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7194 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7195 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7196 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7197 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7198 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7199 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7200 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7201 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7202 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7203 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7204 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7205 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7206 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7207 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7212 * Helper method preparing the stdClass with the emoticon properties
7214 * @param string|array $text or array of strings
7215 * @param string $imagename to be used by {@link pix_emoticon}
7216 * @param string $altidentifier alternative string identifier, null for no alt
7217 * @param string $altcomponent where the alternative string is defined
7218 * @param string $imagecomponent to be used by {@link pix_emoticon}
7221 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7222 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7223 return (object)array(
7225 'imagename' => $imagename,
7226 'imagecomponent' => $imagecomponent,
7227 'altidentifier' => $altidentifier,
7228 'altcomponent' => $altcomponent,
7238 * @param string $data Data to encrypt.
7239 * @return string The now encrypted data.
7241 function rc4encrypt($data) {
7242 return endecrypt(get_site_identifier(), $data, '');
7248 * @param string $data Data to decrypt.
7249 * @return string The now decrypted data.
7251 function rc4decrypt($data) {
7252 return endecrypt(get_site_identifier(), $data, 'de');
7256 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7258 * @todo Finish documenting this function
7260 * @param string $pwd The password to use when encrypting or decrypting
7261 * @param string $data The data to be decrypted/encrypted
7262 * @param string $case Either 'de' for decrypt or '' for encrypt
7265 function endecrypt ($pwd, $data, $case) {
7267 if ($case == 'de') {
7268 $data = urldecode($data);
7273 $pwdlength = strlen($pwd);
7275 for ($i = 0; $i <= 255; $i++
) {
7276 $key[$i] = ord(substr($pwd, ($i %
$pwdlength), 1));
7282 for ($i = 0; $i <= 255; $i++
) {
7283 $x = ($x +
$box[$i] +
$key[$i]) %
256;
7284 $tempswap = $box[$i];
7285 $box[$i] = $box[$x];
7286 $box[$x] = $tempswap;
7294 for ($i = 0; $i < strlen($data); $i++
) {
7295 $a = ($a +
1) %
256;
7296 $j = ($j +
$box[$a]) %
256;
7298 $box[$a] = $box[$j];
7300 $k = $box[(($box[$a] +
$box[$j]) %
256)];
7301 $cipherby = ord(substr($data, $i, 1)) ^
$k;
7302 $cipher .= chr($cipherby);
7305 if ($case == 'de') {
7306 $cipher = urldecode(urlencode($cipher));
7308 $cipher = urlencode($cipher);
7314 // ENVIRONMENT CHECKING.
7317 * This method validates a plug name. It is much faster than calling clean_param.
7319 * @param string $name a string that might be a plugin name.
7320 * @return bool if this string is a valid plugin name.
7322 function is_valid_plugin_name($name) {
7323 // This does not work for 'mod', bad luck, use any other type.
7324 return core_component
::is_valid_plugin_name('tool', $name);
7328 * Get a list of all the plugins of a given type that define a certain API function
7329 * in a certain file. The plugin component names and function names are returned.
7331 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7332 * @param string $function the part of the name of the function after the
7333 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7334 * names like report_courselist_hook.
7335 * @param string $file the name of file within the plugin that defines the
7336 * function. Defaults to lib.php.
7337 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7338 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7340 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7341 $pluginfunctions = array();
7342 $pluginswithfile = core_component
::get_plugin_list_with_file($plugintype, $file, true);
7343 foreach ($pluginswithfile as $plugin => $notused) {
7344 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7346 if (function_exists($fullfunction)) {
7347 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7348 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
7350 } else if ($plugintype === 'mod') {
7351 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7352 $shortfunction = $plugin . '_' . $function;
7353 if (function_exists($shortfunction)) {
7354 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
7358 return $pluginfunctions;
7362 * Lists plugin-like directories within specified directory
7364 * This function was originally used for standard Moodle plugins, please use
7365 * new core_component::get_plugin_list() now.
7367 * This function is used for general directory listing and backwards compatility.
7369 * @param string $directory relative directory from root
7370 * @param string $exclude dir name to exclude from the list (defaults to none)
7371 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7372 * @return array Sorted array of directory names found under the requested parameters
7374 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7379 if (empty($basedir)) {
7380 $basedir = $CFG->dirroot
.'/'. $directory;
7383 $basedir = $basedir .'/'. $directory;
7386 if ($CFG->debugdeveloper
and empty($exclude)) {
7387 // Make sure devs do not use this to list normal plugins,
7388 // this is intended for general directories that are not plugins!
7390 $subtypes = core_component
::get_plugin_types();
7391 if (in_array($basedir, $subtypes)) {
7392 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER
);
7397 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7398 if (!$dirhandle = opendir($basedir)) {
7399 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER
);
7402 while (false !== ($dir = readdir($dirhandle))) {
7403 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7404 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7405 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7408 if (filetype($basedir .'/'. $dir) != 'dir') {
7413 closedir($dirhandle);
7422 * Invoke plugin's callback functions
7424 * @param string $type plugin type e.g. 'mod'
7425 * @param string $name plugin name
7426 * @param string $feature feature name
7427 * @param string $action feature's action
7428 * @param array $params parameters of callback function, should be an array
7429 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7432 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7434 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7435 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7439 * Invoke component's callback functions
7441 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7442 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7443 * @param array $params parameters of callback function
7444 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7447 function component_callback($component, $function, array $params = array(), $default = null) {
7449 $functionname = component_callback_exists($component, $function);
7451 if ($functionname) {
7452 // Function exists, so just return function result.
7453 $ret = call_user_func_array($functionname, $params);
7454 if (is_null($ret)) {
7464 * Determine if a component callback exists and return the function name to call. Note that this
7465 * function will include the required library files so that the functioname returned can be
7468 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7469 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7470 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7471 * @throws coding_exception if invalid component specfied
7473 function component_callback_exists($component, $function) {
7474 global $CFG; // This is needed for the inclusions.
7476 $cleancomponent = clean_param($component, PARAM_COMPONENT
);
7477 if (empty($cleancomponent)) {
7478 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7480 $component = $cleancomponent;
7482 list($type, $name) = core_component
::normalize_component($component);
7483 $component = $type . '_' . $name;
7485 $oldfunction = $name.'_'.$function;
7486 $function = $component.'_'.$function;
7488 $dir = core_component
::get_component_directory($component);
7490 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7493 // Load library and look for function.
7494 if (file_exists($dir.'/lib.php')) {
7495 require_once($dir.'/lib.php');
7498 if (!function_exists($function) and function_exists($oldfunction)) {
7499 if ($type !== 'mod' and $type !== 'core') {
7500 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER
);
7502 $function = $oldfunction;
7505 if (function_exists($function)) {
7512 * Checks whether a plugin supports a specified feature.
7514 * @param string $type Plugin type e.g. 'mod'
7515 * @param string $name Plugin name e.g. 'forum'
7516 * @param string $feature Feature code (FEATURE_xx constant)
7517 * @param mixed $default default value if feature support unknown
7518 * @return mixed Feature result (false if not supported, null if feature is unknown,
7519 * otherwise usually true but may have other feature-specific value such as array)
7520 * @throws coding_exception
7522 function plugin_supports($type, $name, $feature, $default = null) {
7525 if ($type === 'mod' and $name === 'NEWMODULE') {
7526 // Somebody forgot to rename the module template.
7530 $component = clean_param($type . '_' . $name, PARAM_COMPONENT
);
7531 if (empty($component)) {
7532 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7537 if ($type === 'mod') {
7538 // We need this special case because we support subplugins in modules,
7539 // otherwise it would end up in infinite loop.
7540 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7541 include_once("$CFG->dirroot/mod/$name/lib.php");
7542 $function = $component.'_supports';
7543 if (!function_exists($function)) {
7544 // Legacy non-frankenstyle function name.
7545 $function = $name.'_supports';
7550 if (!$path = core_component
::get_plugin_directory($type, $name)) {
7551 // Non existent plugin type.
7554 if (file_exists("$path/lib.php")) {
7555 include_once("$path/lib.php");
7556 $function = $component.'_supports';
7560 if ($function and function_exists($function)) {
7561 $supports = $function($feature);
7562 if (is_null($supports)) {
7563 // Plugin does not know - use default.
7570 // Plugin does not care, so use default.
7575 * Returns true if the current version of PHP is greater that the specified one.
7577 * @todo Check PHP version being required here is it too low?
7579 * @param string $version The version of php being tested.
7582 function check_php_version($version='5.2.4') {
7583 return (version_compare(phpversion(), $version) >= 0);
7587 * Determine if moodle installation requires update.
7589 * Checks version numbers of main code and all plugins to see
7590 * if there are any mismatches.
7594 function moodle_needs_upgrading() {
7597 if (empty($CFG->version
)) {
7601 // There is no need to purge plugininfo caches here because
7602 // these caches are not used during upgrade and they are purged after
7605 if (empty($CFG->allversionshash
)) {
7609 $hash = core_component
::get_all_versions_hash();
7611 return ($hash !== $CFG->allversionshash
);
7615 * Returns the major version of this site
7617 * Moodle version numbers consist of three numbers separated by a dot, for
7618 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7619 * called major version. This function extracts the major version from either
7620 * $CFG->release (default) or eventually from the $release variable defined in
7621 * the main version.php.
7623 * @param bool $fromdisk should the version if source code files be used
7624 * @return string|false the major version like '2.3', false if could not be determined
7626 function moodle_major_version($fromdisk = false) {
7631 require($CFG->dirroot
.'/version.php');
7632 if (empty($release)) {
7637 if (empty($CFG->release
)) {
7640 $release = $CFG->release
;
7643 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7653 * Sets the system locale
7656 * @param string $locale Can be used to force a locale
7658 function moodle_setlocale($locale='') {
7661 static $currentlocale = ''; // Last locale caching.
7663 $oldlocale = $currentlocale;
7665 // Fetch the correct locale based on ostype.
7666 if ($CFG->ostype
== 'WINDOWS') {
7667 $stringtofetch = 'localewin';
7669 $stringtofetch = 'locale';
7672 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7673 if (!empty($locale)) {
7674 $currentlocale = $locale;
7675 } else if (!empty($CFG->locale
)) { // Override locale for all language packs.
7676 $currentlocale = $CFG->locale
;
7678 $currentlocale = get_string($stringtofetch, 'langconfig');
7681 // Do nothing if locale already set up.
7682 if ($oldlocale == $currentlocale) {
7686 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7687 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7688 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7690 // Get current values.
7691 $monetary= setlocale (LC_MONETARY
, 0);
7692 $numeric = setlocale (LC_NUMERIC
, 0);
7693 $ctype = setlocale (LC_CTYPE
, 0);
7694 if ($CFG->ostype
!= 'WINDOWS') {
7695 $messages= setlocale (LC_MESSAGES
, 0);
7697 // Set locale to all.
7698 $result = setlocale (LC_ALL
, $currentlocale);
7699 // If setting of locale fails try the other utf8 or utf-8 variant,
7700 // some operating systems support both (Debian), others just one (OSX).
7701 if ($result === false) {
7702 if (stripos($currentlocale, '.UTF-8') !== false) {
7703 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7704 setlocale (LC_ALL
, $newlocale);
7705 } else if (stripos($currentlocale, '.UTF8') !== false) {
7706 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7707 setlocale (LC_ALL
, $newlocale);
7711 setlocale (LC_MONETARY
, $monetary);
7712 setlocale (LC_NUMERIC
, $numeric);
7713 if ($CFG->ostype
!= 'WINDOWS') {
7714 setlocale (LC_MESSAGES
, $messages);
7716 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7717 // To workaround a well-known PHP problem with Turkish letter Ii.
7718 setlocale (LC_CTYPE
, $ctype);
7723 * Count words in a string.
7725 * Words are defined as things between whitespace.
7728 * @param string $string The text to be searched for words.
7729 * @return int The count of words in the specified string
7731 function count_words($string) {
7732 $string = strip_tags($string);
7733 // Decode HTML entities.
7734 $string = html_entity_decode($string);
7735 // Replace underscores (which are classed as word characters) with spaces.
7736 $string = preg_replace('/_/u', ' ', $string);
7737 // Remove any characters that shouldn't be treated as word boundaries.
7738 $string = preg_replace('/[\'’-]/u', '', $string);
7739 // Remove dots and commas from within numbers only.
7740 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7742 return count(preg_split('/\w\b/u', $string)) - 1;
7746 * Count letters in a string.
7748 * Letters are defined as chars not in tags and different from whitespace.
7751 * @param string $string The text to be searched for letters.
7752 * @return int The count of letters in the specified text.
7754 function count_letters($string) {
7755 $string = strip_tags($string); // Tags are out now.
7756 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7758 return core_text
::strlen($string);
7762 * Generate and return a random string of the specified length.
7764 * @param int $length The length of the string to be created.
7767 function random_string ($length=15) {
7768 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7769 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7770 $pool .= '0123456789';
7771 $poollen = strlen($pool);
7773 for ($i = 0; $i < $length; $i++
) {
7774 $string .= substr($pool, (mt_rand()%
($poollen)), 1);
7780 * Generate a complex random string (useful for md5 salts)
7782 * This function is based on the above {@link random_string()} however it uses a
7783 * larger pool of characters and generates a string between 24 and 32 characters
7785 * @param int $length Optional if set generates a string to exactly this length
7788 function complex_random_string($length=null) {
7789 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7790 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7791 $poollen = strlen($pool);
7792 if ($length===null) {
7793 $length = floor(rand(24, 32));
7796 for ($i = 0; $i < $length; $i++
) {
7797 $string .= $pool[(mt_rand()%
$poollen)];
7803 * Given some text (which may contain HTML) and an ideal length,
7804 * this function truncates the text neatly on a word boundary if possible
7807 * @param string $text text to be shortened
7808 * @param int $ideal ideal string length
7809 * @param boolean $exact if false, $text will not be cut mid-word
7810 * @param string $ending The string to append if the passed string is truncated
7811 * @return string $truncate shortened string
7813 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7814 // If the plain text is shorter than the maximum length, return the whole text.
7815 if (core_text
::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7819 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7820 // and only tag in its 'line'.
7821 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER
);
7823 $totallength = core_text
::strlen($ending);
7826 // This array stores information about open and close tags and their position
7827 // in the truncated string. Each item in the array is an object with fields
7828 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7829 // (byte position in truncated text).
7830 $tagdetails = array();
7832 foreach ($lines as $linematchings) {
7833 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7834 if (!empty($linematchings[1])) {
7835 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7836 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7837 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7838 // Record closing tag.
7839 $tagdetails[] = (object) array(
7841 'tag' => core_text
::strtolower($tagmatchings[1]),
7842 'pos' => core_text
::strlen($truncate),
7845 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7846 // Record opening tag.
7847 $tagdetails[] = (object) array(
7849 'tag' => core_text
::strtolower($tagmatchings[1]),
7850 'pos' => core_text
::strlen($truncate),
7854 // Add html-tag to $truncate'd text.
7855 $truncate .= $linematchings[1];
7858 // Calculate the length of the plain text part of the line; handle entities as one character.
7859 $contentlength = core_text
::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7860 if ($totallength +
$contentlength > $ideal) {
7861 // The number of characters which are left.
7862 $left = $ideal - $totallength;
7863 $entitieslength = 0;
7864 // Search for html entities.
7865 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
)) {
7866 // Calculate the real length of all entities in the legal range.
7867 foreach ($entities[0] as $entity) {
7868 if ($entity[1]+
1-$entitieslength <= $left) {
7870 $entitieslength +
= core_text
::strlen($entity[0]);
7872 // No more characters left.
7877 $breakpos = $left +
$entitieslength;
7879 // If the words shouldn't be cut in the middle...
7881 // Search the last occurence of a space.
7882 for (; $breakpos > 0; $breakpos--) {
7883 if ($char = core_text
::substr($linematchings[2], $breakpos, 1)) {
7884 if ($char === '.' or $char === ' ') {
7887 } else if (strlen($char) > 2) {
7888 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7895 if ($breakpos == 0) {
7896 // This deals with the test_shorten_text_no_spaces case.
7897 $breakpos = $left +
$entitieslength;
7898 } else if ($breakpos > $left +
$entitieslength) {
7899 // This deals with the previous for loop breaking on the first char.
7900 $breakpos = $left +
$entitieslength;
7903 $truncate .= core_text
::substr($linematchings[2], 0, $breakpos);
7904 // Maximum length is reached, so get off the loop.
7907 $truncate .= $linematchings[2];
7908 $totallength +
= $contentlength;
7911 // If the maximum length is reached, get off the loop.
7912 if ($totallength >= $ideal) {
7917 // Add the defined ending to the text.
7918 $truncate .= $ending;
7920 // Now calculate the list of open html tags based on the truncate position.
7921 $opentags = array();
7922 foreach ($tagdetails as $taginfo) {
7923 if ($taginfo->open
) {
7924 // Add tag to the beginning of $opentags list.
7925 array_unshift($opentags, $taginfo->tag
);
7927 // Can have multiple exact same open tags, close the last one.
7928 $pos = array_search($taginfo->tag
, array_reverse($opentags, true));
7929 if ($pos !== false) {
7930 unset($opentags[$pos]);
7935 // Close all unclosed html-tags.
7936 foreach ($opentags as $tag) {
7937 $truncate .= '</' . $tag . '>';
7945 * Given dates in seconds, how many weeks is the date from startdate
7946 * The first week is 1, the second 2 etc ...
7948 * @param int $startdate Timestamp for the start date
7949 * @param int $thedate Timestamp for the end date
7952 function getweek ($startdate, $thedate) {
7953 if ($thedate < $startdate) {
7957 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
7961 * Returns a randomly generated password of length $maxlen. inspired by
7963 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
7964 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
7966 * @param int $maxlen The maximum size of the password being generated.
7969 function generate_password($maxlen=10) {
7972 if (empty($CFG->passwordpolicy
)) {
7973 $fillers = PASSWORD_DIGITS
;
7974 $wordlist = file($CFG->wordlist
);
7975 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7976 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7977 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
7978 $password = $word1 . $filler1 . $word2;
7980 $minlen = !empty($CFG->minpasswordlength
) ?
$CFG->minpasswordlength
: 0;
7981 $digits = $CFG->minpassworddigits
;
7982 $lower = $CFG->minpasswordlower
;
7983 $upper = $CFG->minpasswordupper
;
7984 $nonalphanum = $CFG->minpasswordnonalphanum
;
7985 $total = $lower +
$upper +
$digits +
$nonalphanum;
7986 // Var minlength should be the greater one of the two ( $minlen and $total ).
7987 $minlen = $minlen < $total ?
$total : $minlen;
7988 // Var maxlen can never be smaller than minlen.
7989 $maxlen = $minlen > $maxlen ?
$minlen : $maxlen;
7990 $additional = $maxlen - $total;
7992 // Make sure we have enough characters to fulfill
7993 // complexity requirements.
7994 $passworddigits = PASSWORD_DIGITS
;
7995 while ($digits > strlen($passworddigits)) {
7996 $passworddigits .= PASSWORD_DIGITS
;
7998 $passwordlower = PASSWORD_LOWER
;
7999 while ($lower > strlen($passwordlower)) {
8000 $passwordlower .= PASSWORD_LOWER
;
8002 $passwordupper = PASSWORD_UPPER
;
8003 while ($upper > strlen($passwordupper)) {
8004 $passwordupper .= PASSWORD_UPPER
;
8006 $passwordnonalphanum = PASSWORD_NONALPHANUM
;
8007 while ($nonalphanum > strlen($passwordnonalphanum)) {
8008 $passwordnonalphanum .= PASSWORD_NONALPHANUM
;
8011 // Now mix and shuffle it all.
8012 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8013 substr(str_shuffle ($passwordupper), 0, $upper) .
8014 substr(str_shuffle ($passworddigits), 0, $digits) .
8015 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8016 substr(str_shuffle ($passwordlower .
8019 $passwordnonalphanum), 0 , $additional));
8022 return substr ($password, 0, $maxlen);
8026 * Given a float, prints it nicely.
8027 * Localized floats must not be used in calculations!
8029 * The stripzeros feature is intended for making numbers look nicer in small
8030 * areas where it is not necessary to indicate the degree of accuracy by showing
8031 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8032 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8034 * @param float $float The float to print
8035 * @param int $decimalpoints The number of decimal places to print.
8036 * @param bool $localized use localized decimal separator
8037 * @param bool $stripzeros If true, removes final zeros after decimal point
8038 * @return string locale float
8040 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8041 if (is_null($float)) {
8045 $separator = get_string('decsep', 'langconfig');
8049 $result = number_format($float, $decimalpoints, $separator, '');
8051 // Remove zeros and final dot if not needed.
8052 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8058 * Converts locale specific floating point/comma number back to standard PHP float value
8059 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8061 * @param string $localefloat locale aware float representation
8062 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8063 * @return mixed float|bool - false or the parsed float.
8065 function unformat_float($localefloat, $strict = false) {
8066 $localefloat = trim($localefloat);
8068 if ($localefloat == '') {
8072 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8073 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8075 if ($strict && !is_numeric($localefloat)) {
8079 return (float)$localefloat;
8083 * Given a simple array, this shuffles it up just like shuffle()
8084 * Unlike PHP's shuffle() this function works on any machine.
8086 * @param array $array The array to be rearranged
8089 function swapshuffle($array) {
8091 $last = count($array) - 1;
8092 for ($i = 0; $i <= $last; $i++
) {
8093 $from = rand(0, $last);
8095 $array[$i] = $array[$from];
8096 $array[$from] = $curr;
8102 * Like {@link swapshuffle()}, but works on associative arrays
8104 * @param array $array The associative array to be rearranged
8107 function swapshuffle_assoc($array) {
8109 $newarray = array();
8110 $newkeys = swapshuffle(array_keys($array));
8112 foreach ($newkeys as $newkey) {
8113 $newarray[$newkey] = $array[$newkey];
8119 * Given an arbitrary array, and a number of draws,
8120 * this function returns an array with that amount
8121 * of items. The indexes are retained.
8123 * @todo Finish documenting this function
8125 * @param array $array
8129 function draw_rand_array($array, $draws) {
8133 $last = count($array);
8135 if ($draws > $last) {
8139 while ($draws > 0) {
8142 $keys = array_keys($array);
8143 $rand = rand(0, $last);
8145 $return[$keys[$rand]] = $array[$keys[$rand]];
8146 unset($array[$keys[$rand]]);
8155 * Calculate the difference between two microtimes
8157 * @param string $a The first Microtime
8158 * @param string $b The second Microtime
8161 function microtime_diff($a, $b) {
8162 list($adec, $asec) = explode(' ', $a);
8163 list($bdec, $bsec) = explode(' ', $b);
8164 return $bsec - $asec +
$bdec - $adec;
8168 * Given a list (eg a,b,c,d,e) this function returns
8169 * an array of 1->a, 2->b, 3->c etc
8171 * @param string $list The string to explode into array bits
8172 * @param string $separator The separator used within the list string
8173 * @return array The now assembled array
8175 function make_menu_from_list($list, $separator=',') {
8177 $array = array_reverse(explode($separator, $list), true);
8178 foreach ($array as $key => $item) {
8179 $outarray[$key+
1] = trim($item);
8185 * Creates an array that represents all the current grades that
8186 * can be chosen using the given grading type.
8189 * are scales, zero is no grade, and positive numbers are maximum
8192 * @todo Finish documenting this function or better deprecated this completely!
8194 * @param int $gradingtype
8197 function make_grades_menu($gradingtype) {
8201 if ($gradingtype < 0) {
8202 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8203 return make_menu_from_list($scale->scale
);
8205 } else if ($gradingtype > 0) {
8206 for ($i=$gradingtype; $i>=0; $i--) {
8207 $grades[$i] = $i .' / '. $gradingtype;
8215 * This function returns the number of activities using the given scale in the given course.
8217 * @param int $courseid The course ID to check.
8218 * @param int $scaleid The scale ID to check
8221 function course_scale_used($courseid, $scaleid) {
8226 if (!empty($scaleid)) {
8227 if ($cms = get_course_mods($courseid)) {
8228 foreach ($cms as $cm) {
8229 // Check cm->name/lib.php exists.
8230 if (file_exists($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php')) {
8231 include_once($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php');
8232 $functionname = $cm->modname
.'_scale_used';
8233 if (function_exists($functionname)) {
8234 if ($functionname($cm->instance
, $scaleid)) {
8242 // Check if any course grade item makes use of the scale.
8243 $return +
= $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8245 // Check if any outcome in the course makes use of the scale.
8246 $return +
= $DB->count_records_sql("SELECT COUNT('x')
8247 FROM {grade_outcomes_courses} goc,
8249 WHERE go.id = goc.outcomeid
8250 AND go.scaleid = ? AND goc.courseid = ?",
8251 array($scaleid, $courseid));
8257 * This function returns the number of activities using scaleid in the entire site
8259 * @param int $scaleid
8260 * @param array $courses
8263 function site_scale_used($scaleid, &$courses) {
8266 if (!is_array($courses) ||
count($courses) == 0) {
8267 $courses = get_courses("all", false, "c.id, c.shortname");
8270 if (!empty($scaleid)) {
8271 if (is_array($courses) && count($courses) > 0) {
8272 foreach ($courses as $course) {
8273 $return +
= course_scale_used($course->id
, $scaleid);
8281 * make_unique_id_code
8283 * @todo Finish documenting this function
8286 * @param string $extra Extra string to append to the end of the code
8289 function make_unique_id_code($extra = '') {
8291 $hostname = 'unknownhost';
8292 if (!empty($_SERVER['HTTP_HOST'])) {
8293 $hostname = $_SERVER['HTTP_HOST'];
8294 } else if (!empty($_ENV['HTTP_HOST'])) {
8295 $hostname = $_ENV['HTTP_HOST'];
8296 } else if (!empty($_SERVER['SERVER_NAME'])) {
8297 $hostname = $_SERVER['SERVER_NAME'];
8298 } else if (!empty($_ENV['SERVER_NAME'])) {
8299 $hostname = $_ENV['SERVER_NAME'];
8302 $date = gmdate("ymdHis");
8304 $random = random_string(6);
8307 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8309 return $hostname .'+'. $date .'+'. $random;
8315 * Function to check the passed address is within the passed subnet
8317 * The parameter is a comma separated string of subnet definitions.
8318 * Subnet strings can be in one of three formats:
8319 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8320 * 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)
8321 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8322 * Code for type 1 modified from user posted comments by mediator at
8323 * {@link http://au.php.net/manual/en/function.ip2long.php}
8325 * @param string $addr The address you are checking
8326 * @param string $subnetstr The string of subnet addresses
8329 function address_in_subnet($addr, $subnetstr) {
8331 if ($addr == '0.0.0.0') {
8334 $subnets = explode(',', $subnetstr);
8336 $addr = trim($addr);
8337 $addr = cleanremoteaddr($addr, false); // Normalise.
8338 if ($addr === null) {
8341 $addrparts = explode(':', $addr);
8343 $ipv6 = strpos($addr, ':');
8345 foreach ($subnets as $subnet) {
8346 $subnet = trim($subnet);
8347 if ($subnet === '') {
8351 if (strpos($subnet, '/') !== false) {
8352 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8353 list($ip, $mask) = explode('/', $subnet);
8354 $mask = trim($mask);
8355 if (!is_number($mask)) {
8356 continue; // Incorect mask number, eh?
8358 $ip = cleanremoteaddr($ip, false); // Normalise.
8362 if (strpos($ip, ':') !== false) {
8367 if ($mask > 128 or $mask < 0) {
8368 continue; // Nonsense.
8371 return true; // Any address.
8374 if ($ip === $addr) {
8379 $ipparts = explode(':', $ip);
8380 $modulo = $mask %
16;
8381 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8382 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8383 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8387 $pos = ($mask-$modulo)/16;
8388 $ipnet = hexdec($ipparts[$pos]);
8389 $addrnet = hexdec($addrparts[$pos]);
8390 $mask = 0xffff << (16 - $modulo);
8391 if (($addrnet & $mask) == ($ipnet & $mask)) {
8401 if ($mask > 32 or $mask < 0) {
8402 continue; // Nonsense.
8408 if ($ip === $addr) {
8413 $mask = 0xffffffff << (32 - $mask);
8414 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8419 } else if (strpos($subnet, '-') !== false) {
8420 // 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.
8421 $parts = explode('-', $subnet);
8422 if (count($parts) != 2) {
8426 if (strpos($subnet, ':') !== false) {
8431 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8432 if ($ipstart === null) {
8435 $ipparts = explode(':', $ipstart);
8436 $start = hexdec(array_pop($ipparts));
8437 $ipparts[] = trim($parts[1]);
8438 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8439 if ($ipend === null) {
8443 $ipnet = implode(':', $ipparts);
8444 if (strpos($addr, $ipnet) !== 0) {
8447 $ipparts = explode(':', $ipend);
8448 $end = hexdec($ipparts[7]);
8450 $addrend = hexdec($addrparts[7]);
8452 if (($addrend >= $start) and ($addrend <= $end)) {
8461 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8462 if ($ipstart === null) {
8465 $ipparts = explode('.', $ipstart);
8466 $ipparts[3] = trim($parts[1]);
8467 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8468 if ($ipend === null) {
8472 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8478 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8479 if (strpos($subnet, ':') !== false) {
8484 $parts = explode(':', $subnet);
8485 $count = count($parts);
8486 if ($parts[$count-1] === '') {
8487 unset($parts[$count-1]); // Trim trailing :'s.
8489 $subnet = implode('.', $parts);
8491 $isip = cleanremoteaddr($subnet, false); // Normalise.
8492 if ($isip !== null) {
8493 if ($isip === $addr) {
8497 } else if ($count > 8) {
8500 $zeros = array_fill(0, 8-$count, '0');
8501 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8502 if (address_in_subnet($addr, $subnet)) {
8511 $parts = explode('.', $subnet);
8512 $count = count($parts);
8513 if ($parts[$count-1] === '') {
8514 unset($parts[$count-1]); // Trim trailing .
8516 $subnet = implode('.', $parts);
8519 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8520 if ($subnet === $addr) {
8524 } else if ($count > 4) {
8527 $zeros = array_fill(0, 4-$count, '0');
8528 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8529 if (address_in_subnet($addr, $subnet)) {
8540 * For outputting debugging info
8542 * @param string $string The string to write
8543 * @param string $eol The end of line char(s) to use
8544 * @param string $sleep Period to make the application sleep
8545 * This ensures any messages have time to display before redirect
8547 function mtrace($string, $eol="\n", $sleep=0) {
8549 if (defined('STDOUT') and !PHPUNIT_TEST
) {
8550 fwrite(STDOUT
, $string.$eol);
8552 echo $string . $eol;
8557 // Delay to keep message on user's screen in case of subsequent redirect.
8564 * Replace 1 or more slashes or backslashes to 1 slash
8566 * @param string $path The path to strip
8567 * @return string the path with double slashes removed
8569 function cleardoubleslashes ($path) {
8570 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8574 * Is current ip in give list?
8576 * @param string $list
8579 function remoteip_in_list($list) {
8581 $clientip = getremoteaddr(null);
8584 // Ensure access on cli.
8588 $list = explode("\n", $list);
8589 foreach ($list as $subnet) {
8590 $subnet = trim($subnet);
8591 if (address_in_subnet($clientip, $subnet)) {
8600 * Returns most reliable client address
8602 * @param string $default If an address can't be determined, then return this
8603 * @return string The remote IP address
8605 function getremoteaddr($default='0.0.0.0') {
8608 if (empty($CFG->getremoteaddrconf
)) {
8609 // This will happen, for example, before just after the upgrade, as the
8610 // user is redirected to the admin screen.
8611 $variablestoskip = 0;
8613 $variablestoskip = $CFG->getremoteaddrconf
;
8615 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP
)) {
8616 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8617 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8618 return $address ?
$address : $default;
8621 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR
)) {
8622 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8623 $address = cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
8624 return $address ?
$address : $default;
8627 if (!empty($_SERVER['REMOTE_ADDR'])) {
8628 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8629 return $address ?
$address : $default;
8636 * Cleans an ip address. Internal addresses are now allowed.
8637 * (Originally local addresses were not allowed.)
8639 * @param string $addr IPv4 or IPv6 address
8640 * @param bool $compress use IPv6 address compression
8641 * @return string normalised ip address string, null if error
8643 function cleanremoteaddr($addr, $compress=false) {
8644 $addr = trim($addr);
8646 // TODO: maybe add a separate function is_addr_public() or something like this.
8648 if (strpos($addr, ':') !== false) {
8649 // Can be only IPv6.
8650 $parts = explode(':', $addr);
8651 $count = count($parts);
8653 if (strpos($parts[$count-1], '.') !== false) {
8654 // Legacy ipv4 notation.
8655 $last = array_pop($parts);
8656 $ipv4 = cleanremoteaddr($last, true);
8657 if ($ipv4 === null) {
8660 $bits = explode('.', $ipv4);
8661 $parts[] = dechex($bits[0]).dechex($bits[1]);
8662 $parts[] = dechex($bits[2]).dechex($bits[3]);
8663 $count = count($parts);
8664 $addr = implode(':', $parts);
8667 if ($count < 3 or $count > 8) {
8668 return null; // Severly malformed.
8672 if (strpos($addr, '::') === false) {
8673 return null; // Malformed.
8676 $insertat = array_search('', $parts, true);
8677 $missing = array_fill(0, 1 +
8 - $count, '0');
8678 array_splice($parts, $insertat, 1, $missing);
8679 foreach ($parts as $key => $part) {
8686 $adr = implode(':', $parts);
8687 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8688 return null; // Incorrect format - sorry.
8691 // Normalise 0s and case.
8692 $parts = array_map('hexdec', $parts);
8693 $parts = array_map('dechex', $parts);
8695 $result = implode(':', $parts);
8701 if ($result === '0:0:0:0:0:0:0:0') {
8702 return '::'; // All addresses.
8705 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8706 if ($compressed !== $result) {
8710 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8711 if ($compressed !== $result) {
8715 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8716 if ($compressed !== $result) {
8723 // First get all things that look like IPv4 addresses.
8725 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8730 foreach ($parts as $key => $match) {
8734 $parts[$key] = (int)$match; // Normalise 0s.
8737 return implode('.', $parts);
8741 * This function will make a complete copy of anything it's given,
8742 * regardless of whether it's an object or not.
8744 * @param mixed $thing Something you want cloned
8745 * @return mixed What ever it is you passed it
8747 function fullclone($thing) {
8748 return unserialize(serialize($thing));
8752 * If new messages are waiting for the current user, then insert
8753 * JavaScript to pop up the messaging window into the page
8757 function message_popup_window() {
8758 global $USER, $DB, $PAGE, $CFG;
8760 if (!$PAGE->get_popup_notification_allowed() ||
empty($CFG->messaging
)) {
8764 if (!isloggedin() ||
isguestuser()) {
8768 if (!isset($USER->message_lastpopup
)) {
8769 $USER->message_lastpopup
= 0;
8770 } else if ($USER->message_lastpopup
> (time()-120)) {
8771 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8775 // A quick query to check whether the user has new messages.
8776 $messagecount = $DB->count_records('message', array('useridto' => $USER->id
));
8777 if ($messagecount < 1) {
8781 // There are unread messages so now do a more complex but slower query.
8782 $messagesql = "SELECT m.id, c.blocked
8784 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8785 JOIN {message_processors} p ON mw.processorid=p.id
8786 JOIN {user} u ON m.useridfrom=u.id
8787 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8788 AND c.userid = m.useridto
8789 WHERE m.useridto = :userid
8790 AND p.name='popup'";
8792 // If the user was last notified over an hour ago we can re-notify them of old messages
8793 // so don't worry about when the new message was sent.
8794 $lastnotifiedlongago = $USER->message_lastpopup
< (time()-3600);
8795 if (!$lastnotifiedlongago) {
8796 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8799 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id
, 'lastpopuptime' => $USER->message_lastpopup
));
8802 foreach ($waitingmessages as $messageinfo) {
8803 if ($messageinfo->blocked
) {
8804 // Message is from a user who has since been blocked so just mark it read.
8805 // Get the full message to mark as read.
8806 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id
));
8807 message_mark_message_read($messageobject, time());
8813 if ($validmessages > 0) {
8814 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8815 $strgomessage = get_string('gotomessages', 'message');
8816 $strstaymessage = get_string('ignore', 'admin');
8818 $notificationsound = null;
8819 $beep = get_user_preferences('message_beepnewmessage', '');
8820 if (!empty($beep)) {
8821 // Browsers will work down this list until they find something they support.
8822 $sourcetags = html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.wav', 'type' => 'audio/wav'));
8823 $sourcetags .= html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.ogg', 'type' => 'audio/ogg'));
8824 $sourcetags .= html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8825 $sourcetags .= html_writer
::empty_tag('embed', array('src' => $CFG->wwwroot
.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8827 $notificationsound = html_writer
::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8830 $url = $CFG->wwwroot
.'/message/index.php';
8831 $content = html_writer
::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8832 html_writer
::start_tag('div', array('id' => 'newmessagetext')).
8834 html_writer
::end_tag('div').
8837 html_writer
::start_tag('div', array('id' => 'newmessagelinks')).
8838 html_writer
::link($url, $strgomessage, array('id' => 'notificationyes')).' '.
8839 html_writer
::link('', $strstaymessage, array('id' => 'notificationno')).
8840 html_writer
::end_tag('div');
8841 html_writer
::end_tag('div');
8843 $PAGE->requires
->js_init_call('M.core_message.init_notification', array('', $content, $url));
8845 $USER->message_lastpopup
= time();
8850 * Used to make sure that $min <= $value <= $max
8852 * Make sure that value is between min, and max
8854 * @param int $min The minimum value
8855 * @param int $value The value to check
8856 * @param int $max The maximum value
8859 function bounded_number($min, $value, $max) {
8860 if ($value < $min) {
8863 if ($value > $max) {
8870 * Check if there is a nested array within the passed array
8872 * @param array $array
8873 * @return bool true if there is a nested array false otherwise
8875 function array_is_nested($array) {
8876 foreach ($array as $value) {
8877 if (is_array($value)) {
8885 * get_performance_info() pairs up with init_performance_info()
8886 * loaded in setup.php. Returns an array with 'html' and 'txt'
8887 * values ready for use, and each of the individual stats provided
8888 * separately as well.
8892 function get_performance_info() {
8893 global $CFG, $PERF, $DB, $PAGE;
8896 $info['html'] = ''; // Holds userfriendly HTML representation.
8897 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8899 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
8901 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8902 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8904 if (function_exists('memory_get_usage')) {
8905 $info['memory_total'] = memory_get_usage();
8906 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
8907 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8908 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8909 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8912 if (function_exists('memory_get_peak_usage')) {
8913 $info['memory_peak'] = memory_get_peak_usage();
8914 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8915 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8918 $inc = get_included_files();
8919 $info['includecount'] = count($inc);
8920 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8921 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8923 if (!empty($CFG->early_install_lang
) or empty($PAGE)) {
8924 // We can not track more performance before installation or before PAGE init, sorry.
8928 $filtermanager = filter_manager
::instance();
8929 if (method_exists($filtermanager, 'get_performance_summary')) {
8930 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8931 $info = array_merge($filterinfo, $info);
8932 foreach ($filterinfo as $key => $value) {
8933 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8934 $info['txt'] .= "$key: $value ";
8938 $stringmanager = get_string_manager();
8939 if (method_exists($stringmanager, 'get_performance_summary')) {
8940 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8941 $info = array_merge($filterinfo, $info);
8942 foreach ($filterinfo as $key => $value) {
8943 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8944 $info['txt'] .= "$key: $value ";
8948 if (!empty($PERF->logwrites
)) {
8949 $info['logwrites'] = $PERF->logwrites
;
8950 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8951 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8954 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites
);
8955 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
8956 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8958 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
8959 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
8960 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
8962 if (function_exists('posix_times')) {
8963 $ptimes = posix_times();
8964 if (is_array($ptimes)) {
8965 foreach ($ptimes as $key => $val) {
8966 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
8968 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
8969 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8973 // Grab the load average for the last minute.
8974 // /proc will only work under some linux configurations
8975 // while uptime is there under MacOSX/Darwin and other unices.
8976 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
8977 list($serverload) = explode(' ', $loadavg[0]);
8979 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
8980 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
8981 $serverload = $matches[1];
8983 trigger_error('Could not parse uptime output!');
8986 if (!empty($serverload)) {
8987 $info['serverload'] = $serverload;
8988 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
8989 $info['txt'] .= "serverload: {$info['serverload']} ";
8992 // Display size of session if session started.
8993 if ($si = \core\session\manager
::get_performance_info()) {
8994 $info['sessionsize'] = $si['size'];
8995 $info['html'] .= $si['html'];
8996 $info['txt'] .= $si['txt'];
8999 if ($stats = cache_helper
::get_stats()) {
9000 $html = '<span class="cachesused">';
9001 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
9002 $text = 'Caches used (hits/misses/sets): ';
9006 foreach ($stats as $definition => $stores) {
9007 $html .= '<span class="cache-definition-stats">';
9008 $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
9009 $text .= "$definition {";
9010 foreach ($stores as $store => $data) {
9011 $hits +
= $data['hits'];
9012 $misses +
= $data['misses'];
9013 $sets +
= $data['sets'];
9014 if ($data['hits'] == 0 and $data['misses'] > 0) {
9015 $cachestoreclass = 'nohits';
9016 } else if ($data['hits'] < $data['misses']) {
9017 $cachestoreclass = 'lowhits';
9019 $cachestoreclass = 'hihits';
9021 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9022 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
9027 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
9028 $html .= '</span> ';
9029 $info['cachesused'] = "$hits / $misses / $sets";
9030 $info['html'] .= $html;
9031 $info['txt'] .= $text.'. ';
9033 $info['cachesused'] = '0 / 0 / 0';
9034 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
9035 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9038 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
9045 * @todo Document this function linux people
9047 function apd_get_profiling() {
9048 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
9052 * Delete directory or only its content
9054 * @param string $dir directory path
9055 * @param bool $contentonly
9056 * @return bool success, true also if dir does not exist
9058 function remove_dir($dir, $contentonly=false) {
9059 if (!file_exists($dir)) {
9063 if (!$handle = opendir($dir)) {
9067 while (false!==($item = readdir($handle))) {
9068 if ($item != '.' && $item != '..') {
9069 if (is_dir($dir.'/'.$item)) {
9070 $result = remove_dir($dir.'/'.$item) && $result;
9072 $result = unlink($dir.'/'.$item) && $result;
9078 clearstatcache(); // Make sure file stat cache is properly invalidated.
9081 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9082 clearstatcache(); // Make sure file stat cache is properly invalidated.
9087 * Detect if an object or a class contains a given property
9088 * will take an actual object or the name of a class
9090 * @param mix $obj Name of class or real object to test
9091 * @param string $property name of property to find
9092 * @return bool true if property exists
9094 function object_property_exists( $obj, $property ) {
9095 if (is_string( $obj )) {
9096 $properties = get_class_vars( $obj );
9098 $properties = get_object_vars( $obj );
9100 return array_key_exists( $property, $properties );
9104 * Converts an object into an associative array
9106 * This function converts an object into an associative array by iterating
9107 * over its public properties. Because this function uses the foreach
9108 * construct, Iterators are respected. It works recursively on arrays of objects.
9109 * Arrays and simple values are returned as is.
9111 * If class has magic properties, it can implement IteratorAggregate
9112 * and return all available properties in getIterator()
9117 function convert_to_array($var) {
9120 // Loop over elements/properties.
9121 foreach ($var as $key => $value) {
9122 // Recursively convert objects.
9123 if (is_object($value) ||
is_array($value)) {
9124 $result[$key] = convert_to_array($value);
9126 // Simple values are untouched.
9127 $result[$key] = $value;
9134 * Detect a custom script replacement in the data directory that will
9135 * replace an existing moodle script
9137 * @return string|bool full path name if a custom script exists, false if no custom script exists
9139 function custom_script_path() {
9140 global $CFG, $SCRIPT;
9142 if ($SCRIPT === null) {
9143 // Probably some weird external script.
9147 $scriptpath = $CFG->customscripts
. $SCRIPT;
9149 // Check the custom script exists.
9150 if (file_exists($scriptpath) and is_file($scriptpath)) {
9158 * Returns whether or not the user object is a remote MNET user. This function
9159 * is in moodlelib because it does not rely on loading any of the MNET code.
9161 * @param object $user A valid user object
9162 * @return bool True if the user is from a remote Moodle.
9164 function is_mnet_remote_user($user) {
9167 if (!isset($CFG->mnet_localhost_id
)) {
9168 include_once($CFG->dirroot
. '/mnet/lib.php');
9169 $env = new mnet_environment();
9174 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
9178 * This function will search for browser prefereed languages, setting Moodle
9179 * to use the best one available if $SESSION->lang is undefined
9181 function setup_lang_from_browser() {
9182 global $CFG, $SESSION, $USER;
9184 if (!empty($SESSION->lang
) or !empty($USER->lang
) or empty($CFG->autolang
)) {
9185 // Lang is defined in session or user profile, nothing to do.
9189 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9193 // Extract and clean langs from headers.
9194 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9195 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9196 $rawlangs = explode(',', $rawlangs); // Convert to array.
9200 foreach ($rawlangs as $lang) {
9201 if (strpos($lang, ';') === false) {
9202 $langs[(string)$order] = $lang;
9203 $order = $order-0.01;
9205 $parts = explode(';', $lang);
9206 $pos = strpos($parts[1], '=');
9207 $langs[substr($parts[1], $pos+
1)] = $parts[0];
9210 krsort($langs, SORT_NUMERIC
);
9212 // Look for such langs under standard locations.
9213 foreach ($langs as $lang) {
9214 // Clean it properly for include.
9215 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR
));
9216 if (get_string_manager()->translation_exists($lang, false)) {
9217 // Lang exists, set it in session.
9218 $SESSION->lang
= $lang;
9219 // We have finished. Go out.
9227 * Check if $url matches anything in proxybypass list
9229 * Any errors just result in the proxy being used (least bad)
9231 * @param string $url url to check
9232 * @return boolean true if we should bypass the proxy
9234 function is_proxybypass( $url ) {
9238 if (empty($CFG->proxyhost
) or empty($CFG->proxybypass
)) {
9242 // Get the host part out of the url.
9243 if (!$host = parse_url( $url, PHP_URL_HOST
)) {
9247 // Get the possible bypass hosts into an array.
9248 $matches = explode( ',', $CFG->proxybypass
);
9250 // Check for a match.
9251 // (IPs need to match the left hand side and hosts the right of the url,
9252 // but we can recklessly check both as there can't be a false +ve).
9253 foreach ($matches as $match) {
9254 $match = trim($match);
9256 // Try for IP match (Left side).
9257 $lhs = substr($host, 0, strlen($match));
9258 if (strcasecmp($match, $lhs)==0) {
9262 // Try for host match (Right side).
9263 $rhs = substr($host, -strlen($match));
9264 if (strcasecmp($match, $rhs)==0) {
9274 * Check if the passed navigation is of the new style
9276 * @param mixed $navigation
9277 * @return bool true for yes false for no
9279 function is_newnav($navigation) {
9280 if (is_array($navigation) && !empty($navigation['newnav'])) {
9288 * Checks whether the given variable name is defined as a variable within the given object.
9290 * This will NOT work with stdClass objects, which have no class variables.
9292 * @param string $var The variable name
9293 * @param object $object The object to check
9296 function in_object_vars($var, $object) {
9297 $classvars = get_class_vars(get_class($object));
9298 $classvars = array_keys($classvars);
9299 return in_array($var, $classvars);
9303 * Returns an array without repeated objects.
9304 * This function is similar to array_unique, but for arrays that have objects as values
9306 * @param array $array
9307 * @param bool $keepkeyassoc
9310 function object_array_unique($array, $keepkeyassoc = true) {
9311 $duplicatekeys = array();
9314 foreach ($array as $key => $val) {
9315 // Convert objects to arrays, in_array() does not support objects.
9316 if (is_object($val)) {
9320 if (!in_array($val, $tmp)) {
9323 $duplicatekeys[] = $key;
9327 foreach ($duplicatekeys as $key) {
9328 unset($array[$key]);
9331 return $keepkeyassoc ?
$array : array_values($array);
9335 * Is a userid the primary administrator?
9337 * @param int $userid int id of user to check
9340 function is_primary_admin($userid) {
9341 $primaryadmin = get_admin();
9343 if ($userid == $primaryadmin->id
) {
9351 * Returns the site identifier
9353 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9355 function get_site_identifier() {
9357 // Check to see if it is missing. If so, initialise it.
9358 if (empty($CFG->siteidentifier
)) {
9359 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9362 return $CFG->siteidentifier
;
9366 * Check whether the given password has no more than the specified
9367 * number of consecutive identical characters.
9369 * @param string $password password to be checked against the password policy
9370 * @param integer $maxchars maximum number of consecutive identical characters
9373 function check_consecutive_identical_characters($password, $maxchars) {
9375 if ($maxchars < 1) {
9376 return true; // Zero 0 is to disable this check.
9378 if (strlen($password) <= $maxchars) {
9379 return true; // Too short to fail this test.
9383 $consecutivecount = 1;
9384 foreach (str_split($password) as $char) {
9385 if ($char != $previouschar) {
9386 $consecutivecount = 1;
9388 $consecutivecount++
;
9389 if ($consecutivecount > $maxchars) {
9390 return false; // Check failed already.
9394 $previouschar = $char;
9401 * Helper function to do partial function binding.
9402 * so we can use it for preg_replace_callback, for example
9403 * this works with php functions, user functions, static methods and class methods
9404 * it returns you a callback that you can pass on like so:
9406 * $callback = partial('somefunction', $arg1, $arg2);
9408 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9410 * $obj = new someclass();
9411 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9413 * and then the arguments that are passed through at calltime are appended to the argument list.
9415 * @param mixed $function a php callback
9416 * @param mixed $arg1,... $argv arguments to partially bind with
9417 * @return array Array callback
9419 function partial() {
9420 if (!class_exists('partial')) {
9422 * Used to manage function binding.
9423 * @copyright 2009 Penny Leach
9424 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9428 public $values = array();
9429 /** @var string The function to call as a callback. */
9433 * @param string $func
9434 * @param array $args
9436 public function __construct($func, $args) {
9437 $this->values
= $args;
9438 $this->func
= $func;
9441 * Calls the callback function.
9444 public function method() {
9445 $args = func_get_args();
9446 return call_user_func_array($this->func
, array_merge($this->values
, $args));
9450 $args = func_get_args();
9451 $func = array_shift($args);
9452 $p = new partial($func, $args);
9453 return array($p, 'method');
9457 * helper function to load up and initialise the mnet environment
9458 * this must be called before you use mnet functions.
9460 * @return mnet_environment the equivalent of old $MNET global
9462 function get_mnet_environment() {
9464 require_once($CFG->dirroot
. '/mnet/lib.php');
9465 static $instance = null;
9466 if (empty($instance)) {
9467 $instance = new mnet_environment();
9474 * during xmlrpc server code execution, any code wishing to access
9475 * information about the remote peer must use this to get it.
9477 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9479 function get_mnet_remote_client() {
9480 if (!defined('MNET_SERVER')) {
9481 debugging(get_string('notinxmlrpcserver', 'mnet'));
9484 global $MNET_REMOTE_CLIENT;
9485 if (isset($MNET_REMOTE_CLIENT)) {
9486 return $MNET_REMOTE_CLIENT;
9492 * during the xmlrpc server code execution, this will be called
9493 * to setup the object returned by {@link get_mnet_remote_client}
9495 * @param mnet_remote_client $client the client to set up
9496 * @throws moodle_exception
9498 function set_mnet_remote_client($client) {
9499 if (!defined('MNET_SERVER')) {
9500 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9502 global $MNET_REMOTE_CLIENT;
9503 $MNET_REMOTE_CLIENT = $client;
9507 * return the jump url for a given remote user
9508 * this is used for rewriting forum post links in emails, etc
9510 * @param stdclass $user the user to get the idp url for
9512 function mnet_get_idp_jump_url($user) {
9515 static $mnetjumps = array();
9516 if (!array_key_exists($user->mnethostid
, $mnetjumps)) {
9517 $idp = mnet_get_peer_host($user->mnethostid
);
9518 $idpjumppath = mnet_get_app_jumppath($idp->applicationid
);
9519 $mnetjumps[$user->mnethostid
] = $idp->wwwroot
. $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot
. '&wantsurl=';
9521 return $mnetjumps[$user->mnethostid
];
9525 * Gets the homepage to use for the current user
9527 * @return int One of HOMEPAGE_*
9529 function get_home_page() {
9532 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage
)) {
9533 if ($CFG->defaulthomepage
== HOMEPAGE_MY
) {
9536 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY
);
9539 return HOMEPAGE_SITE
;
9543 * Gets the name of a course to be displayed when showing a list of courses.
9544 * By default this is just $course->fullname but user can configure it. The
9545 * result of this function should be passed through print_string.
9546 * @param stdClass|course_in_list $course Moodle course object
9547 * @return string Display name of course (either fullname or short + fullname)
9549 function get_course_display_name_for_list($course) {
9551 if (!empty($CFG->courselistshortnames
)) {
9552 if (!($course instanceof stdClass
)) {
9553 $course = (object)convert_to_array($course);
9555 return get_string('courseextendednamedisplay', '', $course);
9557 return $course->fullname
;
9562 * The lang_string class
9564 * This special class is used to create an object representation of a string request.
9565 * It is special because processing doesn't occur until the object is first used.
9566 * The class was created especially to aid performance in areas where strings were
9567 * required to be generated but were not necessarily used.
9568 * As an example the admin tree when generated uses over 1500 strings, of which
9569 * normally only 1/3 are ever actually printed at any time.
9570 * The performance advantage is achieved by not actually processing strings that
9571 * arn't being used, as such reducing the processing required for the page.
9573 * How to use the lang_string class?
9574 * There are two methods of using the lang_string class, first through the
9575 * forth argument of the get_string function, and secondly directly.
9576 * The following are examples of both.
9577 * 1. Through get_string calls e.g.
9578 * $string = get_string($identifier, $component, $a, true);
9579 * $string = get_string('yes', 'moodle', null, true);
9580 * 2. Direct instantiation
9581 * $string = new lang_string($identifier, $component, $a, $lang);
9582 * $string = new lang_string('yes');
9584 * How do I use a lang_string object?
9585 * The lang_string object makes use of a magic __toString method so that you
9586 * are able to use the object exactly as you would use a string in most cases.
9587 * This means you are able to collect it into a variable and then directly
9588 * echo it, or concatenate it into another string, or similar.
9589 * The other thing you can do is manually get the string by calling the
9590 * lang_strings out method e.g.
9591 * $string = new lang_string('yes');
9593 * Also worth noting is that the out method can take one argument, $lang which
9594 * allows the developer to change the language on the fly.
9596 * When should I use a lang_string object?
9597 * The lang_string object is designed to be used in any situation where a
9598 * string may not be needed, but needs to be generated.
9599 * The admin tree is a good example of where lang_string objects should be
9601 * A more practical example would be any class that requries strings that may
9602 * not be printed (after all classes get renderer by renderers and who knows
9603 * what they will do ;))
9605 * When should I not use a lang_string object?
9606 * Don't use lang_strings when you are going to use a string immediately.
9607 * There is no need as it will be processed immediately and there will be no
9608 * advantage, and in fact perhaps a negative hit as a class has to be
9609 * instantiated for a lang_string object, however get_string won't require
9613 * 1. You cannot use a lang_string object as an array offset. Doing so will
9614 * result in PHP throwing an error. (You can use it as an object property!)
9618 * @copyright 2011 Sam Hemelryk
9619 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9623 /** @var string The strings identifier */
9624 protected $identifier;
9625 /** @var string The strings component. Default '' */
9626 protected $component = '';
9627 /** @var array|stdClass Any arguments required for the string. Default null */
9628 protected $a = null;
9629 /** @var string The language to use when processing the string. Default null */
9630 protected $lang = null;
9632 /** @var string The processed string (once processed) */
9633 protected $string = null;
9636 * A special boolean. If set to true then the object has been woken up and
9637 * cannot be regenerated. If this is set then $this->string MUST be used.
9640 protected $forcedstring = false;
9643 * Constructs a lang_string object
9645 * This function should do as little processing as possible to ensure the best
9646 * performance for strings that won't be used.
9648 * @param string $identifier The strings identifier
9649 * @param string $component The strings component
9650 * @param stdClass|array $a Any arguments the string requires
9651 * @param string $lang The language to use when processing the string.
9652 * @throws coding_exception
9654 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9655 if (empty($component)) {
9656 $component = 'moodle';
9659 $this->identifier
= $identifier;
9660 $this->component
= $component;
9661 $this->lang
= $lang;
9663 // We MUST duplicate $a to ensure that it if it changes by reference those
9664 // changes are not carried across.
9665 // To do this we always ensure $a or its properties/values are strings
9666 // and that any properties/values that arn't convertable are forgotten.
9668 if (is_scalar($a)) {
9670 } else if ($a instanceof lang_string
) {
9671 $this->a
= $a->out();
9672 } else if (is_object($a) or is_array($a)) {
9675 foreach ($a as $key => $value) {
9676 // Make sure conversion errors don't get displayed (results in '').
9677 if (is_array($value)) {
9678 $this->a
[$key] = '';
9679 } else if (is_object($value)) {
9680 if (method_exists($value, '__toString')) {
9681 $this->a
[$key] = $value->__toString();
9683 $this->a
[$key] = '';
9686 $this->a
[$key] = (string)$value;
9692 if (debugging(false, DEBUG_DEVELOPER
)) {
9693 if (clean_param($this->identifier
, PARAM_STRINGID
) == '') {
9694 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9696 if (!empty($this->component
) && clean_param($this->component
, PARAM_COMPONENT
) == '') {
9697 throw new coding_exception('Invalid string compontent. Please check your string definition');
9699 if (!get_string_manager()->string_exists($this->identifier
, $this->component
)) {
9700 debugging('String does not exist. Please check your string definition for '.$this->identifier
.'/'.$this->component
, DEBUG_DEVELOPER
);
9706 * Processes the string.
9708 * This function actually processes the string, stores it in the string property
9709 * and then returns it.
9710 * You will notice that this function is VERY similar to the get_string method.
9711 * That is because it is pretty much doing the same thing.
9712 * However as this function is an upgrade it isn't as tolerant to backwards
9716 * @throws coding_exception
9718 protected function get_string() {
9721 // Check if we need to process the string.
9722 if ($this->string === null) {
9723 // Check the quality of the identifier.
9724 if ($CFG->debugdeveloper
&& clean_param($this->identifier
, PARAM_STRINGID
) === '') {
9725 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
);
9728 // Process the string.
9729 $this->string = get_string_manager()->get_string($this->identifier
, $this->component
, $this->a
, $this->lang
);
9730 // Debugging feature lets you display string identifier and component.
9731 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
9732 $this->string .= ' {' . $this->identifier
. '/' . $this->component
. '}';
9735 // Return the string.
9736 return $this->string;
9740 * Returns the string
9742 * @param string $lang The langauge to use when processing the string
9745 public function out($lang = null) {
9746 if ($lang !== null && $lang != $this->lang
&& ($this->lang
== null && $lang != current_language())) {
9747 if ($this->forcedstring
) {
9748 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang
.' used)', DEBUG_DEVELOPER
);
9749 return $this->get_string();
9751 $translatedstring = new lang_string($this->identifier
, $this->component
, $this->a
, $lang);
9752 return $translatedstring->out();
9754 return $this->get_string();
9758 * Magic __toString method for printing a string
9762 public function __toString() {
9763 return $this->get_string();
9767 * Magic __set_state method used for var_export
9771 public function __set_state() {
9772 return $this->get_string();
9776 * Prepares the lang_string for sleep and stores only the forcedstring and
9777 * string properties... the string cannot be regenerated so we need to ensure
9778 * it is generated for this.
9782 public function __sleep() {
9783 $this->get_string();
9784 $this->forcedstring
= true;
9785 return array('forcedstring', 'string', 'lang');