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');
417 /** True if module supports groupmembersonly */
418 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
420 /** Type of module */
421 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
422 /** True if module supports intro editor */
423 define('FEATURE_MOD_INTRO', 'mod_intro');
424 /** True if module has default completion */
425 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
427 define('FEATURE_COMMENT', 'comment');
429 define('FEATURE_RATE', 'rate');
430 /** True if module supports backup/restore of moodle2 format */
431 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
433 /** True if module can show description on course main page */
434 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
436 /** True if module uses the question bank */
437 define('FEATURE_USES_QUESTIONS', 'usesquestions');
439 /** Unspecified module archetype */
440 define('MOD_ARCHETYPE_OTHER', 0);
441 /** Resource-like type module */
442 define('MOD_ARCHETYPE_RESOURCE', 1);
443 /** Assignment module archetype */
444 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
445 /** System (not user-addable) module archetype */
446 define('MOD_ARCHETYPE_SYSTEM', 3);
448 /** Return this from modname_get_types callback to use default display in activity chooser */
449 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
452 * Security token used for allowing access
453 * from external application such as web services.
454 * Scripts do not use any session, performance is relatively
455 * low because we need to load access info in each request.
456 * Scripts are executed in parallel.
458 define('EXTERNAL_TOKEN_PERMANENT', 0);
461 * Security token used for allowing access
462 * of embedded applications, the code is executed in the
463 * active user session. Token is invalidated after user logs out.
464 * Scripts are executed serially - normal session locking is used.
466 define('EXTERNAL_TOKEN_EMBEDDED', 1);
469 * The home page should be the site home
471 define('HOMEPAGE_SITE', 0);
473 * The home page should be the users my page
475 define('HOMEPAGE_MY', 1);
477 * The home page can be chosen by the user
479 define('HOMEPAGE_USER', 2);
482 * Hub directory url (should be moodle.org)
484 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
488 * Moodle.org url (should be moodle.org)
490 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
493 * Moodle mobile app service name
495 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
498 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
500 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
503 * Course display settings: display all sections on one page.
505 define('COURSE_DISPLAY_SINGLEPAGE', 0);
507 * Course display settings: split pages into a page per section.
509 define('COURSE_DISPLAY_MULTIPAGE', 1);
512 * Authentication constant: String used in password field when password is not stored.
514 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
516 // PARAMETER HANDLING.
519 * Returns a particular value for the named variable, taken from
520 * POST or GET. If the parameter doesn't exist then an error is
521 * thrown because we require this variable.
523 * This function should be used to initialise all required values
524 * in a script that are based on parameters. Usually it will be
526 * $id = required_param('id', PARAM_INT);
528 * Please note the $type parameter is now required and the value can not be array.
530 * @param string $parname the name of the page parameter we want
531 * @param string $type expected type of parameter
533 * @throws coding_exception
535 function required_param($parname, $type) {
536 if (func_num_args() != 2 or empty($parname) or empty($type)) {
537 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
539 // POST has precedence.
540 if (isset($_POST[$parname])) {
541 $param = $_POST[$parname];
542 } else if (isset($_GET[$parname])) {
543 $param = $_GET[$parname];
545 print_error('missingparam', '', '', $parname);
548 if (is_array($param)) {
549 debugging('Invalid array parameter detected in required_param(): '.$parname);
550 // TODO: switch to fatal error in Moodle 2.3.
551 return required_param_array($parname, $type);
554 return clean_param($param, $type);
558 * Returns a particular array value for the named variable, taken from
559 * POST or GET. If the parameter doesn't exist then an error is
560 * thrown because we require this variable.
562 * This function should be used to initialise all required values
563 * in a script that are based on parameters. Usually it will be
565 * $ids = required_param_array('ids', PARAM_INT);
567 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
569 * @param string $parname the name of the page parameter we want
570 * @param string $type expected type of parameter
572 * @throws coding_exception
574 function required_param_array($parname, $type) {
575 if (func_num_args() != 2 or empty($parname) or empty($type)) {
576 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
578 // POST has precedence.
579 if (isset($_POST[$parname])) {
580 $param = $_POST[$parname];
581 } else if (isset($_GET[$parname])) {
582 $param = $_GET[$parname];
584 print_error('missingparam', '', '', $parname);
586 if (!is_array($param)) {
587 print_error('missingparam', '', '', $parname);
591 foreach ($param as $key => $value) {
592 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
593 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
596 $result[$key] = clean_param($value, $type);
603 * Returns a particular value for the named variable, taken from
604 * POST or GET, otherwise returning a given default.
606 * This function should be used to initialise all optional values
607 * in a script that are based on parameters. Usually it will be
609 * $name = optional_param('name', 'Fred', PARAM_TEXT);
611 * Please note the $type parameter is now required and the value can not be array.
613 * @param string $parname the name of the page parameter we want
614 * @param mixed $default the default value to return if nothing is found
615 * @param string $type expected type of parameter
617 * @throws coding_exception
619 function optional_param($parname, $default, $type) {
620 if (func_num_args() != 3 or empty($parname) or empty($type)) {
621 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
623 if (!isset($default)) {
627 // POST has precedence.
628 if (isset($_POST[$parname])) {
629 $param = $_POST[$parname];
630 } else if (isset($_GET[$parname])) {
631 $param = $_GET[$parname];
636 if (is_array($param)) {
637 debugging('Invalid array parameter detected in required_param(): '.$parname);
638 // TODO: switch to $default in Moodle 2.3.
639 return optional_param_array($parname, $default, $type);
642 return clean_param($param, $type);
646 * Returns a particular array value for the named variable, taken from
647 * POST or GET, otherwise returning a given default.
649 * This function should be used to initialise all optional values
650 * in a script that are based on parameters. Usually it will be
652 * $ids = optional_param('id', array(), PARAM_INT);
654 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
656 * @param string $parname the name of the page parameter we want
657 * @param mixed $default the default value to return if nothing is found
658 * @param string $type expected type of parameter
660 * @throws coding_exception
662 function optional_param_array($parname, $default, $type) {
663 if (func_num_args() != 3 or empty($parname) or empty($type)) {
664 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
667 // POST has precedence.
668 if (isset($_POST[$parname])) {
669 $param = $_POST[$parname];
670 } else if (isset($_GET[$parname])) {
671 $param = $_GET[$parname];
675 if (!is_array($param)) {
676 debugging('optional_param_array() expects array parameters only: '.$parname);
681 foreach ($param as $key => $value) {
682 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
683 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
686 $result[$key] = clean_param($value, $type);
693 * Strict validation of parameter values, the values are only converted
694 * to requested PHP type. Internally it is using clean_param, the values
695 * before and after cleaning must be equal - otherwise
696 * an invalid_parameter_exception is thrown.
697 * Objects and classes are not accepted.
699 * @param mixed $param
700 * @param string $type PARAM_ constant
701 * @param bool $allownull are nulls valid value?
702 * @param string $debuginfo optional debug information
703 * @return mixed the $param value converted to PHP type
704 * @throws invalid_parameter_exception if $param is not of given type
706 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED
, $debuginfo='') {
707 if (is_null($param)) {
708 if ($allownull == NULL_ALLOWED
) {
711 throw new invalid_parameter_exception($debuginfo);
714 if (is_array($param) or is_object($param)) {
715 throw new invalid_parameter_exception($debuginfo);
718 $cleaned = clean_param($param, $type);
720 if ($type == PARAM_FLOAT
) {
721 // Do not detect precision loss here.
722 if (is_float($param) or is_int($param)) {
724 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
725 throw new invalid_parameter_exception($debuginfo);
727 } else if ((string)$param !== (string)$cleaned) {
728 // Conversion to string is usually lossless.
729 throw new invalid_parameter_exception($debuginfo);
736 * Makes sure array contains only the allowed types, this function does not validate array key names!
739 * $options = clean_param($options, PARAM_INT);
742 * @param array $param the variable array we are cleaning
743 * @param string $type expected format of param after cleaning.
744 * @param bool $recursive clean recursive arrays
746 * @throws coding_exception
748 function clean_param_array(array $param = null, $type, $recursive = false) {
749 // Convert null to empty array.
750 $param = (array)$param;
751 foreach ($param as $key => $value) {
752 if (is_array($value)) {
754 $param[$key] = clean_param_array($value, $type, true);
756 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
759 $param[$key] = clean_param($value, $type);
766 * Used by {@link optional_param()} and {@link required_param()} to
767 * clean the variables and/or cast to specific types, based on
770 * $course->format = clean_param($course->format, PARAM_ALPHA);
771 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
774 * @param mixed $param the variable we are cleaning
775 * @param string $type expected format of param after cleaning.
777 * @throws coding_exception
779 function clean_param($param, $type) {
782 if (is_array($param)) {
783 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
784 } else if (is_object($param)) {
785 if (method_exists($param, '__toString')) {
786 $param = $param->__toString();
788 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
794 // No cleaning at all.
795 $param = fix_utf8($param);
798 case PARAM_RAW_TRIMMED
:
799 // No cleaning, but strip leading and trailing whitespace.
800 $param = fix_utf8($param);
804 // General HTML cleaning, try to use more specific type if possible this is deprecated!
805 // Please use more specific type instead.
806 if (is_numeric($param)) {
809 $param = fix_utf8($param);
810 // Sweep for scripts, etc.
811 return clean_text($param);
813 case PARAM_CLEANHTML
:
814 // Clean html fragment.
815 $param = fix_utf8($param);
816 // Sweep for scripts, etc.
817 $param = clean_text($param, FORMAT_HTML
);
821 // Convert to integer.
826 return (float)$param;
829 // Remove everything not `a-z`.
830 return preg_replace('/[^a-zA-Z]/i', '', $param);
833 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
834 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
837 // Remove everything not `a-zA-Z0-9`.
838 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
840 case PARAM_ALPHANUMEXT
:
841 // Remove everything not `a-zA-Z0-9_-`.
842 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
845 // Remove everything not `0-9,`.
846 return preg_replace('/[^0-9,]/i', '', $param);
849 // Convert to 1 or 0.
850 $tempstr = strtolower($param);
851 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
853 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
856 $param = empty($param) ?
0 : 1;
862 $param = fix_utf8($param);
863 return strip_tags($param);
866 // Leave only tags needed for multilang.
867 $param = fix_utf8($param);
868 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
869 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
871 if (strpos($param, '</lang>') !== false) {
872 // Old and future mutilang syntax.
873 $param = strip_tags($param, '<lang>');
874 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
878 foreach ($matches[0] as $match) {
879 if ($match === '</lang>') {
887 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
898 } else if (strpos($param, '</span>') !== false) {
899 // Current problematic multilang syntax.
900 $param = strip_tags($param, '<span>');
901 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
905 foreach ($matches[0] as $match) {
906 if ($match === '</span>') {
914 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
926 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
927 return strip_tags($param);
929 case PARAM_COMPONENT
:
930 // We do not want any guessing here, either the name is correct or not
931 // please note only normalised component names are accepted.
932 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
935 if (strpos($param, '__') !== false) {
938 if (strpos($param, 'mod_') === 0) {
939 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
940 if (substr_count($param, '_') != 1) {
948 // We do not want any guessing here, either the name is correct or not.
949 if (!is_valid_plugin_name($param)) {
955 // Remove everything not a-zA-Z0-9_- .
956 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
959 // Remove everything not a-zA-Z0-9/_- .
960 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
963 // Strip all suspicious characters from filename.
964 $param = fix_utf8($param);
965 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
966 if ($param === '.' ||
$param === '..') {
972 // Strip all suspicious characters from file path.
973 $param = fix_utf8($param);
974 $param = str_replace('\\', '/', $param);
976 // Explode the path and clean each element using the PARAM_FILE rules.
977 $breadcrumb = explode('/', $param);
978 foreach ($breadcrumb as $key => $crumb) {
979 if ($crumb === '.' && $key === 0) {
980 // Special condition to allow for relative current path such as ./currentdirfile.txt.
982 $crumb = clean_param($crumb, PARAM_FILE
);
984 $breadcrumb[$key] = $crumb;
986 $param = implode('/', $breadcrumb);
988 // Remove multiple current path (./././) and multiple slashes (///).
989 $param = preg_replace('~//+~', '/', $param);
990 $param = preg_replace('~/(\./)+~', '/', $param);
994 // Allow FQDN or IPv4 dotted quad.
995 $param = preg_replace('/[^\.\d\w-]/', '', $param );
996 // Match ipv4 dotted quad.
997 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
998 // Confirm values are ok.
1002 ||
$match[4] > 255 ) {
1003 // Hmmm, what kind of dotted quad is this?
1006 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1007 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1008 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1010 // All is ok - $param is respected.
1017 case PARAM_URL
: // Allow safe ftp, http, mailto urls.
1018 $param = fix_utf8($param);
1019 include_once($CFG->dirroot
. '/lib/validateurlsyntax.php');
1020 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1021 // All is ok, param is respected.
1028 case PARAM_LOCALURL
:
1029 // Allow http absolute, root relative and relative URLs within wwwroot.
1030 $param = clean_param($param, PARAM_URL
);
1031 if (!empty($param)) {
1032 if (preg_match(':^/:', $param)) {
1033 // Root-relative, ok!
1034 } else if (preg_match('/^'.preg_quote($CFG->wwwroot
, '/').'/i', $param)) {
1035 // Absolute, and matches our wwwroot.
1037 // Relative - let's make sure there are no tricks.
1038 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1048 $param = trim($param);
1049 // PEM formatted strings may contain letters/numbers and the symbols:
1053 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1054 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1055 list($wholething, $body) = $matches;
1056 unset($wholething, $matches);
1057 $b64 = clean_param($body, PARAM_BASE64
);
1059 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1067 if (!empty($param)) {
1068 // PEM formatted strings may contain letters/numbers and the symbols
1072 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1075 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY
);
1076 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1077 // than (or equal to) 64 characters long.
1078 for ($i=0, $j=count($lines); $i < $j; $i++
) {
1080 if (64 < strlen($lines[$i])) {
1086 if (64 != strlen($lines[$i])) {
1090 return implode("\n", $lines);
1096 $param = fix_utf8($param);
1097 // Please note it is not safe to use the tag name directly anywhere,
1098 // it must be processed with s(), urlencode() before embedding anywhere.
1099 // Remove some nasties.
1100 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1101 // Convert many whitespace chars into one.
1102 $param = preg_replace('/\s+/', ' ', $param);
1103 $param = core_text
::substr(trim($param), 0, TAG_MAX_LENGTH
);
1107 $param = fix_utf8($param);
1108 $tags = explode(',', $param);
1110 foreach ($tags as $tag) {
1111 $res = clean_param($tag, PARAM_TAG
);
1117 return implode(',', $result);
1122 case PARAM_CAPABILITY
:
1123 if (get_capability_info($param)) {
1129 case PARAM_PERMISSION
:
1130 $param = (int)$param;
1131 if (in_array($param, array(CAP_INHERIT
, CAP_ALLOW
, CAP_PREVENT
, CAP_PROHIBIT
))) {
1138 $param = clean_param($param, PARAM_PLUGIN
);
1139 if (empty($param)) {
1141 } else if (exists_auth_plugin($param)) {
1148 $param = clean_param($param, PARAM_SAFEDIR
);
1149 if (get_string_manager()->translation_exists($param)) {
1152 // Specified language is not installed or param malformed.
1157 $param = clean_param($param, PARAM_PLUGIN
);
1158 if (empty($param)) {
1160 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1162 } else if (!empty($CFG->themedir
) and file_exists("$CFG->themedir/$param/config.php")) {
1165 // Specified theme is not installed.
1169 case PARAM_USERNAME
:
1170 $param = fix_utf8($param);
1171 $param = str_replace(" " , "", $param);
1172 // Convert uppercase to lowercase MDL-16919.
1173 $param = core_text
::strtolower($param);
1174 if (empty($CFG->extendedusernamechars
)) {
1175 // Regular expression, eliminate all chars EXCEPT:
1176 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1177 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1182 $param = fix_utf8($param);
1183 if (validate_email($param)) {
1189 case PARAM_STRINGID
:
1190 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1196 case PARAM_TIMEZONE
:
1197 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1198 $param = fix_utf8($param);
1199 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1200 if (preg_match($timezonepattern, $param)) {
1207 // Doh! throw error, switched parameters in optional_param or another serious problem.
1208 print_error("unknownparamtype", '', '', $type);
1213 * Makes sure the data is using valid utf8, invalid characters are discarded.
1215 * Note: this function is not intended for full objects with methods and private properties.
1217 * @param mixed $value
1218 * @return mixed with proper utf-8 encoding
1220 function fix_utf8($value) {
1221 if (is_null($value) or $value === '') {
1224 } else if (is_string($value)) {
1225 if ((string)(int)$value === $value) {
1229 // No null bytes expected in our data, so let's remove it.
1230 $value = str_replace("\0", '', $value);
1232 // Note: this duplicates min_fix_utf8() intentionally.
1233 static $buggyiconv = null;
1234 if ($buggyiconv === null) {
1235 $buggyiconv = (!function_exists('iconv') or @iconv
('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1239 if (function_exists('mb_convert_encoding')) {
1240 $subst = mb_substitute_character();
1241 mb_substitute_character('');
1242 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1243 mb_substitute_character($subst);
1246 // Warn admins on admin/index.php page.
1251 $result = @iconv
('UTF-8', 'UTF-8//IGNORE', $value);
1256 } else if (is_array($value)) {
1257 foreach ($value as $k => $v) {
1258 $value[$k] = fix_utf8($v);
1262 } else if (is_object($value)) {
1263 // Do not modify original.
1264 $value = clone($value);
1265 foreach ($value as $k => $v) {
1266 $value->$k = fix_utf8($v);
1271 // This is some other type, no utf-8 here.
1277 * Return true if given value is integer or string with integer value
1279 * @param mixed $value String or Int
1280 * @return bool true if number, false if not
1282 function is_number($value) {
1283 if (is_int($value)) {
1285 } else if (is_string($value)) {
1286 return ((string)(int)$value) === $value;
1293 * Returns host part from url.
1295 * @param string $url full url
1296 * @return string host, null if not found
1298 function get_host_from_url($url) {
1299 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1307 * Tests whether anything was returned by text editor
1309 * This function is useful for testing whether something you got back from
1310 * the HTML editor actually contains anything. Sometimes the HTML editor
1311 * appear to be empty, but actually you get back a <br> tag or something.
1313 * @param string $string a string containing HTML.
1314 * @return boolean does the string contain any actual content - that is text,
1315 * images, objects, etc.
1317 function html_is_blank($string) {
1318 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1322 * Set a key in global configuration
1324 * Set a key/value pair in both this session's {@link $CFG} global variable
1325 * and in the 'config' database table for future sessions.
1327 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1328 * In that case it doesn't affect $CFG.
1330 * A NULL value will delete the entry.
1332 * NOTE: this function is called from lib/db/upgrade.php
1334 * @param string $name the key to set
1335 * @param string $value the value to set (without magic quotes)
1336 * @param string $plugin (optional) the plugin scope, default null
1337 * @return bool true or exception
1339 function set_config($name, $value, $plugin=null) {
1342 if (empty($plugin)) {
1343 if (!array_key_exists($name, $CFG->config_php_settings
)) {
1344 // So it's defined for this invocation at least.
1345 if (is_null($value)) {
1348 // Settings from db are always strings.
1349 $CFG->$name = (string)$value;
1353 if ($DB->get_field('config', 'name', array('name' => $name))) {
1354 if ($value === null) {
1355 $DB->delete_records('config', array('name' => $name));
1357 $DB->set_field('config', 'value', $value, array('name' => $name));
1360 if ($value !== null) {
1361 $config = new stdClass();
1362 $config->name
= $name;
1363 $config->value
= $value;
1364 $DB->insert_record('config', $config, false);
1367 if ($name === 'siteidentifier') {
1368 cache_helper
::update_site_identifier($value);
1370 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1373 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1374 if ($value===null) {
1375 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1377 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1380 if ($value !== null) {
1381 $config = new stdClass();
1382 $config->plugin
= $plugin;
1383 $config->name
= $name;
1384 $config->value
= $value;
1385 $DB->insert_record('config_plugins', $config, false);
1388 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
1395 * Get configuration values from the global config table
1396 * or the config_plugins table.
1398 * If called with one parameter, it will load all the config
1399 * variables for one plugin, and return them as an object.
1401 * If called with 2 parameters it will return a string single
1402 * value or false if the value is not found.
1404 * NOTE: this function is called from lib/db/upgrade.php
1406 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1407 * that we need only fetch it once per request.
1408 * @param string $plugin full component name
1409 * @param string $name default null
1410 * @return mixed hash-like object or single value, return false no config found
1411 * @throws dml_exception
1413 function get_config($plugin, $name = null) {
1416 static $siteidentifier = null;
1418 if ($plugin === 'moodle' ||
$plugin === 'core' ||
empty($plugin)) {
1419 $forced =& $CFG->config_php_settings
;
1423 if (array_key_exists($plugin, $CFG->forced_plugin_settings
)) {
1424 $forced =& $CFG->forced_plugin_settings
[$plugin];
1431 if ($siteidentifier === null) {
1433 // This may fail during installation.
1434 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1435 // install the database.
1436 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1437 } catch (dml_exception
$ex) {
1438 // Set siteidentifier to false. We don't want to trip this continually.
1439 $siteidentifier = false;
1444 if (!empty($name)) {
1445 if (array_key_exists($name, $forced)) {
1446 return (string)$forced[$name];
1447 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1448 return $siteidentifier;
1452 $cache = cache
::make('core', 'config');
1453 $result = $cache->get($plugin);
1454 if ($result === false) {
1455 // The user is after a recordset.
1457 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1459 // This part is not really used any more, but anyway...
1460 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1462 $cache->set($plugin, $result);
1465 if (!empty($name)) {
1466 if (array_key_exists($name, $result)) {
1467 return $result[$name];
1472 if ($plugin === 'core') {
1473 $result['siteidentifier'] = $siteidentifier;
1476 foreach ($forced as $key => $value) {
1477 if (is_null($value) or is_array($value) or is_object($value)) {
1478 // We do not want any extra mess here, just real settings that could be saved in db.
1479 unset($result[$key]);
1481 // Convert to string as if it went through the DB.
1482 $result[$key] = (string)$value;
1486 return (object)$result;
1490 * Removes a key from global configuration.
1492 * NOTE: this function is called from lib/db/upgrade.php
1494 * @param string $name the key to set
1495 * @param string $plugin (optional) the plugin scope
1496 * @return boolean whether the operation succeeded.
1498 function unset_config($name, $plugin=null) {
1501 if (empty($plugin)) {
1503 $DB->delete_records('config', array('name' => $name));
1504 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1506 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1507 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
1514 * Remove all the config variables for a given plugin.
1516 * NOTE: this function is called from lib/db/upgrade.php
1518 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1519 * @return boolean whether the operation succeeded.
1521 function unset_all_config_for_plugin($plugin) {
1523 // Delete from the obvious config_plugins first.
1524 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1525 // Next delete any suspect settings from config.
1526 $like = $DB->sql_like('name', '?', true, true, false, '|');
1527 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1528 $DB->delete_records_select('config', $like, $params);
1529 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1530 cache_helper
::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1536 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1538 * All users are verified if they still have the necessary capability.
1540 * @param string $value the value of the config setting.
1541 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1542 * @param bool $includeadmins include administrators.
1543 * @return array of user objects.
1545 function get_users_from_config($value, $capability, $includeadmins = true) {
1546 if (empty($value) or $value === '$@NONE@$') {
1550 // We have to make sure that users still have the necessary capability,
1551 // it should be faster to fetch them all first and then test if they are present
1552 // instead of validating them one-by-one.
1553 $users = get_users_by_capability(context_system
::instance(), $capability);
1554 if ($includeadmins) {
1555 $admins = get_admins();
1556 foreach ($admins as $admin) {
1557 $users[$admin->id
] = $admin;
1561 if ($value === '$@ALL@$') {
1565 $result = array(); // Result in correct order.
1566 $allowed = explode(',', $value);
1567 foreach ($allowed as $uid) {
1568 if (isset($users[$uid])) {
1569 $user = $users[$uid];
1570 $result[$user->id
] = $user;
1579 * Invalidates browser caches and cached data in temp.
1581 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1582 * {@link phpunit_util::reset_dataroot()}
1586 function purge_all_caches() {
1589 reset_text_filters_cache();
1590 js_reset_all_caches();
1591 theme_reset_all_caches();
1592 get_string_manager()->reset_caches();
1593 core_text
::reset_caches();
1594 if (class_exists('core_plugin_manager')) {
1595 core_plugin_manager
::reset_caches();
1598 // Bump up cacherev field for all courses.
1600 increment_revision_number('course', 'cacherev', '');
1601 } catch (moodle_exception
$e) {
1602 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1605 $DB->reset_caches();
1606 cache_helper
::purge_all();
1608 // Purge all other caches: rss, simplepie, etc.
1609 remove_dir($CFG->cachedir
.'', true);
1611 // Make sure cache dir is writable, throws exception if not.
1612 make_cache_directory('');
1614 // This is the only place where we purge local caches, we are only adding files there.
1615 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1616 remove_dir($CFG->localcachedir
, true);
1617 set_config('localcachedirpurged', time());
1618 make_localcache_directory('', true);
1619 \core\task\manager
::clear_static_caches();
1623 * Get volatile flags
1625 * @param string $type
1626 * @param int $changedsince default null
1627 * @return array records array
1629 function get_cache_flags($type, $changedsince = null) {
1632 $params = array('type' => $type, 'expiry' => time());
1633 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1634 if ($changedsince !== null) {
1635 $params['changedsince'] = $changedsince;
1636 $sqlwhere .= " AND timemodified > :changedsince";
1639 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1640 foreach ($flags as $flag) {
1641 $cf[$flag->name
] = $flag->value
;
1648 * Get volatile flags
1650 * @param string $type
1651 * @param string $name
1652 * @param int $changedsince default null
1653 * @return string|false The cache flag value or false
1655 function get_cache_flag($type, $name, $changedsince=null) {
1658 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1660 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1661 if ($changedsince !== null) {
1662 $params['changedsince'] = $changedsince;
1663 $sqlwhere .= " AND timemodified > :changedsince";
1666 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1670 * Set a volatile flag
1672 * @param string $type the "type" namespace for the key
1673 * @param string $name the key to set
1674 * @param string $value the value to set (without magic quotes) - null will remove the flag
1675 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1676 * @return bool Always returns true
1678 function set_cache_flag($type, $name, $value, $expiry = null) {
1681 $timemodified = time();
1682 if ($expiry === null ||
$expiry < $timemodified) {
1683 $expiry = $timemodified +
24 * 60 * 60;
1685 $expiry = (int)$expiry;
1688 if ($value === null) {
1689 unset_cache_flag($type, $name);
1693 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE
)) {
1694 // This is a potential problem in DEBUG_DEVELOPER.
1695 if ($f->value
== $value and $f->expiry
== $expiry and $f->timemodified
== $timemodified) {
1696 return true; // No need to update.
1699 $f->expiry
= $expiry;
1700 $f->timemodified
= $timemodified;
1701 $DB->update_record('cache_flags', $f);
1703 $f = new stdClass();
1704 $f->flagtype
= $type;
1707 $f->expiry
= $expiry;
1708 $f->timemodified
= $timemodified;
1709 $DB->insert_record('cache_flags', $f);
1715 * Removes a single volatile flag
1717 * @param string $type the "type" namespace for the key
1718 * @param string $name the key to set
1721 function unset_cache_flag($type, $name) {
1723 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1728 * Garbage-collect volatile flags
1730 * @return bool Always returns true
1732 function gc_cache_flags() {
1734 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1738 // USER PREFERENCE API.
1741 * Refresh user preference cache. This is used most often for $USER
1742 * object that is stored in session, but it also helps with performance in cron script.
1744 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1747 * @category preference
1749 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1750 * @param int $cachelifetime Cache life time on the current page (in seconds)
1751 * @throws coding_exception
1754 function check_user_preferences_loaded(stdClass
$user, $cachelifetime = 120) {
1756 // Static cache, we need to check on each page load, not only every 2 minutes.
1757 static $loadedusers = array();
1759 if (!isset($user->id
)) {
1760 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1763 if (empty($user->id
) or isguestuser($user->id
)) {
1764 // No permanent storage for not-logged-in users and guest.
1765 if (!isset($user->preference
)) {
1766 $user->preference
= array();
1773 if (isset($loadedusers[$user->id
]) and isset($user->preference
) and isset($user->preference
['_lastloaded'])) {
1774 // Already loaded at least once on this page. Are we up to date?
1775 if ($user->preference
['_lastloaded'] +
$cachelifetime > $timenow) {
1776 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1779 } else if (!get_cache_flag('userpreferenceschanged', $user->id
, $user->preference
['_lastloaded'])) {
1780 // No change since the lastcheck on this page.
1781 $user->preference
['_lastloaded'] = $timenow;
1786 // OK, so we have to reload all preferences.
1787 $loadedusers[$user->id
] = true;
1788 $user->preference
= $DB->get_records_menu('user_preferences', array('userid' => $user->id
), '', 'name,value'); // All values.
1789 $user->preference
['_lastloaded'] = $timenow;
1793 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1795 * NOTE: internal function, do not call from other code.
1799 * @param integer $userid the user whose prefs were changed.
1801 function mark_user_preferences_changed($userid) {
1804 if (empty($userid) or isguestuser($userid)) {
1805 // No cache flags for guest and not-logged-in users.
1809 set_cache_flag('userpreferenceschanged', $userid, 1, time() +
$CFG->sessiontimeout
);
1813 * Sets a preference for the specified user.
1815 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1818 * @category preference
1820 * @param string $name The key to set as preference for the specified user
1821 * @param string $value The value to set for the $name key in the specified user's
1822 * record, null means delete current value.
1823 * @param stdClass|int|null $user A moodle user object or id, null means current user
1824 * @throws coding_exception
1825 * @return bool Always true or exception
1827 function set_user_preference($name, $value, $user = null) {
1830 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1831 throw new coding_exception('Invalid preference name in set_user_preference() call');
1834 if (is_null($value)) {
1835 // Null means delete current.
1836 return unset_user_preference($name, $user);
1837 } else if (is_object($value)) {
1838 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1839 } else if (is_array($value)) {
1840 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1842 // Value column maximum length is 1333 characters.
1843 $value = (string)$value;
1844 if (core_text
::strlen($value) > 1333) {
1845 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1848 if (is_null($user)) {
1850 } else if (isset($user->id
)) {
1851 // It is a valid object.
1852 } else if (is_numeric($user)) {
1853 $user = (object)array('id' => (int)$user);
1855 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1858 check_user_preferences_loaded($user);
1860 if (empty($user->id
) or isguestuser($user->id
)) {
1861 // No permanent storage for not-logged-in users and guest.
1862 $user->preference
[$name] = $value;
1866 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => $name))) {
1867 if ($preference->value
=== $value and isset($user->preference
[$name]) and $user->preference
[$name] === $value) {
1868 // Preference already set to this value.
1871 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id
));
1874 $preference = new stdClass();
1875 $preference->userid
= $user->id
;
1876 $preference->name
= $name;
1877 $preference->value
= $value;
1878 $DB->insert_record('user_preferences', $preference);
1881 // Update value in cache.
1882 $user->preference
[$name] = $value;
1884 // Set reload flag for other sessions.
1885 mark_user_preferences_changed($user->id
);
1891 * Sets a whole array of preferences for the current user
1893 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1896 * @category preference
1898 * @param array $prefarray An array of key/value pairs to be set
1899 * @param stdClass|int|null $user A moodle user object or id, null means current user
1900 * @return bool Always true or exception
1902 function set_user_preferences(array $prefarray, $user = null) {
1903 foreach ($prefarray as $name => $value) {
1904 set_user_preference($name, $value, $user);
1910 * Unsets a preference completely by deleting it from the database
1912 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1915 * @category preference
1917 * @param string $name The key to unset as preference for the specified user
1918 * @param stdClass|int|null $user A moodle user object or id, null means current user
1919 * @throws coding_exception
1920 * @return bool Always true or exception
1922 function unset_user_preference($name, $user = null) {
1925 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1926 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1929 if (is_null($user)) {
1931 } else if (isset($user->id
)) {
1932 // It is a valid object.
1933 } else if (is_numeric($user)) {
1934 $user = (object)array('id' => (int)$user);
1936 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1939 check_user_preferences_loaded($user);
1941 if (empty($user->id
) or isguestuser($user->id
)) {
1942 // No permanent storage for not-logged-in user and guest.
1943 unset($user->preference
[$name]);
1948 $DB->delete_records('user_preferences', array('userid' => $user->id
, 'name' => $name));
1950 // Delete the preference from cache.
1951 unset($user->preference
[$name]);
1953 // Set reload flag for other sessions.
1954 mark_user_preferences_changed($user->id
);
1960 * Used to fetch user preference(s)
1962 * If no arguments are supplied this function will return
1963 * all of the current user preferences as an array.
1965 * If a name is specified then this function
1966 * attempts to return that particular preference value. If
1967 * none is found, then the optional value $default is returned,
1970 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1973 * @category preference
1975 * @param string $name Name of the key to use in finding a preference value
1976 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1977 * @param stdClass|int|null $user A moodle user object or id, null means current user
1978 * @throws coding_exception
1979 * @return string|mixed|null A string containing the value of a single preference. An
1980 * array with all of the preferences or null
1982 function get_user_preferences($name = null, $default = null, $user = null) {
1985 if (is_null($name)) {
1987 } else if (is_numeric($name) or $name === '_lastloaded') {
1988 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1991 if (is_null($user)) {
1993 } else if (isset($user->id
)) {
1994 // Is a valid object.
1995 } else if (is_numeric($user)) {
1996 $user = (object)array('id' => (int)$user);
1998 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2001 check_user_preferences_loaded($user);
2005 return $user->preference
;
2006 } else if (isset($user->preference
[$name])) {
2007 // The single string value.
2008 return $user->preference
[$name];
2010 // Default value (null if not specified).
2015 // FUNCTIONS FOR HANDLING TIME.
2018 * Given date parts in user time produce a GMT timestamp.
2022 * @param int $year The year part to create timestamp of
2023 * @param int $month The month part to create timestamp of
2024 * @param int $day The day part to create timestamp of
2025 * @param int $hour The hour part to create timestamp of
2026 * @param int $minute The minute part to create timestamp of
2027 * @param int $second The second part to create timestamp of
2028 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2029 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2030 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2031 * applied only if timezone is 99 or string.
2032 * @return int GMT timestamp
2034 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2036 // Save input timezone, required for dst offset check.
2037 $passedtimezone = $timezone;
2039 $timezone = get_user_timezone_offset($timezone);
2041 if (abs($timezone) > 13) {
2043 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2045 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2046 $time = usertime($time, $timezone);
2048 // Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
2049 if ($applydst && ((99 == $passedtimezone) ||
!is_numeric($passedtimezone))) {
2050 $time -= dst_offset_on($time, $passedtimezone);
2059 * Format a date/time (seconds) as weeks, days, hours etc as needed
2061 * Given an amount of time in seconds, returns string
2062 * formatted nicely as weeks, days, hours etc as needed
2070 * @param int $totalsecs Time in seconds
2071 * @param stdClass $str Should be a time object
2072 * @return string A nicely formatted date/time string
2074 function format_time($totalsecs, $str = null) {
2076 $totalsecs = abs($totalsecs);
2079 // Create the str structure the slow way.
2080 $str = new stdClass();
2081 $str->day
= get_string('day');
2082 $str->days
= get_string('days');
2083 $str->hour
= get_string('hour');
2084 $str->hours
= get_string('hours');
2085 $str->min
= get_string('min');
2086 $str->mins
= get_string('mins');
2087 $str->sec
= get_string('sec');
2088 $str->secs
= get_string('secs');
2089 $str->year
= get_string('year');
2090 $str->years
= get_string('years');
2093 $years = floor($totalsecs/YEARSECS
);
2094 $remainder = $totalsecs - ($years*YEARSECS
);
2095 $days = floor($remainder/DAYSECS
);
2096 $remainder = $totalsecs - ($days*DAYSECS
);
2097 $hours = floor($remainder/HOURSECS
);
2098 $remainder = $remainder - ($hours*HOURSECS
);
2099 $mins = floor($remainder/MINSECS
);
2100 $secs = $remainder - ($mins*MINSECS
);
2102 $ss = ($secs == 1) ?
$str->sec
: $str->secs
;
2103 $sm = ($mins == 1) ?
$str->min
: $str->mins
;
2104 $sh = ($hours == 1) ?
$str->hour
: $str->hours
;
2105 $sd = ($days == 1) ?
$str->day
: $str->days
;
2106 $sy = ($years == 1) ?
$str->year
: $str->years
;
2115 $oyears = $years .' '. $sy;
2118 $odays = $days .' '. $sd;
2121 $ohours = $hours .' '. $sh;
2124 $omins = $mins .' '. $sm;
2127 $osecs = $secs .' '. $ss;
2131 return trim($oyears .' '. $odays);
2134 return trim($odays .' '. $ohours);
2137 return trim($ohours .' '. $omins);
2140 return trim($omins .' '. $osecs);
2145 return get_string('now');
2149 * Returns a formatted string that represents a date in user time.
2153 * @param int $date the timestamp in UTC, as obtained from the database.
2154 * @param string $format strftime format. You should probably get this using
2155 * get_string('strftime...', 'langconfig');
2156 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2157 * not 99 then daylight saving will not be added.
2158 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2159 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2160 * If false then the leading zero is maintained.
2161 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2162 * @return string the formatted date/time.
2164 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2165 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2166 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2170 * Returns a formatted date ensuring it is UTF-8.
2172 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2173 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2175 * This function does not do any calculation regarding the user preferences and should
2176 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2177 * to differentiate the use of server time or not (strftime() against gmstrftime()).
2179 * @param int $date the timestamp.
2180 * @param string $format strftime format.
2181 * @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2182 * @return string the formatted date/time.
2183 * @since Moodle 2.3.3
2185 function date_format_string($date, $format, $tz = 99) {
2188 $localewincharset = null;
2189 // Get the calendar type user is using.
2190 if ($CFG->ostype
== 'WINDOWS') {
2191 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2192 $localewincharset = $calendartype->locale_win_charset();
2195 if (abs($tz) > 13) {
2196 if ($localewincharset) {
2197 $format = core_text
::convert($format, 'utf-8', $localewincharset);
2198 $datestring = strftime($format, $date);
2199 $datestring = core_text
::convert($datestring, $localewincharset, 'utf-8');
2201 $datestring = strftime($format, $date);
2204 if ($localewincharset) {
2205 $format = core_text
::convert($format, 'utf-8', $localewincharset);
2206 $datestring = gmstrftime($format, $date);
2207 $datestring = core_text
::convert($datestring, $localewincharset, 'utf-8');
2209 $datestring = gmstrftime($format, $date);
2216 * Given a $time timestamp in GMT (seconds since epoch),
2217 * returns an array that represents the date in user time
2222 * @param int $time Timestamp in GMT
2223 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2224 * dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
2225 * @return array An array that represents the date in user time
2227 function usergetdate($time, $timezone=99) {
2229 // Save input timezone, required for dst offset check.
2230 $passedtimezone = $timezone;
2232 $timezone = get_user_timezone_offset($timezone);
2234 if (abs($timezone) > 13) {
2236 return getdate($time);
2239 // Add daylight saving offset for string timezones only, as we can't get dst for
2240 // float values. if timezone is 99 (user default timezone), then try update dst.
2241 if ($passedtimezone == 99 ||
!is_numeric($passedtimezone)) {
2242 $time +
= dst_offset_on($time, $passedtimezone);
2245 $time +
= intval((float)$timezone * HOURSECS
);
2247 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2249 // Be careful to ensure the returned array matches that produced by getdate() above.
2252 $getdate['weekday'],
2259 $getdate['minutes'],
2261 ) = explode('_', $datestring);
2263 // Set correct datatype to match with getdate().
2264 $getdate['seconds'] = (int)$getdate['seconds'];
2265 $getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
2266 $getdate['year'] = (int)$getdate['year'];
2267 $getdate['mon'] = (int)$getdate['mon'];
2268 $getdate['wday'] = (int)$getdate['wday'];
2269 $getdate['mday'] = (int)$getdate['mday'];
2270 $getdate['hours'] = (int)$getdate['hours'];
2271 $getdate['minutes'] = (int)$getdate['minutes'];
2276 * Given a GMT timestamp (seconds since epoch), offsets it by
2277 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2282 * @param int $date Timestamp in GMT
2283 * @param float|int|string $timezone timezone to calculate GMT time offset before
2284 * calculating user time, 99 is default user timezone
2285 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2288 function usertime($date, $timezone=99) {
2290 $timezone = get_user_timezone_offset($timezone);
2292 if (abs($timezone) > 13) {
2295 return $date - (int)($timezone * HOURSECS
);
2299 * Given a time, return the GMT timestamp of the most recent midnight
2300 * for the current user.
2304 * @param int $date Timestamp in GMT
2305 * @param float|int|string $timezone timezone to calculate GMT time offset before
2306 * calculating user midnight time, 99 is default user timezone
2307 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2308 * @return int Returns a GMT timestamp
2310 function usergetmidnight($date, $timezone=99) {
2312 $userdate = usergetdate($date, $timezone);
2314 // Time of midnight of this user's day, in GMT.
2315 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2320 * Returns a string that prints the user's timezone
2324 * @param float|int|string $timezone timezone to calculate GMT time offset before
2325 * calculating user timezone, 99 is default user timezone
2326 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2329 function usertimezone($timezone=99) {
2331 $tz = get_user_timezone($timezone);
2333 if (!is_float($tz)) {
2337 if (abs($tz) > 13) {
2339 return get_string('serverlocaltime');
2342 if ($tz == intval($tz)) {
2343 // Don't show .0 for whole hours.
2349 } else if ($tz > 0) {
2358 * Returns a float which represents the user's timezone difference from GMT in hours
2359 * Checks various settings and picks the most dominant of those which have a value
2363 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2364 * 99 is default user timezone
2365 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2368 function get_user_timezone_offset($tz = 99) {
2369 $tz = get_user_timezone($tz);
2371 if (is_float($tz)) {
2374 $tzrecord = get_timezone_record($tz);
2375 if (empty($tzrecord)) {
2378 return (float)$tzrecord->gmtoff
/ HOURMINS
;
2383 * Returns an int which represents the systems's timezone difference from GMT in seconds
2387 * @param float|int|string $tz timezone for which offset is required.
2388 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2389 * @return int|bool if found, false is timezone 99 or error
2391 function get_timezone_offset($tz) {
2396 if (is_numeric($tz)) {
2397 return intval($tz * 60*60);
2400 if (!$tzrecord = get_timezone_record($tz)) {
2403 return intval($tzrecord->gmtoff
* 60);
2407 * Returns a float or a string which denotes the user's timezone
2408 * 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)
2409 * means that for this timezone there are also DST rules to be taken into account
2410 * Checks various settings and picks the most dominant of those which have a value
2414 * @param float|int|string $tz timezone to calculate GMT time offset before
2415 * calculating user timezone, 99 is default user timezone
2416 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2417 * @return float|string
2419 function get_user_timezone($tz = 99) {
2424 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
2425 isset($USER->timezone
) ?
$USER->timezone
: 99,
2426 isset($CFG->timezone
) ?
$CFG->timezone
: 99,
2431 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2432 while (((empty($tz) && !is_numeric($tz)) ||
$tz == 99) && $next = each($timezones)) {
2433 $tz = $next['value'];
2435 return is_numeric($tz) ?
(float) $tz : $tz;
2439 * Returns cached timezone record for given $timezonename
2442 * @param string $timezonename name of the timezone
2443 * @return stdClass|bool timezonerecord or false
2445 function get_timezone_record($timezonename) {
2447 static $cache = null;
2449 if ($cache === null) {
2453 if (isset($cache[$timezonename])) {
2454 return $cache[$timezonename];
2457 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2458 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE
);
2462 * Build and store the users Daylight Saving Time (DST) table
2465 * @param int $fromyear Start year for the table, defaults to 1971
2466 * @param int $toyear End year for the table, defaults to 2035
2467 * @param int|float|string $strtimezone timezone to check if dst should be applied.
2470 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2471 global $SESSION, $DB;
2473 $usertz = get_user_timezone($strtimezone);
2475 if (is_float($usertz)) {
2476 // Trivial timezone, no DST.
2480 if (!empty($SESSION->dst_offsettz
) && $SESSION->dst_offsettz
!= $usertz) {
2481 // We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
2482 unset($SESSION->dst_offsets
);
2483 unset($SESSION->dst_range
);
2486 if (!empty($SESSION->dst_offsets
) && empty($fromyear) && empty($toyear)) {
2487 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
2488 // This will be the return path most of the time, pretty light computationally.
2492 // Reaching here means we either need to extend our table or create it from scratch.
2494 // Remember which TZ we calculated these changes for.
2495 $SESSION->dst_offsettz
= $usertz;
2497 if (empty($SESSION->dst_offsets
)) {
2498 // If we 're creating from scratch, put the two guard elements in there.
2499 $SESSION->dst_offsets
= array(1 => null, 0 => null);
2501 if (empty($SESSION->dst_range
)) {
2502 // If creating from scratch.
2503 $from = max((empty($fromyear) ?
intval(date('Y')) - 3 : $fromyear), 1971);
2504 $to = min((empty($toyear) ?
intval(date('Y')) +
3 : $toyear), 2035);
2506 // Fill in the array with the extra years we need to process.
2507 $yearstoprocess = array();
2508 for ($i = $from; $i <= $to; ++
$i) {
2509 $yearstoprocess[] = $i;
2512 // Take note of which years we have processed for future calls.
2513 $SESSION->dst_range
= array($from, $to);
2515 // If needing to extend the table, do the same.
2516 $yearstoprocess = array();
2518 $from = max((empty($fromyear) ?
$SESSION->dst_range
[0] : $fromyear), 1971);
2519 $to = min((empty($toyear) ?
$SESSION->dst_range
[1] : $toyear), 2035);
2521 if ($from < $SESSION->dst_range
[0]) {
2522 // Take note of which years we need to process and then note that we have processed them for future calls.
2523 for ($i = $from; $i < $SESSION->dst_range
[0]; ++
$i) {
2524 $yearstoprocess[] = $i;
2526 $SESSION->dst_range
[0] = $from;
2528 if ($to > $SESSION->dst_range
[1]) {
2529 // Take note of which years we need to process and then note that we have processed them for future calls.
2530 for ($i = $SESSION->dst_range
[1] +
1; $i <= $to; ++
$i) {
2531 $yearstoprocess[] = $i;
2533 $SESSION->dst_range
[1] = $to;
2537 if (empty($yearstoprocess)) {
2538 // This means that there was a call requesting a SMALLER range than we have already calculated.
2542 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2543 // Also, the array is sorted in descending timestamp order!
2547 static $presetscache = array();
2548 if (!isset($presetscache[$usertz])) {
2549 $presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
2550 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
2551 'std_startday, std_weekday, std_skipweeks, std_time');
2553 if (empty($presetscache[$usertz])) {
2557 // Remove ending guard (first element of the array).
2558 reset($SESSION->dst_offsets
);
2559 unset($SESSION->dst_offsets
[key($SESSION->dst_offsets
)]);
2561 // Add all required change timestamps.
2562 foreach ($yearstoprocess as $y) {
2563 // Find the record which is in effect for the year $y.
2564 foreach ($presetscache[$usertz] as $year => $preset) {
2570 $changes = dst_changes_for_year($y, $preset);
2572 if ($changes === null) {
2575 if ($changes['dst'] != 0) {
2576 $SESSION->dst_offsets
[$changes['dst']] = $preset->dstoff
* MINSECS
;
2578 if ($changes['std'] != 0) {
2579 $SESSION->dst_offsets
[$changes['std']] = 0;
2583 // Put in a guard element at the top.
2584 $maxtimestamp = max(array_keys($SESSION->dst_offsets
));
2585 $SESSION->dst_offsets
[($maxtimestamp + DAYSECS
)] = null; // DAYSECS is arbitrary, any "small" number will do.
2588 krsort($SESSION->dst_offsets
);
2594 * Calculates the required DST change and returns a Timestamp Array
2600 * @param int|string $year Int or String Year to focus on
2601 * @param object $timezone Instatiated Timezone object
2602 * @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
2604 function dst_changes_for_year($year, $timezone) {
2606 if ($timezone->dst_startday
== 0 && $timezone->dst_weekday
== 0 &&
2607 $timezone->std_startday
== 0 && $timezone->std_weekday
== 0) {
2611 $monthdaydst = find_day_in_month($timezone->dst_startday
, $timezone->dst_weekday
, $timezone->dst_month
, $year);
2612 $monthdaystd = find_day_in_month($timezone->std_startday
, $timezone->std_weekday
, $timezone->std_month
, $year);
2614 list($dsthour, $dstmin) = explode(':', $timezone->dst_time
);
2615 list($stdhour, $stdmin) = explode(':', $timezone->std_time
);
2617 $timedst = make_timestamp($year, $timezone->dst_month
, $monthdaydst, 0, 0, 0, 99, false);
2618 $timestd = make_timestamp($year, $timezone->std_month
, $monthdaystd, 0, 0, 0, 99, false);
2620 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2621 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2622 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2624 $timedst +
= $dsthour * HOURSECS +
$dstmin * MINSECS
;
2625 $timestd +
= $stdhour * HOURSECS +
$stdmin * MINSECS
;
2627 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2631 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2632 * - Note: Daylight saving only works for string timezones and not for float.
2636 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2637 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2638 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2641 function dst_offset_on($time, $strtimezone = null) {
2644 if (!calculate_user_dst_table(null, null, $strtimezone) ||
empty($SESSION->dst_offsets
)) {
2648 reset($SESSION->dst_offsets
);
2649 while (list($from, $offset) = each($SESSION->dst_offsets
)) {
2650 if ($from <= $time) {
2655 // This is the normal return path.
2656 if ($offset !== null) {
2660 // Reaching this point means we haven't calculated far enough, do it now:
2661 // Calculate extra DST changes if needed and recurse. The recursion always
2662 // moves toward the stopping condition, so will always end.
2665 // We need a year smaller than $SESSION->dst_range[0].
2666 if ($SESSION->dst_range
[0] == 1971) {
2669 calculate_user_dst_table($SESSION->dst_range
[0] - 5, null, $strtimezone);
2670 return dst_offset_on($time, $strtimezone);
2672 // We need a year larger than $SESSION->dst_range[1].
2673 if ($SESSION->dst_range
[1] == 2035) {
2676 calculate_user_dst_table(null, $SESSION->dst_range
[1] +
5, $strtimezone);
2677 return dst_offset_on($time, $strtimezone);
2682 * Calculates when the day appears in specific month
2686 * @param int $startday starting day of the month
2687 * @param int $weekday The day when week starts (normally taken from user preferences)
2688 * @param int $month The month whose day is sought
2689 * @param int $year The year of the month whose day is sought
2692 function find_day_in_month($startday, $weekday, $month, $year) {
2693 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2695 $daysinmonth = days_in_month($month, $year);
2696 $daysinweek = count($calendartype->get_weekdays());
2698 if ($weekday == -1) {
2699 // Don't care about weekday, so return:
2700 // abs($startday) if $startday != -1
2701 // $daysinmonth otherwise.
2702 return ($startday == -1) ?
$daysinmonth : abs($startday);
2705 // From now on we 're looking for a specific weekday.
2706 // Give "end of month" its actual value, since we know it.
2707 if ($startday == -1) {
2708 $startday = -1 * $daysinmonth;
2711 // Starting from day $startday, the sign is the direction.
2712 if ($startday < 1) {
2713 $startday = abs($startday);
2714 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2716 // This is the last such weekday of the month.
2717 $lastinmonth = $daysinmonth +
$weekday - $lastmonthweekday;
2718 if ($lastinmonth > $daysinmonth) {
2719 $lastinmonth -= $daysinweek;
2722 // Find the first such weekday <= $startday.
2723 while ($lastinmonth > $startday) {
2724 $lastinmonth -= $daysinweek;
2727 return $lastinmonth;
2729 $indexweekday = dayofweek($startday, $month, $year);
2731 $diff = $weekday - $indexweekday;
2733 $diff +
= $daysinweek;
2736 // This is the first such weekday of the month equal to or after $startday.
2737 $firstfromindex = $startday +
$diff;
2739 return $firstfromindex;
2744 * Calculate the number of days in a given month
2748 * @param int $month The month whose day count is sought
2749 * @param int $year The year of the month whose day count is sought
2752 function days_in_month($month, $year) {
2753 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2754 return $calendartype->get_num_days_in_month($year, $month);
2758 * Calculate the position in the week of a specific calendar day
2762 * @param int $day The day of the date whose position in the week is sought
2763 * @param int $month The month of the date whose position in the week is sought
2764 * @param int $year The year of the date whose position in the week is sought
2767 function dayofweek($day, $month, $year) {
2768 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2769 return $calendartype->get_weekday($year, $month, $day);
2772 // USER AUTHENTICATION AND LOGIN.
2775 * Returns full login url.
2777 * @return string login url
2779 function get_login_url() {
2782 $url = "$CFG->wwwroot/login/index.php";
2784 if (!empty($CFG->loginhttps
)) {
2785 $url = str_replace('http:', 'https:', $url);
2792 * This function checks that the current user is logged in and has the
2793 * required privileges
2795 * This function checks that the current user is logged in, and optionally
2796 * whether they are allowed to be in a particular course and view a particular
2798 * If they are not logged in, then it redirects them to the site login unless
2799 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2800 * case they are automatically logged in as guests.
2801 * If $courseid is given and the user is not enrolled in that course then the
2802 * user is redirected to the course enrolment page.
2803 * If $cm is given and the course module is hidden and the user is not a teacher
2804 * in the course then the user is redirected to the course home page.
2806 * When $cm parameter specified, this function sets page layout to 'module'.
2807 * You need to change it manually later if some other layout needed.
2809 * @package core_access
2812 * @param mixed $courseorid id of the course or course object
2813 * @param bool $autologinguest default true
2814 * @param object $cm course module object
2815 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2816 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2817 * in order to keep redirects working properly. MDL-14495
2818 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2819 * @return mixed Void, exit, and die depending on path
2820 * @throws coding_exception
2821 * @throws require_login_exception
2823 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2824 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2826 // Must not redirect when byteserving already started.
2827 if (!empty($_SERVER['HTTP_RANGE'])) {
2828 $preventredirect = true;
2831 // Setup global $COURSE, themes, language and locale.
2832 if (!empty($courseorid)) {
2833 if (is_object($courseorid)) {
2834 $course = $courseorid;
2835 } else if ($courseorid == SITEID
) {
2836 $course = clone($SITE);
2838 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST
);
2841 if ($cm->course
!= $course->id
) {
2842 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2844 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2845 if (!($cm instanceof cm_info
)) {
2846 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2847 // db queries so this is not really a performance concern, however it is obviously
2848 // better if you use get_fast_modinfo to get the cm before calling this.
2849 $modinfo = get_fast_modinfo($course);
2850 $cm = $modinfo->get_cm($cm->id
);
2852 $PAGE->set_cm($cm, $course); // Set's up global $COURSE.
2853 $PAGE->set_pagelayout('incourse');
2855 $PAGE->set_course($course); // Set's up global $COURSE.
2858 // Do not touch global $COURSE via $PAGE->set_course(),
2859 // the reasons is we need to be able to call require_login() at any time!!
2862 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2866 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2867 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2868 // risk leading the user back to the AJAX request URL.
2869 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT
) {
2870 $setwantsurltome = false;
2873 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2874 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out
) && !$preventredirect && !empty($CFG->dbsessions
)) {
2875 if ($setwantsurltome) {
2876 $SESSION->wantsurl
= qualified_me();
2878 redirect(get_login_url());
2881 // If the user is not even logged in yet then make sure they are.
2882 if (!isloggedin()) {
2883 if ($autologinguest and !empty($CFG->guestloginbutton
) and !empty($CFG->autologinguests
)) {
2884 if (!$guest = get_complete_user_data('id', $CFG->siteguest
)) {
2885 // Misconfigured site guest, just redirect to login page.
2886 redirect(get_login_url());
2887 exit; // Never reached.
2889 $lang = isset($SESSION->lang
) ?
$SESSION->lang
: $CFG->lang
;
2890 complete_user_login($guest);
2891 $USER->autologinguest
= true;
2892 $SESSION->lang
= $lang;
2894 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2895 if ($preventredirect) {
2896 throw new require_login_exception('You are not logged in');
2899 if ($setwantsurltome) {
2900 $SESSION->wantsurl
= qualified_me();
2902 if (!empty($_SERVER['HTTP_REFERER'])) {
2903 $SESSION->fromurl
= $_SERVER['HTTP_REFERER'];
2905 redirect(get_login_url());
2906 exit; // Never reached.
2910 // Loginas as redirection if needed.
2911 if ($course->id
!= SITEID
and \core\session\manager
::is_loggedinas()) {
2912 if ($USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
2913 if ($USER->loginascontext
->instanceid
!= $course->id
) {
2914 print_error('loginasonecourse', '', $CFG->wwwroot
.'/course/view.php?id='.$USER->loginascontext
->instanceid
);
2919 // Check whether the user should be changing password (but only if it is REALLY them).
2920 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager
::is_loggedinas()) {
2921 $userauth = get_auth_plugin($USER->auth
);
2922 if ($userauth->can_change_password() and !$preventredirect) {
2923 if ($setwantsurltome) {
2924 $SESSION->wantsurl
= qualified_me();
2926 if ($changeurl = $userauth->change_password_url()) {
2927 // Use plugin custom url.
2928 redirect($changeurl);
2930 // Use moodle internal method.
2931 if (empty($CFG->loginhttps
)) {
2932 redirect($CFG->wwwroot
.'/login/change_password.php');
2934 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot
);
2935 redirect($wwwroot .'/login/change_password.php');
2939 print_error('nopasswordchangeforced', 'auth');
2943 // Check that the user account is properly set up.
2944 if (user_not_fully_set_up($USER)) {
2945 if ($preventredirect) {
2946 throw new require_login_exception('User not fully set-up');
2948 if ($setwantsurltome) {
2949 $SESSION->wantsurl
= qualified_me();
2951 redirect($CFG->wwwroot
.'/user/edit.php?id='. $USER->id
.'&course='. SITEID
);
2954 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2957 // Do not bother admins with any formalities.
2958 if (is_siteadmin()) {
2959 // Set accesstime or the user will appear offline which messes up messaging.
2960 user_accesstime_log($course->id
);
2964 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2965 if (!$USER->policyagreed
and !is_siteadmin()) {
2966 if (!empty($CFG->sitepolicy
) and !isguestuser()) {
2967 if ($preventredirect) {
2968 throw new require_login_exception('Policy not agreed');
2970 if ($setwantsurltome) {
2971 $SESSION->wantsurl
= qualified_me();
2973 redirect($CFG->wwwroot
.'/user/policy.php');
2974 } else if (!empty($CFG->sitepolicyguest
) and isguestuser()) {
2975 if ($preventredirect) {
2976 throw new require_login_exception('Policy not agreed');
2978 if ($setwantsurltome) {
2979 $SESSION->wantsurl
= qualified_me();
2981 redirect($CFG->wwwroot
.'/user/policy.php');
2985 // Fetch the system context, the course context, and prefetch its child contexts.
2986 $sysctx = context_system
::instance();
2987 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
2989 $cmcontext = context_module
::instance($cm->id
, MUST_EXIST
);
2994 // If the site is currently under maintenance, then print a message.
2995 if (!empty($CFG->maintenance_enabled
) and !has_capability('moodle/site:config', $sysctx)) {
2996 if ($preventredirect) {
2997 throw new require_login_exception('Maintenance in progress');
3000 print_maintenance_message();
3003 // Make sure the course itself is not hidden.
3004 if ($course->id
== SITEID
) {
3005 // Frontpage can not be hidden.
3007 if (is_role_switched($course->id
)) {
3008 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
3010 if (!$course->visible
and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3011 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
3012 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
3013 if ($preventredirect) {
3014 throw new require_login_exception('Course is hidden');
3016 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3017 // the navigation will mess up when trying to find it.
3018 navigation_node
::override_active_url(new moodle_url('/'));
3019 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
3024 // Is the user enrolled?
3025 if ($course->id
== SITEID
) {
3026 // Everybody is enrolled on the frontpage.
3028 if (\core\session\manager
::is_loggedinas()) {
3029 // Make sure the REAL person can access this course first.
3030 $realuser = \core\session\manager
::get_realuser();
3031 if (!is_enrolled($coursecontext, $realuser->id
, '', true) and
3032 !is_viewing($coursecontext, $realuser->id
) and !is_siteadmin($realuser->id
)) {
3033 if ($preventredirect) {
3034 throw new require_login_exception('Invalid course login-as access');
3036 echo $OUTPUT->header();
3037 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot
.'/');
3043 if (is_role_switched($course->id
)) {
3044 // Ok, user had to be inside this course before the switch.
3047 } else if (is_viewing($coursecontext, $USER)) {
3048 // Ok, no need to mess with enrol.
3052 if (isset($USER->enrol
['enrolled'][$course->id
])) {
3053 if ($USER->enrol
['enrolled'][$course->id
] > time()) {
3055 if (isset($USER->enrol
['tempguest'][$course->id
])) {
3056 unset($USER->enrol
['tempguest'][$course->id
]);
3057 remove_temp_course_roles($coursecontext);
3061 unset($USER->enrol
['enrolled'][$course->id
]);
3064 if (isset($USER->enrol
['tempguest'][$course->id
])) {
3065 if ($USER->enrol
['tempguest'][$course->id
] == 0) {
3067 } else if ($USER->enrol
['tempguest'][$course->id
] > time()) {
3071 unset($USER->enrol
['tempguest'][$course->id
]);
3072 remove_temp_course_roles($coursecontext);
3078 $until = enrol_get_enrolment_end($coursecontext->instanceid
, $USER->id
);
3079 if ($until !== false) {
3080 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3082 $until = ENROL_MAX_TIMESTAMP
;
3084 $USER->enrol
['enrolled'][$course->id
] = $until;
3088 $params = array('courseid' => $course->id
, 'status' => ENROL_INSTANCE_ENABLED
);
3089 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3090 $enrols = enrol_get_plugins(true);
3091 // First ask all enabled enrol instances in course if they want to auto enrol user.
3092 foreach ($instances as $instance) {
3093 if (!isset($enrols[$instance->enrol
])) {
3096 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3097 $until = $enrols[$instance->enrol
]->try_autoenrol($instance);
3098 if ($until !== false) {
3100 $until = ENROL_MAX_TIMESTAMP
;
3102 $USER->enrol
['enrolled'][$course->id
] = $until;
3107 // If not enrolled yet try to gain temporary guest access.
3109 foreach ($instances as $instance) {
3110 if (!isset($enrols[$instance->enrol
])) {
3113 // Get a duration for the guest access, a timestamp in the future or false.
3114 $until = $enrols[$instance->enrol
]->try_guestaccess($instance);
3115 if ($until !== false and $until > time()) {
3116 $USER->enrol
['tempguest'][$course->id
] = $until;
3127 if ($preventredirect) {
3128 throw new require_login_exception('Not enrolled');
3130 if ($setwantsurltome) {
3131 $SESSION->wantsurl
= qualified_me();
3133 redirect($CFG->wwwroot
.'/enrol/index.php?id='. $course->id
);
3137 // Check visibility of activity to current user; includes visible flag, groupmembersonly, conditional availability, etc.
3138 if ($cm && !$cm->uservisible
) {
3139 if ($preventredirect) {
3140 throw new require_login_exception('Activity is hidden');
3142 if ($course->id
!= SITEID
) {
3143 $url = new moodle_url('/course/view.php', array('id' => $course->id
));
3145 $url = new moodle_url('/');
3147 redirect($url, get_string('activityiscurrentlyhidden'));
3150 // Finally access granted, update lastaccess times.
3151 user_accesstime_log($course->id
);
3156 * This function just makes sure a user is logged out.
3158 * @package core_access
3161 function require_logout() {
3164 if (!isloggedin()) {
3165 // This should not happen often, no need for hooks or events here.
3166 \core\session\manager
::terminate_current();
3170 // Execute hooks before action.
3171 $authsequence = get_enabled_auth_plugins();
3172 foreach ($authsequence as $authname) {
3173 $authplugin = get_auth_plugin($authname);
3174 $authplugin->prelogout_hook();
3177 // Store info that gets removed during logout.
3178 $sid = session_id();
3179 $event = \core\event\user_loggedout
::create(
3181 'userid' => $USER->id
,
3182 'objectid' => $USER->id
,
3183 'other' => array('sessionid' => $sid),
3186 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3187 $event->add_record_snapshot('sessions', $session);
3190 // Delete session record and drop $_SESSION content.
3191 \core\session\manager
::terminate_current();
3193 // Trigger event AFTER action.
3198 * Weaker version of require_login()
3200 * This is a weaker version of {@link require_login()} which only requires login
3201 * when called from within a course rather than the site page, unless
3202 * the forcelogin option is turned on.
3203 * @see require_login()
3205 * @package core_access
3208 * @param mixed $courseorid The course object or id in question
3209 * @param bool $autologinguest Allow autologin guests if that is wanted
3210 * @param object $cm Course activity module if known
3211 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3212 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3213 * in order to keep redirects working properly. MDL-14495
3214 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3216 * @throws coding_exception
3218 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3219 global $CFG, $PAGE, $SITE;
3220 $issite = ((is_object($courseorid) and $courseorid->id
== SITEID
)
3221 or (!is_object($courseorid) and $courseorid == SITEID
));
3222 if ($issite && !empty($cm) && !($cm instanceof cm_info
)) {
3223 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3224 // db queries so this is not really a performance concern, however it is obviously
3225 // better if you use get_fast_modinfo to get the cm before calling this.
3226 if (is_object($courseorid)) {
3227 $course = $courseorid;
3229 $course = clone($SITE);
3231 $modinfo = get_fast_modinfo($course);
3232 $cm = $modinfo->get_cm($cm->id
);
3234 if (!empty($CFG->forcelogin
)) {
3235 // Login required for both SITE and courses.
3236 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3238 } else if ($issite && !empty($cm) and !$cm->uservisible
) {
3239 // Always login for hidden activities.
3240 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3242 } else if ($issite) {
3243 // Login for SITE not required.
3244 if ($cm and empty($cm->visible
)) {
3245 // Hidden activities are not accessible without login.
3246 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3247 } else if ($cm and !empty($CFG->enablegroupmembersonly
) and $cm->groupmembersonly
) {
3248 // Not-logged-in users do not have any group membership.
3249 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3251 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3252 if (!empty($courseorid)) {
3253 if (is_object($courseorid)) {
3254 $course = $courseorid;
3256 $course = clone($SITE);
3259 if ($cm->course
!= $course->id
) {
3260 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3262 $PAGE->set_cm($cm, $course);
3263 $PAGE->set_pagelayout('incourse');
3265 $PAGE->set_course($course);
3268 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3269 $PAGE->set_course($PAGE->course
);
3271 // TODO: verify conditional activities here.
3272 user_accesstime_log(SITEID
);
3277 // Course login always required.
3278 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3283 * Require key login. Function terminates with error if key not found or incorrect.
3285 * @uses NO_MOODLE_COOKIES
3286 * @uses PARAM_ALPHANUM
3287 * @param string $script unique script identifier
3288 * @param int $instance optional instance id
3289 * @return int Instance ID
3291 function require_user_key_login($script, $instance=null) {
3294 if (!NO_MOODLE_COOKIES
) {
3295 print_error('sessioncookiesdisable');
3299 \core\session\manager
::write_close();
3301 $keyvalue = required_param('key', PARAM_ALPHANUM
);
3303 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3304 print_error('invalidkey');
3307 if (!empty($key->validuntil
) and $key->validuntil
< time()) {
3308 print_error('expiredkey');
3311 if ($key->iprestriction
) {
3312 $remoteaddr = getremoteaddr(null);
3313 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction
)) {
3314 print_error('ipmismatch');
3318 if (!$user = $DB->get_record('user', array('id' => $key->userid
))) {
3319 print_error('invaliduserid');
3322 // Emulate normal session.
3323 enrol_check_plugins($user);
3324 \core\session\manager
::set_user($user);
3326 // Note we are not using normal login.
3327 if (!defined('USER_KEY_LOGIN')) {
3328 define('USER_KEY_LOGIN', true);
3331 // Return instance id - it might be empty.
3332 return $key->instance
;
3336 * Creates a new private user access key.
3338 * @param string $script unique target identifier
3339 * @param int $userid
3340 * @param int $instance optional instance id
3341 * @param string $iprestriction optional ip restricted access
3342 * @param timestamp $validuntil key valid only until given data
3343 * @return string access key value
3345 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3348 $key = new stdClass();
3349 $key->script
= $script;
3350 $key->userid
= $userid;
3351 $key->instance
= $instance;
3352 $key->iprestriction
= $iprestriction;
3353 $key->validuntil
= $validuntil;
3354 $key->timecreated
= time();
3356 // Something long and unique.
3357 $key->value
= md5($userid.'_'.time().random_string(40));
3358 while ($DB->record_exists('user_private_key', array('value' => $key->value
))) {
3360 $key->value
= md5($userid.'_'.time().random_string(40));
3362 $DB->insert_record('user_private_key', $key);
3367 * Delete the user's new private user access keys for a particular script.
3369 * @param string $script unique target identifier
3370 * @param int $userid
3373 function delete_user_key($script, $userid) {
3375 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3379 * Gets a private user access key (and creates one if one doesn't exist).
3381 * @param string $script unique target identifier
3382 * @param int $userid
3383 * @param int $instance optional instance id
3384 * @param string $iprestriction optional ip restricted access
3385 * @param timestamp $validuntil key valid only until given data
3386 * @return string access key value
3388 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3391 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3392 'instance' => $instance, 'iprestriction' => $iprestriction,
3393 'validuntil' => $validuntil))) {
3396 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3402 * Modify the user table by setting the currently logged in user's last login to now.
3404 * @return bool Always returns true
3406 function update_user_login_times() {
3409 if (isguestuser()) {
3410 // Do not update guest access times/ips for performance.
3416 $user = new stdClass();
3417 $user->id
= $USER->id
;
3419 // Make sure all users that logged in have some firstaccess.
3420 if ($USER->firstaccess
== 0) {
3421 $USER->firstaccess
= $user->firstaccess
= $now;
3424 // Store the previous current as lastlogin.
3425 $USER->lastlogin
= $user->lastlogin
= $USER->currentlogin
;
3427 $USER->currentlogin
= $user->currentlogin
= $now;
3429 // Function user_accesstime_log() may not update immediately, better do it here.
3430 $USER->lastaccess
= $user->lastaccess
= $now;
3431 $USER->lastip
= $user->lastip
= getremoteaddr();
3433 // Note: do not call user_update_user() here because this is part of the login process,
3434 // the login event means that these fields were updated.
3435 $DB->update_record('user', $user);
3440 * Determines if a user has completed setting up their account.
3442 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3445 function user_not_fully_set_up($user) {
3446 if (isguestuser($user)) {
3449 return (empty($user->firstname
) or empty($user->lastname
) or empty($user->email
) or over_bounce_threshold($user));
3453 * Check whether the user has exceeded the bounce threshold
3455 * @param stdClass $user A {@link $USER} object
3456 * @return bool true => User has exceeded bounce threshold
3458 function over_bounce_threshold($user) {
3461 if (empty($CFG->handlebounces
)) {
3465 if (empty($user->id
)) {
3466 // No real (DB) user, nothing to do here.
3470 // Set sensible defaults.
3471 if (empty($CFG->minbounces
)) {
3472 $CFG->minbounces
= 10;
3474 if (empty($CFG->bounceratio
)) {
3475 $CFG->bounceratio
= .20;
3479 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3480 $bouncecount = $bounce->value
;
3482 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3483 $sendcount = $send->value
;
3485 return ($bouncecount >= $CFG->minbounces
&& $bouncecount/$sendcount >= $CFG->bounceratio
);
3489 * Used to increment or reset email sent count
3491 * @param stdClass $user object containing an id
3492 * @param bool $reset will reset the count to 0
3495 function set_send_count($user, $reset=false) {
3498 if (empty($user->id
)) {
3499 // No real (DB) user, nothing to do here.
3503 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3504 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3505 $DB->update_record('user_preferences', $pref);
3506 } else if (!empty($reset)) {
3507 // If it's not there and we're resetting, don't bother. Make a new one.
3508 $pref = new stdClass();
3509 $pref->name
= 'email_send_count';
3511 $pref->userid
= $user->id
;
3512 $DB->insert_record('user_preferences', $pref, false);
3517 * Increment or reset user's email bounce count
3519 * @param stdClass $user object containing an id
3520 * @param bool $reset will reset the count to 0
3522 function set_bounce_count($user, $reset=false) {
3525 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3526 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3527 $DB->update_record('user_preferences', $pref);
3528 } else if (!empty($reset)) {
3529 // If it's not there and we're resetting, don't bother. Make a new one.
3530 $pref = new stdClass();
3531 $pref->name
= 'email_bounce_count';
3533 $pref->userid
= $user->id
;
3534 $DB->insert_record('user_preferences', $pref, false);
3539 * Determines if the logged in user is currently moving an activity
3541 * @param int $courseid The id of the course being tested
3544 function ismoving($courseid) {
3547 if (!empty($USER->activitycopy
)) {
3548 return ($USER->activitycopycourse
== $courseid);
3554 * Returns a persons full name
3556 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3557 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3560 * @param stdClass $user A {@link $USER} object to get full name of.
3561 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3564 function fullname($user, $override=false) {
3565 global $CFG, $SESSION;
3567 if (!isset($user->firstname
) and !isset($user->lastname
)) {
3571 // Get all of the name fields.
3572 $allnames = get_all_user_name_fields();
3573 if ($CFG->debugdeveloper
) {
3574 foreach ($allnames as $allname) {
3575 if (!array_key_exists($allname, $user)) {
3576 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3577 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER
);
3578 // Message has been sent, no point in sending the message multiple times.
3585 if (!empty($CFG->forcefirstname
)) {
3586 $user->firstname
= $CFG->forcefirstname
;
3588 if (!empty($CFG->forcelastname
)) {
3589 $user->lastname
= $CFG->forcelastname
;
3593 if (!empty($SESSION->fullnamedisplay
)) {
3594 $CFG->fullnamedisplay
= $SESSION->fullnamedisplay
;
3598 // If the fullnamedisplay setting is available, set the template to that.
3599 if (isset($CFG->fullnamedisplay
)) {
3600 $template = $CFG->fullnamedisplay
;
3602 // If the template is empty, or set to language, or $override is set, return the language string.
3603 if (empty($template) ||
$template == 'language' ||
$override) {
3604 return get_string('fullnamedisplay', null, $user);
3607 $requirednames = array();
3608 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3609 foreach ($allnames as $allname) {
3610 if (strpos($template, $allname) !== false) {
3611 $requirednames[] = $allname;
3615 $displayname = $template;
3616 // Switch in the actual data into the template.
3617 foreach ($requirednames as $altname) {
3618 if (isset($user->$altname)) {
3619 // Using empty() on the below if statement causes breakages.
3620 if ((string)$user->$altname == '') {
3621 $displayname = str_replace($altname, 'EMPTY', $displayname);
3623 $displayname = str_replace($altname, $user->$altname, $displayname);
3626 $displayname = str_replace($altname, 'EMPTY', $displayname);
3629 // Tidy up any misc. characters (Not perfect, but gets most characters).
3630 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3631 // katakana and parenthesis.
3632 $patterns = array();
3633 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3634 // filled in by a user.
3635 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3636 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3637 // This regular expression is to remove any double spaces in the display name.
3638 $patterns[] = '/\s{2,}/u';
3639 foreach ($patterns as $pattern) {
3640 $displayname = preg_replace($pattern, ' ', $displayname);
3643 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3644 $displayname = trim($displayname);
3645 if (empty($displayname)) {
3646 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3647 // people in general feel is a good setting to fall back on.
3648 $displayname = $user->firstname
;
3650 return $displayname;
3654 * A centralised location for the all name fields. Returns an array / sql string snippet.
3656 * @param bool $returnsql True for an sql select field snippet.
3657 * @param string $tableprefix table query prefix to use in front of each field.
3658 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3659 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3660 * @return array|string All name fields.
3662 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null) {
3663 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3664 'lastnamephonetic' => 'lastnamephonetic',
3665 'middlename' => 'middlename',
3666 'alternatename' => 'alternatename',
3667 'firstname' => 'firstname',
3668 'lastname' => 'lastname');
3670 // Let's add a prefix to the array of user name fields if provided.
3672 foreach ($alternatenames as $key => $altname) {
3673 $alternatenames[$key] = $prefix . $altname;
3677 // Create an sql field snippet if requested.
3681 foreach ($alternatenames as $key => $altname) {
3682 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3685 foreach ($alternatenames as $key => $altname) {
3686 $alternatenames[$key] = $tableprefix . '.' . $altname;
3690 $alternatenames = implode(',', $alternatenames);
3692 return $alternatenames;
3696 * Reduces lines of duplicated code for getting user name fields.
3698 * See also {@link user_picture::unalias()}
3700 * @param object $addtoobject Object to add user name fields to.
3701 * @param object $secondobject Object that contains user name field information.
3702 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3703 * @param array $additionalfields Additional fields to be matched with data in the second object.
3704 * The key can be set to the user table field name.
3705 * @return object User name fields.
3707 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3708 $fields = get_all_user_name_fields(false, null, $prefix);
3709 if ($additionalfields) {
3710 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3711 // the key is a number and then sets the key to the array value.
3712 foreach ($additionalfields as $key => $value) {
3713 if (is_numeric($key)) {
3714 $additionalfields[$value] = $prefix . $value;
3715 unset($additionalfields[$key]);
3717 $additionalfields[$key] = $prefix . $value;
3720 $fields = array_merge($fields, $additionalfields);
3722 foreach ($fields as $key => $field) {
3723 // Important that we have all of the user name fields present in the object that we are sending back.
3724 $addtoobject->$key = '';
3725 if (isset($secondobject->$field)) {
3726 $addtoobject->$key = $secondobject->$field;
3729 return $addtoobject;
3733 * Returns an array of values in order of occurance in a provided string.
3734 * The key in the result is the character postion in the string.
3736 * @param array $values Values to be found in the string format
3737 * @param string $stringformat The string which may contain values being searched for.
3738 * @return array An array of values in order according to placement in the string format.
3740 function order_in_string($values, $stringformat) {
3741 $valuearray = array();
3742 foreach ($values as $value) {
3743 $pattern = "/$value\b/";
3744 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3745 if (preg_match($pattern, $stringformat)) {
3746 $replacement = "thing";
3747 // Replace the value with something more unique to ensure we get the right position when using strpos().
3748 $newformat = preg_replace($pattern, $replacement, $stringformat);
3749 $position = strpos($newformat, $replacement);
3750 $valuearray[$position] = $value;
3758 * Checks if current user is shown any extra fields when listing users.
3760 * @param object $context Context
3761 * @param array $already Array of fields that we're going to show anyway
3762 * so don't bother listing them
3763 * @return array Array of field names from user table, not including anything
3764 * listed in $already
3766 function get_extra_user_fields($context, $already = array()) {
3769 // Only users with permission get the extra fields.
3770 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3774 // Split showuseridentity on comma.
3775 if (empty($CFG->showuseridentity
)) {
3776 // Explode gives wrong result with empty string.
3779 $extra = explode(',', $CFG->showuseridentity
);
3782 foreach ($extra as $key => $field) {
3783 if (in_array($field, $already)) {
3784 unset($extra[$key]);
3789 // For consistency, if entries are removed from array, renumber it
3790 // so they are numbered as you would expect.
3791 $extra = array_merge($extra);
3797 * If the current user is to be shown extra user fields when listing or
3798 * selecting users, returns a string suitable for including in an SQL select
3799 * clause to retrieve those fields.
3801 * @param context $context Context
3802 * @param string $alias Alias of user table, e.g. 'u' (default none)
3803 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3804 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3805 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3807 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3808 $fields = get_extra_user_fields($context, $already);
3810 // Add punctuation for alias.
3811 if ($alias !== '') {
3814 foreach ($fields as $field) {
3815 $result .= ', ' . $alias . $field;
3817 $result .= ' AS ' . $prefix . $field;
3824 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3825 * @param string $field Field name, e.g. 'phone1'
3826 * @return string Text description taken from language file, e.g. 'Phone number'
3828 function get_user_field_name($field) {
3829 // Some fields have language strings which are not the same as field name.
3832 return get_string('phone');
3835 return get_string('webpage');
3838 return get_string('icqnumber');
3841 return get_string('skypeid');
3844 return get_string('aimid');
3847 return get_string('yahooid');
3850 return get_string('msnid');
3853 // Otherwise just use the same lang string.
3854 return get_string($field);
3858 * Returns whether a given authentication plugin exists.
3860 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3861 * @return boolean Whether the plugin is available.
3863 function exists_auth_plugin($auth) {
3866 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3867 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3873 * Checks if a given plugin is in the list of enabled authentication plugins.
3875 * @param string $auth Authentication plugin.
3876 * @return boolean Whether the plugin is enabled.
3878 function is_enabled_auth($auth) {
3883 $enabled = get_enabled_auth_plugins();
3885 return in_array($auth, $enabled);
3889 * Returns an authentication plugin instance.
3891 * @param string $auth name of authentication plugin
3892 * @return auth_plugin_base An instance of the required authentication plugin.
3894 function get_auth_plugin($auth) {
3897 // Check the plugin exists first.
3898 if (! exists_auth_plugin($auth)) {
3899 print_error('authpluginnotfound', 'debug', '', $auth);
3902 // Return auth plugin instance.
3903 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3904 $class = "auth_plugin_$auth";
3909 * Returns array of active auth plugins.
3911 * @param bool $fix fix $CFG->auth if needed
3914 function get_enabled_auth_plugins($fix=false) {
3917 $default = array('manual', 'nologin');
3919 if (empty($CFG->auth
)) {
3922 $auths = explode(',', $CFG->auth
);
3926 $auths = array_unique($auths);
3927 foreach ($auths as $k => $authname) {
3928 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3932 $newconfig = implode(',', $auths);
3933 if (!isset($CFG->auth
) or $newconfig != $CFG->auth
) {
3934 set_config('auth', $newconfig);
3938 return (array_merge($default, $auths));
3942 * Returns true if an internal authentication method is being used.
3943 * if method not specified then, global default is assumed
3945 * @param string $auth Form of authentication required
3948 function is_internal_auth($auth) {
3949 // Throws error if bad $auth.
3950 $authplugin = get_auth_plugin($auth);
3951 return $authplugin->is_internal();
3955 * Returns true if the user is a 'restored' one.
3957 * Used in the login process to inform the user and allow him/her to reset the password
3959 * @param string $username username to be checked
3962 function is_restored_user($username) {
3965 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'password' => 'restored'));
3969 * Returns an array of user fields
3971 * @return array User field/column names
3973 function get_user_fieldnames() {
3976 $fieldarray = $DB->get_columns('user');
3977 unset($fieldarray['id']);
3978 $fieldarray = array_keys($fieldarray);
3984 * Creates a bare-bones user record
3986 * @todo Outline auth types and provide code example
3988 * @param string $username New user's username to add to record
3989 * @param string $password New user's password to add to record
3990 * @param string $auth Form of authentication required
3991 * @return stdClass A complete user object
3993 function create_user_record($username, $password, $auth = 'manual') {
3995 require_once($CFG->dirroot
.'/user/profile/lib.php');
3996 require_once($CFG->dirroot
.'/user/lib.php');
3998 // Just in case check text case.
3999 $username = trim(core_text
::strtolower($username));
4001 $authplugin = get_auth_plugin($auth);
4002 $customfields = $authplugin->get_custom_user_profile_fields();
4003 $newuser = new stdClass();
4004 if ($newinfo = $authplugin->get_userinfo($username)) {
4005 $newinfo = truncate_userinfo($newinfo);
4006 foreach ($newinfo as $key => $value) {
4007 if (in_array($key, $authplugin->userfields
) ||
(in_array($key, $customfields))) {
4008 $newuser->$key = $value;
4013 if (!empty($newuser->email
)) {
4014 if (email_is_not_allowed($newuser->email
)) {
4015 unset($newuser->email
);
4019 if (!isset($newuser->city
)) {
4020 $newuser->city
= '';
4023 $newuser->auth
= $auth;
4024 $newuser->username
= $username;
4027 // user CFG lang for user if $newuser->lang is empty
4028 // or $user->lang is not an installed language.
4029 if (empty($newuser->lang
) ||
!get_string_manager()->translation_exists($newuser->lang
)) {
4030 $newuser->lang
= $CFG->lang
;
4032 $newuser->confirmed
= 1;
4033 $newuser->lastip
= getremoteaddr();
4034 $newuser->timecreated
= time();
4035 $newuser->timemodified
= $newuser->timecreated
;
4036 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
4038 $newuser->id
= user_create_user($newuser, false, false);
4040 // Save user profile data.
4041 profile_save_data($newuser);
4043 $user = get_complete_user_data('id', $newuser->id
);
4044 if (!empty($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'})) {
4045 set_user_preference('auth_forcepasswordchange', 1, $user);
4047 // Set the password.
4048 update_internal_user_password($user, $password);
4051 \core\event\user_created
::create_from_userid($newuser->id
)->trigger();
4057 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4059 * @param string $username user's username to update the record
4060 * @return stdClass A complete user object
4062 function update_user_record($username) {
4064 // Just in case check text case.
4065 $username = trim(core_text
::strtolower($username));
4067 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
), '*', MUST_EXIST
);
4068 return update_user_record_by_id($oldinfo->id
);
4072 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4074 * @param int $id user id
4075 * @return stdClass A complete user object
4077 function update_user_record_by_id($id) {
4079 require_once($CFG->dirroot
."/user/profile/lib.php");
4080 require_once($CFG->dirroot
.'/user/lib.php');
4082 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'id' => $id, 'deleted' => 0);
4083 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST
);
4086 $userauth = get_auth_plugin($oldinfo->auth
);
4088 if ($newinfo = $userauth->get_userinfo($oldinfo->username
)) {
4089 $newinfo = truncate_userinfo($newinfo);
4090 $customfields = $userauth->get_custom_user_profile_fields();
4092 foreach ($newinfo as $key => $value) {
4093 $key = strtolower($key);
4094 $iscustom = in_array($key, $customfields);
4095 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4096 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4097 // Unknown or must not be changed.
4100 $confval = $userauth->config
->{'field_updatelocal_' . $key};
4101 $lockval = $userauth->config
->{'field_lock_' . $key};
4102 if (empty($confval) ||
empty($lockval)) {
4105 if ($confval === 'onlogin') {
4106 // MDL-4207 Don't overwrite modified user profile values with
4107 // empty LDAP values when 'unlocked if empty' is set. The purpose
4108 // of the setting 'unlocked if empty' is to allow the user to fill
4109 // in a value for the selected field _if LDAP is giving
4110 // nothing_ for this field. Thus it makes sense to let this value
4111 // stand in until LDAP is giving a value for this field.
4112 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4113 if ($iscustom ||
(in_array($key, $userauth->userfields
) &&
4114 ((string)$oldinfo->$key !== (string)$value))) {
4115 $newuser[$key] = (string)$value;
4121 $newuser['id'] = $oldinfo->id
;
4122 $newuser['timemodified'] = time();
4123 user_update_user((object) $newuser, false, false);
4125 // Save user profile data.
4126 profile_save_data((object) $newuser);
4129 \core\event\user_updated
::create_from_userid($newuser['id'])->trigger();
4133 return get_complete_user_data('id', $oldinfo->id
);
4137 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4139 * @param array $info Array of user properties to truncate if needed
4140 * @return array The now truncated information that was passed in
4142 function truncate_userinfo(array $info) {
4143 // Define the limits.
4153 'institution' => 255,
4154 'department' => 255,
4161 // Apply where needed.
4162 foreach (array_keys($info) as $key) {
4163 if (!empty($limit[$key])) {
4164 $info[$key] = trim(core_text
::substr($info[$key], 0, $limit[$key]));
4172 * Marks user deleted in internal user database and notifies the auth plugin.
4173 * Also unenrols user from all roles and does other cleanup.
4175 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4177 * @param stdClass $user full user object before delete
4178 * @return boolean success
4179 * @throws coding_exception if invalid $user parameter detected
4181 function delete_user(stdClass
$user) {
4183 require_once($CFG->libdir
.'/grouplib.php');
4184 require_once($CFG->libdir
.'/gradelib.php');
4185 require_once($CFG->dirroot
.'/message/lib.php');
4186 require_once($CFG->dirroot
.'/tag/lib.php');
4187 require_once($CFG->dirroot
.'/user/lib.php');
4189 // Make sure nobody sends bogus record type as parameter.
4190 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4191 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4194 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4195 if (!$user = $DB->get_record('user', array('id' => $user->id
))) {
4196 debugging('Attempt to delete unknown user account.');
4200 // There must be always exactly one guest record, originally the guest account was identified by username only,
4201 // now we use $CFG->siteguest for performance reasons.
4202 if ($user->username
=== 'guest' or isguestuser($user)) {
4203 debugging('Guest user account can not be deleted.');
4207 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4208 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4209 if ($user->auth
=== 'manual' and is_siteadmin($user)) {
4210 debugging('Local administrator accounts can not be deleted.');
4214 // Keep user record before updating it, as we have to pass this to user_deleted event.
4215 $olduser = clone $user;
4217 // Keep a copy of user context, we need it for event.
4218 $usercontext = context_user
::instance($user->id
);
4220 // Delete all grades - backup is kept in grade_grades_history table.
4221 grade_user_delete($user->id
);
4223 // Move unread messages from this user to read.
4224 message_move_userfrom_unread2read($user->id
);
4226 // TODO: remove from cohorts using standard API here.
4228 // Remove user tags.
4229 tag_set('user', $user->id
, array(), 'core', $usercontext->id
);
4231 // Unconditionally unenrol from all courses.
4232 enrol_user_delete($user);
4234 // Unenrol from all roles in all contexts.
4235 // This might be slow but it is really needed - modules might do some extra cleanup!
4236 role_unassign_all(array('userid' => $user->id
));
4238 // Now do a brute force cleanup.
4240 // Remove from all cohorts.
4241 $DB->delete_records('cohort_members', array('userid' => $user->id
));
4243 // Remove from all groups.
4244 $DB->delete_records('groups_members', array('userid' => $user->id
));
4246 // Brute force unenrol from all courses.
4247 $DB->delete_records('user_enrolments', array('userid' => $user->id
));
4249 // Purge user preferences.
4250 $DB->delete_records('user_preferences', array('userid' => $user->id
));
4252 // Purge user extra profile info.
4253 $DB->delete_records('user_info_data', array('userid' => $user->id
));
4255 // Last course access not necessary either.
4256 $DB->delete_records('user_lastaccess', array('userid' => $user->id
));
4257 // Remove all user tokens.
4258 $DB->delete_records('external_tokens', array('userid' => $user->id
));
4260 // Unauthorise the user for all services.
4261 $DB->delete_records('external_services_users', array('userid' => $user->id
));
4263 // Remove users private keys.
4264 $DB->delete_records('user_private_key', array('userid' => $user->id
));
4266 // Remove users customised pages.
4267 $DB->delete_records('my_pages', array('userid' => $user->id
, 'private' => 1));
4269 // Force logout - may fail if file based sessions used, sorry.
4270 \core\session\manager
::kill_user_sessions($user->id
);
4272 // Workaround for bulk deletes of users with the same email address.
4273 $delname = clean_param($user->email
. "." . time(), PARAM_USERNAME
);
4274 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4278 // Mark internal user record as "deleted".
4279 $updateuser = new stdClass();
4280 $updateuser->id
= $user->id
;
4281 $updateuser->deleted
= 1;
4282 $updateuser->username
= $delname; // Remember it just in case.
4283 $updateuser->email
= md5($user->username
);// Store hash of username, useful importing/restoring users.
4284 $updateuser->idnumber
= ''; // Clear this field to free it up.
4285 $updateuser->picture
= 0;
4286 $updateuser->timemodified
= time();
4288 // Don't trigger update event, as user is being deleted.
4289 user_update_user($updateuser, false, false);
4291 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4292 context_helper
::delete_instance(CONTEXT_USER
, $user->id
);
4294 // Any plugin that needs to cleanup should register this event.
4296 $event = \core\event\user_deleted
::create(
4298 'objectid' => $user->id
,
4299 'relateduserid' => $user->id
,
4300 'context' => $usercontext,
4302 'username' => $user->username
,
4303 'email' => $user->email
,
4304 'idnumber' => $user->idnumber
,
4305 'picture' => $user->picture
,
4306 'mnethostid' => $user->mnethostid
4310 $event->add_record_snapshot('user', $olduser);
4313 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4314 // should know about this updated property persisted to the user's table.
4315 $user->timemodified
= $updateuser->timemodified
;
4317 // Notify auth plugin - do not block the delete even when plugin fails.
4318 $authplugin = get_auth_plugin($user->auth
);
4319 $authplugin->user_delete($user);
4325 * Retrieve the guest user object.
4327 * @return stdClass A {@link $USER} object
4329 function guest_user() {
4332 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest
))) {
4333 $newuser->confirmed
= 1;
4334 $newuser->lang
= $CFG->lang
;
4335 $newuser->lastip
= getremoteaddr();
4342 * Authenticates a user against the chosen authentication mechanism
4344 * Given a username and password, this function looks them
4345 * up using the currently selected authentication mechanism,
4346 * and if the authentication is successful, it returns a
4347 * valid $user object from the 'user' table.
4349 * Uses auth_ functions from the currently active auth module
4351 * After authenticate_user_login() returns success, you will need to
4352 * log that the user has logged in, and call complete_user_login() to set
4355 * Note: this function works only with non-mnet accounts!
4357 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4358 * @param string $password User's password
4359 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4360 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4361 * @return stdClass|false A {@link $USER} object or false if error
4363 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4365 require_once("$CFG->libdir/authlib.php");
4367 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id
)) {
4368 // we have found the user
4370 } else if (!empty($CFG->authloginviaemail
)) {
4371 if ($email = clean_param($username, PARAM_EMAIL
)) {
4372 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4373 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'email' => $email);
4374 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4375 if (count($users) === 1) {
4376 // Use email for login only if unique.
4377 $user = reset($users);
4378 $user = get_complete_user_data('id', $user->id
);
4379 $username = $user->username
;
4385 $authsenabled = get_enabled_auth_plugins();
4388 // Use manual if auth not set.
4389 $auth = empty($user->auth
) ?
'manual' : $user->auth
;
4390 if (!empty($user->suspended
)) {
4391 $failurereason = AUTH_LOGIN_SUSPENDED
;
4393 // Trigger login failed event.
4394 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4395 'other' => array('username' => $username, 'reason' => $failurereason)));
4397 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4400 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4401 // Legacy way to suspend user.
4402 $failurereason = AUTH_LOGIN_SUSPENDED
;
4404 // Trigger login failed event.
4405 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4406 'other' => array('username' => $username, 'reason' => $failurereason)));
4408 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4411 $auths = array($auth);
4414 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4415 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'deleted' => 1))) {
4416 $failurereason = AUTH_LOGIN_NOUSER
;
4418 // Trigger login failed event.
4419 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4420 'reason' => $failurereason)));
4422 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4426 // Do not try to authenticate non-existent accounts when user creation is disabled.
4427 if (!empty($CFG->authpreventaccountcreation
)) {
4428 $failurereason = AUTH_LOGIN_NOUSER
;
4430 // Trigger login failed event.
4431 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4432 'reason' => $failurereason)));
4435 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4436 $_SERVER['HTTP_USER_AGENT']);
4440 // User does not exist.
4441 $auths = $authsenabled;
4442 $user = new stdClass();
4446 if ($ignorelockout) {
4447 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4448 // or this function is called from a SSO script.
4449 } else if ($user->id
) {
4450 // Verify login lockout after other ways that may prevent user login.
4451 if (login_is_lockedout($user)) {
4452 $failurereason = AUTH_LOGIN_LOCKOUT
;
4454 // Trigger login failed event.
4455 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4456 'other' => array('username' => $username, 'reason' => $failurereason)));
4459 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4463 // We can not lockout non-existing accounts.
4466 foreach ($auths as $auth) {
4467 $authplugin = get_auth_plugin($auth);
4469 // On auth fail fall through to the next plugin.
4470 if (!$authplugin->user_login($username, $password)) {
4474 // Successful authentication.
4476 // User already exists in database.
4477 if (empty($user->auth
)) {
4478 // For some reason auth isn't set yet.
4479 $DB->set_field('user', 'auth', $auth, array('id' => $user->id
));
4480 $user->auth
= $auth;
4483 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4484 // the current hash algorithm while we have access to the user's password.
4485 update_internal_user_password($user, $password);
4487 if ($authplugin->is_synchronised_with_external()) {
4488 // Update user record from external DB.
4489 $user = update_user_record_by_id($user->id
);
4492 // Create account, we verified above that user creation is allowed.
4493 $user = create_user_record($username, $password, $auth);
4496 $authplugin->sync_roles($user);
4498 foreach ($authsenabled as $hau) {
4499 $hauth = get_auth_plugin($hau);
4500 $hauth->user_authenticated_hook($user, $username, $password);
4503 if (empty($user->id
)) {
4504 $failurereason = AUTH_LOGIN_NOUSER
;
4505 // Trigger login failed event.
4506 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4507 'reason' => $failurereason)));
4512 if (!empty($user->suspended
)) {
4513 // Just in case some auth plugin suspended account.
4514 $failurereason = AUTH_LOGIN_SUSPENDED
;
4515 // Trigger login failed event.
4516 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4517 'other' => array('username' => $username, 'reason' => $failurereason)));
4519 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4523 login_attempt_valid($user);
4524 $failurereason = AUTH_LOGIN_OK
;
4528 // Failed if all the plugins have failed.
4529 if (debugging('', DEBUG_ALL
)) {
4530 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4534 login_attempt_failed($user);
4535 $failurereason = AUTH_LOGIN_FAILED
;
4536 // Trigger login failed event.
4537 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4538 'other' => array('username' => $username, 'reason' => $failurereason)));
4541 $failurereason = AUTH_LOGIN_NOUSER
;
4542 // Trigger login failed event.
4543 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4544 'reason' => $failurereason)));
4552 * Call to complete the user login process after authenticate_user_login()
4553 * has succeeded. It will setup the $USER variable and other required bits
4557 * - It will NOT log anything -- up to the caller to decide what to log.
4558 * - this function does not set any cookies any more!
4560 * @param stdClass $user
4561 * @return stdClass A {@link $USER} object - BC only, do not use
4563 function complete_user_login($user) {
4566 \core\session\manager
::login_user($user);
4568 // Reload preferences from DB.
4569 unset($USER->preference
);
4570 check_user_preferences_loaded($USER);
4572 // Update login times.
4573 update_user_login_times();
4575 // Extra session prefs init.
4576 set_login_session_preferences();
4578 // Trigger login event.
4579 $event = \core\event\user_loggedin
::create(
4581 'userid' => $USER->id
,
4582 'objectid' => $USER->id
,
4583 'other' => array('username' => $USER->username
),
4588 if (isguestuser()) {
4589 // No need to continue when user is THE guest.
4594 // We can redirect to password change URL only in browser.
4598 // Select password change url.
4599 $userauth = get_auth_plugin($USER->auth
);
4601 // Check whether the user should be changing password.
4602 if (get_user_preferences('auth_forcepasswordchange', false)) {
4603 if ($userauth->can_change_password()) {
4604 if ($changeurl = $userauth->change_password_url()) {
4605 redirect($changeurl);
4607 redirect($CFG->httpswwwroot
.'/login/change_password.php');
4610 print_error('nopasswordchangeforced', 'auth');
4617 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4619 * @param string $password String to check.
4620 * @return boolean True if the $password matches the format of an md5 sum.
4622 function password_is_legacy_hash($password) {
4623 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4627 * Compare password against hash stored in user object to determine if it is valid.
4629 * If necessary it also updates the stored hash to the current format.
4631 * @param stdClass $user (Password property may be updated).
4632 * @param string $password Plain text password.
4633 * @return bool True if password is valid.
4635 function validate_internal_user_password($user, $password) {
4637 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4639 if ($user->password
=== AUTH_PASSWORD_NOT_CACHED
) {
4640 // Internal password is not used at all, it can not validate.
4644 // If hash isn't a legacy (md5) hash, validate using the library function.
4645 if (!password_is_legacy_hash($user->password
)) {
4646 return password_verify($password, $user->password
);
4649 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4650 // is valid we can then update it to the new algorithm.
4652 $sitesalt = isset($CFG->passwordsaltmain
) ?
$CFG->passwordsaltmain
: '';
4655 if ($user->password
=== md5($password.$sitesalt)
4656 or $user->password
=== md5($password)
4657 or $user->password
=== md5(addslashes($password).$sitesalt)
4658 or $user->password
=== md5(addslashes($password))) {
4659 // Note: we are intentionally using the addslashes() here because we
4660 // need to accept old password hashes of passwords with magic quotes.
4664 for ($i=1; $i<=20; $i++
) { // 20 alternative salts should be enough, right?
4665 $alt = 'passwordsaltalt'.$i;
4666 if (!empty($CFG->$alt)) {
4667 if ($user->password
=== md5($password.$CFG->$alt) or $user->password
=== md5(addslashes($password).$CFG->$alt)) {
4676 // If the password matches the existing md5 hash, update to the
4677 // current hash algorithm while we have access to the user's password.
4678 update_internal_user_password($user, $password);
4685 * Calculate hash for a plain text password.
4687 * @param string $password Plain text password to be hashed.
4688 * @param bool $fasthash If true, use a low cost factor when generating the hash
4689 * This is much faster to generate but makes the hash
4690 * less secure. It is used when lots of hashes need to
4691 * be generated quickly.
4692 * @return string The hashed password.
4694 * @throws moodle_exception If a problem occurs while generating the hash.
4696 function hash_internal_user_password($password, $fasthash = false) {
4698 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4700 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4701 $options = ($fasthash) ?
array('cost' => 4) : array();
4703 $generatedhash = password_hash($password, PASSWORD_DEFAULT
, $options);
4705 if ($generatedhash === false ||
$generatedhash === null) {
4706 throw new moodle_exception('Failed to generate password hash.');
4709 return $generatedhash;
4713 * Update password hash in user object (if necessary).
4715 * The password is updated if:
4716 * 1. The password has changed (the hash of $user->password is different
4717 * to the hash of $password).
4718 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4721 * Updating the password will modify the $user object and the database
4722 * record to use the current hashing algorithm.
4724 * @param stdClass $user User object (password property may be updated).
4725 * @param string $password Plain text password.
4726 * @param bool $fasthash If true, use a low cost factor when generating the hash
4727 * This is much faster to generate but makes the hash
4728 * less secure. It is used when lots of hashes need to
4729 * be generated quickly.
4730 * @return bool Always returns true.
4732 function update_internal_user_password($user, $password, $fasthash = false) {
4734 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4736 // Figure out what the hashed password should be.
4737 if (!isset($user->auth
)) {
4738 $user->auth
= $DB->get_field('user', 'auth', array('id' => $user->id
));
4740 $authplugin = get_auth_plugin($user->auth
);
4741 if ($authplugin->prevent_local_passwords()) {
4742 $hashedpassword = AUTH_PASSWORD_NOT_CACHED
;
4744 $hashedpassword = hash_internal_user_password($password, $fasthash);
4747 // If verification fails then it means the password has changed.
4748 if (isset($user->password
)) {
4749 // While creating new user, password in unset in $user object, to avoid
4750 // saving it with user_create()
4751 $passwordchanged = !password_verify($password, $user->password
);
4752 $algorithmchanged = password_needs_rehash($user->password
, PASSWORD_DEFAULT
);
4754 $passwordchanged = true;
4757 if ($passwordchanged ||
$algorithmchanged) {
4758 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id
));
4759 $user->password
= $hashedpassword;
4762 $user = $DB->get_record('user', array('id' => $user->id
));
4763 \core\event\user_password_updated
::create_from_user($user)->trigger();
4770 * Get a complete user record, which includes all the info in the user record.
4772 * Intended for setting as $USER session variable
4774 * @param string $field The user field to be checked for a given value.
4775 * @param string $value The value to match for $field.
4776 * @param int $mnethostid
4777 * @return mixed False, or A {@link $USER} object.
4779 function get_complete_user_data($field, $value, $mnethostid = null) {
4782 if (!$field ||
!$value) {
4786 // Build the WHERE clause for an SQL query.
4787 $params = array('fieldval' => $value);
4788 $constraints = "$field = :fieldval AND deleted <> 1";
4790 // If we are loading user data based on anything other than id,
4791 // we must also restrict our search based on mnet host.
4792 if ($field != 'id') {
4793 if (empty($mnethostid)) {
4794 // If empty, we restrict to local users.
4795 $mnethostid = $CFG->mnet_localhost_id
;
4798 if (!empty($mnethostid)) {
4799 $params['mnethostid'] = $mnethostid;
4800 $constraints .= " AND mnethostid = :mnethostid";
4803 // Get all the basic user data.
4804 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4808 // Get various settings and preferences.
4810 // Preload preference cache.
4811 check_user_preferences_loaded($user);
4813 // Load course enrolment related stuff.
4814 $user->lastcourseaccess
= array(); // During last session.
4815 $user->currentcourseaccess
= array(); // During current session.
4816 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id
))) {
4817 foreach ($lastaccesses as $lastaccess) {
4818 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
4822 $sql = "SELECT g.id, g.courseid
4823 FROM {groups} g, {groups_members} gm
4824 WHERE gm.groupid=g.id AND gm.userid=?";
4826 // This is a special hack to speedup calendar display.
4827 $user->groupmember
= array();
4828 if (!isguestuser($user)) {
4829 if ($groups = $DB->get_records_sql($sql, array($user->id
))) {
4830 foreach ($groups as $group) {
4831 if (!array_key_exists($group->courseid
, $user->groupmember
)) {
4832 $user->groupmember
[$group->courseid
] = array();
4834 $user->groupmember
[$group->courseid
][$group->id
] = $group->id
;
4839 // Add the custom profile fields to the user record.
4840 $user->profile
= array();
4841 if (!isguestuser($user)) {
4842 require_once($CFG->dirroot
.'/user/profile/lib.php');
4843 profile_load_custom_fields($user);
4846 // Rewrite some variables if necessary.
4847 if (!empty($user->description
)) {
4848 // No need to cart all of it around.
4849 $user->description
= true;
4851 if (isguestuser($user)) {
4852 // Guest language always same as site.
4853 $user->lang
= $CFG->lang
;
4854 // Name always in current language.
4855 $user->firstname
= get_string('guestuser');
4856 $user->lastname
= ' ';
4863 * Validate a password against the configured password policy
4865 * @param string $password the password to be checked against the password policy
4866 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4867 * @return bool true if the password is valid according to the policy. false otherwise.
4869 function check_password_policy($password, &$errmsg) {
4872 if (empty($CFG->passwordpolicy
)) {
4877 if (core_text
::strlen($password) < $CFG->minpasswordlength
) {
4878 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength
) .'</div>';
4881 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits
) {
4882 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits
) .'</div>';
4885 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower
) {
4886 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower
) .'</div>';
4889 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper
) {
4890 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper
) .'</div>';
4893 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum
) {
4894 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
) .'</div>';
4896 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars
)) {
4897 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars
) .'</div>';
4900 if ($errmsg == '') {
4909 * When logging in, this function is run to set certain preferences for the current SESSION.
4911 function set_login_session_preferences() {
4914 $SESSION->justloggedin
= true;
4916 unset($SESSION->lang
);
4917 unset($SESSION->forcelang
);
4918 unset($SESSION->load_navigation_admin
);
4923 * Delete a course, including all related data from the database, and any associated files.
4925 * @param mixed $courseorid The id of the course or course object to delete.
4926 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4927 * @return bool true if all the removals succeeded. false if there were any failures. If this
4928 * method returns false, some of the removals will probably have succeeded, and others
4929 * failed, but you have no way of knowing which.
4931 function delete_course($courseorid, $showfeedback = true) {
4934 if (is_object($courseorid)) {
4935 $courseid = $courseorid->id
;
4936 $course = $courseorid;
4938 $courseid = $courseorid;
4939 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4943 $context = context_course
::instance($courseid);
4945 // Frontpage course can not be deleted!!
4946 if ($courseid == SITEID
) {
4950 // Make the course completely empty.
4951 remove_course_contents($courseid, $showfeedback);
4953 // Delete the course and related context instance.
4954 context_helper
::delete_instance(CONTEXT_COURSE
, $courseid);
4956 $DB->delete_records("course", array("id" => $courseid));
4957 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4959 // Reset all course related caches here.
4960 if (class_exists('format_base', false)) {
4961 format_base
::reset_course_cache($courseid);
4964 // Trigger a course deleted event.
4965 $event = \core\event\course_deleted
::create(array(
4966 'objectid' => $course->id
,
4967 'context' => $context,
4969 'shortname' => $course->shortname
,
4970 'fullname' => $course->fullname
,
4971 'idnumber' => $course->idnumber
4974 $event->add_record_snapshot('course', $course);
4981 * Clear a course out completely, deleting all content but don't delete the course itself.
4983 * This function does not verify any permissions.
4985 * Please note this function also deletes all user enrolments,
4986 * enrolment instances and role assignments by default.
4989 * - 'keep_roles_and_enrolments' - false by default
4990 * - 'keep_groups_and_groupings' - false by default
4992 * @param int $courseid The id of the course that is being deleted
4993 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4994 * @param array $options extra options
4995 * @return bool true if all the removals succeeded. false if there were any failures. If this
4996 * method returns false, some of the removals will probably have succeeded, and others
4997 * failed, but you have no way of knowing which.
4999 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5000 global $CFG, $DB, $OUTPUT;
5002 require_once($CFG->libdir
.'/badgeslib.php');
5003 require_once($CFG->libdir
.'/completionlib.php');
5004 require_once($CFG->libdir
.'/questionlib.php');
5005 require_once($CFG->libdir
.'/gradelib.php');
5006 require_once($CFG->dirroot
.'/group/lib.php');
5007 require_once($CFG->dirroot
.'/tag/coursetagslib.php');
5008 require_once($CFG->dirroot
.'/comment/lib.php');
5009 require_once($CFG->dirroot
.'/rating/lib.php');
5010 require_once($CFG->dirroot
.'/notes/lib.php');
5012 // Handle course badges.
5013 badges_handle_course_deletion($courseid);
5015 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5016 $strdeleted = get_string('deleted').' - ';
5018 // Some crazy wishlist of stuff we should skip during purging of course content.
5019 $options = (array)$options;
5021 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST
);
5022 $coursecontext = context_course
::instance($courseid);
5023 $fs = get_file_storage();
5025 // Delete course completion information, this has to be done before grades and enrols.
5026 $cc = new completion_info($course);
5027 $cc->clear_criteria();
5028 if ($showfeedback) {
5029 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5032 // Remove all data from gradebook - this needs to be done before course modules
5033 // because while deleting this information, the system may need to reference
5034 // the course modules that own the grades.
5035 remove_course_grades($courseid, $showfeedback);
5036 remove_grade_letters($coursecontext, $showfeedback);
5038 // Delete course blocks in any all child contexts,
5039 // they may depend on modules so delete them first.
5040 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5041 foreach ($childcontexts as $childcontext) {
5042 blocks_delete_all_for_context($childcontext->id
);
5044 unset($childcontexts);
5045 blocks_delete_all_for_context($coursecontext->id
);
5046 if ($showfeedback) {
5047 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5050 // Delete every instance of every module,
5051 // this has to be done before deleting of course level stuff.
5052 $locations = core_component
::get_plugin_list('mod');
5053 foreach ($locations as $modname => $moddir) {
5054 if ($modname === 'NEWMODULE') {
5057 if ($module = $DB->get_record('modules', array('name' => $modname))) {
5058 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5059 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5060 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
5062 if ($instances = $DB->get_records($modname, array('course' => $course->id
))) {
5063 foreach ($instances as $instance) {
5064 if ($cm = get_coursemodule_from_instance($modname, $instance->id
, $course->id
)) {
5065 // Delete activity context questions and question categories.
5066 question_delete_activity($cm, $showfeedback);
5068 if (function_exists($moddelete)) {
5069 // This purges all module data in related tables, extra user prefs, settings, etc.
5070 $moddelete($instance->id
);
5072 // NOTE: we should not allow installation of modules with missing delete support!
5073 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5074 $DB->delete_records($modname, array('id' => $instance->id
));
5078 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5079 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5080 $DB->delete_records('course_modules', array('id' => $cm->id
));
5084 if (function_exists($moddeletecourse)) {
5085 // Execute ptional course cleanup callback.
5086 $moddeletecourse($course, $showfeedback);
5088 if ($instances and $showfeedback) {
5089 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5092 // Ooops, this module is not properly installed, force-delete it in the next block.
5096 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5098 // Remove all data from availability and completion tables that is associated
5099 // with course-modules belonging to this course. Note this is done even if the
5100 // features are not enabled now, in case they were enabled previously.
5101 $DB->delete_records_select('course_modules_completion',
5102 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5105 // Remove course-module data.
5106 $cms = $DB->get_records('course_modules', array('course' => $course->id
));
5107 foreach ($cms as $cm) {
5108 if ($module = $DB->get_record('modules', array('id' => $cm->module
))) {
5110 $DB->delete_records($module->name
, array('id' => $cm->instance
));
5111 } catch (Exception
$e) {
5112 // Ignore weird or missing table problems.
5115 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5116 $DB->delete_records('course_modules', array('id' => $cm->id
));
5119 if ($showfeedback) {
5120 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5123 // Cleanup the rest of plugins.
5124 $cleanuplugintypes = array('report', 'coursereport', 'format');
5125 foreach ($cleanuplugintypes as $type) {
5126 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
5127 foreach ($plugins as $plugin => $pluginfunction) {
5128 $pluginfunction($course->id
, $showfeedback);
5130 if ($showfeedback) {
5131 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5135 // Delete questions and question categories.
5136 question_delete_course($course, $showfeedback);
5137 if ($showfeedback) {
5138 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5141 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5142 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5143 foreach ($childcontexts as $childcontext) {
5144 $childcontext->delete();
5146 unset($childcontexts);
5148 // Remove all roles and enrolments by default.
5149 if (empty($options['keep_roles_and_enrolments'])) {
5150 // This hack is used in restore when deleting contents of existing course.
5151 role_unassign_all(array('contextid' => $coursecontext->id
, 'component' => ''), true);
5152 enrol_course_delete($course);
5153 if ($showfeedback) {
5154 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5158 // Delete any groups, removing members and grouping/course links first.
5159 if (empty($options['keep_groups_and_groupings'])) {
5160 groups_delete_groupings($course->id
, $showfeedback);
5161 groups_delete_groups($course->id
, $showfeedback);
5165 filter_delete_all_for_context($coursecontext->id
);
5167 // Notes, you shall not pass!
5168 note_delete_all($course->id
);
5171 comment
::delete_comments($coursecontext->id
);
5173 // Ratings are history too.
5174 $delopt = new stdclass();
5175 $delopt->contextid
= $coursecontext->id
;
5176 $rm = new rating_manager();
5177 $rm->delete_ratings($delopt);
5179 // Delete course tags.
5180 coursetag_delete_course_tags($course->id
, $showfeedback);
5182 // Delete calendar events.
5183 $DB->delete_records('event', array('courseid' => $course->id
));
5184 $fs->delete_area_files($coursecontext->id
, 'calendar');
5186 // Delete all related records in other core tables that may have a courseid
5187 // This array stores the tables that need to be cleared, as
5188 // table_name => column_name that contains the course id.
5189 $tablestoclear = array(
5190 'backup_courses' => 'courseid', // Scheduled backup stuff.
5191 'user_lastaccess' => 'courseid', // User access info.
5193 foreach ($tablestoclear as $table => $col) {
5194 $DB->delete_records($table, array($col => $course->id
));
5197 // Delete all course backup files.
5198 $fs->delete_area_files($coursecontext->id
, 'backup');
5200 // Cleanup course record - remove links to deleted stuff.
5201 $oldcourse = new stdClass();
5202 $oldcourse->id
= $course->id
;
5203 $oldcourse->summary
= '';
5204 $oldcourse->cacherev
= 0;
5205 $oldcourse->legacyfiles
= 0;
5206 $oldcourse->enablecompletion
= 0;
5207 if (!empty($options['keep_groups_and_groupings'])) {
5208 $oldcourse->defaultgroupingid
= 0;
5210 $DB->update_record('course', $oldcourse);
5212 // Delete course sections.
5213 $DB->delete_records('course_sections', array('course' => $course->id
));
5215 // Delete legacy, section and any other course files.
5216 $fs->delete_area_files($coursecontext->id
, 'course'); // Files from summary and section.
5218 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5219 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5220 // Easy, do not delete the context itself...
5221 $coursecontext->delete_content();
5224 // We can not drop all context stuff because it would bork enrolments and roles,
5225 // there might be also files used by enrol plugins...
5228 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5229 // also some non-standard unsupported plugins may try to store something there.
5230 fulldelete($CFG->dataroot
.'/'.$course->id
);
5232 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5233 $cachemodinfo = cache
::make('core', 'coursemodinfo');
5234 $cachemodinfo->delete($courseid);
5236 // Trigger a course content deleted event.
5237 $event = \core\event\course_content_deleted
::create(array(
5238 'objectid' => $course->id
,
5239 'context' => $coursecontext,
5240 'other' => array('shortname' => $course->shortname
,
5241 'fullname' => $course->fullname
,
5242 'options' => $options) // Passing this for legacy reasons.
5244 $event->add_record_snapshot('course', $course);
5251 * Change dates in module - used from course reset.
5253 * @param string $modname forum, assignment, etc
5254 * @param array $fields array of date fields from mod table
5255 * @param int $timeshift time difference
5256 * @param int $courseid
5257 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5258 * @return bool success
5260 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5262 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
5265 $params = array($timeshift, $courseid);
5266 foreach ($fields as $field) {
5267 $updatesql = "UPDATE {".$modname."}
5268 SET $field = $field + ?
5269 WHERE course=? AND $field<>0";
5271 $updatesql .= ' AND id=?';
5274 $return = $DB->execute($updatesql, $params) && $return;
5277 $refreshfunction = $modname.'_refresh_events';
5278 if (function_exists($refreshfunction)) {
5279 $refreshfunction($courseid);
5286 * This function will empty a course of user data.
5287 * It will retain the activities and the structure of the course.
5289 * @param object $data an object containing all the settings including courseid (without magic quotes)
5290 * @return array status array of array component, item, error
5292 function reset_course_userdata($data) {
5294 require_once($CFG->libdir
.'/gradelib.php');
5295 require_once($CFG->libdir
.'/completionlib.php');
5296 require_once($CFG->dirroot
.'/group/lib.php');
5298 $data->courseid
= $data->id
;
5299 $context = context_course
::instance($data->courseid
);
5301 $eventparams = array(
5302 'context' => $context,
5303 'courseid' => $data->id
,
5305 'reset_options' => (array) $data
5308 $event = \core\event\course_reset_started
::create($eventparams);
5311 // Calculate the time shift of dates.
5312 if (!empty($data->reset_start_date
)) {
5313 // Time part of course startdate should be zero.
5314 $data->timeshift
= $data->reset_start_date
- usergetmidnight($data->reset_start_date_old
);
5316 $data->timeshift
= 0;
5319 // Result array: component, item, error.
5322 // Start the resetting.
5323 $componentstr = get_string('general');
5325 // Move the course start time.
5326 if (!empty($data->reset_start_date
) and $data->timeshift
) {
5327 // Change course start data.
5328 $DB->set_field('course', 'startdate', $data->reset_start_date
, array('id' => $data->courseid
));
5329 // Update all course and group events - do not move activity events.
5330 $updatesql = "UPDATE {event}
5331 SET timestart = timestart + ?
5332 WHERE courseid=? AND instance=0";
5333 $DB->execute($updatesql, array($data->timeshift
, $data->courseid
));
5335 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5338 if (!empty($data->reset_events
)) {
5339 $DB->delete_records('event', array('courseid' => $data->courseid
));
5340 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5343 if (!empty($data->reset_notes
)) {
5344 require_once($CFG->dirroot
.'/notes/lib.php');
5345 note_delete_all($data->courseid
);
5346 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5349 if (!empty($data->delete_blog_associations
)) {
5350 require_once($CFG->dirroot
.'/blog/lib.php');
5351 blog_remove_associations_for_course($data->courseid
);
5352 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5355 if (!empty($data->reset_completion
)) {
5356 // Delete course and activity completion information.
5357 $course = $DB->get_record('course', array('id' => $data->courseid
));
5358 $cc = new completion_info($course);
5359 $cc->delete_all_completion_data();
5360 $status[] = array('component' => $componentstr,
5361 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5364 $componentstr = get_string('roles');
5366 if (!empty($data->reset_roles_overrides
)) {
5367 $children = $context->get_child_contexts();
5368 foreach ($children as $child) {
5369 $DB->delete_records('role_capabilities', array('contextid' => $child->id
));
5371 $DB->delete_records('role_capabilities', array('contextid' => $context->id
));
5372 // Force refresh for logged in users.
5373 $context->mark_dirty();
5374 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5377 if (!empty($data->reset_roles_local
)) {
5378 $children = $context->get_child_contexts();
5379 foreach ($children as $child) {
5380 role_unassign_all(array('contextid' => $child->id
));
5382 // Force refresh for logged in users.
5383 $context->mark_dirty();
5384 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5387 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5388 $data->unenrolled
= array();
5389 if (!empty($data->unenrol_users
)) {
5390 $plugins = enrol_get_plugins(true);
5391 $instances = enrol_get_instances($data->courseid
, true);
5392 foreach ($instances as $key => $instance) {
5393 if (!isset($plugins[$instance->enrol
])) {
5394 unset($instances[$key]);
5399 foreach ($data->unenrol_users
as $withroleid) {
5402 FROM {user_enrolments} ue
5403 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5404 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5405 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5406 $params = array('courseid' => $data->courseid
, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE
);
5409 // Without any role assigned at course context.
5411 FROM {user_enrolments} ue
5412 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5413 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5414 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5415 WHERE ra.id IS null";
5416 $params = array('courseid' => $data->courseid
, 'courselevel' => CONTEXT_COURSE
);
5419 $rs = $DB->get_recordset_sql($sql, $params);
5420 foreach ($rs as $ue) {
5421 if (!isset($instances[$ue->enrolid
])) {
5424 $instance = $instances[$ue->enrolid
];
5425 $plugin = $plugins[$instance->enrol
];
5426 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5430 $plugin->unenrol_user($instance, $ue->userid
);
5431 $data->unenrolled
[$ue->userid
] = $ue->userid
;
5436 if (!empty($data->unenrolled
)) {
5438 'component' => $componentstr,
5439 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled
).')',
5444 $componentstr = get_string('groups');
5446 // Remove all group members.
5447 if (!empty($data->reset_groups_members
)) {
5448 groups_delete_group_members($data->courseid
);
5449 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5452 // Remove all groups.
5453 if (!empty($data->reset_groups_remove
)) {
5454 groups_delete_groups($data->courseid
, false);
5455 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5458 // Remove all grouping members.
5459 if (!empty($data->reset_groupings_members
)) {
5460 groups_delete_groupings_groups($data->courseid
, false);
5461 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5464 // Remove all groupings.
5465 if (!empty($data->reset_groupings_remove
)) {
5466 groups_delete_groupings($data->courseid
, false);
5467 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5470 // Look in every instance of every module for data to delete.
5471 $unsupportedmods = array();
5472 if ($allmods = $DB->get_records('modules') ) {
5473 foreach ($allmods as $mod) {
5474 $modname = $mod->name
;
5475 $modfile = $CFG->dirroot
.'/mod/'. $modname.'/lib.php';
5476 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5477 if (file_exists($modfile)) {
5478 if (!$DB->count_records($modname, array('course' => $data->courseid
))) {
5479 continue; // Skip mods with no instances.
5481 include_once($modfile);
5482 if (function_exists($moddeleteuserdata)) {
5483 $modstatus = $moddeleteuserdata($data);
5484 if (is_array($modstatus)) {
5485 $status = array_merge($status, $modstatus);
5487 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5490 $unsupportedmods[] = $mod;
5493 debugging('Missing lib.php in '.$modname.' module!');
5498 // Mention unsupported mods.
5499 if (!empty($unsupportedmods)) {
5500 foreach ($unsupportedmods as $mod) {
5502 'component' => get_string('modulenameplural', $mod->name
),
5504 'error' => get_string('resetnotimplemented')
5509 $componentstr = get_string('gradebook', 'grades');
5510 // Reset gradebook,.
5511 if (!empty($data->reset_gradebook_items
)) {
5512 remove_course_grades($data->courseid
, false);
5513 grade_grab_course_grades($data->courseid
);
5514 grade_regrade_final_grades($data->courseid
);
5515 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5517 } else if (!empty($data->reset_gradebook_grades
)) {
5518 grade_course_reset($data->courseid
);
5519 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5522 if (!empty($data->reset_comments
)) {
5523 require_once($CFG->dirroot
.'/comment/lib.php');
5524 comment
::reset_course_page_comments($context);
5527 $event = \core\event\course_reset_ended
::create($eventparams);
5534 * Generate an email processing address.
5537 * @param string $modargs
5538 * @return string Returns email processing address
5540 function generate_email_processing_address($modid, $modargs) {
5543 $header = $CFG->mailprefix
. substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5544 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain
;
5550 * @todo Finish documenting this function
5552 * @param string $modargs
5553 * @param string $body Currently unused
5555 function moodle_process_email($modargs, $body) {
5558 // The first char should be an unencoded letter. We'll take this as an action.
5559 switch ($modargs{0}) {
5560 case 'B': { // Bounce.
5561 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5562 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5563 // Check the half md5 of their email.
5564 $md5check = substr(md5($user->email
), 0, 16);
5565 if ($md5check == substr($modargs, -16)) {
5566 set_bounce_count($user);
5568 // Else maybe they've already changed it?
5572 // Maybe more later?
5579 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5581 * @param string $action 'get', 'buffer', 'close' or 'flush'
5582 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5584 function get_mailer($action='get') {
5587 /** @var moodle_phpmailer $mailer */
5588 static $mailer = null;
5589 static $counter = 0;
5591 if (!isset($CFG->smtpmaxbulk
)) {
5592 $CFG->smtpmaxbulk
= 1;
5595 if ($action == 'get') {
5596 $prevkeepalive = false;
5598 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5599 if ($counter < $CFG->smtpmaxbulk
and !$mailer->isError()) {
5601 // Reset the mailer.
5602 $mailer->Priority
= 3;
5603 $mailer->CharSet
= 'UTF-8'; // Our default.
5604 $mailer->ContentType
= "text/plain";
5605 $mailer->Encoding
= "8bit";
5606 $mailer->From
= "root@localhost";
5607 $mailer->FromName
= "Root User";
5608 $mailer->Sender
= "";
5609 $mailer->Subject
= "";
5611 $mailer->AltBody
= "";
5612 $mailer->ConfirmReadingTo
= "";
5614 $mailer->clearAllRecipients();
5615 $mailer->clearReplyTos();
5616 $mailer->clearAttachments();
5617 $mailer->clearCustomHeaders();
5621 $prevkeepalive = $mailer->SMTPKeepAlive
;
5622 get_mailer('flush');
5625 require_once($CFG->libdir
.'/phpmailer/moodle_phpmailer.php');
5626 $mailer = new moodle_phpmailer();
5630 if ($CFG->smtphosts
== 'qmail') {
5631 // Use Qmail system.
5634 } else if (empty($CFG->smtphosts
)) {
5635 // Use PHP mail() = sendmail.
5639 // Use SMTP directly.
5641 if (!empty($CFG->debugsmtp
)) {
5642 $mailer->SMTPDebug
= true;
5644 // Specify main and backup servers.
5645 $mailer->Host
= $CFG->smtphosts
;
5646 // Specify secure connection protocol.
5647 $mailer->SMTPSecure
= $CFG->smtpsecure
;
5648 // Use previous keepalive.
5649 $mailer->SMTPKeepAlive
= $prevkeepalive;
5651 if ($CFG->smtpuser
) {
5652 // Use SMTP authentication.
5653 $mailer->SMTPAuth
= true;
5654 $mailer->Username
= $CFG->smtpuser
;
5655 $mailer->Password
= $CFG->smtppass
;
5664 // Keep smtp session open after sending.
5665 if ($action == 'buffer') {
5666 if (!empty($CFG->smtpmaxbulk
)) {
5667 get_mailer('flush');
5669 if ($m->Mailer
== 'smtp') {
5670 $m->SMTPKeepAlive
= true;
5676 // Close smtp session, but continue buffering.
5677 if ($action == 'flush') {
5678 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5679 if (!empty($mailer->SMTPDebug
)) {
5682 $mailer->SmtpClose();
5683 if (!empty($mailer->SMTPDebug
)) {
5690 // Close smtp session, do not buffer anymore.
5691 if ($action == 'close') {
5692 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5693 get_mailer('flush');
5694 $mailer->SMTPKeepAlive
= false;
5696 $mailer = null; // Better force new instance.
5702 * Send an email to a specified user
5704 * @param stdClass $user A {@link $USER} object
5705 * @param stdClass $from A {@link $USER} object
5706 * @param string $subject plain text subject line of the email
5707 * @param string $messagetext plain text version of the message
5708 * @param string $messagehtml complete html version of the message (optional)
5709 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
5710 * @param string $attachname the name of the file (extension indicates MIME)
5711 * @param bool $usetrueaddress determines whether $from email address should
5712 * be sent out. Will be overruled by user profile setting for maildisplay
5713 * @param string $replyto Email address to reply to
5714 * @param string $replytoname Name of reply to recipient
5715 * @param int $wordwrapwidth custom word wrap width, default 79
5716 * @return bool Returns true if mail was sent OK and false if there was an error.
5718 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5719 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5723 if (empty($user) or empty($user->id
)) {
5724 debugging('Can not send email to null user', DEBUG_DEVELOPER
);
5728 if (empty($user->email
)) {
5729 debugging('Can not send email to user without email: '.$user->id
, DEBUG_DEVELOPER
);
5733 if (!empty($user->deleted
)) {
5734 debugging('Can not send email to deleted user: '.$user->id
, DEBUG_DEVELOPER
);
5738 if (defined('BEHAT_SITE_RUNNING')) {
5739 // Fake email sending in behat.
5743 if (!empty($CFG->noemailever
)) {
5744 // Hidden setting for development sites, set in config.php if needed.
5745 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL
);
5749 if (!empty($CFG->divertallemailsto
)) {
5750 $subject = "[DIVERTED {$user->email}] $subject";
5751 $user = clone($user);
5752 $user->email
= $CFG->divertallemailsto
;
5755 // Skip mail to suspended users.
5756 if ((isset($user->auth
) && $user->auth
=='nologin') or (isset($user->suspended
) && $user->suspended
)) {
5760 if (!validate_email($user->email
)) {
5761 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5762 $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
5763 error_log($invalidemail);
5765 mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
5770 if (over_bounce_threshold($user)) {
5771 $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
5772 error_log($bouncemsg);
5774 mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
5779 // If the user is a remote mnet user, parse the email text for URL to the
5780 // wwwroot and modify the url to direct the user's browser to login at their
5781 // home site (identity provider - idp) before hitting the link itself.
5782 if (is_mnet_remote_user($user)) {
5783 require_once($CFG->dirroot
.'/mnet/lib.php');
5785 $jumpurl = mnet_get_idp_jump_url($user);
5786 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5788 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5791 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5795 $mail = get_mailer();
5797 if (!empty($mail->SMTPDebug
)) {
5798 echo '<pre>' . "\n";
5801 $temprecipients = array();
5802 $tempreplyto = array();
5804 $supportuser = core_user
::get_support_user();
5806 // Make up an email address for handling bounces.
5807 if (!empty($CFG->handlebounces
)) {
5808 $modargs = 'B'.base64_encode(pack('V', $user->id
)).substr(md5($user->email
), 0, 16);
5809 $mail->Sender
= generate_email_processing_address(0, $modargs);
5811 $mail->Sender
= $supportuser->email
;
5814 if (!empty($CFG->emailonlyfromnoreplyaddress
)) {
5815 $usetrueaddress = false;
5816 if (empty($replyto) && $from->maildisplay
) {
5817 $replyto = $from->email
;
5818 $replytoname = fullname($from);
5822 if (is_string($from)) { // So we can pass whatever we want if there is need.
5823 $mail->From
= $CFG->noreplyaddress
;
5824 $mail->FromName
= $from;
5825 } else if ($usetrueaddress and $from->maildisplay
) {
5826 $mail->From
= $from->email
;
5827 $mail->FromName
= fullname($from);
5829 $mail->From
= $CFG->noreplyaddress
;
5830 $mail->FromName
= fullname($from);
5831 if (empty($replyto)) {
5832 $tempreplyto[] = array($CFG->noreplyaddress
, get_string('noreplyname'));
5836 if (!empty($replyto)) {
5837 $tempreplyto[] = array($replyto, $replytoname);
5840 $mail->Subject
= substr($subject, 0, 900);
5842 $temprecipients[] = array($user->email
, fullname($user));
5845 $mail->WordWrap
= $wordwrapwidth;
5847 if (!empty($from->customheaders
)) {
5848 // Add custom headers.
5849 if (is_array($from->customheaders
)) {
5850 foreach ($from->customheaders
as $customheader) {
5851 $mail->addCustomHeader($customheader);
5854 $mail->addCustomHeader($from->customheaders
);
5858 if (!empty($from->priority
)) {
5859 $mail->Priority
= $from->priority
;
5862 if ($messagehtml && !empty($user->mailformat
) && $user->mailformat
== 1) {
5863 // Don't ever send HTML to users who don't want it.
5864 $mail->isHTML(true);
5865 $mail->Encoding
= 'quoted-printable';
5866 $mail->Body
= $messagehtml;
5867 $mail->AltBody
= "\n$messagetext\n";
5869 $mail->IsHTML(false);
5870 $mail->Body
= "\n$messagetext\n";
5873 if ($attachment && $attachname) {
5874 if (preg_match( "~\\.\\.~" , $attachment )) {
5875 // Security check for ".." in dir path.
5876 $temprecipients[] = array($supportuser->email
, fullname($supportuser, true));
5877 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5879 require_once($CFG->libdir
.'/filelib.php');
5880 $mimetype = mimeinfo('type', $attachname);
5881 $mail->addAttachment($CFG->dataroot
.'/'. $attachment, $attachname, 'base64', $mimetype);
5885 // Check if the email should be sent in an other charset then the default UTF-8.
5886 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
5888 // Use the defined site mail charset or eventually the one preferred by the recipient.
5889 $charset = $CFG->sitemailcharset
;
5890 if (!empty($CFG->allowusermailcharset
)) {
5891 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
5892 $charset = $useremailcharset;
5896 // Convert all the necessary strings if the charset is supported.
5897 $charsets = get_list_of_charsets();
5898 unset($charsets['UTF-8']);
5899 if (in_array($charset, $charsets)) {
5900 $mail->CharSet
= $charset;
5901 $mail->FromName
= core_text
::convert($mail->FromName
, 'utf-8', strtolower($charset));
5902 $mail->Subject
= core_text
::convert($mail->Subject
, 'utf-8', strtolower($charset));
5903 $mail->Body
= core_text
::convert($mail->Body
, 'utf-8', strtolower($charset));
5904 $mail->AltBody
= core_text
::convert($mail->AltBody
, 'utf-8', strtolower($charset));
5906 foreach ($temprecipients as $key => $values) {
5907 $temprecipients[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
5909 foreach ($tempreplyto as $key => $values) {
5910 $tempreplyto[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
5915 foreach ($temprecipients as $values) {
5916 $mail->addAddress($values[0], $values[1]);
5918 foreach ($tempreplyto as $values) {
5919 $mail->addReplyTo($values[0], $values[1]);
5922 if ($mail->send()) {
5923 set_send_count($user);
5924 if (!empty($mail->SMTPDebug
)) {
5929 // Trigger event for failing to send email.
5930 $event = \core\event\email_failed
::create(array(
5931 'context' => context_system
::instance(),
5932 'userid' => $from->id
,
5933 'relateduserid' => $user->id
,
5935 'subject' => $subject,
5936 'message' => $messagetext,
5937 'errorinfo' => $mail->ErrorInfo
5942 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo
);
5944 if (!empty($mail->SMTPDebug
)) {
5952 * Generate a signoff for emails based on support settings
5956 function generate_email_signoff() {
5960 if (!empty($CFG->supportname
)) {
5961 $signoff .= $CFG->supportname
."\n";
5963 if (!empty($CFG->supportemail
)) {
5964 $signoff .= $CFG->supportemail
."\n";
5966 if (!empty($CFG->supportpage
)) {
5967 $signoff .= $CFG->supportpage
."\n";
5973 * Sets specified user's password and send the new password to the user via email.
5975 * @param stdClass $user A {@link $USER} object
5976 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
5977 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
5979 function setnew_password_and_mail($user, $fasthash = false) {
5982 // We try to send the mail in language the user understands,
5983 // unfortunately the filter_string() does not support alternative langs yet
5984 // so multilang will not work properly for site->fullname.
5985 $lang = empty($user->lang
) ?
$CFG->lang
: $user->lang
;
5989 $supportuser = core_user
::get_support_user();
5991 $newpassword = generate_password();
5993 update_internal_user_password($user, $newpassword, $fasthash);
5995 $a = new stdClass();
5996 $a->firstname
= fullname($user, true);
5997 $a->sitename
= format_string($site->fullname
);
5998 $a->username
= $user->username
;
5999 $a->newpassword
= $newpassword;
6000 $a->link
= $CFG->wwwroot
.'/login/';
6001 $a->signoff
= generate_email_signoff();
6003 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6005 $subject = format_string($site->fullname
) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6007 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6008 return email_to_user($user, $supportuser, $subject, $message);
6013 * Resets specified user's password and send the new password to the user via email.
6015 * @param stdClass $user A {@link $USER} object
6016 * @return bool Returns true if mail was sent OK and false if there was an error.
6018 function reset_password_and_mail($user) {
6022 $supportuser = core_user
::get_support_user();
6024 $userauth = get_auth_plugin($user->auth
);
6025 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth
)) {
6026 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6030 $newpassword = generate_password();
6032 if (!$userauth->user_update_password($user, $newpassword)) {
6033 print_error("cannotsetpassword");
6036 $a = new stdClass();
6037 $a->firstname
= $user->firstname
;
6038 $a->lastname
= $user->lastname
;
6039 $a->sitename
= format_string($site->fullname
);
6040 $a->username
= $user->username
;
6041 $a->newpassword
= $newpassword;
6042 $a->link
= $CFG->httpswwwroot
.'/login/change_password.php';
6043 $a->signoff
= generate_email_signoff();
6045 $message = get_string('newpasswordtext', '', $a);
6047 $subject = format_string($site->fullname
) .': '. get_string('changedpassword');
6049 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6051 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6052 return email_to_user($user, $supportuser, $subject, $message);
6056 * Send email to specified user with confirmation text and activation link.
6058 * @param stdClass $user A {@link $USER} object
6059 * @return bool Returns true if mail was sent OK and false if there was an error.
6061 function send_confirmation_email($user) {
6065 $supportuser = core_user
::get_support_user();
6067 $data = new stdClass();
6068 $data->firstname
= fullname($user);
6069 $data->sitename
= format_string($site->fullname
);
6070 $data->admin
= generate_email_signoff();
6072 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname
));
6074 $username = urlencode($user->username
);
6075 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
6076 $data->link
= $CFG->wwwroot
.'/login/confirm.php?data='. $user->secret
.'/'. $username;
6077 $message = get_string('emailconfirmation', '', $data);
6078 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6080 $user->mailformat
= 1; // Always send HTML version as well.
6082 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6083 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6087 * Sends a password change confirmation email.
6089 * @param stdClass $user A {@link $USER} object
6090 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6091 * @return bool Returns true if mail was sent OK and false if there was an error.
6093 function send_password_change_confirmation_email($user, $resetrecord) {
6097 $supportuser = core_user
::get_support_user();
6098 $pwresetmins = isset($CFG->pwresettime
) ?
floor($CFG->pwresettime
/ MINSECS
) : 30;
6100 $data = new stdClass();
6101 $data->firstname
= $user->firstname
;
6102 $data->lastname
= $user->lastname
;
6103 $data->username
= $user->username
;
6104 $data->sitename
= format_string($site->fullname
);
6105 $data->link
= $CFG->httpswwwroot
.'/login/forgot_password.php?token='. $resetrecord->token
;
6106 $data->admin
= generate_email_signoff();
6107 $data->resetminutes
= $pwresetmins;
6109 $message = get_string('emailresetconfirmation', '', $data);
6110 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname
));
6112 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6113 return email_to_user($user, $supportuser, $subject, $message);
6118 * Sends an email containinginformation on how to change your password.
6120 * @param stdClass $user A {@link $USER} object
6121 * @return bool Returns true if mail was sent OK and false if there was an error.
6123 function send_password_change_info($user) {
6127 $supportuser = core_user
::get_support_user();
6128 $systemcontext = context_system
::instance();
6130 $data = new stdClass();
6131 $data->firstname
= $user->firstname
;
6132 $data->lastname
= $user->lastname
;
6133 $data->sitename
= format_string($site->fullname
);
6134 $data->admin
= generate_email_signoff();
6136 $userauth = get_auth_plugin($user->auth
);
6138 if (!is_enabled_auth($user->auth
) or $user->auth
== 'nologin') {
6139 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6140 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6141 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6142 return email_to_user($user, $supportuser, $subject, $message);
6145 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6146 // We have some external url for password changing.
6147 $data->link
.= $userauth->change_password_url();
6150 // No way to change password, sorry.
6154 if (!empty($data->link
) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id
)) {
6155 $message = get_string('emailpasswordchangeinfo', '', $data);
6156 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6158 $message = get_string('emailpasswordchangeinfofail', '', $data);
6159 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6162 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6163 return email_to_user($user, $supportuser, $subject, $message);
6168 * Check that an email is allowed. It returns an error message if there was a problem.
6170 * @param string $email Content of email
6171 * @return string|false
6173 function email_is_not_allowed($email) {
6176 if (!empty($CFG->allowemailaddresses
)) {
6177 $allowed = explode(' ', $CFG->allowemailaddresses
);
6178 foreach ($allowed as $allowedpattern) {
6179 $allowedpattern = trim($allowedpattern);
6180 if (!$allowedpattern) {
6183 if (strpos($allowedpattern, '.') === 0) {
6184 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6185 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6189 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6193 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
6195 } else if (!empty($CFG->denyemailaddresses
)) {
6196 $denied = explode(' ', $CFG->denyemailaddresses
);
6197 foreach ($denied as $deniedpattern) {
6198 $deniedpattern = trim($deniedpattern);
6199 if (!$deniedpattern) {
6202 if (strpos($deniedpattern, '.') === 0) {
6203 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6204 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6205 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6208 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6209 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6220 * Returns local file storage instance
6222 * @return file_storage
6224 function get_file_storage() {
6233 require_once("$CFG->libdir/filelib.php");
6235 if (isset($CFG->filedir
)) {
6236 $filedir = $CFG->filedir
;
6238 $filedir = $CFG->dataroot
.'/filedir';
6241 if (isset($CFG->trashdir
)) {
6242 $trashdirdir = $CFG->trashdir
;
6244 $trashdirdir = $CFG->dataroot
.'/trashdir';
6247 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions
, $CFG->filepermissions
);
6253 * Returns local file storage instance
6255 * @return file_browser
6257 function get_file_browser() {
6266 require_once("$CFG->libdir/filelib.php");
6268 $fb = new file_browser();
6274 * Returns file packer
6276 * @param string $mimetype default application/zip
6277 * @return file_packer
6279 function get_file_packer($mimetype='application/zip') {
6282 static $fp = array();
6284 if (isset($fp[$mimetype])) {
6285 return $fp[$mimetype];
6288 switch ($mimetype) {
6289 case 'application/zip':
6290 case 'application/vnd.moodle.profiling':
6291 $classname = 'zip_packer';
6294 case 'application/x-gzip' :
6295 $classname = 'tgz_packer';
6298 case 'application/vnd.moodle.backup':
6299 $classname = 'mbz_packer';
6306 require_once("$CFG->libdir/filestorage/$classname.php");
6307 $fp[$mimetype] = new $classname();
6309 return $fp[$mimetype];
6313 * Returns current name of file on disk if it exists.
6315 * @param string $newfile File to be verified
6316 * @return string Current name of file on disk if true
6318 function valid_uploaded_file($newfile) {
6319 if (empty($newfile)) {
6322 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6323 return $newfile['tmp_name'];
6330 * Returns the maximum size for uploading files.
6332 * There are seven possible upload limits:
6333 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6334 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6335 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6336 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6337 * 5. by the Moodle admin in $CFG->maxbytes
6338 * 6. by the teacher in the current course $course->maxbytes
6339 * 7. by the teacher for the current module, eg $assignment->maxbytes
6341 * These last two are passed to this function as arguments (in bytes).
6342 * Anything defined as 0 is ignored.
6343 * The smallest of all the non-zero numbers is returned.
6345 * @todo Finish documenting this function
6347 * @param int $sitebytes Set maximum size
6348 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6349 * @param int $modulebytes Current module ->maxbytes (in bytes)
6350 * @return int The maximum size for uploading files.
6352 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6354 if (! $filesize = ini_get('upload_max_filesize')) {
6357 $minimumsize = get_real_size($filesize);
6359 if ($postsize = ini_get('post_max_size')) {
6360 $postsize = get_real_size($postsize);
6361 if ($postsize < $minimumsize) {
6362 $minimumsize = $postsize;
6366 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6367 $minimumsize = $sitebytes;
6370 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6371 $minimumsize = $coursebytes;
6374 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6375 $minimumsize = $modulebytes;
6378 return $minimumsize;
6382 * Returns the maximum size for uploading files for the current user
6384 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6386 * @param context $context The context in which to check user capabilities
6387 * @param int $sitebytes Set maximum size
6388 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6389 * @param int $modulebytes Current module ->maxbytes (in bytes)
6390 * @param stdClass $user The user
6391 * @return int The maximum size for uploading files.
6393 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6400 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6401 return USER_CAN_IGNORE_FILE_SIZE_LIMITS
;
6404 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6408 * Returns an array of possible sizes in local language
6410 * Related to {@link get_max_upload_file_size()} - this function returns an
6411 * array of possible sizes in an array, translated to the
6414 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6416 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6417 * with the value set to 0. This option will be the first in the list.
6419 * @uses SORT_NUMERIC
6420 * @param int $sitebytes Set maximum size
6421 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6422 * @param int $modulebytes Current module ->maxbytes (in bytes)
6423 * @param int|array $custombytes custom upload size/s which will be added to list,
6424 * Only value/s smaller then maxsize will be added to list.
6427 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6430 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6434 if ($sitebytes == 0) {
6435 // Will get the minimum of upload_max_filesize or post_max_size.
6436 $sitebytes = get_max_upload_file_size();
6439 $filesize = array();
6440 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6441 5242880, 10485760, 20971520, 52428800, 104857600);
6443 // If custombytes is given and is valid then add it to the list.
6444 if (is_number($custombytes) and $custombytes > 0) {
6445 $custombytes = (int)$custombytes;
6446 if (!in_array($custombytes, $sizelist)) {
6447 $sizelist[] = $custombytes;
6449 } else if (is_array($custombytes)) {
6450 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6453 // Allow maxbytes to be selected if it falls outside the above boundaries.
6454 if (isset($CFG->maxbytes
) && !in_array(get_real_size($CFG->maxbytes
), $sizelist)) {
6455 // Note: get_real_size() is used in order to prevent problems with invalid values.
6456 $sizelist[] = get_real_size($CFG->maxbytes
);
6459 foreach ($sizelist as $sizebytes) {
6460 if ($sizebytes < $maxsize && $sizebytes > 0) {
6461 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6468 (($modulebytes < $coursebytes ||
$coursebytes == 0) &&
6469 ($modulebytes < $sitebytes ||
$sitebytes == 0))) {
6470 $limitlevel = get_string('activity', 'core');
6471 $displaysize = display_size($modulebytes);
6472 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6474 } else if ($coursebytes && ($coursebytes < $sitebytes ||
$sitebytes == 0)) {
6475 $limitlevel = get_string('course', 'core');
6476 $displaysize = display_size($coursebytes);
6477 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6479 } else if ($sitebytes) {
6480 $limitlevel = get_string('site', 'core');
6481 $displaysize = display_size($sitebytes);
6482 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6485 krsort($filesize, SORT_NUMERIC
);
6487 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6488 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) +
$filesize;
6495 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6497 * If excludefiles is defined, then that file/directory is ignored
6498 * If getdirs is true, then (sub)directories are included in the output
6499 * If getfiles is true, then files are included in the output
6500 * (at least one of these must be true!)
6502 * @todo Finish documenting this function. Add examples of $excludefile usage.
6504 * @param string $rootdir A given root directory to start from
6505 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6506 * @param bool $descend If true then subdirectories are recursed as well
6507 * @param bool $getdirs If true then (sub)directories are included in the output
6508 * @param bool $getfiles If true then files are included in the output
6509 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6511 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6515 if (!$getdirs and !$getfiles) { // Nothing to show.
6519 if (!is_dir($rootdir)) { // Must be a directory.
6523 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6527 if (!is_array($excludefiles)) {
6528 $excludefiles = array($excludefiles);
6531 while (false !== ($file = readdir($dir))) {
6532 $firstchar = substr($file, 0, 1);
6533 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6536 $fullfile = $rootdir .'/'. $file;
6537 if (filetype($fullfile) == 'dir') {
6542 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6543 foreach ($subdirs as $subdir) {
6544 $dirs[] = $file .'/'. $subdir;
6547 } else if ($getfiles) {
6560 * Adds up all the files in a directory and works out the size.
6562 * @param string $rootdir The directory to start from
6563 * @param string $excludefile A file to exclude when summing directory size
6564 * @return int The summed size of all files and subfiles within the root directory
6566 function get_directory_size($rootdir, $excludefile='') {
6569 // Do it this way if we can, it's much faster.
6570 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
6571 $command = trim($CFG->pathtodu
).' -sk '.escapeshellarg($rootdir);
6574 exec($command, $output, $return);
6575 if (is_array($output)) {
6576 // We told it to return k.
6577 return get_real_size(intval($output[0]).'k');
6581 if (!is_dir($rootdir)) {
6582 // Must be a directory.
6586 if (!$dir = @opendir
($rootdir)) {
6587 // Can't open it for some reason.
6593 while (false !== ($file = readdir($dir))) {
6594 $firstchar = substr($file, 0, 1);
6595 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6598 $fullfile = $rootdir .'/'. $file;
6599 if (filetype($fullfile) == 'dir') {
6600 $size +
= get_directory_size($fullfile, $excludefile);
6602 $size +
= filesize($fullfile);
6611 * Converts bytes into display form
6613 * @static string $gb Localized string for size in gigabytes
6614 * @static string $mb Localized string for size in megabytes
6615 * @static string $kb Localized string for size in kilobytes
6616 * @static string $b Localized string for size in bytes
6617 * @param int $size The size to convert to human readable form
6620 function display_size($size) {
6622 static $gb, $mb, $kb, $b;
6624 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS
) {
6625 return get_string('unlimited');
6629 $gb = get_string('sizegb');
6630 $mb = get_string('sizemb');
6631 $kb = get_string('sizekb');
6632 $b = get_string('sizeb');
6635 if ($size >= 1073741824) {
6636 $size = round($size / 1073741824 * 10) / 10 . $gb;
6637 } else if ($size >= 1048576) {
6638 $size = round($size / 1048576 * 10) / 10 . $mb;
6639 } else if ($size >= 1024) {
6640 $size = round($size / 1024 * 10) / 10 . $kb;
6642 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6648 * Cleans a given filename by removing suspicious or troublesome characters
6650 * @see clean_param()
6651 * @param string $string file name
6652 * @return string cleaned file name
6654 function clean_filename($string) {
6655 return clean_param($string, PARAM_FILE
);
6659 // STRING TRANSLATION.
6662 * Returns the code for the current language
6667 function current_language() {
6668 global $CFG, $USER, $SESSION, $COURSE;
6670 if (!empty($SESSION->forcelang
)) {
6671 // Allows overriding course-forced language (useful for admins to check
6672 // issues in courses whose language they don't understand).
6673 // Also used by some code to temporarily get language-related information in a
6674 // specific language (see force_current_language()).
6675 $return = $SESSION->forcelang
;
6677 } else if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) {
6678 // Course language can override all other settings for this page.
6679 $return = $COURSE->lang
;
6681 } else if (!empty($SESSION->lang
)) {
6682 // Session language can override other settings.
6683 $return = $SESSION->lang
;
6685 } else if (!empty($USER->lang
)) {
6686 $return = $USER->lang
;
6688 } else if (isset($CFG->lang
)) {
6689 $return = $CFG->lang
;
6695 // Just in case this slipped in from somewhere by accident.
6696 $return = str_replace('_utf8', '', $return);
6702 * Returns parent language of current active language if defined
6705 * @param string $lang null means current language
6708 function get_parent_language($lang=null) {
6710 // Let's hack around the current language.
6711 if (!empty($lang)) {
6712 $oldforcelang = force_current_language($lang);
6715 $parentlang = get_string('parentlanguage', 'langconfig');
6716 if ($parentlang === 'en') {
6720 // Let's hack around the current language.
6721 if (!empty($lang)) {
6722 force_current_language($oldforcelang);
6729 * Force the current language to get strings and dates localised in the given language.
6731 * After calling this function, all strings will be provided in the given language
6732 * until this function is called again, or equivalent code is run.
6734 * @param string $language
6735 * @return string previous $SESSION->forcelang value
6737 function force_current_language($language) {
6739 $sessionforcelang = isset($SESSION->forcelang
) ?
$SESSION->forcelang
: '';
6740 if ($language !== $sessionforcelang) {
6741 // Seting forcelang to null or an empty string disables it's effect.
6742 if (empty($language) ||
get_string_manager()->translation_exists($language, false)) {
6743 $SESSION->forcelang
= $language;
6747 return $sessionforcelang;
6751 * Returns current string_manager instance.
6753 * The param $forcereload is needed for CLI installer only where the string_manager instance
6754 * must be replaced during the install.php script life time.
6757 * @param bool $forcereload shall the singleton be released and new instance created instead?
6758 * @return core_string_manager
6760 function get_string_manager($forcereload=false) {
6763 static $singleton = null;
6768 if ($singleton === null) {
6769 if (empty($CFG->early_install_lang
)) {
6771 if (empty($CFG->langlist
)) {
6772 $translist = array();
6774 $translist = explode(',', $CFG->langlist
);
6777 $singleton = new core_string_manager_standard($CFG->langotherroot
, $CFG->langlocalroot
, $translist);
6780 $singleton = new core_string_manager_install();
6788 * Returns a localized string.
6790 * Returns the translated string specified by $identifier as
6791 * for $module. Uses the same format files as STphp.
6792 * $a is an object, string or number that can be used
6793 * within translation strings
6795 * eg 'hello {$a->firstname} {$a->lastname}'
6798 * If you would like to directly echo the localized string use
6799 * the function {@link print_string()}
6801 * Example usage of this function involves finding the string you would
6802 * like a local equivalent of and using its identifier and module information
6803 * to retrieve it.<br/>
6804 * If you open moodle/lang/en/moodle.php and look near line 278
6805 * you will find a string to prompt a user for their word for 'course'
6807 * $string['course'] = 'Course';
6809 * So if you want to display the string 'Course'
6810 * in any language that supports it on your site
6811 * you just need to use the identifier 'course'
6813 * $mystring = '<strong>'. get_string('course') .'</strong>';
6816 * If the string you want is in another file you'd take a slightly
6817 * different approach. Looking in moodle/lang/en/calendar.php you find
6820 * $string['typecourse'] = 'Course event';
6822 * If you want to display the string "Course event" in any language
6823 * supported you would use the identifier 'typecourse' and the module 'calendar'
6824 * (because it is in the file calendar.php):
6826 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6829 * As a last resort, should the identifier fail to map to a string
6830 * the returned string will be [[ $identifier ]]
6832 * In Moodle 2.3 there is a new argument to this function $lazyload.
6833 * Setting $lazyload to true causes get_string to return a lang_string object
6834 * rather than the string itself. The fetching of the string is then put off until
6835 * the string object is first used. The object can be used by calling it's out
6836 * method or by casting the object to a string, either directly e.g.
6837 * (string)$stringobject
6838 * or indirectly by using the string within another string or echoing it out e.g.
6839 * echo $stringobject
6840 * return "<p>{$stringobject}</p>";
6841 * It is worth noting that using $lazyload and attempting to use the string as an
6842 * array key will cause a fatal error as objects cannot be used as array keys.
6843 * But you should never do that anyway!
6844 * For more information {@link lang_string}
6847 * @param string $identifier The key identifier for the localized string
6848 * @param string $component The module where the key identifier is stored,
6849 * usually expressed as the filename in the language pack without the
6850 * .php on the end but can also be written as mod/forum or grade/export/xls.
6851 * If none is specified then moodle.php is used.
6852 * @param string|object|array $a An object, string or number that can be used
6853 * within translation strings
6854 * @param bool $lazyload If set to true a string object is returned instead of
6855 * the string itself. The string then isn't calculated until it is first used.
6856 * @return string The localized string.
6857 * @throws coding_exception
6859 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6862 // If the lazy load argument has been supplied return a lang_string object
6864 // We need to make sure it is true (and a bool) as you will see below there
6865 // used to be a forth argument at one point.
6866 if ($lazyload === true) {
6867 return new lang_string($identifier, $component, $a);
6870 if ($CFG->debugdeveloper
&& clean_param($identifier, PARAM_STRINGID
) === '') {
6871 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER
);
6874 // There is now a forth argument again, this time it is a boolean however so
6875 // we can still check for the old extralocations parameter.
6876 if (!is_bool($lazyload) && !empty($lazyload)) {
6877 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6880 if (strpos($component, '/') !== false) {
6881 debugging('The module name you passed to get_string is the deprecated format ' .
6882 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER
);
6883 $componentpath = explode('/', $component);
6885 switch ($componentpath[0]) {
6887 $component = $componentpath[1];
6891 $component = 'block_'.$componentpath[1];
6894 $component = 'enrol_'.$componentpath[1];
6897 $component = 'format_'.$componentpath[1];
6900 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6905 $result = get_string_manager()->get_string($identifier, $component, $a);
6907 // Debugging feature lets you display string identifier and component.
6908 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
6909 $result .= ' {' . $identifier . '/' . $component . '}';
6915 * Converts an array of strings to their localized value.
6917 * @param array $array An array of strings
6918 * @param string $component The language module that these strings can be found in.
6919 * @return stdClass translated strings.
6921 function get_strings($array, $component = '') {
6922 $string = new stdClass
;
6923 foreach ($array as $item) {
6924 $string->$item = get_string($item, $component);
6930 * Prints out a translated string.
6932 * Prints out a translated string using the return value from the {@link get_string()} function.
6934 * Example usage of this function when the string is in the moodle.php file:<br/>
6937 * print_string('course');
6941 * Example usage of this function when the string is not in the moodle.php file:<br/>
6944 * print_string('typecourse', 'calendar');
6949 * @param string $identifier The key identifier for the localized string
6950 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6951 * @param string|object|array $a An object, string or number that can be used within translation strings
6953 function print_string($identifier, $component = '', $a = null) {
6954 echo get_string($identifier, $component, $a);
6958 * Returns a list of charset codes
6960 * Returns a list of charset codes. It's hardcoded, so they should be added manually
6961 * (checking that such charset is supported by the texlib library!)
6963 * @return array And associative array with contents in the form of charset => charset
6965 function get_list_of_charsets() {
6968 'EUC-JP' => 'EUC-JP',
6969 'ISO-2022-JP'=> 'ISO-2022-JP',
6970 'ISO-8859-1' => 'ISO-8859-1',
6971 'SHIFT-JIS' => 'SHIFT-JIS',
6972 'GB2312' => 'GB2312',
6973 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
6974 'UTF-8' => 'UTF-8');
6982 * Returns a list of valid and compatible themes
6986 function get_list_of_themes() {
6991 if (!empty($CFG->themelist
)) { // Use admin's list of themes.
6992 $themelist = explode(',', $CFG->themelist
);
6994 $themelist = array_keys(core_component
::get_plugin_list("theme"));
6997 foreach ($themelist as $key => $themename) {
6998 $theme = theme_config
::load($themename);
6999 $themes[$themename] = $theme;
7002 core_collator
::asort_objects_by_method($themes, 'get_theme_name');
7008 * Returns a list of timezones in the current language
7012 function get_list_of_timezones() {
7017 if (!empty($timezones)) { // This function has been called recently.
7021 $timezones = array();
7023 if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
7024 foreach ($rawtimezones as $timezone) {
7025 if (!empty($timezone->name
)) {
7026 if (get_string_manager()->string_exists(strtolower($timezone->name
), 'timezones')) {
7027 $timezones[$timezone->name
] = get_string(strtolower($timezone->name
), 'timezones');
7029 $timezones[$timezone->name
] = $timezone->name
;
7031 if (substr($timezones[$timezone->name
], 0, 1) == '[') { // No translation found.
7032 $timezones[$timezone->name
] = $timezone->name
;
7040 for ($i = -13; $i <= 13; $i +
= .5) {
7043 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
7044 } else if ($i > 0) {
7045 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
7047 $timezones[sprintf("%.1f", $i)] = $tzstring;
7055 * Factory function for emoticon_manager
7057 * @return emoticon_manager singleton
7059 function get_emoticon_manager() {
7060 static $singleton = null;
7062 if (is_null($singleton)) {
7063 $singleton = new emoticon_manager();
7070 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7072 * Whenever this manager mentiones 'emoticon object', the following data
7073 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7074 * altidentifier and altcomponent
7076 * @see admin_setting_emoticons
7078 * @copyright 2010 David Mudrak
7079 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7081 class emoticon_manager
{
7084 * Returns the currently enabled emoticons
7086 * @return array of emoticon objects
7088 public function get_emoticons() {
7091 if (empty($CFG->emoticons
)) {
7095 $emoticons = $this->decode_stored_config($CFG->emoticons
);
7097 if (!is_array($emoticons)) {
7098 // Something is wrong with the format of stored setting.
7099 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL
);
7107 * Converts emoticon object into renderable pix_emoticon object
7109 * @param stdClass $emoticon emoticon object
7110 * @param array $attributes explicit HTML attributes to set
7111 * @return pix_emoticon
7113 public function prepare_renderable_emoticon(stdClass
$emoticon, array $attributes = array()) {
7114 $stringmanager = get_string_manager();
7115 if ($stringmanager->string_exists($emoticon->altidentifier
, $emoticon->altcomponent
)) {
7116 $alt = get_string($emoticon->altidentifier
, $emoticon->altcomponent
);
7118 $alt = s($emoticon->text
);
7120 return new pix_emoticon($emoticon->imagename
, $alt, $emoticon->imagecomponent
, $attributes);
7124 * Encodes the array of emoticon objects into a string storable in config table
7126 * @see self::decode_stored_config()
7127 * @param array $emoticons array of emtocion objects
7130 public function encode_stored_config(array $emoticons) {
7131 return json_encode($emoticons);
7135 * Decodes the string into an array of emoticon objects
7137 * @see self::encode_stored_config()
7138 * @param string $encoded
7139 * @return string|null
7141 public function decode_stored_config($encoded) {
7142 $decoded = json_decode($encoded);
7143 if (!is_array($decoded)) {
7150 * Returns default set of emoticons supported by Moodle
7152 * @return array of sdtClasses
7154 public function default_emoticons() {
7156 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7157 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7158 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7159 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7160 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7161 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7162 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7163 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7164 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7165 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7166 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7167 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7168 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7169 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7170 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7171 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7172 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7173 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7174 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7175 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7176 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7177 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7178 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7179 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7180 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7181 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7182 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7183 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7184 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7185 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7190 * Helper method preparing the stdClass with the emoticon properties
7192 * @param string|array $text or array of strings
7193 * @param string $imagename to be used by {@link pix_emoticon}
7194 * @param string $altidentifier alternative string identifier, null for no alt
7195 * @param string $altcomponent where the alternative string is defined
7196 * @param string $imagecomponent to be used by {@link pix_emoticon}
7199 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7200 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7201 return (object)array(
7203 'imagename' => $imagename,
7204 'imagecomponent' => $imagecomponent,
7205 'altidentifier' => $altidentifier,
7206 'altcomponent' => $altcomponent,
7216 * @param string $data Data to encrypt.
7217 * @return string The now encrypted data.
7219 function rc4encrypt($data) {
7220 return endecrypt(get_site_identifier(), $data, '');
7226 * @param string $data Data to decrypt.
7227 * @return string The now decrypted data.
7229 function rc4decrypt($data) {
7230 return endecrypt(get_site_identifier(), $data, 'de');
7234 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7236 * @todo Finish documenting this function
7238 * @param string $pwd The password to use when encrypting or decrypting
7239 * @param string $data The data to be decrypted/encrypted
7240 * @param string $case Either 'de' for decrypt or '' for encrypt
7243 function endecrypt ($pwd, $data, $case) {
7245 if ($case == 'de') {
7246 $data = urldecode($data);
7251 $pwdlength = strlen($pwd);
7253 for ($i = 0; $i <= 255; $i++
) {
7254 $key[$i] = ord(substr($pwd, ($i %
$pwdlength), 1));
7260 for ($i = 0; $i <= 255; $i++
) {
7261 $x = ($x +
$box[$i] +
$key[$i]) %
256;
7262 $tempswap = $box[$i];
7263 $box[$i] = $box[$x];
7264 $box[$x] = $tempswap;
7272 for ($i = 0; $i < strlen($data); $i++
) {
7273 $a = ($a +
1) %
256;
7274 $j = ($j +
$box[$a]) %
256;
7276 $box[$a] = $box[$j];
7278 $k = $box[(($box[$a] +
$box[$j]) %
256)];
7279 $cipherby = ord(substr($data, $i, 1)) ^
$k;
7280 $cipher .= chr($cipherby);
7283 if ($case == 'de') {
7284 $cipher = urldecode(urlencode($cipher));
7286 $cipher = urlencode($cipher);
7292 // ENVIRONMENT CHECKING.
7295 * This method validates a plug name. It is much faster than calling clean_param.
7297 * @param string $name a string that might be a plugin name.
7298 * @return bool if this string is a valid plugin name.
7300 function is_valid_plugin_name($name) {
7301 // This does not work for 'mod', bad luck, use any other type.
7302 return core_component
::is_valid_plugin_name('tool', $name);
7306 * Get a list of all the plugins of a given type that define a certain API function
7307 * in a certain file. The plugin component names and function names are returned.
7309 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7310 * @param string $function the part of the name of the function after the
7311 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7312 * names like report_courselist_hook.
7313 * @param string $file the name of file within the plugin that defines the
7314 * function. Defaults to lib.php.
7315 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7316 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7318 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7319 $pluginfunctions = array();
7320 $pluginswithfile = core_component
::get_plugin_list_with_file($plugintype, $file, true);
7321 foreach ($pluginswithfile as $plugin => $notused) {
7322 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7324 if (function_exists($fullfunction)) {
7325 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7326 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
7328 } else if ($plugintype === 'mod') {
7329 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7330 $shortfunction = $plugin . '_' . $function;
7331 if (function_exists($shortfunction)) {
7332 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
7336 return $pluginfunctions;
7340 * Lists plugin-like directories within specified directory
7342 * This function was originally used for standard Moodle plugins, please use
7343 * new core_component::get_plugin_list() now.
7345 * This function is used for general directory listing and backwards compatility.
7347 * @param string $directory relative directory from root
7348 * @param string $exclude dir name to exclude from the list (defaults to none)
7349 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7350 * @return array Sorted array of directory names found under the requested parameters
7352 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7357 if (empty($basedir)) {
7358 $basedir = $CFG->dirroot
.'/'. $directory;
7361 $basedir = $basedir .'/'. $directory;
7364 if ($CFG->debugdeveloper
and empty($exclude)) {
7365 // Make sure devs do not use this to list normal plugins,
7366 // this is intended for general directories that are not plugins!
7368 $subtypes = core_component
::get_plugin_types();
7369 if (in_array($basedir, $subtypes)) {
7370 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER
);
7375 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7376 if (!$dirhandle = opendir($basedir)) {
7377 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER
);
7380 while (false !== ($dir = readdir($dirhandle))) {
7381 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7382 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7383 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7386 if (filetype($basedir .'/'. $dir) != 'dir') {
7391 closedir($dirhandle);
7400 * Invoke plugin's callback functions
7402 * @param string $type plugin type e.g. 'mod'
7403 * @param string $name plugin name
7404 * @param string $feature feature name
7405 * @param string $action feature's action
7406 * @param array $params parameters of callback function, should be an array
7407 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7410 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7412 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7413 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7417 * Invoke component's callback functions
7419 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7420 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7421 * @param array $params parameters of callback function
7422 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7425 function component_callback($component, $function, array $params = array(), $default = null) {
7427 $functionname = component_callback_exists($component, $function);
7429 if ($functionname) {
7430 // Function exists, so just return function result.
7431 $ret = call_user_func_array($functionname, $params);
7432 if (is_null($ret)) {
7442 * Determine if a component callback exists and return the function name to call. Note that this
7443 * function will include the required library files so that the functioname returned can be
7446 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7447 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7448 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7449 * @throws coding_exception if invalid component specfied
7451 function component_callback_exists($component, $function) {
7452 global $CFG; // This is needed for the inclusions.
7454 $cleancomponent = clean_param($component, PARAM_COMPONENT
);
7455 if (empty($cleancomponent)) {
7456 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7458 $component = $cleancomponent;
7460 list($type, $name) = core_component
::normalize_component($component);
7461 $component = $type . '_' . $name;
7463 $oldfunction = $name.'_'.$function;
7464 $function = $component.'_'.$function;
7466 $dir = core_component
::get_component_directory($component);
7468 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7471 // Load library and look for function.
7472 if (file_exists($dir.'/lib.php')) {
7473 require_once($dir.'/lib.php');
7476 if (!function_exists($function) and function_exists($oldfunction)) {
7477 if ($type !== 'mod' and $type !== 'core') {
7478 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER
);
7480 $function = $oldfunction;
7483 if (function_exists($function)) {
7490 * Checks whether a plugin supports a specified feature.
7492 * @param string $type Plugin type e.g. 'mod'
7493 * @param string $name Plugin name e.g. 'forum'
7494 * @param string $feature Feature code (FEATURE_xx constant)
7495 * @param mixed $default default value if feature support unknown
7496 * @return mixed Feature result (false if not supported, null if feature is unknown,
7497 * otherwise usually true but may have other feature-specific value such as array)
7498 * @throws coding_exception
7500 function plugin_supports($type, $name, $feature, $default = null) {
7503 if ($type === 'mod' and $name === 'NEWMODULE') {
7504 // Somebody forgot to rename the module template.
7508 $component = clean_param($type . '_' . $name, PARAM_COMPONENT
);
7509 if (empty($component)) {
7510 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7515 if ($type === 'mod') {
7516 // We need this special case because we support subplugins in modules,
7517 // otherwise it would end up in infinite loop.
7518 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7519 include_once("$CFG->dirroot/mod/$name/lib.php");
7520 $function = $component.'_supports';
7521 if (!function_exists($function)) {
7522 // Legacy non-frankenstyle function name.
7523 $function = $name.'_supports';
7528 if (!$path = core_component
::get_plugin_directory($type, $name)) {
7529 // Non existent plugin type.
7532 if (file_exists("$path/lib.php")) {
7533 include_once("$path/lib.php");
7534 $function = $component.'_supports';
7538 if ($function and function_exists($function)) {
7539 $supports = $function($feature);
7540 if (is_null($supports)) {
7541 // Plugin does not know - use default.
7548 // Plugin does not care, so use default.
7553 * Returns true if the current version of PHP is greater that the specified one.
7555 * @todo Check PHP version being required here is it too low?
7557 * @param string $version The version of php being tested.
7560 function check_php_version($version='5.2.4') {
7561 return (version_compare(phpversion(), $version) >= 0);
7565 * Determine if moodle installation requires update.
7567 * Checks version numbers of main code and all plugins to see
7568 * if there are any mismatches.
7572 function moodle_needs_upgrading() {
7575 if (empty($CFG->version
)) {
7579 // There is no need to purge plugininfo caches here because
7580 // these caches are not used during upgrade and they are purged after
7583 if (empty($CFG->allversionshash
)) {
7587 $hash = core_component
::get_all_versions_hash();
7589 return ($hash !== $CFG->allversionshash
);
7593 * Returns the major version of this site
7595 * Moodle version numbers consist of three numbers separated by a dot, for
7596 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7597 * called major version. This function extracts the major version from either
7598 * $CFG->release (default) or eventually from the $release variable defined in
7599 * the main version.php.
7601 * @param bool $fromdisk should the version if source code files be used
7602 * @return string|false the major version like '2.3', false if could not be determined
7604 function moodle_major_version($fromdisk = false) {
7609 require($CFG->dirroot
.'/version.php');
7610 if (empty($release)) {
7615 if (empty($CFG->release
)) {
7618 $release = $CFG->release
;
7621 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7631 * Sets the system locale
7634 * @param string $locale Can be used to force a locale
7636 function moodle_setlocale($locale='') {
7639 static $currentlocale = ''; // Last locale caching.
7641 $oldlocale = $currentlocale;
7643 // Fetch the correct locale based on ostype.
7644 if ($CFG->ostype
== 'WINDOWS') {
7645 $stringtofetch = 'localewin';
7647 $stringtofetch = 'locale';
7650 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7651 if (!empty($locale)) {
7652 $currentlocale = $locale;
7653 } else if (!empty($CFG->locale
)) { // Override locale for all language packs.
7654 $currentlocale = $CFG->locale
;
7656 $currentlocale = get_string($stringtofetch, 'langconfig');
7659 // Do nothing if locale already set up.
7660 if ($oldlocale == $currentlocale) {
7664 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7665 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7666 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7668 // Get current values.
7669 $monetary= setlocale (LC_MONETARY
, 0);
7670 $numeric = setlocale (LC_NUMERIC
, 0);
7671 $ctype = setlocale (LC_CTYPE
, 0);
7672 if ($CFG->ostype
!= 'WINDOWS') {
7673 $messages= setlocale (LC_MESSAGES
, 0);
7675 // Set locale to all.
7676 $result = setlocale (LC_ALL
, $currentlocale);
7677 // If setting of locale fails try the other utf8 or utf-8 variant,
7678 // some operating systems support both (Debian), others just one (OSX).
7679 if ($result === false) {
7680 if (stripos($currentlocale, '.UTF-8') !== false) {
7681 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7682 setlocale (LC_ALL
, $newlocale);
7683 } else if (stripos($currentlocale, '.UTF8') !== false) {
7684 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7685 setlocale (LC_ALL
, $newlocale);
7689 setlocale (LC_MONETARY
, $monetary);
7690 setlocale (LC_NUMERIC
, $numeric);
7691 if ($CFG->ostype
!= 'WINDOWS') {
7692 setlocale (LC_MESSAGES
, $messages);
7694 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7695 // To workaround a well-known PHP problem with Turkish letter Ii.
7696 setlocale (LC_CTYPE
, $ctype);
7701 * Count words in a string.
7703 * Words are defined as things between whitespace.
7706 * @param string $string The text to be searched for words.
7707 * @return int The count of words in the specified string
7709 function count_words($string) {
7710 $string = strip_tags($string);
7711 // Decode HTML entities.
7712 $string = html_entity_decode($string);
7713 // Replace underscores (which are classed as word characters) with spaces.
7714 $string = preg_replace('/_/u', ' ', $string);
7715 // Remove any characters that shouldn't be treated as word boundaries.
7716 $string = preg_replace('/[\'’-]/u', '', $string);
7717 // Remove dots and commas from within numbers only.
7718 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7720 return count(preg_split('/\w\b/u', $string)) - 1;
7724 * Count letters in a string.
7726 * Letters are defined as chars not in tags and different from whitespace.
7729 * @param string $string The text to be searched for letters.
7730 * @return int The count of letters in the specified text.
7732 function count_letters($string) {
7733 $string = strip_tags($string); // Tags are out now.
7734 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7736 return core_text
::strlen($string);
7740 * Generate and return a random string of the specified length.
7742 * @param int $length The length of the string to be created.
7745 function random_string ($length=15) {
7746 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7747 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7748 $pool .= '0123456789';
7749 $poollen = strlen($pool);
7751 for ($i = 0; $i < $length; $i++
) {
7752 $string .= substr($pool, (mt_rand()%
($poollen)), 1);
7758 * Generate a complex random string (useful for md5 salts)
7760 * This function is based on the above {@link random_string()} however it uses a
7761 * larger pool of characters and generates a string between 24 and 32 characters
7763 * @param int $length Optional if set generates a string to exactly this length
7766 function complex_random_string($length=null) {
7767 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7768 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7769 $poollen = strlen($pool);
7770 if ($length===null) {
7771 $length = floor(rand(24, 32));
7774 for ($i = 0; $i < $length; $i++
) {
7775 $string .= $pool[(mt_rand()%
$poollen)];
7781 * Given some text (which may contain HTML) and an ideal length,
7782 * this function truncates the text neatly on a word boundary if possible
7785 * @param string $text text to be shortened
7786 * @param int $ideal ideal string length
7787 * @param boolean $exact if false, $text will not be cut mid-word
7788 * @param string $ending The string to append if the passed string is truncated
7789 * @return string $truncate shortened string
7791 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7792 // If the plain text is shorter than the maximum length, return the whole text.
7793 if (core_text
::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7797 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7798 // and only tag in its 'line'.
7799 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER
);
7801 $totallength = core_text
::strlen($ending);
7804 // This array stores information about open and close tags and their position
7805 // in the truncated string. Each item in the array is an object with fields
7806 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7807 // (byte position in truncated text).
7808 $tagdetails = array();
7810 foreach ($lines as $linematchings) {
7811 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7812 if (!empty($linematchings[1])) {
7813 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7814 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7815 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7816 // Record closing tag.
7817 $tagdetails[] = (object) array(
7819 'tag' => core_text
::strtolower($tagmatchings[1]),
7820 'pos' => core_text
::strlen($truncate),
7823 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7824 // Record opening tag.
7825 $tagdetails[] = (object) array(
7827 'tag' => core_text
::strtolower($tagmatchings[1]),
7828 'pos' => core_text
::strlen($truncate),
7832 // Add html-tag to $truncate'd text.
7833 $truncate .= $linematchings[1];
7836 // Calculate the length of the plain text part of the line; handle entities as one character.
7837 $contentlength = core_text
::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7838 if ($totallength +
$contentlength > $ideal) {
7839 // The number of characters which are left.
7840 $left = $ideal - $totallength;
7841 $entitieslength = 0;
7842 // Search for html entities.
7843 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
)) {
7844 // Calculate the real length of all entities in the legal range.
7845 foreach ($entities[0] as $entity) {
7846 if ($entity[1]+
1-$entitieslength <= $left) {
7848 $entitieslength +
= core_text
::strlen($entity[0]);
7850 // No more characters left.
7855 $breakpos = $left +
$entitieslength;
7857 // If the words shouldn't be cut in the middle...
7859 // Search the last occurence of a space.
7860 for (; $breakpos > 0; $breakpos--) {
7861 if ($char = core_text
::substr($linematchings[2], $breakpos, 1)) {
7862 if ($char === '.' or $char === ' ') {
7865 } else if (strlen($char) > 2) {
7866 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7873 if ($breakpos == 0) {
7874 // This deals with the test_shorten_text_no_spaces case.
7875 $breakpos = $left +
$entitieslength;
7876 } else if ($breakpos > $left +
$entitieslength) {
7877 // This deals with the previous for loop breaking on the first char.
7878 $breakpos = $left +
$entitieslength;
7881 $truncate .= core_text
::substr($linematchings[2], 0, $breakpos);
7882 // Maximum length is reached, so get off the loop.
7885 $truncate .= $linematchings[2];
7886 $totallength +
= $contentlength;
7889 // If the maximum length is reached, get off the loop.
7890 if ($totallength >= $ideal) {
7895 // Add the defined ending to the text.
7896 $truncate .= $ending;
7898 // Now calculate the list of open html tags based on the truncate position.
7899 $opentags = array();
7900 foreach ($tagdetails as $taginfo) {
7901 if ($taginfo->open
) {
7902 // Add tag to the beginning of $opentags list.
7903 array_unshift($opentags, $taginfo->tag
);
7905 // Can have multiple exact same open tags, close the last one.
7906 $pos = array_search($taginfo->tag
, array_reverse($opentags, true));
7907 if ($pos !== false) {
7908 unset($opentags[$pos]);
7913 // Close all unclosed html-tags.
7914 foreach ($opentags as $tag) {
7915 $truncate .= '</' . $tag . '>';
7923 * Given dates in seconds, how many weeks is the date from startdate
7924 * The first week is 1, the second 2 etc ...
7926 * @param int $startdate Timestamp for the start date
7927 * @param int $thedate Timestamp for the end date
7930 function getweek ($startdate, $thedate) {
7931 if ($thedate < $startdate) {
7935 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
7939 * Returns a randomly generated password of length $maxlen. inspired by
7941 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
7942 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
7944 * @param int $maxlen The maximum size of the password being generated.
7947 function generate_password($maxlen=10) {
7950 if (empty($CFG->passwordpolicy
)) {
7951 $fillers = PASSWORD_DIGITS
;
7952 $wordlist = file($CFG->wordlist
);
7953 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7954 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7955 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
7956 $password = $word1 . $filler1 . $word2;
7958 $minlen = !empty($CFG->minpasswordlength
) ?
$CFG->minpasswordlength
: 0;
7959 $digits = $CFG->minpassworddigits
;
7960 $lower = $CFG->minpasswordlower
;
7961 $upper = $CFG->minpasswordupper
;
7962 $nonalphanum = $CFG->minpasswordnonalphanum
;
7963 $total = $lower +
$upper +
$digits +
$nonalphanum;
7964 // Var minlength should be the greater one of the two ( $minlen and $total ).
7965 $minlen = $minlen < $total ?
$total : $minlen;
7966 // Var maxlen can never be smaller than minlen.
7967 $maxlen = $minlen > $maxlen ?
$minlen : $maxlen;
7968 $additional = $maxlen - $total;
7970 // Make sure we have enough characters to fulfill
7971 // complexity requirements.
7972 $passworddigits = PASSWORD_DIGITS
;
7973 while ($digits > strlen($passworddigits)) {
7974 $passworddigits .= PASSWORD_DIGITS
;
7976 $passwordlower = PASSWORD_LOWER
;
7977 while ($lower > strlen($passwordlower)) {
7978 $passwordlower .= PASSWORD_LOWER
;
7980 $passwordupper = PASSWORD_UPPER
;
7981 while ($upper > strlen($passwordupper)) {
7982 $passwordupper .= PASSWORD_UPPER
;
7984 $passwordnonalphanum = PASSWORD_NONALPHANUM
;
7985 while ($nonalphanum > strlen($passwordnonalphanum)) {
7986 $passwordnonalphanum .= PASSWORD_NONALPHANUM
;
7989 // Now mix and shuffle it all.
7990 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
7991 substr(str_shuffle ($passwordupper), 0, $upper) .
7992 substr(str_shuffle ($passworddigits), 0, $digits) .
7993 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
7994 substr(str_shuffle ($passwordlower .
7997 $passwordnonalphanum), 0 , $additional));
8000 return substr ($password, 0, $maxlen);
8004 * Given a float, prints it nicely.
8005 * Localized floats must not be used in calculations!
8007 * The stripzeros feature is intended for making numbers look nicer in small
8008 * areas where it is not necessary to indicate the degree of accuracy by showing
8009 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8010 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8012 * @param float $float The float to print
8013 * @param int $decimalpoints The number of decimal places to print.
8014 * @param bool $localized use localized decimal separator
8015 * @param bool $stripzeros If true, removes final zeros after decimal point
8016 * @return string locale float
8018 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8019 if (is_null($float)) {
8023 $separator = get_string('decsep', 'langconfig');
8027 $result = number_format($float, $decimalpoints, $separator, '');
8029 // Remove zeros and final dot if not needed.
8030 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8036 * Converts locale specific floating point/comma number back to standard PHP float value
8037 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8039 * @param string $localefloat locale aware float representation
8040 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8041 * @return mixed float|bool - false or the parsed float.
8043 function unformat_float($localefloat, $strict = false) {
8044 $localefloat = trim($localefloat);
8046 if ($localefloat == '') {
8050 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8051 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8053 if ($strict && !is_numeric($localefloat)) {
8057 return (float)$localefloat;
8061 * Given a simple array, this shuffles it up just like shuffle()
8062 * Unlike PHP's shuffle() this function works on any machine.
8064 * @param array $array The array to be rearranged
8067 function swapshuffle($array) {
8069 $last = count($array) - 1;
8070 for ($i = 0; $i <= $last; $i++
) {
8071 $from = rand(0, $last);
8073 $array[$i] = $array[$from];
8074 $array[$from] = $curr;
8080 * Like {@link swapshuffle()}, but works on associative arrays
8082 * @param array $array The associative array to be rearranged
8085 function swapshuffle_assoc($array) {
8087 $newarray = array();
8088 $newkeys = swapshuffle(array_keys($array));
8090 foreach ($newkeys as $newkey) {
8091 $newarray[$newkey] = $array[$newkey];
8097 * Given an arbitrary array, and a number of draws,
8098 * this function returns an array with that amount
8099 * of items. The indexes are retained.
8101 * @todo Finish documenting this function
8103 * @param array $array
8107 function draw_rand_array($array, $draws) {
8111 $last = count($array);
8113 if ($draws > $last) {
8117 while ($draws > 0) {
8120 $keys = array_keys($array);
8121 $rand = rand(0, $last);
8123 $return[$keys[$rand]] = $array[$keys[$rand]];
8124 unset($array[$keys[$rand]]);
8133 * Calculate the difference between two microtimes
8135 * @param string $a The first Microtime
8136 * @param string $b The second Microtime
8139 function microtime_diff($a, $b) {
8140 list($adec, $asec) = explode(' ', $a);
8141 list($bdec, $bsec) = explode(' ', $b);
8142 return $bsec - $asec +
$bdec - $adec;
8146 * Given a list (eg a,b,c,d,e) this function returns
8147 * an array of 1->a, 2->b, 3->c etc
8149 * @param string $list The string to explode into array bits
8150 * @param string $separator The separator used within the list string
8151 * @return array The now assembled array
8153 function make_menu_from_list($list, $separator=',') {
8155 $array = array_reverse(explode($separator, $list), true);
8156 foreach ($array as $key => $item) {
8157 $outarray[$key+
1] = trim($item);
8163 * Creates an array that represents all the current grades that
8164 * can be chosen using the given grading type.
8167 * are scales, zero is no grade, and positive numbers are maximum
8170 * @todo Finish documenting this function or better deprecated this completely!
8172 * @param int $gradingtype
8175 function make_grades_menu($gradingtype) {
8179 if ($gradingtype < 0) {
8180 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8181 return make_menu_from_list($scale->scale
);
8183 } else if ($gradingtype > 0) {
8184 for ($i=$gradingtype; $i>=0; $i--) {
8185 $grades[$i] = $i .' / '. $gradingtype;
8193 * This function returns the number of activities using the given scale in the given course.
8195 * @param int $courseid The course ID to check.
8196 * @param int $scaleid The scale ID to check
8199 function course_scale_used($courseid, $scaleid) {
8204 if (!empty($scaleid)) {
8205 if ($cms = get_course_mods($courseid)) {
8206 foreach ($cms as $cm) {
8207 // Check cm->name/lib.php exists.
8208 if (file_exists($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php')) {
8209 include_once($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php');
8210 $functionname = $cm->modname
.'_scale_used';
8211 if (function_exists($functionname)) {
8212 if ($functionname($cm->instance
, $scaleid)) {
8220 // Check if any course grade item makes use of the scale.
8221 $return +
= $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8223 // Check if any outcome in the course makes use of the scale.
8224 $return +
= $DB->count_records_sql("SELECT COUNT('x')
8225 FROM {grade_outcomes_courses} goc,
8227 WHERE go.id = goc.outcomeid
8228 AND go.scaleid = ? AND goc.courseid = ?",
8229 array($scaleid, $courseid));
8235 * This function returns the number of activities using scaleid in the entire site
8237 * @param int $scaleid
8238 * @param array $courses
8241 function site_scale_used($scaleid, &$courses) {
8244 if (!is_array($courses) ||
count($courses) == 0) {
8245 $courses = get_courses("all", false, "c.id, c.shortname");
8248 if (!empty($scaleid)) {
8249 if (is_array($courses) && count($courses) > 0) {
8250 foreach ($courses as $course) {
8251 $return +
= course_scale_used($course->id
, $scaleid);
8259 * make_unique_id_code
8261 * @todo Finish documenting this function
8264 * @param string $extra Extra string to append to the end of the code
8267 function make_unique_id_code($extra = '') {
8269 $hostname = 'unknownhost';
8270 if (!empty($_SERVER['HTTP_HOST'])) {
8271 $hostname = $_SERVER['HTTP_HOST'];
8272 } else if (!empty($_ENV['HTTP_HOST'])) {
8273 $hostname = $_ENV['HTTP_HOST'];
8274 } else if (!empty($_SERVER['SERVER_NAME'])) {
8275 $hostname = $_SERVER['SERVER_NAME'];
8276 } else if (!empty($_ENV['SERVER_NAME'])) {
8277 $hostname = $_ENV['SERVER_NAME'];
8280 $date = gmdate("ymdHis");
8282 $random = random_string(6);
8285 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8287 return $hostname .'+'. $date .'+'. $random;
8293 * Function to check the passed address is within the passed subnet
8295 * The parameter is a comma separated string of subnet definitions.
8296 * Subnet strings can be in one of three formats:
8297 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8298 * 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)
8299 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8300 * Code for type 1 modified from user posted comments by mediator at
8301 * {@link http://au.php.net/manual/en/function.ip2long.php}
8303 * @param string $addr The address you are checking
8304 * @param string $subnetstr The string of subnet addresses
8307 function address_in_subnet($addr, $subnetstr) {
8309 if ($addr == '0.0.0.0') {
8312 $subnets = explode(',', $subnetstr);
8314 $addr = trim($addr);
8315 $addr = cleanremoteaddr($addr, false); // Normalise.
8316 if ($addr === null) {
8319 $addrparts = explode(':', $addr);
8321 $ipv6 = strpos($addr, ':');
8323 foreach ($subnets as $subnet) {
8324 $subnet = trim($subnet);
8325 if ($subnet === '') {
8329 if (strpos($subnet, '/') !== false) {
8330 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8331 list($ip, $mask) = explode('/', $subnet);
8332 $mask = trim($mask);
8333 if (!is_number($mask)) {
8334 continue; // Incorect mask number, eh?
8336 $ip = cleanremoteaddr($ip, false); // Normalise.
8340 if (strpos($ip, ':') !== false) {
8345 if ($mask > 128 or $mask < 0) {
8346 continue; // Nonsense.
8349 return true; // Any address.
8352 if ($ip === $addr) {
8357 $ipparts = explode(':', $ip);
8358 $modulo = $mask %
16;
8359 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8360 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8361 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8365 $pos = ($mask-$modulo)/16;
8366 $ipnet = hexdec($ipparts[$pos]);
8367 $addrnet = hexdec($addrparts[$pos]);
8368 $mask = 0xffff << (16 - $modulo);
8369 if (($addrnet & $mask) == ($ipnet & $mask)) {
8379 if ($mask > 32 or $mask < 0) {
8380 continue; // Nonsense.
8386 if ($ip === $addr) {
8391 $mask = 0xffffffff << (32 - $mask);
8392 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8397 } else if (strpos($subnet, '-') !== false) {
8398 // 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.
8399 $parts = explode('-', $subnet);
8400 if (count($parts) != 2) {
8404 if (strpos($subnet, ':') !== false) {
8409 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8410 if ($ipstart === null) {
8413 $ipparts = explode(':', $ipstart);
8414 $start = hexdec(array_pop($ipparts));
8415 $ipparts[] = trim($parts[1]);
8416 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8417 if ($ipend === null) {
8421 $ipnet = implode(':', $ipparts);
8422 if (strpos($addr, $ipnet) !== 0) {
8425 $ipparts = explode(':', $ipend);
8426 $end = hexdec($ipparts[7]);
8428 $addrend = hexdec($addrparts[7]);
8430 if (($addrend >= $start) and ($addrend <= $end)) {
8439 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8440 if ($ipstart === null) {
8443 $ipparts = explode('.', $ipstart);
8444 $ipparts[3] = trim($parts[1]);
8445 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8446 if ($ipend === null) {
8450 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8456 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8457 if (strpos($subnet, ':') !== false) {
8462 $parts = explode(':', $subnet);
8463 $count = count($parts);
8464 if ($parts[$count-1] === '') {
8465 unset($parts[$count-1]); // Trim trailing :'s.
8467 $subnet = implode('.', $parts);
8469 $isip = cleanremoteaddr($subnet, false); // Normalise.
8470 if ($isip !== null) {
8471 if ($isip === $addr) {
8475 } else if ($count > 8) {
8478 $zeros = array_fill(0, 8-$count, '0');
8479 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8480 if (address_in_subnet($addr, $subnet)) {
8489 $parts = explode('.', $subnet);
8490 $count = count($parts);
8491 if ($parts[$count-1] === '') {
8492 unset($parts[$count-1]); // Trim trailing .
8494 $subnet = implode('.', $parts);
8497 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8498 if ($subnet === $addr) {
8502 } else if ($count > 4) {
8505 $zeros = array_fill(0, 4-$count, '0');
8506 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8507 if (address_in_subnet($addr, $subnet)) {
8518 * For outputting debugging info
8520 * @param string $string The string to write
8521 * @param string $eol The end of line char(s) to use
8522 * @param string $sleep Period to make the application sleep
8523 * This ensures any messages have time to display before redirect
8525 function mtrace($string, $eol="\n", $sleep=0) {
8527 if (defined('STDOUT') and !PHPUNIT_TEST
) {
8528 fwrite(STDOUT
, $string.$eol);
8530 echo $string . $eol;
8535 // Delay to keep message on user's screen in case of subsequent redirect.
8542 * Replace 1 or more slashes or backslashes to 1 slash
8544 * @param string $path The path to strip
8545 * @return string the path with double slashes removed
8547 function cleardoubleslashes ($path) {
8548 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8552 * Is current ip in give list?
8554 * @param string $list
8557 function remoteip_in_list($list) {
8559 $clientip = getremoteaddr(null);
8562 // Ensure access on cli.
8566 $list = explode("\n", $list);
8567 foreach ($list as $subnet) {
8568 $subnet = trim($subnet);
8569 if (address_in_subnet($clientip, $subnet)) {
8578 * Returns most reliable client address
8580 * @param string $default If an address can't be determined, then return this
8581 * @return string The remote IP address
8583 function getremoteaddr($default='0.0.0.0') {
8586 if (empty($CFG->getremoteaddrconf
)) {
8587 // This will happen, for example, before just after the upgrade, as the
8588 // user is redirected to the admin screen.
8589 $variablestoskip = 0;
8591 $variablestoskip = $CFG->getremoteaddrconf
;
8593 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP
)) {
8594 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8595 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8596 return $address ?
$address : $default;
8599 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR
)) {
8600 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8601 $address = cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
8602 return $address ?
$address : $default;
8605 if (!empty($_SERVER['REMOTE_ADDR'])) {
8606 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8607 return $address ?
$address : $default;
8614 * Cleans an ip address. Internal addresses are now allowed.
8615 * (Originally local addresses were not allowed.)
8617 * @param string $addr IPv4 or IPv6 address
8618 * @param bool $compress use IPv6 address compression
8619 * @return string normalised ip address string, null if error
8621 function cleanremoteaddr($addr, $compress=false) {
8622 $addr = trim($addr);
8624 // TODO: maybe add a separate function is_addr_public() or something like this.
8626 if (strpos($addr, ':') !== false) {
8627 // Can be only IPv6.
8628 $parts = explode(':', $addr);
8629 $count = count($parts);
8631 if (strpos($parts[$count-1], '.') !== false) {
8632 // Legacy ipv4 notation.
8633 $last = array_pop($parts);
8634 $ipv4 = cleanremoteaddr($last, true);
8635 if ($ipv4 === null) {
8638 $bits = explode('.', $ipv4);
8639 $parts[] = dechex($bits[0]).dechex($bits[1]);
8640 $parts[] = dechex($bits[2]).dechex($bits[3]);
8641 $count = count($parts);
8642 $addr = implode(':', $parts);
8645 if ($count < 3 or $count > 8) {
8646 return null; // Severly malformed.
8650 if (strpos($addr, '::') === false) {
8651 return null; // Malformed.
8654 $insertat = array_search('', $parts, true);
8655 $missing = array_fill(0, 1 +
8 - $count, '0');
8656 array_splice($parts, $insertat, 1, $missing);
8657 foreach ($parts as $key => $part) {
8664 $adr = implode(':', $parts);
8665 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8666 return null; // Incorrect format - sorry.
8669 // Normalise 0s and case.
8670 $parts = array_map('hexdec', $parts);
8671 $parts = array_map('dechex', $parts);
8673 $result = implode(':', $parts);
8679 if ($result === '0:0:0:0:0:0:0:0') {
8680 return '::'; // All addresses.
8683 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8684 if ($compressed !== $result) {
8688 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8689 if ($compressed !== $result) {
8693 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8694 if ($compressed !== $result) {
8701 // First get all things that look like IPv4 addresses.
8703 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8708 foreach ($parts as $key => $match) {
8712 $parts[$key] = (int)$match; // Normalise 0s.
8715 return implode('.', $parts);
8719 * This function will make a complete copy of anything it's given,
8720 * regardless of whether it's an object or not.
8722 * @param mixed $thing Something you want cloned
8723 * @return mixed What ever it is you passed it
8725 function fullclone($thing) {
8726 return unserialize(serialize($thing));
8730 * If new messages are waiting for the current user, then insert
8731 * JavaScript to pop up the messaging window into the page
8735 function message_popup_window() {
8736 global $USER, $DB, $PAGE, $CFG;
8738 if (!$PAGE->get_popup_notification_allowed() ||
empty($CFG->messaging
)) {
8742 if (!isloggedin() ||
isguestuser()) {
8746 if (!isset($USER->message_lastpopup
)) {
8747 $USER->message_lastpopup
= 0;
8748 } else if ($USER->message_lastpopup
> (time()-120)) {
8749 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8753 // A quick query to check whether the user has new messages.
8754 $messagecount = $DB->count_records('message', array('useridto' => $USER->id
));
8755 if ($messagecount < 1) {
8759 // There are unread messages so now do a more complex but slower query.
8760 $messagesql = "SELECT m.id, c.blocked
8762 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8763 JOIN {message_processors} p ON mw.processorid=p.id
8764 JOIN {user} u ON m.useridfrom=u.id
8765 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8766 AND c.userid = m.useridto
8767 WHERE m.useridto = :userid
8768 AND p.name='popup'";
8770 // If the user was last notified over an hour ago we can re-notify them of old messages
8771 // so don't worry about when the new message was sent.
8772 $lastnotifiedlongago = $USER->message_lastpopup
< (time()-3600);
8773 if (!$lastnotifiedlongago) {
8774 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8777 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id
, 'lastpopuptime' => $USER->message_lastpopup
));
8780 foreach ($waitingmessages as $messageinfo) {
8781 if ($messageinfo->blocked
) {
8782 // Message is from a user who has since been blocked so just mark it read.
8783 // Get the full message to mark as read.
8784 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id
));
8785 message_mark_message_read($messageobject, time());
8791 if ($validmessages > 0) {
8792 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8793 $strgomessage = get_string('gotomessages', 'message');
8794 $strstaymessage = get_string('ignore', 'admin');
8796 $notificationsound = null;
8797 $beep = get_user_preferences('message_beepnewmessage', '');
8798 if (!empty($beep)) {
8799 // Browsers will work down this list until they find something they support.
8800 $sourcetags = html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.wav', 'type' => 'audio/wav'));
8801 $sourcetags .= html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.ogg', 'type' => 'audio/ogg'));
8802 $sourcetags .= html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8803 $sourcetags .= html_writer
::empty_tag('embed', array('src' => $CFG->wwwroot
.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8805 $notificationsound = html_writer
::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8808 $url = $CFG->wwwroot
.'/message/index.php';
8809 $content = html_writer
::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8810 html_writer
::start_tag('div', array('id' => 'newmessagetext')).
8812 html_writer
::end_tag('div').
8815 html_writer
::start_tag('div', array('id' => 'newmessagelinks')).
8816 html_writer
::link($url, $strgomessage, array('id' => 'notificationyes')).' '.
8817 html_writer
::link('', $strstaymessage, array('id' => 'notificationno')).
8818 html_writer
::end_tag('div');
8819 html_writer
::end_tag('div');
8821 $PAGE->requires
->js_init_call('M.core_message.init_notification', array('', $content, $url));
8823 $USER->message_lastpopup
= time();
8828 * Used to make sure that $min <= $value <= $max
8830 * Make sure that value is between min, and max
8832 * @param int $min The minimum value
8833 * @param int $value The value to check
8834 * @param int $max The maximum value
8837 function bounded_number($min, $value, $max) {
8838 if ($value < $min) {
8841 if ($value > $max) {
8848 * Check if there is a nested array within the passed array
8850 * @param array $array
8851 * @return bool true if there is a nested array false otherwise
8853 function array_is_nested($array) {
8854 foreach ($array as $value) {
8855 if (is_array($value)) {
8863 * get_performance_info() pairs up with init_performance_info()
8864 * loaded in setup.php. Returns an array with 'html' and 'txt'
8865 * values ready for use, and each of the individual stats provided
8866 * separately as well.
8870 function get_performance_info() {
8871 global $CFG, $PERF, $DB, $PAGE;
8874 $info['html'] = ''; // Holds userfriendly HTML representation.
8875 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8877 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
8879 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8880 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8882 if (function_exists('memory_get_usage')) {
8883 $info['memory_total'] = memory_get_usage();
8884 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
8885 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8886 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8887 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8890 if (function_exists('memory_get_peak_usage')) {
8891 $info['memory_peak'] = memory_get_peak_usage();
8892 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8893 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8896 $inc = get_included_files();
8897 $info['includecount'] = count($inc);
8898 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8899 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8901 if (!empty($CFG->early_install_lang
) or empty($PAGE)) {
8902 // We can not track more performance before installation or before PAGE init, sorry.
8906 $filtermanager = filter_manager
::instance();
8907 if (method_exists($filtermanager, 'get_performance_summary')) {
8908 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8909 $info = array_merge($filterinfo, $info);
8910 foreach ($filterinfo as $key => $value) {
8911 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8912 $info['txt'] .= "$key: $value ";
8916 $stringmanager = get_string_manager();
8917 if (method_exists($stringmanager, 'get_performance_summary')) {
8918 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8919 $info = array_merge($filterinfo, $info);
8920 foreach ($filterinfo as $key => $value) {
8921 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8922 $info['txt'] .= "$key: $value ";
8926 if (!empty($PERF->logwrites
)) {
8927 $info['logwrites'] = $PERF->logwrites
;
8928 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8929 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8932 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites
);
8933 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
8934 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8936 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
8937 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
8938 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
8940 if (function_exists('posix_times')) {
8941 $ptimes = posix_times();
8942 if (is_array($ptimes)) {
8943 foreach ($ptimes as $key => $val) {
8944 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
8946 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
8947 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8951 // Grab the load average for the last minute.
8952 // /proc will only work under some linux configurations
8953 // while uptime is there under MacOSX/Darwin and other unices.
8954 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
8955 list($serverload) = explode(' ', $loadavg[0]);
8957 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
8958 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
8959 $serverload = $matches[1];
8961 trigger_error('Could not parse uptime output!');
8964 if (!empty($serverload)) {
8965 $info['serverload'] = $serverload;
8966 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
8967 $info['txt'] .= "serverload: {$info['serverload']} ";
8970 // Display size of session if session started.
8971 if ($si = \core\session\manager
::get_performance_info()) {
8972 $info['sessionsize'] = $si['size'];
8973 $info['html'] .= $si['html'];
8974 $info['txt'] .= $si['txt'];
8977 if ($stats = cache_helper
::get_stats()) {
8978 $html = '<span class="cachesused">';
8979 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
8980 $text = 'Caches used (hits/misses/sets): ';
8984 foreach ($stats as $definition => $stores) {
8985 $html .= '<span class="cache-definition-stats">';
8986 $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
8987 $text .= "$definition {";
8988 foreach ($stores as $store => $data) {
8989 $hits +
= $data['hits'];
8990 $misses +
= $data['misses'];
8991 $sets +
= $data['sets'];
8992 if ($data['hits'] == 0 and $data['misses'] > 0) {
8993 $cachestoreclass = 'nohits';
8994 } else if ($data['hits'] < $data['misses']) {
8995 $cachestoreclass = 'lowhits';
8997 $cachestoreclass = 'hihits';
8999 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9000 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
9005 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
9006 $html .= '</span> ';
9007 $info['cachesused'] = "$hits / $misses / $sets";
9008 $info['html'] .= $html;
9009 $info['txt'] .= $text.'. ';
9011 $info['cachesused'] = '0 / 0 / 0';
9012 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
9013 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9016 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
9023 * @todo Document this function linux people
9025 function apd_get_profiling() {
9026 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
9030 * Delete directory or only its content
9032 * @param string $dir directory path
9033 * @param bool $contentonly
9034 * @return bool success, true also if dir does not exist
9036 function remove_dir($dir, $contentonly=false) {
9037 if (!file_exists($dir)) {
9041 if (!$handle = opendir($dir)) {
9045 while (false!==($item = readdir($handle))) {
9046 if ($item != '.' && $item != '..') {
9047 if (is_dir($dir.'/'.$item)) {
9048 $result = remove_dir($dir.'/'.$item) && $result;
9050 $result = unlink($dir.'/'.$item) && $result;
9056 clearstatcache(); // Make sure file stat cache is properly invalidated.
9059 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9060 clearstatcache(); // Make sure file stat cache is properly invalidated.
9065 * Detect if an object or a class contains a given property
9066 * will take an actual object or the name of a class
9068 * @param mix $obj Name of class or real object to test
9069 * @param string $property name of property to find
9070 * @return bool true if property exists
9072 function object_property_exists( $obj, $property ) {
9073 if (is_string( $obj )) {
9074 $properties = get_class_vars( $obj );
9076 $properties = get_object_vars( $obj );
9078 return array_key_exists( $property, $properties );
9082 * Converts an object into an associative array
9084 * This function converts an object into an associative array by iterating
9085 * over its public properties. Because this function uses the foreach
9086 * construct, Iterators are respected. It works recursively on arrays of objects.
9087 * Arrays and simple values are returned as is.
9089 * If class has magic properties, it can implement IteratorAggregate
9090 * and return all available properties in getIterator()
9095 function convert_to_array($var) {
9098 // Loop over elements/properties.
9099 foreach ($var as $key => $value) {
9100 // Recursively convert objects.
9101 if (is_object($value) ||
is_array($value)) {
9102 $result[$key] = convert_to_array($value);
9104 // Simple values are untouched.
9105 $result[$key] = $value;
9112 * Detect a custom script replacement in the data directory that will
9113 * replace an existing moodle script
9115 * @return string|bool full path name if a custom script exists, false if no custom script exists
9117 function custom_script_path() {
9118 global $CFG, $SCRIPT;
9120 if ($SCRIPT === null) {
9121 // Probably some weird external script.
9125 $scriptpath = $CFG->customscripts
. $SCRIPT;
9127 // Check the custom script exists.
9128 if (file_exists($scriptpath) and is_file($scriptpath)) {
9136 * Returns whether or not the user object is a remote MNET user. This function
9137 * is in moodlelib because it does not rely on loading any of the MNET code.
9139 * @param object $user A valid user object
9140 * @return bool True if the user is from a remote Moodle.
9142 function is_mnet_remote_user($user) {
9145 if (!isset($CFG->mnet_localhost_id
)) {
9146 include_once($CFG->dirroot
. '/mnet/lib.php');
9147 $env = new mnet_environment();
9152 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
9156 * This function will search for browser prefereed languages, setting Moodle
9157 * to use the best one available if $SESSION->lang is undefined
9159 function setup_lang_from_browser() {
9160 global $CFG, $SESSION, $USER;
9162 if (!empty($SESSION->lang
) or !empty($USER->lang
) or empty($CFG->autolang
)) {
9163 // Lang is defined in session or user profile, nothing to do.
9167 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9171 // Extract and clean langs from headers.
9172 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9173 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9174 $rawlangs = explode(',', $rawlangs); // Convert to array.
9178 foreach ($rawlangs as $lang) {
9179 if (strpos($lang, ';') === false) {
9180 $langs[(string)$order] = $lang;
9181 $order = $order-0.01;
9183 $parts = explode(';', $lang);
9184 $pos = strpos($parts[1], '=');
9185 $langs[substr($parts[1], $pos+
1)] = $parts[0];
9188 krsort($langs, SORT_NUMERIC
);
9190 // Look for such langs under standard locations.
9191 foreach ($langs as $lang) {
9192 // Clean it properly for include.
9193 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR
));
9194 if (get_string_manager()->translation_exists($lang, false)) {
9195 // Lang exists, set it in session.
9196 $SESSION->lang
= $lang;
9197 // We have finished. Go out.
9205 * Check if $url matches anything in proxybypass list
9207 * Any errors just result in the proxy being used (least bad)
9209 * @param string $url url to check
9210 * @return boolean true if we should bypass the proxy
9212 function is_proxybypass( $url ) {
9216 if (empty($CFG->proxyhost
) or empty($CFG->proxybypass
)) {
9220 // Get the host part out of the url.
9221 if (!$host = parse_url( $url, PHP_URL_HOST
)) {
9225 // Get the possible bypass hosts into an array.
9226 $matches = explode( ',', $CFG->proxybypass
);
9228 // Check for a match.
9229 // (IPs need to match the left hand side and hosts the right of the url,
9230 // but we can recklessly check both as there can't be a false +ve).
9231 foreach ($matches as $match) {
9232 $match = trim($match);
9234 // Try for IP match (Left side).
9235 $lhs = substr($host, 0, strlen($match));
9236 if (strcasecmp($match, $lhs)==0) {
9240 // Try for host match (Right side).
9241 $rhs = substr($host, -strlen($match));
9242 if (strcasecmp($match, $rhs)==0) {
9252 * Check if the passed navigation is of the new style
9254 * @param mixed $navigation
9255 * @return bool true for yes false for no
9257 function is_newnav($navigation) {
9258 if (is_array($navigation) && !empty($navigation['newnav'])) {
9266 * Checks whether the given variable name is defined as a variable within the given object.
9268 * This will NOT work with stdClass objects, which have no class variables.
9270 * @param string $var The variable name
9271 * @param object $object The object to check
9274 function in_object_vars($var, $object) {
9275 $classvars = get_class_vars(get_class($object));
9276 $classvars = array_keys($classvars);
9277 return in_array($var, $classvars);
9281 * Returns an array without repeated objects.
9282 * This function is similar to array_unique, but for arrays that have objects as values
9284 * @param array $array
9285 * @param bool $keepkeyassoc
9288 function object_array_unique($array, $keepkeyassoc = true) {
9289 $duplicatekeys = array();
9292 foreach ($array as $key => $val) {
9293 // Convert objects to arrays, in_array() does not support objects.
9294 if (is_object($val)) {
9298 if (!in_array($val, $tmp)) {
9301 $duplicatekeys[] = $key;
9305 foreach ($duplicatekeys as $key) {
9306 unset($array[$key]);
9309 return $keepkeyassoc ?
$array : array_values($array);
9313 * Is a userid the primary administrator?
9315 * @param int $userid int id of user to check
9318 function is_primary_admin($userid) {
9319 $primaryadmin = get_admin();
9321 if ($userid == $primaryadmin->id
) {
9329 * Returns the site identifier
9331 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9333 function get_site_identifier() {
9335 // Check to see if it is missing. If so, initialise it.
9336 if (empty($CFG->siteidentifier
)) {
9337 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9340 return $CFG->siteidentifier
;
9344 * Check whether the given password has no more than the specified
9345 * number of consecutive identical characters.
9347 * @param string $password password to be checked against the password policy
9348 * @param integer $maxchars maximum number of consecutive identical characters
9351 function check_consecutive_identical_characters($password, $maxchars) {
9353 if ($maxchars < 1) {
9354 return true; // Zero 0 is to disable this check.
9356 if (strlen($password) <= $maxchars) {
9357 return true; // Too short to fail this test.
9361 $consecutivecount = 1;
9362 foreach (str_split($password) as $char) {
9363 if ($char != $previouschar) {
9364 $consecutivecount = 1;
9366 $consecutivecount++
;
9367 if ($consecutivecount > $maxchars) {
9368 return false; // Check failed already.
9372 $previouschar = $char;
9379 * Helper function to do partial function binding.
9380 * so we can use it for preg_replace_callback, for example
9381 * this works with php functions, user functions, static methods and class methods
9382 * it returns you a callback that you can pass on like so:
9384 * $callback = partial('somefunction', $arg1, $arg2);
9386 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9388 * $obj = new someclass();
9389 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9391 * and then the arguments that are passed through at calltime are appended to the argument list.
9393 * @param mixed $function a php callback
9394 * @param mixed $arg1,... $argv arguments to partially bind with
9395 * @return array Array callback
9397 function partial() {
9398 if (!class_exists('partial')) {
9400 * Used to manage function binding.
9401 * @copyright 2009 Penny Leach
9402 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9406 public $values = array();
9407 /** @var string The function to call as a callback. */
9411 * @param string $func
9412 * @param array $args
9414 public function __construct($func, $args) {
9415 $this->values
= $args;
9416 $this->func
= $func;
9419 * Calls the callback function.
9422 public function method() {
9423 $args = func_get_args();
9424 return call_user_func_array($this->func
, array_merge($this->values
, $args));
9428 $args = func_get_args();
9429 $func = array_shift($args);
9430 $p = new partial($func, $args);
9431 return array($p, 'method');
9435 * helper function to load up and initialise the mnet environment
9436 * this must be called before you use mnet functions.
9438 * @return mnet_environment the equivalent of old $MNET global
9440 function get_mnet_environment() {
9442 require_once($CFG->dirroot
. '/mnet/lib.php');
9443 static $instance = null;
9444 if (empty($instance)) {
9445 $instance = new mnet_environment();
9452 * during xmlrpc server code execution, any code wishing to access
9453 * information about the remote peer must use this to get it.
9455 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9457 function get_mnet_remote_client() {
9458 if (!defined('MNET_SERVER')) {
9459 debugging(get_string('notinxmlrpcserver', 'mnet'));
9462 global $MNET_REMOTE_CLIENT;
9463 if (isset($MNET_REMOTE_CLIENT)) {
9464 return $MNET_REMOTE_CLIENT;
9470 * during the xmlrpc server code execution, this will be called
9471 * to setup the object returned by {@link get_mnet_remote_client}
9473 * @param mnet_remote_client $client the client to set up
9474 * @throws moodle_exception
9476 function set_mnet_remote_client($client) {
9477 if (!defined('MNET_SERVER')) {
9478 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9480 global $MNET_REMOTE_CLIENT;
9481 $MNET_REMOTE_CLIENT = $client;
9485 * return the jump url for a given remote user
9486 * this is used for rewriting forum post links in emails, etc
9488 * @param stdclass $user the user to get the idp url for
9490 function mnet_get_idp_jump_url($user) {
9493 static $mnetjumps = array();
9494 if (!array_key_exists($user->mnethostid
, $mnetjumps)) {
9495 $idp = mnet_get_peer_host($user->mnethostid
);
9496 $idpjumppath = mnet_get_app_jumppath($idp->applicationid
);
9497 $mnetjumps[$user->mnethostid
] = $idp->wwwroot
. $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot
. '&wantsurl=';
9499 return $mnetjumps[$user->mnethostid
];
9503 * Gets the homepage to use for the current user
9505 * @return int One of HOMEPAGE_*
9507 function get_home_page() {
9510 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage
)) {
9511 if ($CFG->defaulthomepage
== HOMEPAGE_MY
) {
9514 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY
);
9517 return HOMEPAGE_SITE
;
9521 * Gets the name of a course to be displayed when showing a list of courses.
9522 * By default this is just $course->fullname but user can configure it. The
9523 * result of this function should be passed through print_string.
9524 * @param stdClass|course_in_list $course Moodle course object
9525 * @return string Display name of course (either fullname or short + fullname)
9527 function get_course_display_name_for_list($course) {
9529 if (!empty($CFG->courselistshortnames
)) {
9530 if (!($course instanceof stdClass
)) {
9531 $course = (object)convert_to_array($course);
9533 return get_string('courseextendednamedisplay', '', $course);
9535 return $course->fullname
;
9540 * The lang_string class
9542 * This special class is used to create an object representation of a string request.
9543 * It is special because processing doesn't occur until the object is first used.
9544 * The class was created especially to aid performance in areas where strings were
9545 * required to be generated but were not necessarily used.
9546 * As an example the admin tree when generated uses over 1500 strings, of which
9547 * normally only 1/3 are ever actually printed at any time.
9548 * The performance advantage is achieved by not actually processing strings that
9549 * arn't being used, as such reducing the processing required for the page.
9551 * How to use the lang_string class?
9552 * There are two methods of using the lang_string class, first through the
9553 * forth argument of the get_string function, and secondly directly.
9554 * The following are examples of both.
9555 * 1. Through get_string calls e.g.
9556 * $string = get_string($identifier, $component, $a, true);
9557 * $string = get_string('yes', 'moodle', null, true);
9558 * 2. Direct instantiation
9559 * $string = new lang_string($identifier, $component, $a, $lang);
9560 * $string = new lang_string('yes');
9562 * How do I use a lang_string object?
9563 * The lang_string object makes use of a magic __toString method so that you
9564 * are able to use the object exactly as you would use a string in most cases.
9565 * This means you are able to collect it into a variable and then directly
9566 * echo it, or concatenate it into another string, or similar.
9567 * The other thing you can do is manually get the string by calling the
9568 * lang_strings out method e.g.
9569 * $string = new lang_string('yes');
9571 * Also worth noting is that the out method can take one argument, $lang which
9572 * allows the developer to change the language on the fly.
9574 * When should I use a lang_string object?
9575 * The lang_string object is designed to be used in any situation where a
9576 * string may not be needed, but needs to be generated.
9577 * The admin tree is a good example of where lang_string objects should be
9579 * A more practical example would be any class that requries strings that may
9580 * not be printed (after all classes get renderer by renderers and who knows
9581 * what they will do ;))
9583 * When should I not use a lang_string object?
9584 * Don't use lang_strings when you are going to use a string immediately.
9585 * There is no need as it will be processed immediately and there will be no
9586 * advantage, and in fact perhaps a negative hit as a class has to be
9587 * instantiated for a lang_string object, however get_string won't require
9591 * 1. You cannot use a lang_string object as an array offset. Doing so will
9592 * result in PHP throwing an error. (You can use it as an object property!)
9596 * @copyright 2011 Sam Hemelryk
9597 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9601 /** @var string The strings identifier */
9602 protected $identifier;
9603 /** @var string The strings component. Default '' */
9604 protected $component = '';
9605 /** @var array|stdClass Any arguments required for the string. Default null */
9606 protected $a = null;
9607 /** @var string The language to use when processing the string. Default null */
9608 protected $lang = null;
9610 /** @var string The processed string (once processed) */
9611 protected $string = null;
9614 * A special boolean. If set to true then the object has been woken up and
9615 * cannot be regenerated. If this is set then $this->string MUST be used.
9618 protected $forcedstring = false;
9621 * Constructs a lang_string object
9623 * This function should do as little processing as possible to ensure the best
9624 * performance for strings that won't be used.
9626 * @param string $identifier The strings identifier
9627 * @param string $component The strings component
9628 * @param stdClass|array $a Any arguments the string requires
9629 * @param string $lang The language to use when processing the string.
9630 * @throws coding_exception
9632 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9633 if (empty($component)) {
9634 $component = 'moodle';
9637 $this->identifier
= $identifier;
9638 $this->component
= $component;
9639 $this->lang
= $lang;
9641 // We MUST duplicate $a to ensure that it if it changes by reference those
9642 // changes are not carried across.
9643 // To do this we always ensure $a or its properties/values are strings
9644 // and that any properties/values that arn't convertable are forgotten.
9646 if (is_scalar($a)) {
9648 } else if ($a instanceof lang_string
) {
9649 $this->a
= $a->out();
9650 } else if (is_object($a) or is_array($a)) {
9653 foreach ($a as $key => $value) {
9654 // Make sure conversion errors don't get displayed (results in '').
9655 if (is_array($value)) {
9656 $this->a
[$key] = '';
9657 } else if (is_object($value)) {
9658 if (method_exists($value, '__toString')) {
9659 $this->a
[$key] = $value->__toString();
9661 $this->a
[$key] = '';
9664 $this->a
[$key] = (string)$value;
9670 if (debugging(false, DEBUG_DEVELOPER
)) {
9671 if (clean_param($this->identifier
, PARAM_STRINGID
) == '') {
9672 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9674 if (!empty($this->component
) && clean_param($this->component
, PARAM_COMPONENT
) == '') {
9675 throw new coding_exception('Invalid string compontent. Please check your string definition');
9677 if (!get_string_manager()->string_exists($this->identifier
, $this->component
)) {
9678 debugging('String does not exist. Please check your string definition for '.$this->identifier
.'/'.$this->component
, DEBUG_DEVELOPER
);
9684 * Processes the string.
9686 * This function actually processes the string, stores it in the string property
9687 * and then returns it.
9688 * You will notice that this function is VERY similar to the get_string method.
9689 * That is because it is pretty much doing the same thing.
9690 * However as this function is an upgrade it isn't as tolerant to backwards
9694 * @throws coding_exception
9696 protected function get_string() {
9699 // Check if we need to process the string.
9700 if ($this->string === null) {
9701 // Check the quality of the identifier.
9702 if ($CFG->debugdeveloper
&& clean_param($this->identifier
, PARAM_STRINGID
) === '') {
9703 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
);
9706 // Process the string.
9707 $this->string = get_string_manager()->get_string($this->identifier
, $this->component
, $this->a
, $this->lang
);
9708 // Debugging feature lets you display string identifier and component.
9709 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
9710 $this->string .= ' {' . $this->identifier
. '/' . $this->component
. '}';
9713 // Return the string.
9714 return $this->string;
9718 * Returns the string
9720 * @param string $lang The langauge to use when processing the string
9723 public function out($lang = null) {
9724 if ($lang !== null && $lang != $this->lang
&& ($this->lang
== null && $lang != current_language())) {
9725 if ($this->forcedstring
) {
9726 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang
.' used)', DEBUG_DEVELOPER
);
9727 return $this->get_string();
9729 $translatedstring = new lang_string($this->identifier
, $this->component
, $this->a
, $lang);
9730 return $translatedstring->out();
9732 return $this->get_string();
9736 * Magic __toString method for printing a string
9740 public function __toString() {
9741 return $this->get_string();
9745 * Magic __set_state method used for var_export
9749 public function __set_state() {
9750 return $this->get_string();
9754 * Prepares the lang_string for sleep and stores only the forcedstring and
9755 * string properties... the string cannot be regenerated so we need to ensure
9756 * it is generated for this.
9760 public function __sleep() {
9761 $this->get_string();
9762 $this->forcedstring
= true;
9763 return array('forcedstring', 'string', 'lang');