2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') ||
die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 // Parameter constants - every call to optional_param(), required_param()
72 // or clean_param() should have a specified type of parameter.
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
77 define('PARAM_ALPHA', 'alpha');
80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
83 define('PARAM_ALPHAEXT', 'alphaext');
86 * PARAM_ALPHANUM - expected numbers and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
98 define('PARAM_AUTH', 'auth');
101 * PARAM_BASE64 - Base 64 encoded format
103 define('PARAM_BASE64', 'base64');
106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
108 define('PARAM_BOOL', 'bool');
111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112 * checked against the list of capabilities in the database.
114 define('PARAM_CAPABILITY', 'capability');
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
119 * the input (required/optional_param or formslib) and then sanitse the HTML
120 * using format_text on output. This is for the rare cases when you want to
121 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
123 define('PARAM_CLEANHTML', 'cleanhtml');
126 * PARAM_EMAIL - an email address following the RFC
128 define('PARAM_EMAIL', 'email');
131 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
133 define('PARAM_FILE', 'file');
136 * PARAM_FLOAT - a real/floating point number.
138 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139 * It does not work for languages that use , as a decimal separator.
140 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
146 define('PARAM_FLOAT', 'float');
149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
151 define('PARAM_HOST', 'host');
154 * PARAM_INT - integers only, use when expecting only numbers.
156 define('PARAM_INT', 'int');
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
161 define('PARAM_LANG', 'lang');
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
167 define('PARAM_LOCALURL', 'localurl');
170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
172 define('PARAM_NOTAGS', 'notags');
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
178 define('PARAM_PATH', 'path');
181 * PARAM_PEM - Privacy Enhanced Mail format
183 define('PARAM_PEM', 'pem');
186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
188 define('PARAM_PERMISSION', 'permission');
191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
193 define('PARAM_RAW', 'raw');
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
198 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
203 define('PARAM_SAFEDIR', 'safedir');
206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
208 define('PARAM_SAFEPATH', 'safepath');
211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
213 define('PARAM_SEQUENCE', 'sequence');
216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
218 define('PARAM_TAG', 'tag');
221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
223 define('PARAM_TAGLIST', 'taglist');
226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
228 define('PARAM_TEXT', 'text');
231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
233 define('PARAM_THEME', 'theme');
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * http://localhost.localdomain/ is ok.
239 define('PARAM_URL', 'url');
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243 * accounts, do NOT use when syncing with external systems!!
245 define('PARAM_USERNAME', 'username');
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
250 define('PARAM_STRINGID', 'stringid');
252 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
256 * @deprecated since 2.0
258 define('PARAM_CLEAN', 'clean');
261 * PARAM_INTEGER - deprecated alias for PARAM_INT
262 * @deprecated since 2.0
264 define('PARAM_INTEGER', 'int');
267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268 * @deprecated since 2.0
270 define('PARAM_NUMBER', 'float');
273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274 * NOTE: originally alias for PARAM_APLHA
275 * @deprecated since 2.0
277 define('PARAM_ACTION', 'alphanumext');
280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
282 * @deprecated since 2.0
284 define('PARAM_FORMAT', 'alphanumext');
287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288 * @deprecated since 2.0
290 define('PARAM_MULTILANG', 'text');
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295 * America/Port-au-Prince)
297 define('PARAM_TIMEZONE', 'timezone');
300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
302 define('PARAM_CLEANFILE', 'file');
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
310 define('PARAM_COMPONENT', 'component');
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
317 define('PARAM_AREA', 'area');
320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
324 define('PARAM_PLUGIN', 'plugin');
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
332 define('VALUE_REQUIRED', 1);
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
337 define('VALUE_OPTIONAL', 2);
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
342 define('VALUE_DEFAULT', 0);
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
347 define('NULL_NOT_ALLOWED', false);
350 * NULL_ALLOWED - the parameter can be set to null in the database
352 define('NULL_ALLOWED', true);
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True if module supports outcomes */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
421 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
423 /** Type of module */
424 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425 /** True if module supports intro editor */
426 define('FEATURE_MOD_INTRO', 'mod_intro');
427 /** True if module has default completion */
428 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
430 define('FEATURE_COMMENT', 'comment');
432 define('FEATURE_RATE', 'rate');
433 /** True if module supports backup/restore of moodle2 format */
434 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
436 /** True if module can show description on course main page */
437 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
439 /** True if module uses the question bank */
440 define('FEATURE_USES_QUESTIONS', 'usesquestions');
442 /** Unspecified module archetype */
443 define('MOD_ARCHETYPE_OTHER', 0);
444 /** Resource-like type module */
445 define('MOD_ARCHETYPE_RESOURCE', 1);
446 /** Assignment module archetype */
447 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
448 /** System (not user-addable) module archetype */
449 define('MOD_ARCHETYPE_SYSTEM', 3);
451 /** Return this from modname_get_types callback to use default display in activity chooser */
452 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
455 * Security token used for allowing access
456 * from external application such as web services.
457 * Scripts do not use any session, performance is relatively
458 * low because we need to load access info in each request.
459 * Scripts are executed in parallel.
461 define('EXTERNAL_TOKEN_PERMANENT', 0);
464 * Security token used for allowing access
465 * of embedded applications, the code is executed in the
466 * active user session. Token is invalidated after user logs out.
467 * Scripts are executed serially - normal session locking is used.
469 define('EXTERNAL_TOKEN_EMBEDDED', 1);
472 * The home page should be the site home
474 define('HOMEPAGE_SITE', 0);
476 * The home page should be the users my page
478 define('HOMEPAGE_MY', 1);
480 * The home page can be chosen by the user
482 define('HOMEPAGE_USER', 2);
485 * Hub directory url (should be moodle.org)
487 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
491 * Moodle.org url (should be moodle.org)
493 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
496 * Moodle mobile app service name
498 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
501 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
503 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
506 * Course display settings: display all sections on one page.
508 define('COURSE_DISPLAY_SINGLEPAGE', 0);
510 * Course display settings: split pages into a page per section.
512 define('COURSE_DISPLAY_MULTIPAGE', 1);
515 * Authentication constant: String used in password field when password is not stored.
517 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
519 // PARAMETER HANDLING.
522 * Returns a particular value for the named variable, taken from
523 * POST or GET. If the parameter doesn't exist then an error is
524 * thrown because we require this variable.
526 * This function should be used to initialise all required values
527 * in a script that are based on parameters. Usually it will be
529 * $id = required_param('id', PARAM_INT);
531 * Please note the $type parameter is now required and the value can not be array.
533 * @param string $parname the name of the page parameter we want
534 * @param string $type expected type of parameter
536 * @throws coding_exception
538 function required_param($parname, $type) {
539 if (func_num_args() != 2 or empty($parname) or empty($type)) {
540 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
542 // POST has precedence.
543 if (isset($_POST[$parname])) {
544 $param = $_POST[$parname];
545 } else if (isset($_GET[$parname])) {
546 $param = $_GET[$parname];
548 print_error('missingparam', '', '', $parname);
551 if (is_array($param)) {
552 debugging('Invalid array parameter detected in required_param(): '.$parname);
553 // TODO: switch to fatal error in Moodle 2.3.
554 return required_param_array($parname, $type);
557 return clean_param($param, $type);
561 * Returns a particular array value for the named variable, taken from
562 * POST or GET. If the parameter doesn't exist then an error is
563 * thrown because we require this variable.
565 * This function should be used to initialise all required values
566 * in a script that are based on parameters. Usually it will be
568 * $ids = required_param_array('ids', PARAM_INT);
570 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
572 * @param string $parname the name of the page parameter we want
573 * @param string $type expected type of parameter
575 * @throws coding_exception
577 function required_param_array($parname, $type) {
578 if (func_num_args() != 2 or empty($parname) or empty($type)) {
579 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
581 // POST has precedence.
582 if (isset($_POST[$parname])) {
583 $param = $_POST[$parname];
584 } else if (isset($_GET[$parname])) {
585 $param = $_GET[$parname];
587 print_error('missingparam', '', '', $parname);
589 if (!is_array($param)) {
590 print_error('missingparam', '', '', $parname);
594 foreach ($param as $key => $value) {
595 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
596 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
599 $result[$key] = clean_param($value, $type);
606 * Returns a particular value for the named variable, taken from
607 * POST or GET, otherwise returning a given default.
609 * This function should be used to initialise all optional values
610 * in a script that are based on parameters. Usually it will be
612 * $name = optional_param('name', 'Fred', PARAM_TEXT);
614 * Please note the $type parameter is now required and the value can not be array.
616 * @param string $parname the name of the page parameter we want
617 * @param mixed $default the default value to return if nothing is found
618 * @param string $type expected type of parameter
620 * @throws coding_exception
622 function optional_param($parname, $default, $type) {
623 if (func_num_args() != 3 or empty($parname) or empty($type)) {
624 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
626 if (!isset($default)) {
630 // POST has precedence.
631 if (isset($_POST[$parname])) {
632 $param = $_POST[$parname];
633 } else if (isset($_GET[$parname])) {
634 $param = $_GET[$parname];
639 if (is_array($param)) {
640 debugging('Invalid array parameter detected in required_param(): '.$parname);
641 // TODO: switch to $default in Moodle 2.3.
642 return optional_param_array($parname, $default, $type);
645 return clean_param($param, $type);
649 * Returns a particular array value for the named variable, taken from
650 * POST or GET, otherwise returning a given default.
652 * This function should be used to initialise all optional values
653 * in a script that are based on parameters. Usually it will be
655 * $ids = optional_param('id', array(), PARAM_INT);
657 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
659 * @param string $parname the name of the page parameter we want
660 * @param mixed $default the default value to return if nothing is found
661 * @param string $type expected type of parameter
663 * @throws coding_exception
665 function optional_param_array($parname, $default, $type) {
666 if (func_num_args() != 3 or empty($parname) or empty($type)) {
667 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
670 // POST has precedence.
671 if (isset($_POST[$parname])) {
672 $param = $_POST[$parname];
673 } else if (isset($_GET[$parname])) {
674 $param = $_GET[$parname];
678 if (!is_array($param)) {
679 debugging('optional_param_array() expects array parameters only: '.$parname);
684 foreach ($param as $key => $value) {
685 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
686 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
689 $result[$key] = clean_param($value, $type);
696 * Strict validation of parameter values, the values are only converted
697 * to requested PHP type. Internally it is using clean_param, the values
698 * before and after cleaning must be equal - otherwise
699 * an invalid_parameter_exception is thrown.
700 * Objects and classes are not accepted.
702 * @param mixed $param
703 * @param string $type PARAM_ constant
704 * @param bool $allownull are nulls valid value?
705 * @param string $debuginfo optional debug information
706 * @return mixed the $param value converted to PHP type
707 * @throws invalid_parameter_exception if $param is not of given type
709 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED
, $debuginfo='') {
710 if (is_null($param)) {
711 if ($allownull == NULL_ALLOWED
) {
714 throw new invalid_parameter_exception($debuginfo);
717 if (is_array($param) or is_object($param)) {
718 throw new invalid_parameter_exception($debuginfo);
721 $cleaned = clean_param($param, $type);
723 if ($type == PARAM_FLOAT
) {
724 // Do not detect precision loss here.
725 if (is_float($param) or is_int($param)) {
727 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
728 throw new invalid_parameter_exception($debuginfo);
730 } else if ((string)$param !== (string)$cleaned) {
731 // Conversion to string is usually lossless.
732 throw new invalid_parameter_exception($debuginfo);
739 * Makes sure array contains only the allowed types, this function does not validate array key names!
742 * $options = clean_param($options, PARAM_INT);
745 * @param array $param the variable array we are cleaning
746 * @param string $type expected format of param after cleaning.
747 * @param bool $recursive clean recursive arrays
749 * @throws coding_exception
751 function clean_param_array(array $param = null, $type, $recursive = false) {
752 // Convert null to empty array.
753 $param = (array)$param;
754 foreach ($param as $key => $value) {
755 if (is_array($value)) {
757 $param[$key] = clean_param_array($value, $type, true);
759 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
762 $param[$key] = clean_param($value, $type);
769 * Used by {@link optional_param()} and {@link required_param()} to
770 * clean the variables and/or cast to specific types, based on
773 * $course->format = clean_param($course->format, PARAM_ALPHA);
774 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
777 * @param mixed $param the variable we are cleaning
778 * @param string $type expected format of param after cleaning.
780 * @throws coding_exception
782 function clean_param($param, $type) {
785 if (is_array($param)) {
786 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
787 } else if (is_object($param)) {
788 if (method_exists($param, '__toString')) {
789 $param = $param->__toString();
791 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
797 // No cleaning at all.
798 $param = fix_utf8($param);
801 case PARAM_RAW_TRIMMED
:
802 // No cleaning, but strip leading and trailing whitespace.
803 $param = fix_utf8($param);
807 // General HTML cleaning, try to use more specific type if possible this is deprecated!
808 // Please use more specific type instead.
809 if (is_numeric($param)) {
812 $param = fix_utf8($param);
813 // Sweep for scripts, etc.
814 return clean_text($param);
816 case PARAM_CLEANHTML
:
817 // Clean html fragment.
818 $param = fix_utf8($param);
819 // Sweep for scripts, etc.
820 $param = clean_text($param, FORMAT_HTML
);
824 // Convert to integer.
829 return (float)$param;
832 // Remove everything not `a-z`.
833 return preg_replace('/[^a-zA-Z]/i', '', $param);
836 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
837 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
840 // Remove everything not `a-zA-Z0-9`.
841 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
843 case PARAM_ALPHANUMEXT
:
844 // Remove everything not `a-zA-Z0-9_-`.
845 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
848 // Remove everything not `0-9,`.
849 return preg_replace('/[^0-9,]/i', '', $param);
852 // Convert to 1 or 0.
853 $tempstr = strtolower($param);
854 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
856 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
859 $param = empty($param) ?
0 : 1;
865 $param = fix_utf8($param);
866 return strip_tags($param);
869 // Leave only tags needed for multilang.
870 $param = fix_utf8($param);
871 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
872 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
874 if (strpos($param, '</lang>') !== false) {
875 // Old and future mutilang syntax.
876 $param = strip_tags($param, '<lang>');
877 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
881 foreach ($matches[0] as $match) {
882 if ($match === '</lang>') {
890 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
901 } else if (strpos($param, '</span>') !== false) {
902 // Current problematic multilang syntax.
903 $param = strip_tags($param, '<span>');
904 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
908 foreach ($matches[0] as $match) {
909 if ($match === '</span>') {
917 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
929 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
930 return strip_tags($param);
932 case PARAM_COMPONENT
:
933 // We do not want any guessing here, either the name is correct or not
934 // please note only normalised component names are accepted.
935 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
938 if (strpos($param, '__') !== false) {
941 if (strpos($param, 'mod_') === 0) {
942 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
943 if (substr_count($param, '_') != 1) {
951 // We do not want any guessing here, either the name is correct or not.
952 if (!is_valid_plugin_name($param)) {
958 // Remove everything not a-zA-Z0-9_- .
959 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
962 // Remove everything not a-zA-Z0-9/_- .
963 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
966 // Strip all suspicious characters from filename.
967 $param = fix_utf8($param);
968 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
969 if ($param === '.' ||
$param === '..') {
975 // Strip all suspicious characters from file path.
976 $param = fix_utf8($param);
977 $param = str_replace('\\', '/', $param);
979 // Explode the path and clean each element using the PARAM_FILE rules.
980 $breadcrumb = explode('/', $param);
981 foreach ($breadcrumb as $key => $crumb) {
982 if ($crumb === '.' && $key === 0) {
983 // Special condition to allow for relative current path such as ./currentdirfile.txt.
985 $crumb = clean_param($crumb, PARAM_FILE
);
987 $breadcrumb[$key] = $crumb;
989 $param = implode('/', $breadcrumb);
991 // Remove multiple current path (./././) and multiple slashes (///).
992 $param = preg_replace('~//+~', '/', $param);
993 $param = preg_replace('~/(\./)+~', '/', $param);
997 // Allow FQDN or IPv4 dotted quad.
998 $param = preg_replace('/[^\.\d\w-]/', '', $param );
999 // Match ipv4 dotted quad.
1000 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1001 // Confirm values are ok.
1002 if ( $match[0] > 255
1005 ||
$match[4] > 255 ) {
1006 // Hmmm, what kind of dotted quad is this?
1009 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1010 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1011 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1013 // All is ok - $param is respected.
1020 case PARAM_URL
: // Allow safe ftp, http, mailto urls.
1021 $param = fix_utf8($param);
1022 include_once($CFG->dirroot
. '/lib/validateurlsyntax.php');
1023 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1024 // All is ok, param is respected.
1031 case PARAM_LOCALURL
:
1032 // Allow http absolute, root relative and relative URLs within wwwroot.
1033 $param = clean_param($param, PARAM_URL
);
1034 if (!empty($param)) {
1035 if (preg_match(':^/:', $param)) {
1036 // Root-relative, ok!
1037 } else if (preg_match('/^'.preg_quote($CFG->wwwroot
, '/').'/i', $param)) {
1038 // Absolute, and matches our wwwroot.
1040 // Relative - let's make sure there are no tricks.
1041 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1051 $param = trim($param);
1052 // PEM formatted strings may contain letters/numbers and the symbols:
1056 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1057 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1058 list($wholething, $body) = $matches;
1059 unset($wholething, $matches);
1060 $b64 = clean_param($body, PARAM_BASE64
);
1062 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1070 if (!empty($param)) {
1071 // PEM formatted strings may contain letters/numbers and the symbols
1075 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1078 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY
);
1079 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1080 // than (or equal to) 64 characters long.
1081 for ($i=0, $j=count($lines); $i < $j; $i++
) {
1083 if (64 < strlen($lines[$i])) {
1089 if (64 != strlen($lines[$i])) {
1093 return implode("\n", $lines);
1099 $param = fix_utf8($param);
1100 // Please note it is not safe to use the tag name directly anywhere,
1101 // it must be processed with s(), urlencode() before embedding anywhere.
1102 // Remove some nasties.
1103 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1104 // Convert many whitespace chars into one.
1105 $param = preg_replace('/\s+/', ' ', $param);
1106 $param = core_text
::substr(trim($param), 0, TAG_MAX_LENGTH
);
1110 $param = fix_utf8($param);
1111 $tags = explode(',', $param);
1113 foreach ($tags as $tag) {
1114 $res = clean_param($tag, PARAM_TAG
);
1120 return implode(',', $result);
1125 case PARAM_CAPABILITY
:
1126 if (get_capability_info($param)) {
1132 case PARAM_PERMISSION
:
1133 $param = (int)$param;
1134 if (in_array($param, array(CAP_INHERIT
, CAP_ALLOW
, CAP_PREVENT
, CAP_PROHIBIT
))) {
1141 $param = clean_param($param, PARAM_PLUGIN
);
1142 if (empty($param)) {
1144 } else if (exists_auth_plugin($param)) {
1151 $param = clean_param($param, PARAM_SAFEDIR
);
1152 if (get_string_manager()->translation_exists($param)) {
1155 // Specified language is not installed or param malformed.
1160 $param = clean_param($param, PARAM_PLUGIN
);
1161 if (empty($param)) {
1163 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1165 } else if (!empty($CFG->themedir
) and file_exists("$CFG->themedir/$param/config.php")) {
1168 // Specified theme is not installed.
1172 case PARAM_USERNAME
:
1173 $param = fix_utf8($param);
1174 $param = trim($param);
1175 // Convert uppercase to lowercase MDL-16919.
1176 $param = core_text
::strtolower($param);
1177 if (empty($CFG->extendedusernamechars
)) {
1178 $param = str_replace(" " , "", $param);
1179 // Regular expression, eliminate all chars EXCEPT:
1180 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1181 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1186 $param = fix_utf8($param);
1187 if (validate_email($param)) {
1193 case PARAM_STRINGID
:
1194 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1200 case PARAM_TIMEZONE
:
1201 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1202 $param = fix_utf8($param);
1203 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1204 if (preg_match($timezonepattern, $param)) {
1211 // Doh! throw error, switched parameters in optional_param or another serious problem.
1212 print_error("unknownparamtype", '', '', $type);
1217 * Makes sure the data is using valid utf8, invalid characters are discarded.
1219 * Note: this function is not intended for full objects with methods and private properties.
1221 * @param mixed $value
1222 * @return mixed with proper utf-8 encoding
1224 function fix_utf8($value) {
1225 if (is_null($value) or $value === '') {
1228 } else if (is_string($value)) {
1229 if ((string)(int)$value === $value) {
1233 // No null bytes expected in our data, so let's remove it.
1234 $value = str_replace("\0", '', $value);
1236 // Note: this duplicates min_fix_utf8() intentionally.
1237 static $buggyiconv = null;
1238 if ($buggyiconv === null) {
1239 $buggyiconv = (!function_exists('iconv') or @iconv
('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1243 if (function_exists('mb_convert_encoding')) {
1244 $subst = mb_substitute_character();
1245 mb_substitute_character('');
1246 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1247 mb_substitute_character($subst);
1250 // Warn admins on admin/index.php page.
1255 $result = @iconv
('UTF-8', 'UTF-8//IGNORE', $value);
1260 } else if (is_array($value)) {
1261 foreach ($value as $k => $v) {
1262 $value[$k] = fix_utf8($v);
1266 } else if (is_object($value)) {
1267 // Do not modify original.
1268 $value = clone($value);
1269 foreach ($value as $k => $v) {
1270 $value->$k = fix_utf8($v);
1275 // This is some other type, no utf-8 here.
1281 * Return true if given value is integer or string with integer value
1283 * @param mixed $value String or Int
1284 * @return bool true if number, false if not
1286 function is_number($value) {
1287 if (is_int($value)) {
1289 } else if (is_string($value)) {
1290 return ((string)(int)$value) === $value;
1297 * Returns host part from url.
1299 * @param string $url full url
1300 * @return string host, null if not found
1302 function get_host_from_url($url) {
1303 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1311 * Tests whether anything was returned by text editor
1313 * This function is useful for testing whether something you got back from
1314 * the HTML editor actually contains anything. Sometimes the HTML editor
1315 * appear to be empty, but actually you get back a <br> tag or something.
1317 * @param string $string a string containing HTML.
1318 * @return boolean does the string contain any actual content - that is text,
1319 * images, objects, etc.
1321 function html_is_blank($string) {
1322 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1326 * Set a key in global configuration
1328 * Set a key/value pair in both this session's {@link $CFG} global variable
1329 * and in the 'config' database table for future sessions.
1331 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1332 * In that case it doesn't affect $CFG.
1334 * A NULL value will delete the entry.
1336 * NOTE: this function is called from lib/db/upgrade.php
1338 * @param string $name the key to set
1339 * @param string $value the value to set (without magic quotes)
1340 * @param string $plugin (optional) the plugin scope, default null
1341 * @return bool true or exception
1343 function set_config($name, $value, $plugin=null) {
1346 if (empty($plugin)) {
1347 if (!array_key_exists($name, $CFG->config_php_settings
)) {
1348 // So it's defined for this invocation at least.
1349 if (is_null($value)) {
1352 // Settings from db are always strings.
1353 $CFG->$name = (string)$value;
1357 if ($DB->get_field('config', 'name', array('name' => $name))) {
1358 if ($value === null) {
1359 $DB->delete_records('config', array('name' => $name));
1361 $DB->set_field('config', 'value', $value, array('name' => $name));
1364 if ($value !== null) {
1365 $config = new stdClass();
1366 $config->name
= $name;
1367 $config->value
= $value;
1368 $DB->insert_record('config', $config, false);
1371 if ($name === 'siteidentifier') {
1372 cache_helper
::update_site_identifier($value);
1374 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1377 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1378 if ($value===null) {
1379 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1381 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1384 if ($value !== null) {
1385 $config = new stdClass();
1386 $config->plugin
= $plugin;
1387 $config->name
= $name;
1388 $config->value
= $value;
1389 $DB->insert_record('config_plugins', $config, false);
1392 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
1399 * Get configuration values from the global config table
1400 * or the config_plugins table.
1402 * If called with one parameter, it will load all the config
1403 * variables for one plugin, and return them as an object.
1405 * If called with 2 parameters it will return a string single
1406 * value or false if the value is not found.
1408 * NOTE: this function is called from lib/db/upgrade.php
1410 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1411 * that we need only fetch it once per request.
1412 * @param string $plugin full component name
1413 * @param string $name default null
1414 * @return mixed hash-like object or single value, return false no config found
1415 * @throws dml_exception
1417 function get_config($plugin, $name = null) {
1420 static $siteidentifier = null;
1422 if ($plugin === 'moodle' ||
$plugin === 'core' ||
empty($plugin)) {
1423 $forced =& $CFG->config_php_settings
;
1427 if (array_key_exists($plugin, $CFG->forced_plugin_settings
)) {
1428 $forced =& $CFG->forced_plugin_settings
[$plugin];
1435 if ($siteidentifier === null) {
1437 // This may fail during installation.
1438 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1439 // install the database.
1440 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1441 } catch (dml_exception
$ex) {
1442 // Set siteidentifier to false. We don't want to trip this continually.
1443 $siteidentifier = false;
1448 if (!empty($name)) {
1449 if (array_key_exists($name, $forced)) {
1450 return (string)$forced[$name];
1451 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1452 return $siteidentifier;
1456 $cache = cache
::make('core', 'config');
1457 $result = $cache->get($plugin);
1458 if ($result === false) {
1459 // The user is after a recordset.
1461 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1463 // This part is not really used any more, but anyway...
1464 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1466 $cache->set($plugin, $result);
1469 if (!empty($name)) {
1470 if (array_key_exists($name, $result)) {
1471 return $result[$name];
1476 if ($plugin === 'core') {
1477 $result['siteidentifier'] = $siteidentifier;
1480 foreach ($forced as $key => $value) {
1481 if (is_null($value) or is_array($value) or is_object($value)) {
1482 // We do not want any extra mess here, just real settings that could be saved in db.
1483 unset($result[$key]);
1485 // Convert to string as if it went through the DB.
1486 $result[$key] = (string)$value;
1490 return (object)$result;
1494 * Removes a key from global configuration.
1496 * NOTE: this function is called from lib/db/upgrade.php
1498 * @param string $name the key to set
1499 * @param string $plugin (optional) the plugin scope
1500 * @return boolean whether the operation succeeded.
1502 function unset_config($name, $plugin=null) {
1505 if (empty($plugin)) {
1507 $DB->delete_records('config', array('name' => $name));
1508 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1510 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1511 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
1518 * Remove all the config variables for a given plugin.
1520 * NOTE: this function is called from lib/db/upgrade.php
1522 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1523 * @return boolean whether the operation succeeded.
1525 function unset_all_config_for_plugin($plugin) {
1527 // Delete from the obvious config_plugins first.
1528 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1529 // Next delete any suspect settings from config.
1530 $like = $DB->sql_like('name', '?', true, true, false, '|');
1531 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1532 $DB->delete_records_select('config', $like, $params);
1533 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1534 cache_helper
::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1540 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1542 * All users are verified if they still have the necessary capability.
1544 * @param string $value the value of the config setting.
1545 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1546 * @param bool $includeadmins include administrators.
1547 * @return array of user objects.
1549 function get_users_from_config($value, $capability, $includeadmins = true) {
1550 if (empty($value) or $value === '$@NONE@$') {
1554 // We have to make sure that users still have the necessary capability,
1555 // it should be faster to fetch them all first and then test if they are present
1556 // instead of validating them one-by-one.
1557 $users = get_users_by_capability(context_system
::instance(), $capability);
1558 if ($includeadmins) {
1559 $admins = get_admins();
1560 foreach ($admins as $admin) {
1561 $users[$admin->id
] = $admin;
1565 if ($value === '$@ALL@$') {
1569 $result = array(); // Result in correct order.
1570 $allowed = explode(',', $value);
1571 foreach ($allowed as $uid) {
1572 if (isset($users[$uid])) {
1573 $user = $users[$uid];
1574 $result[$user->id
] = $user;
1583 * Invalidates browser caches and cached data in temp.
1585 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1586 * {@link phpunit_util::reset_dataroot()}
1590 function purge_all_caches() {
1593 reset_text_filters_cache();
1594 js_reset_all_caches();
1595 theme_reset_all_caches();
1596 get_string_manager()->reset_caches();
1597 core_text
::reset_caches();
1598 if (class_exists('core_plugin_manager')) {
1599 core_plugin_manager
::reset_caches();
1602 // Bump up cacherev field for all courses.
1604 increment_revision_number('course', 'cacherev', '');
1605 } catch (moodle_exception
$e) {
1606 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1609 $DB->reset_caches();
1610 cache_helper
::purge_all();
1612 // Purge all other caches: rss, simplepie, etc.
1613 remove_dir($CFG->cachedir
.'', true);
1615 // Make sure cache dir is writable, throws exception if not.
1616 make_cache_directory('');
1618 // This is the only place where we purge local caches, we are only adding files there.
1619 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1620 remove_dir($CFG->localcachedir
, true);
1621 set_config('localcachedirpurged', time());
1622 make_localcache_directory('', true);
1623 \core\task\manager
::clear_static_caches();
1627 * Get volatile flags
1629 * @param string $type
1630 * @param int $changedsince default null
1631 * @return array records array
1633 function get_cache_flags($type, $changedsince = null) {
1636 $params = array('type' => $type, 'expiry' => time());
1637 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1638 if ($changedsince !== null) {
1639 $params['changedsince'] = $changedsince;
1640 $sqlwhere .= " AND timemodified > :changedsince";
1643 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1644 foreach ($flags as $flag) {
1645 $cf[$flag->name
] = $flag->value
;
1652 * Get volatile flags
1654 * @param string $type
1655 * @param string $name
1656 * @param int $changedsince default null
1657 * @return string|false The cache flag value or false
1659 function get_cache_flag($type, $name, $changedsince=null) {
1662 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1664 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1665 if ($changedsince !== null) {
1666 $params['changedsince'] = $changedsince;
1667 $sqlwhere .= " AND timemodified > :changedsince";
1670 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1674 * Set a volatile flag
1676 * @param string $type the "type" namespace for the key
1677 * @param string $name the key to set
1678 * @param string $value the value to set (without magic quotes) - null will remove the flag
1679 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1680 * @return bool Always returns true
1682 function set_cache_flag($type, $name, $value, $expiry = null) {
1685 $timemodified = time();
1686 if ($expiry === null ||
$expiry < $timemodified) {
1687 $expiry = $timemodified +
24 * 60 * 60;
1689 $expiry = (int)$expiry;
1692 if ($value === null) {
1693 unset_cache_flag($type, $name);
1697 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE
)) {
1698 // This is a potential problem in DEBUG_DEVELOPER.
1699 if ($f->value
== $value and $f->expiry
== $expiry and $f->timemodified
== $timemodified) {
1700 return true; // No need to update.
1703 $f->expiry
= $expiry;
1704 $f->timemodified
= $timemodified;
1705 $DB->update_record('cache_flags', $f);
1707 $f = new stdClass();
1708 $f->flagtype
= $type;
1711 $f->expiry
= $expiry;
1712 $f->timemodified
= $timemodified;
1713 $DB->insert_record('cache_flags', $f);
1719 * Removes a single volatile flag
1721 * @param string $type the "type" namespace for the key
1722 * @param string $name the key to set
1725 function unset_cache_flag($type, $name) {
1727 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1732 * Garbage-collect volatile flags
1734 * @return bool Always returns true
1736 function gc_cache_flags() {
1738 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1742 // USER PREFERENCE API.
1745 * Refresh user preference cache. This is used most often for $USER
1746 * object that is stored in session, but it also helps with performance in cron script.
1748 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1751 * @category preference
1753 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1754 * @param int $cachelifetime Cache life time on the current page (in seconds)
1755 * @throws coding_exception
1758 function check_user_preferences_loaded(stdClass
$user, $cachelifetime = 120) {
1760 // Static cache, we need to check on each page load, not only every 2 minutes.
1761 static $loadedusers = array();
1763 if (!isset($user->id
)) {
1764 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1767 if (empty($user->id
) or isguestuser($user->id
)) {
1768 // No permanent storage for not-logged-in users and guest.
1769 if (!isset($user->preference
)) {
1770 $user->preference
= array();
1777 if (isset($loadedusers[$user->id
]) and isset($user->preference
) and isset($user->preference
['_lastloaded'])) {
1778 // Already loaded at least once on this page. Are we up to date?
1779 if ($user->preference
['_lastloaded'] +
$cachelifetime > $timenow) {
1780 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1783 } else if (!get_cache_flag('userpreferenceschanged', $user->id
, $user->preference
['_lastloaded'])) {
1784 // No change since the lastcheck on this page.
1785 $user->preference
['_lastloaded'] = $timenow;
1790 // OK, so we have to reload all preferences.
1791 $loadedusers[$user->id
] = true;
1792 $user->preference
= $DB->get_records_menu('user_preferences', array('userid' => $user->id
), '', 'name,value'); // All values.
1793 $user->preference
['_lastloaded'] = $timenow;
1797 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1799 * NOTE: internal function, do not call from other code.
1803 * @param integer $userid the user whose prefs were changed.
1805 function mark_user_preferences_changed($userid) {
1808 if (empty($userid) or isguestuser($userid)) {
1809 // No cache flags for guest and not-logged-in users.
1813 set_cache_flag('userpreferenceschanged', $userid, 1, time() +
$CFG->sessiontimeout
);
1817 * Sets a preference for the specified user.
1819 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1822 * @category preference
1824 * @param string $name The key to set as preference for the specified user
1825 * @param string $value The value to set for the $name key in the specified user's
1826 * record, null means delete current value.
1827 * @param stdClass|int|null $user A moodle user object or id, null means current user
1828 * @throws coding_exception
1829 * @return bool Always true or exception
1831 function set_user_preference($name, $value, $user = null) {
1834 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1835 throw new coding_exception('Invalid preference name in set_user_preference() call');
1838 if (is_null($value)) {
1839 // Null means delete current.
1840 return unset_user_preference($name, $user);
1841 } else if (is_object($value)) {
1842 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1843 } else if (is_array($value)) {
1844 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1846 // Value column maximum length is 1333 characters.
1847 $value = (string)$value;
1848 if (core_text
::strlen($value) > 1333) {
1849 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1852 if (is_null($user)) {
1854 } else if (isset($user->id
)) {
1855 // It is a valid object.
1856 } else if (is_numeric($user)) {
1857 $user = (object)array('id' => (int)$user);
1859 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1862 check_user_preferences_loaded($user);
1864 if (empty($user->id
) or isguestuser($user->id
)) {
1865 // No permanent storage for not-logged-in users and guest.
1866 $user->preference
[$name] = $value;
1870 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => $name))) {
1871 if ($preference->value
=== $value and isset($user->preference
[$name]) and $user->preference
[$name] === $value) {
1872 // Preference already set to this value.
1875 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id
));
1878 $preference = new stdClass();
1879 $preference->userid
= $user->id
;
1880 $preference->name
= $name;
1881 $preference->value
= $value;
1882 $DB->insert_record('user_preferences', $preference);
1885 // Update value in cache.
1886 $user->preference
[$name] = $value;
1888 // Set reload flag for other sessions.
1889 mark_user_preferences_changed($user->id
);
1895 * Sets a whole array of preferences for the current user
1897 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1900 * @category preference
1902 * @param array $prefarray An array of key/value pairs to be set
1903 * @param stdClass|int|null $user A moodle user object or id, null means current user
1904 * @return bool Always true or exception
1906 function set_user_preferences(array $prefarray, $user = null) {
1907 foreach ($prefarray as $name => $value) {
1908 set_user_preference($name, $value, $user);
1914 * Unsets a preference completely by deleting it from the database
1916 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1919 * @category preference
1921 * @param string $name The key to unset as preference for the specified user
1922 * @param stdClass|int|null $user A moodle user object or id, null means current user
1923 * @throws coding_exception
1924 * @return bool Always true or exception
1926 function unset_user_preference($name, $user = null) {
1929 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1930 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1933 if (is_null($user)) {
1935 } else if (isset($user->id
)) {
1936 // It is a valid object.
1937 } else if (is_numeric($user)) {
1938 $user = (object)array('id' => (int)$user);
1940 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1943 check_user_preferences_loaded($user);
1945 if (empty($user->id
) or isguestuser($user->id
)) {
1946 // No permanent storage for not-logged-in user and guest.
1947 unset($user->preference
[$name]);
1952 $DB->delete_records('user_preferences', array('userid' => $user->id
, 'name' => $name));
1954 // Delete the preference from cache.
1955 unset($user->preference
[$name]);
1957 // Set reload flag for other sessions.
1958 mark_user_preferences_changed($user->id
);
1964 * Used to fetch user preference(s)
1966 * If no arguments are supplied this function will return
1967 * all of the current user preferences as an array.
1969 * If a name is specified then this function
1970 * attempts to return that particular preference value. If
1971 * none is found, then the optional value $default is returned,
1974 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1977 * @category preference
1979 * @param string $name Name of the key to use in finding a preference value
1980 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1981 * @param stdClass|int|null $user A moodle user object or id, null means current user
1982 * @throws coding_exception
1983 * @return string|mixed|null A string containing the value of a single preference. An
1984 * array with all of the preferences or null
1986 function get_user_preferences($name = null, $default = null, $user = null) {
1989 if (is_null($name)) {
1991 } else if (is_numeric($name) or $name === '_lastloaded') {
1992 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1995 if (is_null($user)) {
1997 } else if (isset($user->id
)) {
1998 // Is a valid object.
1999 } else if (is_numeric($user)) {
2000 $user = (object)array('id' => (int)$user);
2002 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2005 check_user_preferences_loaded($user);
2009 return $user->preference
;
2010 } else if (isset($user->preference
[$name])) {
2011 // The single string value.
2012 return $user->preference
[$name];
2014 // Default value (null if not specified).
2019 // FUNCTIONS FOR HANDLING TIME.
2022 * Given date parts in user time produce a GMT timestamp.
2026 * @param int $year The year part to create timestamp of
2027 * @param int $month The month part to create timestamp of
2028 * @param int $day The day part to create timestamp of
2029 * @param int $hour The hour part to create timestamp of
2030 * @param int $minute The minute part to create timestamp of
2031 * @param int $second The second part to create timestamp of
2032 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2033 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2034 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2035 * applied only if timezone is 99 or string.
2036 * @return int GMT timestamp
2038 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2040 // Save input timezone, required for dst offset check.
2041 $passedtimezone = $timezone;
2043 $timezone = get_user_timezone_offset($timezone);
2045 if (abs($timezone) > 13) {
2047 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2049 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2050 $time = usertime($time, $timezone);
2052 // Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
2053 if ($applydst && ((99 == $passedtimezone) ||
!is_numeric($passedtimezone))) {
2054 $time -= dst_offset_on($time, $passedtimezone);
2063 * Format a date/time (seconds) as weeks, days, hours etc as needed
2065 * Given an amount of time in seconds, returns string
2066 * formatted nicely as weeks, days, hours etc as needed
2074 * @param int $totalsecs Time in seconds
2075 * @param stdClass $str Should be a time object
2076 * @return string A nicely formatted date/time string
2078 function format_time($totalsecs, $str = null) {
2080 $totalsecs = abs($totalsecs);
2083 // Create the str structure the slow way.
2084 $str = new stdClass();
2085 $str->day
= get_string('day');
2086 $str->days
= get_string('days');
2087 $str->hour
= get_string('hour');
2088 $str->hours
= get_string('hours');
2089 $str->min
= get_string('min');
2090 $str->mins
= get_string('mins');
2091 $str->sec
= get_string('sec');
2092 $str->secs
= get_string('secs');
2093 $str->year
= get_string('year');
2094 $str->years
= get_string('years');
2097 $years = floor($totalsecs/YEARSECS
);
2098 $remainder = $totalsecs - ($years*YEARSECS
);
2099 $days = floor($remainder/DAYSECS
);
2100 $remainder = $totalsecs - ($days*DAYSECS
);
2101 $hours = floor($remainder/HOURSECS
);
2102 $remainder = $remainder - ($hours*HOURSECS
);
2103 $mins = floor($remainder/MINSECS
);
2104 $secs = $remainder - ($mins*MINSECS
);
2106 $ss = ($secs == 1) ?
$str->sec
: $str->secs
;
2107 $sm = ($mins == 1) ?
$str->min
: $str->mins
;
2108 $sh = ($hours == 1) ?
$str->hour
: $str->hours
;
2109 $sd = ($days == 1) ?
$str->day
: $str->days
;
2110 $sy = ($years == 1) ?
$str->year
: $str->years
;
2119 $oyears = $years .' '. $sy;
2122 $odays = $days .' '. $sd;
2125 $ohours = $hours .' '. $sh;
2128 $omins = $mins .' '. $sm;
2131 $osecs = $secs .' '. $ss;
2135 return trim($oyears .' '. $odays);
2138 return trim($odays .' '. $ohours);
2141 return trim($ohours .' '. $omins);
2144 return trim($omins .' '. $osecs);
2149 return get_string('now');
2153 * Returns a formatted string that represents a date in user time.
2157 * @param int $date the timestamp in UTC, as obtained from the database.
2158 * @param string $format strftime format. You should probably get this using
2159 * get_string('strftime...', 'langconfig');
2160 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2161 * not 99 then daylight saving will not be added.
2162 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2163 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2164 * If false then the leading zero is maintained.
2165 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2166 * @return string the formatted date/time.
2168 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2169 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2170 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2174 * Returns a formatted date ensuring it is UTF-8.
2176 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2177 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2179 * This function does not do any calculation regarding the user preferences and should
2180 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2181 * to differentiate the use of server time or not (strftime() against gmstrftime()).
2183 * @param int $date the timestamp.
2184 * @param string $format strftime format.
2185 * @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2186 * @return string the formatted date/time.
2187 * @since Moodle 2.3.3
2189 function date_format_string($date, $format, $tz = 99) {
2192 $localewincharset = null;
2193 // Get the calendar type user is using.
2194 if ($CFG->ostype
== 'WINDOWS') {
2195 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2196 $localewincharset = $calendartype->locale_win_charset();
2199 if (abs($tz) > 13) {
2200 if ($localewincharset) {
2201 $format = core_text
::convert($format, 'utf-8', $localewincharset);
2202 $datestring = strftime($format, $date);
2203 $datestring = core_text
::convert($datestring, $localewincharset, 'utf-8');
2205 $datestring = strftime($format, $date);
2208 if ($localewincharset) {
2209 $format = core_text
::convert($format, 'utf-8', $localewincharset);
2210 $datestring = gmstrftime($format, $date);
2211 $datestring = core_text
::convert($datestring, $localewincharset, 'utf-8');
2213 $datestring = gmstrftime($format, $date);
2220 * Given a $time timestamp in GMT (seconds since epoch),
2221 * returns an array that represents the date in user time
2226 * @param int $time Timestamp in GMT
2227 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2228 * dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
2229 * @return array An array that represents the date in user time
2231 function usergetdate($time, $timezone=99) {
2233 // Save input timezone, required for dst offset check.
2234 $passedtimezone = $timezone;
2236 $timezone = get_user_timezone_offset($timezone);
2238 if (abs($timezone) > 13) {
2240 return getdate($time);
2243 // Add daylight saving offset for string timezones only, as we can't get dst for
2244 // float values. if timezone is 99 (user default timezone), then try update dst.
2245 if ($passedtimezone == 99 ||
!is_numeric($passedtimezone)) {
2246 $time +
= dst_offset_on($time, $passedtimezone);
2249 $time +
= intval((float)$timezone * HOURSECS
);
2251 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2253 // Be careful to ensure the returned array matches that produced by getdate() above.
2256 $getdate['weekday'],
2263 $getdate['minutes'],
2265 ) = explode('_', $datestring);
2267 // Set correct datatype to match with getdate().
2268 $getdate['seconds'] = (int)$getdate['seconds'];
2269 $getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
2270 $getdate['year'] = (int)$getdate['year'];
2271 $getdate['mon'] = (int)$getdate['mon'];
2272 $getdate['wday'] = (int)$getdate['wday'];
2273 $getdate['mday'] = (int)$getdate['mday'];
2274 $getdate['hours'] = (int)$getdate['hours'];
2275 $getdate['minutes'] = (int)$getdate['minutes'];
2280 * Given a GMT timestamp (seconds since epoch), offsets it by
2281 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2286 * @param int $date Timestamp in GMT
2287 * @param float|int|string $timezone timezone to calculate GMT time offset before
2288 * calculating user time, 99 is default user timezone
2289 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2292 function usertime($date, $timezone=99) {
2294 $timezone = get_user_timezone_offset($timezone);
2296 if (abs($timezone) > 13) {
2299 return $date - (int)($timezone * HOURSECS
);
2303 * Given a time, return the GMT timestamp of the most recent midnight
2304 * for the current user.
2308 * @param int $date Timestamp in GMT
2309 * @param float|int|string $timezone timezone to calculate GMT time offset before
2310 * calculating user midnight time, 99 is default user timezone
2311 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2312 * @return int Returns a GMT timestamp
2314 function usergetmidnight($date, $timezone=99) {
2316 $userdate = usergetdate($date, $timezone);
2318 // Time of midnight of this user's day, in GMT.
2319 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2324 * Returns a string that prints the user's timezone
2328 * @param float|int|string $timezone timezone to calculate GMT time offset before
2329 * calculating user timezone, 99 is default user timezone
2330 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2333 function usertimezone($timezone=99) {
2335 $tz = get_user_timezone($timezone);
2337 if (!is_float($tz)) {
2341 if (abs($tz) > 13) {
2343 return get_string('serverlocaltime');
2346 if ($tz == intval($tz)) {
2347 // Don't show .0 for whole hours.
2353 } else if ($tz > 0) {
2362 * Returns a float which represents the user's timezone difference from GMT in hours
2363 * Checks various settings and picks the most dominant of those which have a value
2367 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2368 * 99 is default user timezone
2369 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2372 function get_user_timezone_offset($tz = 99) {
2373 $tz = get_user_timezone($tz);
2375 if (is_float($tz)) {
2378 $tzrecord = get_timezone_record($tz);
2379 if (empty($tzrecord)) {
2382 return (float)$tzrecord->gmtoff
/ HOURMINS
;
2387 * Returns an int which represents the systems's timezone difference from GMT in seconds
2391 * @param float|int|string $tz timezone for which offset is required.
2392 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2393 * @return int|bool if found, false is timezone 99 or error
2395 function get_timezone_offset($tz) {
2400 if (is_numeric($tz)) {
2401 return intval($tz * 60*60);
2404 if (!$tzrecord = get_timezone_record($tz)) {
2407 return intval($tzrecord->gmtoff
* 60);
2411 * Returns a float or a string which denotes the user's timezone
2412 * 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)
2413 * means that for this timezone there are also DST rules to be taken into account
2414 * Checks various settings and picks the most dominant of those which have a value
2418 * @param float|int|string $tz timezone to calculate GMT time offset before
2419 * calculating user timezone, 99 is default user timezone
2420 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2421 * @return float|string
2423 function get_user_timezone($tz = 99) {
2428 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
2429 isset($USER->timezone
) ?
$USER->timezone
: 99,
2430 isset($CFG->timezone
) ?
$CFG->timezone
: 99,
2435 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2436 while (((empty($tz) && !is_numeric($tz)) ||
$tz == 99) && $next = each($timezones)) {
2437 $tz = $next['value'];
2439 return is_numeric($tz) ?
(float) $tz : $tz;
2443 * Returns cached timezone record for given $timezonename
2446 * @param string $timezonename name of the timezone
2447 * @return stdClass|bool timezonerecord or false
2449 function get_timezone_record($timezonename) {
2451 static $cache = null;
2453 if ($cache === null) {
2457 if (isset($cache[$timezonename])) {
2458 return $cache[$timezonename];
2461 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2462 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE
);
2466 * Build and store the users Daylight Saving Time (DST) table
2469 * @param int $fromyear Start year for the table, defaults to 1971
2470 * @param int $toyear End year for the table, defaults to 2035
2471 * @param int|float|string $strtimezone timezone to check if dst should be applied.
2474 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2475 global $SESSION, $DB;
2477 $usertz = get_user_timezone($strtimezone);
2479 if (is_float($usertz)) {
2480 // Trivial timezone, no DST.
2484 if (!empty($SESSION->dst_offsettz
) && $SESSION->dst_offsettz
!= $usertz) {
2485 // We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
2486 unset($SESSION->dst_offsets
);
2487 unset($SESSION->dst_range
);
2490 if (!empty($SESSION->dst_offsets
) && empty($fromyear) && empty($toyear)) {
2491 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
2492 // This will be the return path most of the time, pretty light computationally.
2496 // Reaching here means we either need to extend our table or create it from scratch.
2498 // Remember which TZ we calculated these changes for.
2499 $SESSION->dst_offsettz
= $usertz;
2501 if (empty($SESSION->dst_offsets
)) {
2502 // If we 're creating from scratch, put the two guard elements in there.
2503 $SESSION->dst_offsets
= array(1 => null, 0 => null);
2505 if (empty($SESSION->dst_range
)) {
2506 // If creating from scratch.
2507 $from = max((empty($fromyear) ?
intval(date('Y')) - 3 : $fromyear), 1971);
2508 $to = min((empty($toyear) ?
intval(date('Y')) +
3 : $toyear), 2035);
2510 // Fill in the array with the extra years we need to process.
2511 $yearstoprocess = array();
2512 for ($i = $from; $i <= $to; ++
$i) {
2513 $yearstoprocess[] = $i;
2516 // Take note of which years we have processed for future calls.
2517 $SESSION->dst_range
= array($from, $to);
2519 // If needing to extend the table, do the same.
2520 $yearstoprocess = array();
2522 $from = max((empty($fromyear) ?
$SESSION->dst_range
[0] : $fromyear), 1971);
2523 $to = min((empty($toyear) ?
$SESSION->dst_range
[1] : $toyear), 2035);
2525 if ($from < $SESSION->dst_range
[0]) {
2526 // Take note of which years we need to process and then note that we have processed them for future calls.
2527 for ($i = $from; $i < $SESSION->dst_range
[0]; ++
$i) {
2528 $yearstoprocess[] = $i;
2530 $SESSION->dst_range
[0] = $from;
2532 if ($to > $SESSION->dst_range
[1]) {
2533 // Take note of which years we need to process and then note that we have processed them for future calls.
2534 for ($i = $SESSION->dst_range
[1] +
1; $i <= $to; ++
$i) {
2535 $yearstoprocess[] = $i;
2537 $SESSION->dst_range
[1] = $to;
2541 if (empty($yearstoprocess)) {
2542 // This means that there was a call requesting a SMALLER range than we have already calculated.
2546 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2547 // Also, the array is sorted in descending timestamp order!
2551 static $presetscache = array();
2552 if (!isset($presetscache[$usertz])) {
2553 $presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
2554 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
2555 'std_startday, std_weekday, std_skipweeks, std_time');
2557 if (empty($presetscache[$usertz])) {
2561 // Remove ending guard (first element of the array).
2562 reset($SESSION->dst_offsets
);
2563 unset($SESSION->dst_offsets
[key($SESSION->dst_offsets
)]);
2565 // Add all required change timestamps.
2566 foreach ($yearstoprocess as $y) {
2567 // Find the record which is in effect for the year $y.
2568 foreach ($presetscache[$usertz] as $year => $preset) {
2574 $changes = dst_changes_for_year($y, $preset);
2576 if ($changes === null) {
2579 if ($changes['dst'] != 0) {
2580 $SESSION->dst_offsets
[$changes['dst']] = $preset->dstoff
* MINSECS
;
2582 if ($changes['std'] != 0) {
2583 $SESSION->dst_offsets
[$changes['std']] = 0;
2587 // Put in a guard element at the top.
2588 $maxtimestamp = max(array_keys($SESSION->dst_offsets
));
2589 $SESSION->dst_offsets
[($maxtimestamp + DAYSECS
)] = null; // DAYSECS is arbitrary, any "small" number will do.
2592 krsort($SESSION->dst_offsets
);
2598 * Calculates the required DST change and returns a Timestamp Array
2604 * @param int|string $year Int or String Year to focus on
2605 * @param object $timezone Instatiated Timezone object
2606 * @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
2608 function dst_changes_for_year($year, $timezone) {
2610 if ($timezone->dst_startday
== 0 && $timezone->dst_weekday
== 0 &&
2611 $timezone->std_startday
== 0 && $timezone->std_weekday
== 0) {
2615 $monthdaydst = find_day_in_month($timezone->dst_startday
, $timezone->dst_weekday
, $timezone->dst_month
, $year);
2616 $monthdaystd = find_day_in_month($timezone->std_startday
, $timezone->std_weekday
, $timezone->std_month
, $year);
2618 list($dsthour, $dstmin) = explode(':', $timezone->dst_time
);
2619 list($stdhour, $stdmin) = explode(':', $timezone->std_time
);
2621 $timedst = make_timestamp($year, $timezone->dst_month
, $monthdaydst, 0, 0, 0, 99, false);
2622 $timestd = make_timestamp($year, $timezone->std_month
, $monthdaystd, 0, 0, 0, 99, false);
2624 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2625 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2626 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2628 $timedst +
= $dsthour * HOURSECS +
$dstmin * MINSECS
;
2629 $timestd +
= $stdhour * HOURSECS +
$stdmin * MINSECS
;
2631 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2635 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2636 * - Note: Daylight saving only works for string timezones and not for float.
2640 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2641 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2642 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2645 function dst_offset_on($time, $strtimezone = null) {
2648 if (!calculate_user_dst_table(null, null, $strtimezone) ||
empty($SESSION->dst_offsets
)) {
2652 reset($SESSION->dst_offsets
);
2653 while (list($from, $offset) = each($SESSION->dst_offsets
)) {
2654 if ($from <= $time) {
2659 // This is the normal return path.
2660 if ($offset !== null) {
2664 // Reaching this point means we haven't calculated far enough, do it now:
2665 // Calculate extra DST changes if needed and recurse. The recursion always
2666 // moves toward the stopping condition, so will always end.
2669 // We need a year smaller than $SESSION->dst_range[0].
2670 if ($SESSION->dst_range
[0] == 1971) {
2673 calculate_user_dst_table($SESSION->dst_range
[0] - 5, null, $strtimezone);
2674 return dst_offset_on($time, $strtimezone);
2676 // We need a year larger than $SESSION->dst_range[1].
2677 if ($SESSION->dst_range
[1] == 2035) {
2680 calculate_user_dst_table(null, $SESSION->dst_range
[1] +
5, $strtimezone);
2681 return dst_offset_on($time, $strtimezone);
2686 * Calculates when the day appears in specific month
2690 * @param int $startday starting day of the month
2691 * @param int $weekday The day when week starts (normally taken from user preferences)
2692 * @param int $month The month whose day is sought
2693 * @param int $year The year of the month whose day is sought
2696 function find_day_in_month($startday, $weekday, $month, $year) {
2697 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2699 $daysinmonth = days_in_month($month, $year);
2700 $daysinweek = count($calendartype->get_weekdays());
2702 if ($weekday == -1) {
2703 // Don't care about weekday, so return:
2704 // abs($startday) if $startday != -1
2705 // $daysinmonth otherwise.
2706 return ($startday == -1) ?
$daysinmonth : abs($startday);
2709 // From now on we 're looking for a specific weekday.
2710 // Give "end of month" its actual value, since we know it.
2711 if ($startday == -1) {
2712 $startday = -1 * $daysinmonth;
2715 // Starting from day $startday, the sign is the direction.
2716 if ($startday < 1) {
2717 $startday = abs($startday);
2718 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2720 // This is the last such weekday of the month.
2721 $lastinmonth = $daysinmonth +
$weekday - $lastmonthweekday;
2722 if ($lastinmonth > $daysinmonth) {
2723 $lastinmonth -= $daysinweek;
2726 // Find the first such weekday <= $startday.
2727 while ($lastinmonth > $startday) {
2728 $lastinmonth -= $daysinweek;
2731 return $lastinmonth;
2733 $indexweekday = dayofweek($startday, $month, $year);
2735 $diff = $weekday - $indexweekday;
2737 $diff +
= $daysinweek;
2740 // This is the first such weekday of the month equal to or after $startday.
2741 $firstfromindex = $startday +
$diff;
2743 return $firstfromindex;
2748 * Calculate the number of days in a given month
2752 * @param int $month The month whose day count is sought
2753 * @param int $year The year of the month whose day count is sought
2756 function days_in_month($month, $year) {
2757 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2758 return $calendartype->get_num_days_in_month($year, $month);
2762 * Calculate the position in the week of a specific calendar day
2766 * @param int $day The day of the date whose position in the week is sought
2767 * @param int $month The month of the date whose position in the week is sought
2768 * @param int $year The year of the date whose position in the week is sought
2771 function dayofweek($day, $month, $year) {
2772 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2773 return $calendartype->get_weekday($year, $month, $day);
2776 // USER AUTHENTICATION AND LOGIN.
2779 * Returns full login url.
2781 * @return string login url
2783 function get_login_url() {
2786 $url = "$CFG->wwwroot/login/index.php";
2788 if (!empty($CFG->loginhttps
)) {
2789 $url = str_replace('http:', 'https:', $url);
2796 * This function checks that the current user is logged in and has the
2797 * required privileges
2799 * This function checks that the current user is logged in, and optionally
2800 * whether they are allowed to be in a particular course and view a particular
2802 * If they are not logged in, then it redirects them to the site login unless
2803 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2804 * case they are automatically logged in as guests.
2805 * If $courseid is given and the user is not enrolled in that course then the
2806 * user is redirected to the course enrolment page.
2807 * If $cm is given and the course module is hidden and the user is not a teacher
2808 * in the course then the user is redirected to the course home page.
2810 * When $cm parameter specified, this function sets page layout to 'module'.
2811 * You need to change it manually later if some other layout needed.
2813 * @package core_access
2816 * @param mixed $courseorid id of the course or course object
2817 * @param bool $autologinguest default true
2818 * @param object $cm course module object
2819 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2820 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2821 * in order to keep redirects working properly. MDL-14495
2822 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2823 * @return mixed Void, exit, and die depending on path
2824 * @throws coding_exception
2825 * @throws require_login_exception
2827 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2828 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2830 // Must not redirect when byteserving already started.
2831 if (!empty($_SERVER['HTTP_RANGE'])) {
2832 $preventredirect = true;
2835 // Setup global $COURSE, themes, language and locale.
2836 if (!empty($courseorid)) {
2837 if (is_object($courseorid)) {
2838 $course = $courseorid;
2839 } else if ($courseorid == SITEID
) {
2840 $course = clone($SITE);
2842 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST
);
2845 if ($cm->course
!= $course->id
) {
2846 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2848 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2849 if (!($cm instanceof cm_info
)) {
2850 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2851 // db queries so this is not really a performance concern, however it is obviously
2852 // better if you use get_fast_modinfo to get the cm before calling this.
2853 $modinfo = get_fast_modinfo($course);
2854 $cm = $modinfo->get_cm($cm->id
);
2856 $PAGE->set_cm($cm, $course); // Set's up global $COURSE.
2857 $PAGE->set_pagelayout('incourse');
2859 $PAGE->set_course($course); // Set's up global $COURSE.
2862 // Do not touch global $COURSE via $PAGE->set_course(),
2863 // the reasons is we need to be able to call require_login() at any time!!
2866 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2870 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2871 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2872 // risk leading the user back to the AJAX request URL.
2873 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT
) {
2874 $setwantsurltome = false;
2877 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2878 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out
) && !$preventredirect && !empty($CFG->dbsessions
)) {
2879 if ($setwantsurltome) {
2880 $SESSION->wantsurl
= qualified_me();
2882 redirect(get_login_url());
2885 // If the user is not even logged in yet then make sure they are.
2886 if (!isloggedin()) {
2887 if ($autologinguest and !empty($CFG->guestloginbutton
) and !empty($CFG->autologinguests
)) {
2888 if (!$guest = get_complete_user_data('id', $CFG->siteguest
)) {
2889 // Misconfigured site guest, just redirect to login page.
2890 redirect(get_login_url());
2891 exit; // Never reached.
2893 $lang = isset($SESSION->lang
) ?
$SESSION->lang
: $CFG->lang
;
2894 complete_user_login($guest);
2895 $USER->autologinguest
= true;
2896 $SESSION->lang
= $lang;
2898 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2899 if ($preventredirect) {
2900 throw new require_login_exception('You are not logged in');
2903 if ($setwantsurltome) {
2904 $SESSION->wantsurl
= qualified_me();
2906 if (!empty($_SERVER['HTTP_REFERER'])) {
2907 $SESSION->fromurl
= $_SERVER['HTTP_REFERER'];
2909 redirect(get_login_url());
2910 exit; // Never reached.
2914 // Loginas as redirection if needed.
2915 if ($course->id
!= SITEID
and \core\session\manager
::is_loggedinas()) {
2916 if ($USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
2917 if ($USER->loginascontext
->instanceid
!= $course->id
) {
2918 print_error('loginasonecourse', '', $CFG->wwwroot
.'/course/view.php?id='.$USER->loginascontext
->instanceid
);
2923 // Check whether the user should be changing password (but only if it is REALLY them).
2924 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager
::is_loggedinas()) {
2925 $userauth = get_auth_plugin($USER->auth
);
2926 if ($userauth->can_change_password() and !$preventredirect) {
2927 if ($setwantsurltome) {
2928 $SESSION->wantsurl
= qualified_me();
2930 if ($changeurl = $userauth->change_password_url()) {
2931 // Use plugin custom url.
2932 redirect($changeurl);
2934 // Use moodle internal method.
2935 if (empty($CFG->loginhttps
)) {
2936 redirect($CFG->wwwroot
.'/login/change_password.php');
2938 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot
);
2939 redirect($wwwroot .'/login/change_password.php');
2943 print_error('nopasswordchangeforced', 'auth');
2947 // Check that the user account is properly set up.
2948 if (user_not_fully_set_up($USER)) {
2949 if ($preventredirect) {
2950 throw new require_login_exception('User not fully set-up');
2952 if ($setwantsurltome) {
2953 $SESSION->wantsurl
= qualified_me();
2955 redirect($CFG->wwwroot
.'/user/edit.php?id='. $USER->id
.'&course='. SITEID
);
2958 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2961 // Do not bother admins with any formalities.
2962 if (is_siteadmin()) {
2963 // Set accesstime or the user will appear offline which messes up messaging.
2964 user_accesstime_log($course->id
);
2968 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2969 if (!$USER->policyagreed
and !is_siteadmin()) {
2970 if (!empty($CFG->sitepolicy
) and !isguestuser()) {
2971 if ($preventredirect) {
2972 throw new require_login_exception('Policy not agreed');
2974 if ($setwantsurltome) {
2975 $SESSION->wantsurl
= qualified_me();
2977 redirect($CFG->wwwroot
.'/user/policy.php');
2978 } else if (!empty($CFG->sitepolicyguest
) and isguestuser()) {
2979 if ($preventredirect) {
2980 throw new require_login_exception('Policy not agreed');
2982 if ($setwantsurltome) {
2983 $SESSION->wantsurl
= qualified_me();
2985 redirect($CFG->wwwroot
.'/user/policy.php');
2989 // Fetch the system context, the course context, and prefetch its child contexts.
2990 $sysctx = context_system
::instance();
2991 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
2993 $cmcontext = context_module
::instance($cm->id
, MUST_EXIST
);
2998 // If the site is currently under maintenance, then print a message.
2999 if (!empty($CFG->maintenance_enabled
) and !has_capability('moodle/site:config', $sysctx)) {
3000 if ($preventredirect) {
3001 throw new require_login_exception('Maintenance in progress');
3004 print_maintenance_message();
3007 // Make sure the course itself is not hidden.
3008 if ($course->id
== SITEID
) {
3009 // Frontpage can not be hidden.
3011 if (is_role_switched($course->id
)) {
3012 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
3014 if (!$course->visible
and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3015 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
3016 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
3017 if ($preventredirect) {
3018 throw new require_login_exception('Course is hidden');
3020 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3021 // the navigation will mess up when trying to find it.
3022 navigation_node
::override_active_url(new moodle_url('/'));
3023 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
3028 // Is the user enrolled?
3029 if ($course->id
== SITEID
) {
3030 // Everybody is enrolled on the frontpage.
3032 if (\core\session\manager
::is_loggedinas()) {
3033 // Make sure the REAL person can access this course first.
3034 $realuser = \core\session\manager
::get_realuser();
3035 if (!is_enrolled($coursecontext, $realuser->id
, '', true) and
3036 !is_viewing($coursecontext, $realuser->id
) and !is_siteadmin($realuser->id
)) {
3037 if ($preventredirect) {
3038 throw new require_login_exception('Invalid course login-as access');
3040 echo $OUTPUT->header();
3041 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot
.'/');
3047 if (is_role_switched($course->id
)) {
3048 // Ok, user had to be inside this course before the switch.
3051 } else if (is_viewing($coursecontext, $USER)) {
3052 // Ok, no need to mess with enrol.
3056 if (isset($USER->enrol
['enrolled'][$course->id
])) {
3057 if ($USER->enrol
['enrolled'][$course->id
] > time()) {
3059 if (isset($USER->enrol
['tempguest'][$course->id
])) {
3060 unset($USER->enrol
['tempguest'][$course->id
]);
3061 remove_temp_course_roles($coursecontext);
3065 unset($USER->enrol
['enrolled'][$course->id
]);
3068 if (isset($USER->enrol
['tempguest'][$course->id
])) {
3069 if ($USER->enrol
['tempguest'][$course->id
] == 0) {
3071 } else if ($USER->enrol
['tempguest'][$course->id
] > time()) {
3075 unset($USER->enrol
['tempguest'][$course->id
]);
3076 remove_temp_course_roles($coursecontext);
3082 $until = enrol_get_enrolment_end($coursecontext->instanceid
, $USER->id
);
3083 if ($until !== false) {
3084 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3086 $until = ENROL_MAX_TIMESTAMP
;
3088 $USER->enrol
['enrolled'][$course->id
] = $until;
3092 $params = array('courseid' => $course->id
, 'status' => ENROL_INSTANCE_ENABLED
);
3093 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3094 $enrols = enrol_get_plugins(true);
3095 // First ask all enabled enrol instances in course if they want to auto enrol user.
3096 foreach ($instances as $instance) {
3097 if (!isset($enrols[$instance->enrol
])) {
3100 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3101 $until = $enrols[$instance->enrol
]->try_autoenrol($instance);
3102 if ($until !== false) {
3104 $until = ENROL_MAX_TIMESTAMP
;
3106 $USER->enrol
['enrolled'][$course->id
] = $until;
3111 // If not enrolled yet try to gain temporary guest access.
3113 foreach ($instances as $instance) {
3114 if (!isset($enrols[$instance->enrol
])) {
3117 // Get a duration for the guest access, a timestamp in the future or false.
3118 $until = $enrols[$instance->enrol
]->try_guestaccess($instance);
3119 if ($until !== false and $until > time()) {
3120 $USER->enrol
['tempguest'][$course->id
] = $until;
3131 if ($preventredirect) {
3132 throw new require_login_exception('Not enrolled');
3134 if ($setwantsurltome) {
3135 $SESSION->wantsurl
= qualified_me();
3137 redirect($CFG->wwwroot
.'/enrol/index.php?id='. $course->id
);
3141 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3142 if ($cm && !$cm->uservisible
) {
3143 if ($preventredirect) {
3144 throw new require_login_exception('Activity is hidden');
3146 if ($course->id
!= SITEID
) {
3147 $url = new moodle_url('/course/view.php', array('id' => $course->id
));
3149 $url = new moodle_url('/');
3151 redirect($url, get_string('activityiscurrentlyhidden'));
3154 // Finally access granted, update lastaccess times.
3155 user_accesstime_log($course->id
);
3160 * This function just makes sure a user is logged out.
3162 * @package core_access
3165 function require_logout() {
3168 if (!isloggedin()) {
3169 // This should not happen often, no need for hooks or events here.
3170 \core\session\manager
::terminate_current();
3174 // Execute hooks before action.
3175 $authplugins = array();
3176 $authsequence = get_enabled_auth_plugins();
3177 foreach ($authsequence as $authname) {
3178 $authplugins[$authname] = get_auth_plugin($authname);
3179 $authplugins[$authname]->prelogout_hook();
3182 // Store info that gets removed during logout.
3183 $sid = session_id();
3184 $event = \core\event\user_loggedout
::create(
3186 'userid' => $USER->id
,
3187 'objectid' => $USER->id
,
3188 'other' => array('sessionid' => $sid),
3191 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3192 $event->add_record_snapshot('sessions', $session);
3195 // Clone of $USER object to be used by auth plugins.
3196 $user = fullclone($USER);
3198 // Delete session record and drop $_SESSION content.
3199 \core\session\manager
::terminate_current();
3201 // Trigger event AFTER action.
3204 // Hook to execute auth plugins redirection after event trigger.
3205 foreach ($authplugins as $authplugin) {
3206 $authplugin->postlogout_hook($user);
3211 * Weaker version of require_login()
3213 * This is a weaker version of {@link require_login()} which only requires login
3214 * when called from within a course rather than the site page, unless
3215 * the forcelogin option is turned on.
3216 * @see require_login()
3218 * @package core_access
3221 * @param mixed $courseorid The course object or id in question
3222 * @param bool $autologinguest Allow autologin guests if that is wanted
3223 * @param object $cm Course activity module if known
3224 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3225 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3226 * in order to keep redirects working properly. MDL-14495
3227 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3229 * @throws coding_exception
3231 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3232 global $CFG, $PAGE, $SITE;
3233 $issite = ((is_object($courseorid) and $courseorid->id
== SITEID
)
3234 or (!is_object($courseorid) and $courseorid == SITEID
));
3235 if ($issite && !empty($cm) && !($cm instanceof cm_info
)) {
3236 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3237 // db queries so this is not really a performance concern, however it is obviously
3238 // better if you use get_fast_modinfo to get the cm before calling this.
3239 if (is_object($courseorid)) {
3240 $course = $courseorid;
3242 $course = clone($SITE);
3244 $modinfo = get_fast_modinfo($course);
3245 $cm = $modinfo->get_cm($cm->id
);
3247 if (!empty($CFG->forcelogin
)) {
3248 // Login required for both SITE and courses.
3249 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3251 } else if ($issite && !empty($cm) and !$cm->uservisible
) {
3252 // Always login for hidden activities.
3253 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3255 } else if ($issite) {
3256 // Login for SITE not required.
3257 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3258 if (!empty($courseorid)) {
3259 if (is_object($courseorid)) {
3260 $course = $courseorid;
3262 $course = clone $SITE;
3265 if ($cm->course
!= $course->id
) {
3266 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3268 $PAGE->set_cm($cm, $course);
3269 $PAGE->set_pagelayout('incourse');
3271 $PAGE->set_course($course);
3274 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3275 $PAGE->set_course($PAGE->course
);
3277 user_accesstime_log(SITEID
);
3281 // Course login always required.
3282 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3287 * Require key login. Function terminates with error if key not found or incorrect.
3289 * @uses NO_MOODLE_COOKIES
3290 * @uses PARAM_ALPHANUM
3291 * @param string $script unique script identifier
3292 * @param int $instance optional instance id
3293 * @return int Instance ID
3295 function require_user_key_login($script, $instance=null) {
3298 if (!NO_MOODLE_COOKIES
) {
3299 print_error('sessioncookiesdisable');
3303 \core\session\manager
::write_close();
3305 $keyvalue = required_param('key', PARAM_ALPHANUM
);
3307 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3308 print_error('invalidkey');
3311 if (!empty($key->validuntil
) and $key->validuntil
< time()) {
3312 print_error('expiredkey');
3315 if ($key->iprestriction
) {
3316 $remoteaddr = getremoteaddr(null);
3317 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction
)) {
3318 print_error('ipmismatch');
3322 if (!$user = $DB->get_record('user', array('id' => $key->userid
))) {
3323 print_error('invaliduserid');
3326 // Emulate normal session.
3327 enrol_check_plugins($user);
3328 \core\session\manager
::set_user($user);
3330 // Note we are not using normal login.
3331 if (!defined('USER_KEY_LOGIN')) {
3332 define('USER_KEY_LOGIN', true);
3335 // Return instance id - it might be empty.
3336 return $key->instance
;
3340 * Creates a new private user access key.
3342 * @param string $script unique target identifier
3343 * @param int $userid
3344 * @param int $instance optional instance id
3345 * @param string $iprestriction optional ip restricted access
3346 * @param timestamp $validuntil key valid only until given data
3347 * @return string access key value
3349 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3352 $key = new stdClass();
3353 $key->script
= $script;
3354 $key->userid
= $userid;
3355 $key->instance
= $instance;
3356 $key->iprestriction
= $iprestriction;
3357 $key->validuntil
= $validuntil;
3358 $key->timecreated
= time();
3360 // Something long and unique.
3361 $key->value
= md5($userid.'_'.time().random_string(40));
3362 while ($DB->record_exists('user_private_key', array('value' => $key->value
))) {
3364 $key->value
= md5($userid.'_'.time().random_string(40));
3366 $DB->insert_record('user_private_key', $key);
3371 * Delete the user's new private user access keys for a particular script.
3373 * @param string $script unique target identifier
3374 * @param int $userid
3377 function delete_user_key($script, $userid) {
3379 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3383 * Gets a private user access key (and creates one if one doesn't exist).
3385 * @param string $script unique target identifier
3386 * @param int $userid
3387 * @param int $instance optional instance id
3388 * @param string $iprestriction optional ip restricted access
3389 * @param timestamp $validuntil key valid only until given data
3390 * @return string access key value
3392 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3395 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3396 'instance' => $instance, 'iprestriction' => $iprestriction,
3397 'validuntil' => $validuntil))) {
3400 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3406 * Modify the user table by setting the currently logged in user's last login to now.
3408 * @return bool Always returns true
3410 function update_user_login_times() {
3413 if (isguestuser()) {
3414 // Do not update guest access times/ips for performance.
3420 $user = new stdClass();
3421 $user->id
= $USER->id
;
3423 // Make sure all users that logged in have some firstaccess.
3424 if ($USER->firstaccess
== 0) {
3425 $USER->firstaccess
= $user->firstaccess
= $now;
3428 // Store the previous current as lastlogin.
3429 $USER->lastlogin
= $user->lastlogin
= $USER->currentlogin
;
3431 $USER->currentlogin
= $user->currentlogin
= $now;
3433 // Function user_accesstime_log() may not update immediately, better do it here.
3434 $USER->lastaccess
= $user->lastaccess
= $now;
3435 $USER->lastip
= $user->lastip
= getremoteaddr();
3437 // Note: do not call user_update_user() here because this is part of the login process,
3438 // the login event means that these fields were updated.
3439 $DB->update_record('user', $user);
3444 * Determines if a user has completed setting up their account.
3446 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3449 function user_not_fully_set_up($user) {
3450 if (isguestuser($user)) {
3453 return (empty($user->firstname
) or empty($user->lastname
) or empty($user->email
) or over_bounce_threshold($user));
3457 * Check whether the user has exceeded the bounce threshold
3459 * @param stdClass $user A {@link $USER} object
3460 * @return bool true => User has exceeded bounce threshold
3462 function over_bounce_threshold($user) {
3465 if (empty($CFG->handlebounces
)) {
3469 if (empty($user->id
)) {
3470 // No real (DB) user, nothing to do here.
3474 // Set sensible defaults.
3475 if (empty($CFG->minbounces
)) {
3476 $CFG->minbounces
= 10;
3478 if (empty($CFG->bounceratio
)) {
3479 $CFG->bounceratio
= .20;
3483 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3484 $bouncecount = $bounce->value
;
3486 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3487 $sendcount = $send->value
;
3489 return ($bouncecount >= $CFG->minbounces
&& $bouncecount/$sendcount >= $CFG->bounceratio
);
3493 * Used to increment or reset email sent count
3495 * @param stdClass $user object containing an id
3496 * @param bool $reset will reset the count to 0
3499 function set_send_count($user, $reset=false) {
3502 if (empty($user->id
)) {
3503 // No real (DB) user, nothing to do here.
3507 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3508 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3509 $DB->update_record('user_preferences', $pref);
3510 } else if (!empty($reset)) {
3511 // If it's not there and we're resetting, don't bother. Make a new one.
3512 $pref = new stdClass();
3513 $pref->name
= 'email_send_count';
3515 $pref->userid
= $user->id
;
3516 $DB->insert_record('user_preferences', $pref, false);
3521 * Increment or reset user's email bounce count
3523 * @param stdClass $user object containing an id
3524 * @param bool $reset will reset the count to 0
3526 function set_bounce_count($user, $reset=false) {
3529 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3530 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3531 $DB->update_record('user_preferences', $pref);
3532 } else if (!empty($reset)) {
3533 // If it's not there and we're resetting, don't bother. Make a new one.
3534 $pref = new stdClass();
3535 $pref->name
= 'email_bounce_count';
3537 $pref->userid
= $user->id
;
3538 $DB->insert_record('user_preferences', $pref, false);
3543 * Determines if the logged in user is currently moving an activity
3545 * @param int $courseid The id of the course being tested
3548 function ismoving($courseid) {
3551 if (!empty($USER->activitycopy
)) {
3552 return ($USER->activitycopycourse
== $courseid);
3558 * Returns a persons full name
3560 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3561 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3564 * @param stdClass $user A {@link $USER} object to get full name of.
3565 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3568 function fullname($user, $override=false) {
3569 global $CFG, $SESSION;
3571 if (!isset($user->firstname
) and !isset($user->lastname
)) {
3575 // Get all of the name fields.
3576 $allnames = get_all_user_name_fields();
3577 if ($CFG->debugdeveloper
) {
3578 foreach ($allnames as $allname) {
3579 if (!array_key_exists($allname, $user)) {
3580 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3581 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER
);
3582 // Message has been sent, no point in sending the message multiple times.
3589 if (!empty($CFG->forcefirstname
)) {
3590 $user->firstname
= $CFG->forcefirstname
;
3592 if (!empty($CFG->forcelastname
)) {
3593 $user->lastname
= $CFG->forcelastname
;
3597 if (!empty($SESSION->fullnamedisplay
)) {
3598 $CFG->fullnamedisplay
= $SESSION->fullnamedisplay
;
3602 // If the fullnamedisplay setting is available, set the template to that.
3603 if (isset($CFG->fullnamedisplay
)) {
3604 $template = $CFG->fullnamedisplay
;
3606 // If the template is empty, or set to language, return the language string.
3607 if ((empty($template) ||
$template == 'language') && !$override) {
3608 return get_string('fullnamedisplay', null, $user);
3611 // Check to see if we are displaying according to the alternative full name format.
3613 if (empty($CFG->alternativefullnameformat
) ||
$CFG->alternativefullnameformat
== 'language') {
3614 // Default to show just the user names according to the fullnamedisplay string.
3615 return get_string('fullnamedisplay', null, $user);
3617 // If the override is true, then change the template to use the complete name.
3618 $template = $CFG->alternativefullnameformat
;
3622 $requirednames = array();
3623 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3624 foreach ($allnames as $allname) {
3625 if (strpos($template, $allname) !== false) {
3626 $requirednames[] = $allname;
3630 $displayname = $template;
3631 // Switch in the actual data into the template.
3632 foreach ($requirednames as $altname) {
3633 if (isset($user->$altname)) {
3634 // Using empty() on the below if statement causes breakages.
3635 if ((string)$user->$altname == '') {
3636 $displayname = str_replace($altname, 'EMPTY', $displayname);
3638 $displayname = str_replace($altname, $user->$altname, $displayname);
3641 $displayname = str_replace($altname, 'EMPTY', $displayname);
3644 // Tidy up any misc. characters (Not perfect, but gets most characters).
3645 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3646 // katakana and parenthesis.
3647 $patterns = array();
3648 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3649 // filled in by a user.
3650 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3651 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3652 // This regular expression is to remove any double spaces in the display name.
3653 $patterns[] = '/\s{2,}/u';
3654 foreach ($patterns as $pattern) {
3655 $displayname = preg_replace($pattern, ' ', $displayname);
3658 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3659 $displayname = trim($displayname);
3660 if (empty($displayname)) {
3661 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3662 // people in general feel is a good setting to fall back on.
3663 $displayname = $user->firstname
;
3665 return $displayname;
3669 * A centralised location for the all name fields. Returns an array / sql string snippet.
3671 * @param bool $returnsql True for an sql select field snippet.
3672 * @param string $tableprefix table query prefix to use in front of each field.
3673 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3674 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3675 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3676 * @return array|string All name fields.
3678 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3679 // This array is provided in this order because when called by fullname() (above) if firstname is before
3680 // firstnamephonetic str_replace() will change the wrong placeholder.
3681 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3682 'lastnamephonetic' => 'lastnamephonetic',
3683 'middlename' => 'middlename',
3684 'alternatename' => 'alternatename',
3685 'firstname' => 'firstname',
3686 'lastname' => 'lastname');
3688 // Let's add a prefix to the array of user name fields if provided.
3690 foreach ($alternatenames as $key => $altname) {
3691 $alternatenames[$key] = $prefix . $altname;
3695 // If we want the end result to have firstname and lastname at the front / top of the result.
3697 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3698 for ($i = 0; $i < 2; $i++
) {
3699 // Get the last element.
3700 $lastelement = end($alternatenames);
3701 // Remove it from the array.
3702 unset($alternatenames[$lastelement]);
3703 // Put the element back on the top of the array.
3704 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3708 // Create an sql field snippet if requested.
3712 foreach ($alternatenames as $key => $altname) {
3713 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3716 foreach ($alternatenames as $key => $altname) {
3717 $alternatenames[$key] = $tableprefix . '.' . $altname;
3721 $alternatenames = implode(',', $alternatenames);
3723 return $alternatenames;
3727 * Reduces lines of duplicated code for getting user name fields.
3729 * See also {@link user_picture::unalias()}
3731 * @param object $addtoobject Object to add user name fields to.
3732 * @param object $secondobject Object that contains user name field information.
3733 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3734 * @param array $additionalfields Additional fields to be matched with data in the second object.
3735 * The key can be set to the user table field name.
3736 * @return object User name fields.
3738 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3739 $fields = get_all_user_name_fields(false, null, $prefix);
3740 if ($additionalfields) {
3741 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3742 // the key is a number and then sets the key to the array value.
3743 foreach ($additionalfields as $key => $value) {
3744 if (is_numeric($key)) {
3745 $additionalfields[$value] = $prefix . $value;
3746 unset($additionalfields[$key]);
3748 $additionalfields[$key] = $prefix . $value;
3751 $fields = array_merge($fields, $additionalfields);
3753 foreach ($fields as $key => $field) {
3754 // Important that we have all of the user name fields present in the object that we are sending back.
3755 $addtoobject->$key = '';
3756 if (isset($secondobject->$field)) {
3757 $addtoobject->$key = $secondobject->$field;
3760 return $addtoobject;
3764 * Returns an array of values in order of occurance in a provided string.
3765 * The key in the result is the character postion in the string.
3767 * @param array $values Values to be found in the string format
3768 * @param string $stringformat The string which may contain values being searched for.
3769 * @return array An array of values in order according to placement in the string format.
3771 function order_in_string($values, $stringformat) {
3772 $valuearray = array();
3773 foreach ($values as $value) {
3774 $pattern = "/$value\b/";
3775 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3776 if (preg_match($pattern, $stringformat)) {
3777 $replacement = "thing";
3778 // Replace the value with something more unique to ensure we get the right position when using strpos().
3779 $newformat = preg_replace($pattern, $replacement, $stringformat);
3780 $position = strpos($newformat, $replacement);
3781 $valuearray[$position] = $value;
3789 * Checks if current user is shown any extra fields when listing users.
3791 * @param object $context Context
3792 * @param array $already Array of fields that we're going to show anyway
3793 * so don't bother listing them
3794 * @return array Array of field names from user table, not including anything
3795 * listed in $already
3797 function get_extra_user_fields($context, $already = array()) {
3800 // Only users with permission get the extra fields.
3801 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3805 // Split showuseridentity on comma.
3806 if (empty($CFG->showuseridentity
)) {
3807 // Explode gives wrong result with empty string.
3810 $extra = explode(',', $CFG->showuseridentity
);
3813 foreach ($extra as $key => $field) {
3814 if (in_array($field, $already)) {
3815 unset($extra[$key]);
3820 // For consistency, if entries are removed from array, renumber it
3821 // so they are numbered as you would expect.
3822 $extra = array_merge($extra);
3828 * If the current user is to be shown extra user fields when listing or
3829 * selecting users, returns a string suitable for including in an SQL select
3830 * clause to retrieve those fields.
3832 * @param context $context Context
3833 * @param string $alias Alias of user table, e.g. 'u' (default none)
3834 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3835 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3836 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3838 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3839 $fields = get_extra_user_fields($context, $already);
3841 // Add punctuation for alias.
3842 if ($alias !== '') {
3845 foreach ($fields as $field) {
3846 $result .= ', ' . $alias . $field;
3848 $result .= ' AS ' . $prefix . $field;
3855 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3856 * @param string $field Field name, e.g. 'phone1'
3857 * @return string Text description taken from language file, e.g. 'Phone number'
3859 function get_user_field_name($field) {
3860 // Some fields have language strings which are not the same as field name.
3863 return get_string('phone');
3866 return get_string('webpage');
3869 return get_string('icqnumber');
3872 return get_string('skypeid');
3875 return get_string('aimid');
3878 return get_string('yahooid');
3881 return get_string('msnid');
3884 // Otherwise just use the same lang string.
3885 return get_string($field);
3889 * Returns whether a given authentication plugin exists.
3891 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3892 * @return boolean Whether the plugin is available.
3894 function exists_auth_plugin($auth) {
3897 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3898 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3904 * Checks if a given plugin is in the list of enabled authentication plugins.
3906 * @param string $auth Authentication plugin.
3907 * @return boolean Whether the plugin is enabled.
3909 function is_enabled_auth($auth) {
3914 $enabled = get_enabled_auth_plugins();
3916 return in_array($auth, $enabled);
3920 * Returns an authentication plugin instance.
3922 * @param string $auth name of authentication plugin
3923 * @return auth_plugin_base An instance of the required authentication plugin.
3925 function get_auth_plugin($auth) {
3928 // Check the plugin exists first.
3929 if (! exists_auth_plugin($auth)) {
3930 print_error('authpluginnotfound', 'debug', '', $auth);
3933 // Return auth plugin instance.
3934 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3935 $class = "auth_plugin_$auth";
3940 * Returns array of active auth plugins.
3942 * @param bool $fix fix $CFG->auth if needed
3945 function get_enabled_auth_plugins($fix=false) {
3948 $default = array('manual', 'nologin');
3950 if (empty($CFG->auth
)) {
3953 $auths = explode(',', $CFG->auth
);
3957 $auths = array_unique($auths);
3958 foreach ($auths as $k => $authname) {
3959 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3963 $newconfig = implode(',', $auths);
3964 if (!isset($CFG->auth
) or $newconfig != $CFG->auth
) {
3965 set_config('auth', $newconfig);
3969 return (array_merge($default, $auths));
3973 * Returns true if an internal authentication method is being used.
3974 * if method not specified then, global default is assumed
3976 * @param string $auth Form of authentication required
3979 function is_internal_auth($auth) {
3980 // Throws error if bad $auth.
3981 $authplugin = get_auth_plugin($auth);
3982 return $authplugin->is_internal();
3986 * Returns true if the user is a 'restored' one.
3988 * Used in the login process to inform the user and allow him/her to reset the password
3990 * @param string $username username to be checked
3993 function is_restored_user($username) {
3996 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'password' => 'restored'));
4000 * Returns an array of user fields
4002 * @return array User field/column names
4004 function get_user_fieldnames() {
4007 $fieldarray = $DB->get_columns('user');
4008 unset($fieldarray['id']);
4009 $fieldarray = array_keys($fieldarray);
4015 * Creates a bare-bones user record
4017 * @todo Outline auth types and provide code example
4019 * @param string $username New user's username to add to record
4020 * @param string $password New user's password to add to record
4021 * @param string $auth Form of authentication required
4022 * @return stdClass A complete user object
4024 function create_user_record($username, $password, $auth = 'manual') {
4026 require_once($CFG->dirroot
.'/user/profile/lib.php');
4027 require_once($CFG->dirroot
.'/user/lib.php');
4029 // Just in case check text case.
4030 $username = trim(core_text
::strtolower($username));
4032 $authplugin = get_auth_plugin($auth);
4033 $customfields = $authplugin->get_custom_user_profile_fields();
4034 $newuser = new stdClass();
4035 if ($newinfo = $authplugin->get_userinfo($username)) {
4036 $newinfo = truncate_userinfo($newinfo);
4037 foreach ($newinfo as $key => $value) {
4038 if (in_array($key, $authplugin->userfields
) ||
(in_array($key, $customfields))) {
4039 $newuser->$key = $value;
4044 if (!empty($newuser->email
)) {
4045 if (email_is_not_allowed($newuser->email
)) {
4046 unset($newuser->email
);
4050 if (!isset($newuser->city
)) {
4051 $newuser->city
= '';
4054 $newuser->auth
= $auth;
4055 $newuser->username
= $username;
4058 // user CFG lang for user if $newuser->lang is empty
4059 // or $user->lang is not an installed language.
4060 if (empty($newuser->lang
) ||
!get_string_manager()->translation_exists($newuser->lang
)) {
4061 $newuser->lang
= $CFG->lang
;
4063 $newuser->confirmed
= 1;
4064 $newuser->lastip
= getremoteaddr();
4065 $newuser->timecreated
= time();
4066 $newuser->timemodified
= $newuser->timecreated
;
4067 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
4069 $newuser->id
= user_create_user($newuser, false, false);
4071 // Save user profile data.
4072 profile_save_data($newuser);
4074 $user = get_complete_user_data('id', $newuser->id
);
4075 if (!empty($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'})) {
4076 set_user_preference('auth_forcepasswordchange', 1, $user);
4078 // Set the password.
4079 update_internal_user_password($user, $password);
4082 \core\event\user_created
::create_from_userid($newuser->id
)->trigger();
4088 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4090 * @param string $username user's username to update the record
4091 * @return stdClass A complete user object
4093 function update_user_record($username) {
4095 // Just in case check text case.
4096 $username = trim(core_text
::strtolower($username));
4098 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
), '*', MUST_EXIST
);
4099 return update_user_record_by_id($oldinfo->id
);
4103 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4105 * @param int $id user id
4106 * @return stdClass A complete user object
4108 function update_user_record_by_id($id) {
4110 require_once($CFG->dirroot
."/user/profile/lib.php");
4111 require_once($CFG->dirroot
.'/user/lib.php');
4113 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'id' => $id, 'deleted' => 0);
4114 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST
);
4117 $userauth = get_auth_plugin($oldinfo->auth
);
4119 if ($newinfo = $userauth->get_userinfo($oldinfo->username
)) {
4120 $newinfo = truncate_userinfo($newinfo);
4121 $customfields = $userauth->get_custom_user_profile_fields();
4123 foreach ($newinfo as $key => $value) {
4124 $key = strtolower($key);
4125 $iscustom = in_array($key, $customfields);
4126 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4127 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4128 // Unknown or must not be changed.
4131 $confval = $userauth->config
->{'field_updatelocal_' . $key};
4132 $lockval = $userauth->config
->{'field_lock_' . $key};
4133 if (empty($confval) ||
empty($lockval)) {
4136 if ($confval === 'onlogin') {
4137 // MDL-4207 Don't overwrite modified user profile values with
4138 // empty LDAP values when 'unlocked if empty' is set. The purpose
4139 // of the setting 'unlocked if empty' is to allow the user to fill
4140 // in a value for the selected field _if LDAP is giving
4141 // nothing_ for this field. Thus it makes sense to let this value
4142 // stand in until LDAP is giving a value for this field.
4143 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4144 if ($iscustom ||
(in_array($key, $userauth->userfields
) &&
4145 ((string)$oldinfo->$key !== (string)$value))) {
4146 $newuser[$key] = (string)$value;
4152 $newuser['id'] = $oldinfo->id
;
4153 $newuser['timemodified'] = time();
4154 user_update_user((object) $newuser, false, false);
4156 // Save user profile data.
4157 profile_save_data((object) $newuser);
4160 \core\event\user_updated
::create_from_userid($newuser['id'])->trigger();
4164 return get_complete_user_data('id', $oldinfo->id
);
4168 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4170 * @param array $info Array of user properties to truncate if needed
4171 * @return array The now truncated information that was passed in
4173 function truncate_userinfo(array $info) {
4174 // Define the limits.
4184 'institution' => 255,
4185 'department' => 255,
4192 // Apply where needed.
4193 foreach (array_keys($info) as $key) {
4194 if (!empty($limit[$key])) {
4195 $info[$key] = trim(core_text
::substr($info[$key], 0, $limit[$key]));
4203 * Marks user deleted in internal user database and notifies the auth plugin.
4204 * Also unenrols user from all roles and does other cleanup.
4206 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4208 * @param stdClass $user full user object before delete
4209 * @return boolean success
4210 * @throws coding_exception if invalid $user parameter detected
4212 function delete_user(stdClass
$user) {
4214 require_once($CFG->libdir
.'/grouplib.php');
4215 require_once($CFG->libdir
.'/gradelib.php');
4216 require_once($CFG->dirroot
.'/message/lib.php');
4217 require_once($CFG->dirroot
.'/tag/lib.php');
4218 require_once($CFG->dirroot
.'/user/lib.php');
4220 // Make sure nobody sends bogus record type as parameter.
4221 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4222 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4225 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4226 if (!$user = $DB->get_record('user', array('id' => $user->id
))) {
4227 debugging('Attempt to delete unknown user account.');
4231 // There must be always exactly one guest record, originally the guest account was identified by username only,
4232 // now we use $CFG->siteguest for performance reasons.
4233 if ($user->username
=== 'guest' or isguestuser($user)) {
4234 debugging('Guest user account can not be deleted.');
4238 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4239 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4240 if ($user->auth
=== 'manual' and is_siteadmin($user)) {
4241 debugging('Local administrator accounts can not be deleted.');
4245 // Keep user record before updating it, as we have to pass this to user_deleted event.
4246 $olduser = clone $user;
4248 // Keep a copy of user context, we need it for event.
4249 $usercontext = context_user
::instance($user->id
);
4251 // Delete all grades - backup is kept in grade_grades_history table.
4252 grade_user_delete($user->id
);
4254 // Move unread messages from this user to read.
4255 message_move_userfrom_unread2read($user->id
);
4257 // TODO: remove from cohorts using standard API here.
4259 // Remove user tags.
4260 tag_set('user', $user->id
, array(), 'core', $usercontext->id
);
4262 // Unconditionally unenrol from all courses.
4263 enrol_user_delete($user);
4265 // Unenrol from all roles in all contexts.
4266 // This might be slow but it is really needed - modules might do some extra cleanup!
4267 role_unassign_all(array('userid' => $user->id
));
4269 // Now do a brute force cleanup.
4271 // Remove from all cohorts.
4272 $DB->delete_records('cohort_members', array('userid' => $user->id
));
4274 // Remove from all groups.
4275 $DB->delete_records('groups_members', array('userid' => $user->id
));
4277 // Brute force unenrol from all courses.
4278 $DB->delete_records('user_enrolments', array('userid' => $user->id
));
4280 // Purge user preferences.
4281 $DB->delete_records('user_preferences', array('userid' => $user->id
));
4283 // Purge user extra profile info.
4284 $DB->delete_records('user_info_data', array('userid' => $user->id
));
4286 // Last course access not necessary either.
4287 $DB->delete_records('user_lastaccess', array('userid' => $user->id
));
4288 // Remove all user tokens.
4289 $DB->delete_records('external_tokens', array('userid' => $user->id
));
4291 // Unauthorise the user for all services.
4292 $DB->delete_records('external_services_users', array('userid' => $user->id
));
4294 // Remove users private keys.
4295 $DB->delete_records('user_private_key', array('userid' => $user->id
));
4297 // Remove users customised pages.
4298 $DB->delete_records('my_pages', array('userid' => $user->id
, 'private' => 1));
4300 // Force logout - may fail if file based sessions used, sorry.
4301 \core\session\manager
::kill_user_sessions($user->id
);
4303 // Workaround for bulk deletes of users with the same email address.
4304 $delname = clean_param($user->email
. "." . time(), PARAM_USERNAME
);
4305 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4309 // Mark internal user record as "deleted".
4310 $updateuser = new stdClass();
4311 $updateuser->id
= $user->id
;
4312 $updateuser->deleted
= 1;
4313 $updateuser->username
= $delname; // Remember it just in case.
4314 $updateuser->email
= md5($user->username
);// Store hash of username, useful importing/restoring users.
4315 $updateuser->idnumber
= ''; // Clear this field to free it up.
4316 $updateuser->picture
= 0;
4317 $updateuser->timemodified
= time();
4319 // Don't trigger update event, as user is being deleted.
4320 user_update_user($updateuser, false, false);
4322 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4323 context_helper
::delete_instance(CONTEXT_USER
, $user->id
);
4325 // Any plugin that needs to cleanup should register this event.
4327 $event = \core\event\user_deleted
::create(
4329 'objectid' => $user->id
,
4330 'relateduserid' => $user->id
,
4331 'context' => $usercontext,
4333 'username' => $user->username
,
4334 'email' => $user->email
,
4335 'idnumber' => $user->idnumber
,
4336 'picture' => $user->picture
,
4337 'mnethostid' => $user->mnethostid
4341 $event->add_record_snapshot('user', $olduser);
4344 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4345 // should know about this updated property persisted to the user's table.
4346 $user->timemodified
= $updateuser->timemodified
;
4348 // Notify auth plugin - do not block the delete even when plugin fails.
4349 $authplugin = get_auth_plugin($user->auth
);
4350 $authplugin->user_delete($user);
4356 * Retrieve the guest user object.
4358 * @return stdClass A {@link $USER} object
4360 function guest_user() {
4363 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest
))) {
4364 $newuser->confirmed
= 1;
4365 $newuser->lang
= $CFG->lang
;
4366 $newuser->lastip
= getremoteaddr();
4373 * Authenticates a user against the chosen authentication mechanism
4375 * Given a username and password, this function looks them
4376 * up using the currently selected authentication mechanism,
4377 * and if the authentication is successful, it returns a
4378 * valid $user object from the 'user' table.
4380 * Uses auth_ functions from the currently active auth module
4382 * After authenticate_user_login() returns success, you will need to
4383 * log that the user has logged in, and call complete_user_login() to set
4386 * Note: this function works only with non-mnet accounts!
4388 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4389 * @param string $password User's password
4390 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4391 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4392 * @return stdClass|false A {@link $USER} object or false if error
4394 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4396 require_once("$CFG->libdir/authlib.php");
4398 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id
)) {
4399 // we have found the user
4401 } else if (!empty($CFG->authloginviaemail
)) {
4402 if ($email = clean_param($username, PARAM_EMAIL
)) {
4403 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4404 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'email' => $email);
4405 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4406 if (count($users) === 1) {
4407 // Use email for login only if unique.
4408 $user = reset($users);
4409 $user = get_complete_user_data('id', $user->id
);
4410 $username = $user->username
;
4416 $authsenabled = get_enabled_auth_plugins();
4419 // Use manual if auth not set.
4420 $auth = empty($user->auth
) ?
'manual' : $user->auth
;
4421 if (!empty($user->suspended
)) {
4422 $failurereason = AUTH_LOGIN_SUSPENDED
;
4424 // Trigger login failed event.
4425 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4426 'other' => array('username' => $username, 'reason' => $failurereason)));
4428 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4431 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4432 // Legacy way to suspend user.
4433 $failurereason = AUTH_LOGIN_SUSPENDED
;
4435 // Trigger login failed event.
4436 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4437 'other' => array('username' => $username, 'reason' => $failurereason)));
4439 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4442 $auths = array($auth);
4445 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4446 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'deleted' => 1))) {
4447 $failurereason = AUTH_LOGIN_NOUSER
;
4449 // Trigger login failed event.
4450 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4451 'reason' => $failurereason)));
4453 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4457 // User does not exist.
4458 $auths = $authsenabled;
4459 $user = new stdClass();
4463 if ($ignorelockout) {
4464 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4465 // or this function is called from a SSO script.
4466 } else if ($user->id
) {
4467 // Verify login lockout after other ways that may prevent user login.
4468 if (login_is_lockedout($user)) {
4469 $failurereason = AUTH_LOGIN_LOCKOUT
;
4471 // Trigger login failed event.
4472 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4473 'other' => array('username' => $username, 'reason' => $failurereason)));
4476 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4480 // We can not lockout non-existing accounts.
4483 foreach ($auths as $auth) {
4484 $authplugin = get_auth_plugin($auth);
4486 // On auth fail fall through to the next plugin.
4487 if (!$authplugin->user_login($username, $password)) {
4491 // Successful authentication.
4493 // User already exists in database.
4494 if (empty($user->auth
)) {
4495 // For some reason auth isn't set yet.
4496 $DB->set_field('user', 'auth', $auth, array('id' => $user->id
));
4497 $user->auth
= $auth;
4500 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4501 // the current hash algorithm while we have access to the user's password.
4502 update_internal_user_password($user, $password);
4504 if ($authplugin->is_synchronised_with_external()) {
4505 // Update user record from external DB.
4506 $user = update_user_record_by_id($user->id
);
4509 // The user is authenticated but user creation may be disabled.
4510 if (!empty($CFG->authpreventaccountcreation
)) {
4511 $failurereason = AUTH_LOGIN_UNAUTHORISED
;
4513 // Trigger login failed event.
4514 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4515 'reason' => $failurereason)));
4518 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4519 $_SERVER['HTTP_USER_AGENT']);
4522 $user = create_user_record($username, $password, $auth);
4526 $authplugin->sync_roles($user);
4528 foreach ($authsenabled as $hau) {
4529 $hauth = get_auth_plugin($hau);
4530 $hauth->user_authenticated_hook($user, $username, $password);
4533 if (empty($user->id
)) {
4534 $failurereason = AUTH_LOGIN_NOUSER
;
4535 // Trigger login failed event.
4536 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4537 'reason' => $failurereason)));
4542 if (!empty($user->suspended
)) {
4543 // Just in case some auth plugin suspended account.
4544 $failurereason = AUTH_LOGIN_SUSPENDED
;
4545 // Trigger login failed event.
4546 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4547 'other' => array('username' => $username, 'reason' => $failurereason)));
4549 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4553 login_attempt_valid($user);
4554 $failurereason = AUTH_LOGIN_OK
;
4558 // Failed if all the plugins have failed.
4559 if (debugging('', DEBUG_ALL
)) {
4560 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4564 login_attempt_failed($user);
4565 $failurereason = AUTH_LOGIN_FAILED
;
4566 // Trigger login failed event.
4567 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4568 'other' => array('username' => $username, 'reason' => $failurereason)));
4571 $failurereason = AUTH_LOGIN_NOUSER
;
4572 // Trigger login failed event.
4573 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4574 'reason' => $failurereason)));
4582 * Call to complete the user login process after authenticate_user_login()
4583 * has succeeded. It will setup the $USER variable and other required bits
4587 * - It will NOT log anything -- up to the caller to decide what to log.
4588 * - this function does not set any cookies any more!
4590 * @param stdClass $user
4591 * @return stdClass A {@link $USER} object - BC only, do not use
4593 function complete_user_login($user) {
4596 \core\session\manager
::login_user($user);
4598 // Reload preferences from DB.
4599 unset($USER->preference
);
4600 check_user_preferences_loaded($USER);
4602 // Update login times.
4603 update_user_login_times();
4605 // Extra session prefs init.
4606 set_login_session_preferences();
4608 // Trigger login event.
4609 $event = \core\event\user_loggedin
::create(
4611 'userid' => $USER->id
,
4612 'objectid' => $USER->id
,
4613 'other' => array('username' => $USER->username
),
4618 if (isguestuser()) {
4619 // No need to continue when user is THE guest.
4624 // We can redirect to password change URL only in browser.
4628 // Select password change url.
4629 $userauth = get_auth_plugin($USER->auth
);
4631 // Check whether the user should be changing password.
4632 if (get_user_preferences('auth_forcepasswordchange', false)) {
4633 if ($userauth->can_change_password()) {
4634 if ($changeurl = $userauth->change_password_url()) {
4635 redirect($changeurl);
4637 redirect($CFG->httpswwwroot
.'/login/change_password.php');
4640 print_error('nopasswordchangeforced', 'auth');
4647 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4649 * @param string $password String to check.
4650 * @return boolean True if the $password matches the format of an md5 sum.
4652 function password_is_legacy_hash($password) {
4653 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4657 * Compare password against hash stored in user object to determine if it is valid.
4659 * If necessary it also updates the stored hash to the current format.
4661 * @param stdClass $user (Password property may be updated).
4662 * @param string $password Plain text password.
4663 * @return bool True if password is valid.
4665 function validate_internal_user_password($user, $password) {
4667 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4669 if ($user->password
=== AUTH_PASSWORD_NOT_CACHED
) {
4670 // Internal password is not used at all, it can not validate.
4674 // If hash isn't a legacy (md5) hash, validate using the library function.
4675 if (!password_is_legacy_hash($user->password
)) {
4676 return password_verify($password, $user->password
);
4679 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4680 // is valid we can then update it to the new algorithm.
4682 $sitesalt = isset($CFG->passwordsaltmain
) ?
$CFG->passwordsaltmain
: '';
4685 if ($user->password
=== md5($password.$sitesalt)
4686 or $user->password
=== md5($password)
4687 or $user->password
=== md5(addslashes($password).$sitesalt)
4688 or $user->password
=== md5(addslashes($password))) {
4689 // Note: we are intentionally using the addslashes() here because we
4690 // need to accept old password hashes of passwords with magic quotes.
4694 for ($i=1; $i<=20; $i++
) { // 20 alternative salts should be enough, right?
4695 $alt = 'passwordsaltalt'.$i;
4696 if (!empty($CFG->$alt)) {
4697 if ($user->password
=== md5($password.$CFG->$alt) or $user->password
=== md5(addslashes($password).$CFG->$alt)) {
4706 // If the password matches the existing md5 hash, update to the
4707 // current hash algorithm while we have access to the user's password.
4708 update_internal_user_password($user, $password);
4715 * Calculate hash for a plain text password.
4717 * @param string $password Plain text password to be hashed.
4718 * @param bool $fasthash If true, use a low cost factor when generating the hash
4719 * This is much faster to generate but makes the hash
4720 * less secure. It is used when lots of hashes need to
4721 * be generated quickly.
4722 * @return string The hashed password.
4724 * @throws moodle_exception If a problem occurs while generating the hash.
4726 function hash_internal_user_password($password, $fasthash = false) {
4728 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4730 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4731 $options = ($fasthash) ?
array('cost' => 4) : array();
4733 $generatedhash = password_hash($password, PASSWORD_DEFAULT
, $options);
4735 if ($generatedhash === false ||
$generatedhash === null) {
4736 throw new moodle_exception('Failed to generate password hash.');
4739 return $generatedhash;
4743 * Update password hash in user object (if necessary).
4745 * The password is updated if:
4746 * 1. The password has changed (the hash of $user->password is different
4747 * to the hash of $password).
4748 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4751 * Updating the password will modify the $user object and the database
4752 * record to use the current hashing algorithm.
4754 * @param stdClass $user User object (password property may be updated).
4755 * @param string $password Plain text password.
4756 * @param bool $fasthash If true, use a low cost factor when generating the hash
4757 * This is much faster to generate but makes the hash
4758 * less secure. It is used when lots of hashes need to
4759 * be generated quickly.
4760 * @return bool Always returns true.
4762 function update_internal_user_password($user, $password, $fasthash = false) {
4764 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4766 // Figure out what the hashed password should be.
4767 if (!isset($user->auth
)) {
4768 debugging('User record in update_internal_user_password() must include field auth',
4770 $user->auth
= $DB->get_field('user', 'auth', array('id' => $user->id
));
4772 $authplugin = get_auth_plugin($user->auth
);
4773 if ($authplugin->prevent_local_passwords()) {
4774 $hashedpassword = AUTH_PASSWORD_NOT_CACHED
;
4776 $hashedpassword = hash_internal_user_password($password, $fasthash);
4779 $algorithmchanged = false;
4781 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED
) {
4782 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4783 $passwordchanged = ($user->password
!== $hashedpassword);
4785 } else if (isset($user->password
)) {
4786 // If verification fails then it means the password has changed.
4787 $passwordchanged = !password_verify($password, $user->password
);
4788 $algorithmchanged = password_needs_rehash($user->password
, PASSWORD_DEFAULT
);
4790 // While creating new user, password in unset in $user object, to avoid
4791 // saving it with user_create()
4792 $passwordchanged = true;
4795 if ($passwordchanged ||
$algorithmchanged) {
4796 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id
));
4797 $user->password
= $hashedpassword;
4800 $user = $DB->get_record('user', array('id' => $user->id
));
4801 \core\event\user_password_updated
::create_from_user($user)->trigger();
4808 * Get a complete user record, which includes all the info in the user record.
4810 * Intended for setting as $USER session variable
4812 * @param string $field The user field to be checked for a given value.
4813 * @param string $value The value to match for $field.
4814 * @param int $mnethostid
4815 * @return mixed False, or A {@link $USER} object.
4817 function get_complete_user_data($field, $value, $mnethostid = null) {
4820 if (!$field ||
!$value) {
4824 // Build the WHERE clause for an SQL query.
4825 $params = array('fieldval' => $value);
4826 $constraints = "$field = :fieldval AND deleted <> 1";
4828 // If we are loading user data based on anything other than id,
4829 // we must also restrict our search based on mnet host.
4830 if ($field != 'id') {
4831 if (empty($mnethostid)) {
4832 // If empty, we restrict to local users.
4833 $mnethostid = $CFG->mnet_localhost_id
;
4836 if (!empty($mnethostid)) {
4837 $params['mnethostid'] = $mnethostid;
4838 $constraints .= " AND mnethostid = :mnethostid";
4841 // Get all the basic user data.
4842 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4846 // Get various settings and preferences.
4848 // Preload preference cache.
4849 check_user_preferences_loaded($user);
4851 // Load course enrolment related stuff.
4852 $user->lastcourseaccess
= array(); // During last session.
4853 $user->currentcourseaccess
= array(); // During current session.
4854 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id
))) {
4855 foreach ($lastaccesses as $lastaccess) {
4856 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
4860 $sql = "SELECT g.id, g.courseid
4861 FROM {groups} g, {groups_members} gm
4862 WHERE gm.groupid=g.id AND gm.userid=?";
4864 // This is a special hack to speedup calendar display.
4865 $user->groupmember
= array();
4866 if (!isguestuser($user)) {
4867 if ($groups = $DB->get_records_sql($sql, array($user->id
))) {
4868 foreach ($groups as $group) {
4869 if (!array_key_exists($group->courseid
, $user->groupmember
)) {
4870 $user->groupmember
[$group->courseid
] = array();
4872 $user->groupmember
[$group->courseid
][$group->id
] = $group->id
;
4877 // Add the custom profile fields to the user record.
4878 $user->profile
= array();
4879 if (!isguestuser($user)) {
4880 require_once($CFG->dirroot
.'/user/profile/lib.php');
4881 profile_load_custom_fields($user);
4884 // Rewrite some variables if necessary.
4885 if (!empty($user->description
)) {
4886 // No need to cart all of it around.
4887 $user->description
= true;
4889 if (isguestuser($user)) {
4890 // Guest language always same as site.
4891 $user->lang
= $CFG->lang
;
4892 // Name always in current language.
4893 $user->firstname
= get_string('guestuser');
4894 $user->lastname
= ' ';
4901 * Validate a password against the configured password policy
4903 * @param string $password the password to be checked against the password policy
4904 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4905 * @return bool true if the password is valid according to the policy. false otherwise.
4907 function check_password_policy($password, &$errmsg) {
4910 if (empty($CFG->passwordpolicy
)) {
4915 if (core_text
::strlen($password) < $CFG->minpasswordlength
) {
4916 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength
) .'</div>';
4919 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits
) {
4920 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits
) .'</div>';
4923 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower
) {
4924 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower
) .'</div>';
4927 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper
) {
4928 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper
) .'</div>';
4931 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum
) {
4932 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
) .'</div>';
4934 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars
)) {
4935 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars
) .'</div>';
4938 if ($errmsg == '') {
4947 * When logging in, this function is run to set certain preferences for the current SESSION.
4949 function set_login_session_preferences() {
4952 $SESSION->justloggedin
= true;
4954 unset($SESSION->lang
);
4955 unset($SESSION->forcelang
);
4956 unset($SESSION->load_navigation_admin
);
4961 * Delete a course, including all related data from the database, and any associated files.
4963 * @param mixed $courseorid The id of the course or course object to delete.
4964 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4965 * @return bool true if all the removals succeeded. false if there were any failures. If this
4966 * method returns false, some of the removals will probably have succeeded, and others
4967 * failed, but you have no way of knowing which.
4969 function delete_course($courseorid, $showfeedback = true) {
4972 if (is_object($courseorid)) {
4973 $courseid = $courseorid->id
;
4974 $course = $courseorid;
4976 $courseid = $courseorid;
4977 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4981 $context = context_course
::instance($courseid);
4983 // Frontpage course can not be deleted!!
4984 if ($courseid == SITEID
) {
4988 // Make the course completely empty.
4989 remove_course_contents($courseid, $showfeedback);
4991 // Delete the course and related context instance.
4992 context_helper
::delete_instance(CONTEXT_COURSE
, $courseid);
4994 $DB->delete_records("course", array("id" => $courseid));
4995 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4997 // Reset all course related caches here.
4998 if (class_exists('format_base', false)) {
4999 format_base
::reset_course_cache($courseid);
5002 // Trigger a course deleted event.
5003 $event = \core\event\course_deleted
::create(array(
5004 'objectid' => $course->id
,
5005 'context' => $context,
5007 'shortname' => $course->shortname
,
5008 'fullname' => $course->fullname
,
5009 'idnumber' => $course->idnumber
5012 $event->add_record_snapshot('course', $course);
5019 * Clear a course out completely, deleting all content but don't delete the course itself.
5021 * This function does not verify any permissions.
5023 * Please note this function also deletes all user enrolments,
5024 * enrolment instances and role assignments by default.
5027 * - 'keep_roles_and_enrolments' - false by default
5028 * - 'keep_groups_and_groupings' - false by default
5030 * @param int $courseid The id of the course that is being deleted
5031 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5032 * @param array $options extra options
5033 * @return bool true if all the removals succeeded. false if there were any failures. If this
5034 * method returns false, some of the removals will probably have succeeded, and others
5035 * failed, but you have no way of knowing which.
5037 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5038 global $CFG, $DB, $OUTPUT;
5040 require_once($CFG->libdir
.'/badgeslib.php');
5041 require_once($CFG->libdir
.'/completionlib.php');
5042 require_once($CFG->libdir
.'/questionlib.php');
5043 require_once($CFG->libdir
.'/gradelib.php');
5044 require_once($CFG->dirroot
.'/group/lib.php');
5045 require_once($CFG->dirroot
.'/tag/coursetagslib.php');
5046 require_once($CFG->dirroot
.'/comment/lib.php');
5047 require_once($CFG->dirroot
.'/rating/lib.php');
5048 require_once($CFG->dirroot
.'/notes/lib.php');
5050 // Handle course badges.
5051 badges_handle_course_deletion($courseid);
5053 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5054 $strdeleted = get_string('deleted').' - ';
5056 // Some crazy wishlist of stuff we should skip during purging of course content.
5057 $options = (array)$options;
5059 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST
);
5060 $coursecontext = context_course
::instance($courseid);
5061 $fs = get_file_storage();
5063 // Delete course completion information, this has to be done before grades and enrols.
5064 $cc = new completion_info($course);
5065 $cc->clear_criteria();
5066 if ($showfeedback) {
5067 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5070 // Remove all data from gradebook - this needs to be done before course modules
5071 // because while deleting this information, the system may need to reference
5072 // the course modules that own the grades.
5073 remove_course_grades($courseid, $showfeedback);
5074 remove_grade_letters($coursecontext, $showfeedback);
5076 // Delete course blocks in any all child contexts,
5077 // they may depend on modules so delete them first.
5078 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5079 foreach ($childcontexts as $childcontext) {
5080 blocks_delete_all_for_context($childcontext->id
);
5082 unset($childcontexts);
5083 blocks_delete_all_for_context($coursecontext->id
);
5084 if ($showfeedback) {
5085 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5088 // Delete every instance of every module,
5089 // this has to be done before deleting of course level stuff.
5090 $locations = core_component
::get_plugin_list('mod');
5091 foreach ($locations as $modname => $moddir) {
5092 if ($modname === 'NEWMODULE') {
5095 if ($module = $DB->get_record('modules', array('name' => $modname))) {
5096 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5097 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5098 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
5100 if ($instances = $DB->get_records($modname, array('course' => $course->id
))) {
5101 foreach ($instances as $instance) {
5102 if ($cm = get_coursemodule_from_instance($modname, $instance->id
, $course->id
)) {
5103 // Delete activity context questions and question categories.
5104 question_delete_activity($cm, $showfeedback);
5106 if (function_exists($moddelete)) {
5107 // This purges all module data in related tables, extra user prefs, settings, etc.
5108 $moddelete($instance->id
);
5110 // NOTE: we should not allow installation of modules with missing delete support!
5111 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5112 $DB->delete_records($modname, array('id' => $instance->id
));
5116 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5117 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5118 $DB->delete_records('course_modules', array('id' => $cm->id
));
5122 if (function_exists($moddeletecourse)) {
5123 // Execute ptional course cleanup callback.
5124 $moddeletecourse($course, $showfeedback);
5126 if ($instances and $showfeedback) {
5127 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5130 // Ooops, this module is not properly installed, force-delete it in the next block.
5134 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5136 // Remove all data from availability and completion tables that is associated
5137 // with course-modules belonging to this course. Note this is done even if the
5138 // features are not enabled now, in case they were enabled previously.
5139 $DB->delete_records_select('course_modules_completion',
5140 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5143 // Remove course-module data.
5144 $cms = $DB->get_records('course_modules', array('course' => $course->id
));
5145 foreach ($cms as $cm) {
5146 if ($module = $DB->get_record('modules', array('id' => $cm->module
))) {
5148 $DB->delete_records($module->name
, array('id' => $cm->instance
));
5149 } catch (Exception
$e) {
5150 // Ignore weird or missing table problems.
5153 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5154 $DB->delete_records('course_modules', array('id' => $cm->id
));
5157 if ($showfeedback) {
5158 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5161 // Cleanup the rest of plugins.
5162 $cleanuplugintypes = array('report', 'coursereport', 'format');
5163 foreach ($cleanuplugintypes as $type) {
5164 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
5165 foreach ($plugins as $plugin => $pluginfunction) {
5166 $pluginfunction($course->id
, $showfeedback);
5168 if ($showfeedback) {
5169 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5173 // Delete questions and question categories.
5174 question_delete_course($course, $showfeedback);
5175 if ($showfeedback) {
5176 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5179 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5180 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5181 foreach ($childcontexts as $childcontext) {
5182 $childcontext->delete();
5184 unset($childcontexts);
5186 // Remove all roles and enrolments by default.
5187 if (empty($options['keep_roles_and_enrolments'])) {
5188 // This hack is used in restore when deleting contents of existing course.
5189 role_unassign_all(array('contextid' => $coursecontext->id
, 'component' => ''), true);
5190 enrol_course_delete($course);
5191 if ($showfeedback) {
5192 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5196 // Delete any groups, removing members and grouping/course links first.
5197 if (empty($options['keep_groups_and_groupings'])) {
5198 groups_delete_groupings($course->id
, $showfeedback);
5199 groups_delete_groups($course->id
, $showfeedback);
5203 filter_delete_all_for_context($coursecontext->id
);
5205 // Notes, you shall not pass!
5206 note_delete_all($course->id
);
5209 comment
::delete_comments($coursecontext->id
);
5211 // Ratings are history too.
5212 $delopt = new stdclass();
5213 $delopt->contextid
= $coursecontext->id
;
5214 $rm = new rating_manager();
5215 $rm->delete_ratings($delopt);
5217 // Delete course tags.
5218 coursetag_delete_course_tags($course->id
, $showfeedback);
5220 // Delete calendar events.
5221 $DB->delete_records('event', array('courseid' => $course->id
));
5222 $fs->delete_area_files($coursecontext->id
, 'calendar');
5224 // Delete all related records in other core tables that may have a courseid
5225 // This array stores the tables that need to be cleared, as
5226 // table_name => column_name that contains the course id.
5227 $tablestoclear = array(
5228 'backup_courses' => 'courseid', // Scheduled backup stuff.
5229 'user_lastaccess' => 'courseid', // User access info.
5231 foreach ($tablestoclear as $table => $col) {
5232 $DB->delete_records($table, array($col => $course->id
));
5235 // Delete all course backup files.
5236 $fs->delete_area_files($coursecontext->id
, 'backup');
5238 // Cleanup course record - remove links to deleted stuff.
5239 $oldcourse = new stdClass();
5240 $oldcourse->id
= $course->id
;
5241 $oldcourse->summary
= '';
5242 $oldcourse->cacherev
= 0;
5243 $oldcourse->legacyfiles
= 0;
5244 $oldcourse->enablecompletion
= 0;
5245 if (!empty($options['keep_groups_and_groupings'])) {
5246 $oldcourse->defaultgroupingid
= 0;
5248 $DB->update_record('course', $oldcourse);
5250 // Delete course sections.
5251 $DB->delete_records('course_sections', array('course' => $course->id
));
5253 // Delete legacy, section and any other course files.
5254 $fs->delete_area_files($coursecontext->id
, 'course'); // Files from summary and section.
5256 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5257 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5258 // Easy, do not delete the context itself...
5259 $coursecontext->delete_content();
5262 // We can not drop all context stuff because it would bork enrolments and roles,
5263 // there might be also files used by enrol plugins...
5266 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5267 // also some non-standard unsupported plugins may try to store something there.
5268 fulldelete($CFG->dataroot
.'/'.$course->id
);
5270 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5271 $cachemodinfo = cache
::make('core', 'coursemodinfo');
5272 $cachemodinfo->delete($courseid);
5274 // Trigger a course content deleted event.
5275 $event = \core\event\course_content_deleted
::create(array(
5276 'objectid' => $course->id
,
5277 'context' => $coursecontext,
5278 'other' => array('shortname' => $course->shortname
,
5279 'fullname' => $course->fullname
,
5280 'options' => $options) // Passing this for legacy reasons.
5282 $event->add_record_snapshot('course', $course);
5289 * Change dates in module - used from course reset.
5291 * @param string $modname forum, assignment, etc
5292 * @param array $fields array of date fields from mod table
5293 * @param int $timeshift time difference
5294 * @param int $courseid
5295 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5296 * @return bool success
5298 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5300 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
5303 $params = array($timeshift, $courseid);
5304 foreach ($fields as $field) {
5305 $updatesql = "UPDATE {".$modname."}
5306 SET $field = $field + ?
5307 WHERE course=? AND $field<>0";
5309 $updatesql .= ' AND id=?';
5312 $return = $DB->execute($updatesql, $params) && $return;
5315 $refreshfunction = $modname.'_refresh_events';
5316 if (function_exists($refreshfunction)) {
5317 $refreshfunction($courseid);
5324 * This function will empty a course of user data.
5325 * It will retain the activities and the structure of the course.
5327 * @param object $data an object containing all the settings including courseid (without magic quotes)
5328 * @return array status array of array component, item, error
5330 function reset_course_userdata($data) {
5332 require_once($CFG->libdir
.'/gradelib.php');
5333 require_once($CFG->libdir
.'/completionlib.php');
5334 require_once($CFG->dirroot
.'/group/lib.php');
5336 $data->courseid
= $data->id
;
5337 $context = context_course
::instance($data->courseid
);
5339 $eventparams = array(
5340 'context' => $context,
5341 'courseid' => $data->id
,
5343 'reset_options' => (array) $data
5346 $event = \core\event\course_reset_started
::create($eventparams);
5349 // Calculate the time shift of dates.
5350 if (!empty($data->reset_start_date
)) {
5351 // Time part of course startdate should be zero.
5352 $data->timeshift
= $data->reset_start_date
- usergetmidnight($data->reset_start_date_old
);
5354 $data->timeshift
= 0;
5357 // Result array: component, item, error.
5360 // Start the resetting.
5361 $componentstr = get_string('general');
5363 // Move the course start time.
5364 if (!empty($data->reset_start_date
) and $data->timeshift
) {
5365 // Change course start data.
5366 $DB->set_field('course', 'startdate', $data->reset_start_date
, array('id' => $data->courseid
));
5367 // Update all course and group events - do not move activity events.
5368 $updatesql = "UPDATE {event}
5369 SET timestart = timestart + ?
5370 WHERE courseid=? AND instance=0";
5371 $DB->execute($updatesql, array($data->timeshift
, $data->courseid
));
5373 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5376 if (!empty($data->reset_events
)) {
5377 $DB->delete_records('event', array('courseid' => $data->courseid
));
5378 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5381 if (!empty($data->reset_notes
)) {
5382 require_once($CFG->dirroot
.'/notes/lib.php');
5383 note_delete_all($data->courseid
);
5384 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5387 if (!empty($data->delete_blog_associations
)) {
5388 require_once($CFG->dirroot
.'/blog/lib.php');
5389 blog_remove_associations_for_course($data->courseid
);
5390 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5393 if (!empty($data->reset_completion
)) {
5394 // Delete course and activity completion information.
5395 $course = $DB->get_record('course', array('id' => $data->courseid
));
5396 $cc = new completion_info($course);
5397 $cc->delete_all_completion_data();
5398 $status[] = array('component' => $componentstr,
5399 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5402 $componentstr = get_string('roles');
5404 if (!empty($data->reset_roles_overrides
)) {
5405 $children = $context->get_child_contexts();
5406 foreach ($children as $child) {
5407 $DB->delete_records('role_capabilities', array('contextid' => $child->id
));
5409 $DB->delete_records('role_capabilities', array('contextid' => $context->id
));
5410 // Force refresh for logged in users.
5411 $context->mark_dirty();
5412 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5415 if (!empty($data->reset_roles_local
)) {
5416 $children = $context->get_child_contexts();
5417 foreach ($children as $child) {
5418 role_unassign_all(array('contextid' => $child->id
));
5420 // Force refresh for logged in users.
5421 $context->mark_dirty();
5422 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5425 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5426 $data->unenrolled
= array();
5427 if (!empty($data->unenrol_users
)) {
5428 $plugins = enrol_get_plugins(true);
5429 $instances = enrol_get_instances($data->courseid
, true);
5430 foreach ($instances as $key => $instance) {
5431 if (!isset($plugins[$instance->enrol
])) {
5432 unset($instances[$key]);
5437 foreach ($data->unenrol_users
as $withroleid) {
5440 FROM {user_enrolments} ue
5441 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5442 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5443 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5444 $params = array('courseid' => $data->courseid
, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE
);
5447 // Without any role assigned at course context.
5449 FROM {user_enrolments} ue
5450 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5451 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5452 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5453 WHERE ra.id IS null";
5454 $params = array('courseid' => $data->courseid
, 'courselevel' => CONTEXT_COURSE
);
5457 $rs = $DB->get_recordset_sql($sql, $params);
5458 foreach ($rs as $ue) {
5459 if (!isset($instances[$ue->enrolid
])) {
5462 $instance = $instances[$ue->enrolid
];
5463 $plugin = $plugins[$instance->enrol
];
5464 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5468 $plugin->unenrol_user($instance, $ue->userid
);
5469 $data->unenrolled
[$ue->userid
] = $ue->userid
;
5474 if (!empty($data->unenrolled
)) {
5476 'component' => $componentstr,
5477 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled
).')',
5482 $componentstr = get_string('groups');
5484 // Remove all group members.
5485 if (!empty($data->reset_groups_members
)) {
5486 groups_delete_group_members($data->courseid
);
5487 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5490 // Remove all groups.
5491 if (!empty($data->reset_groups_remove
)) {
5492 groups_delete_groups($data->courseid
, false);
5493 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5496 // Remove all grouping members.
5497 if (!empty($data->reset_groupings_members
)) {
5498 groups_delete_groupings_groups($data->courseid
, false);
5499 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5502 // Remove all groupings.
5503 if (!empty($data->reset_groupings_remove
)) {
5504 groups_delete_groupings($data->courseid
, false);
5505 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5508 // Look in every instance of every module for data to delete.
5509 $unsupportedmods = array();
5510 if ($allmods = $DB->get_records('modules') ) {
5511 foreach ($allmods as $mod) {
5512 $modname = $mod->name
;
5513 $modfile = $CFG->dirroot
.'/mod/'. $modname.'/lib.php';
5514 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5515 if (file_exists($modfile)) {
5516 if (!$DB->count_records($modname, array('course' => $data->courseid
))) {
5517 continue; // Skip mods with no instances.
5519 include_once($modfile);
5520 if (function_exists($moddeleteuserdata)) {
5521 $modstatus = $moddeleteuserdata($data);
5522 if (is_array($modstatus)) {
5523 $status = array_merge($status, $modstatus);
5525 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5528 $unsupportedmods[] = $mod;
5531 debugging('Missing lib.php in '.$modname.' module!');
5536 // Mention unsupported mods.
5537 if (!empty($unsupportedmods)) {
5538 foreach ($unsupportedmods as $mod) {
5540 'component' => get_string('modulenameplural', $mod->name
),
5542 'error' => get_string('resetnotimplemented')
5547 $componentstr = get_string('gradebook', 'grades');
5548 // Reset gradebook,.
5549 if (!empty($data->reset_gradebook_items
)) {
5550 remove_course_grades($data->courseid
, false);
5551 grade_grab_course_grades($data->courseid
);
5552 grade_regrade_final_grades($data->courseid
);
5553 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5555 } else if (!empty($data->reset_gradebook_grades
)) {
5556 grade_course_reset($data->courseid
);
5557 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5560 if (!empty($data->reset_comments
)) {
5561 require_once($CFG->dirroot
.'/comment/lib.php');
5562 comment
::reset_course_page_comments($context);
5565 $event = \core\event\course_reset_ended
::create($eventparams);
5572 * Generate an email processing address.
5575 * @param string $modargs
5576 * @return string Returns email processing address
5578 function generate_email_processing_address($modid, $modargs) {
5581 $header = $CFG->mailprefix
. substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5582 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain
;
5588 * @todo Finish documenting this function
5590 * @param string $modargs
5591 * @param string $body Currently unused
5593 function moodle_process_email($modargs, $body) {
5596 // The first char should be an unencoded letter. We'll take this as an action.
5597 switch ($modargs{0}) {
5598 case 'B': { // Bounce.
5599 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5600 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5601 // Check the half md5 of their email.
5602 $md5check = substr(md5($user->email
), 0, 16);
5603 if ($md5check == substr($modargs, -16)) {
5604 set_bounce_count($user);
5606 // Else maybe they've already changed it?
5610 // Maybe more later?
5617 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5619 * @param string $action 'get', 'buffer', 'close' or 'flush'
5620 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5622 function get_mailer($action='get') {
5625 /** @var moodle_phpmailer $mailer */
5626 static $mailer = null;
5627 static $counter = 0;
5629 if (!isset($CFG->smtpmaxbulk
)) {
5630 $CFG->smtpmaxbulk
= 1;
5633 if ($action == 'get') {
5634 $prevkeepalive = false;
5636 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5637 if ($counter < $CFG->smtpmaxbulk
and !$mailer->isError()) {
5639 // Reset the mailer.
5640 $mailer->Priority
= 3;
5641 $mailer->CharSet
= 'UTF-8'; // Our default.
5642 $mailer->ContentType
= "text/plain";
5643 $mailer->Encoding
= "8bit";
5644 $mailer->From
= "root@localhost";
5645 $mailer->FromName
= "Root User";
5646 $mailer->Sender
= "";
5647 $mailer->Subject
= "";
5649 $mailer->AltBody
= "";
5650 $mailer->ConfirmReadingTo
= "";
5652 $mailer->clearAllRecipients();
5653 $mailer->clearReplyTos();
5654 $mailer->clearAttachments();
5655 $mailer->clearCustomHeaders();
5659 $prevkeepalive = $mailer->SMTPKeepAlive
;
5660 get_mailer('flush');
5663 require_once($CFG->libdir
.'/phpmailer/moodle_phpmailer.php');
5664 $mailer = new moodle_phpmailer();
5668 if ($CFG->smtphosts
== 'qmail') {
5669 // Use Qmail system.
5672 } else if (empty($CFG->smtphosts
)) {
5673 // Use PHP mail() = sendmail.
5677 // Use SMTP directly.
5679 if (!empty($CFG->debugsmtp
)) {
5680 $mailer->SMTPDebug
= true;
5682 // Specify main and backup servers.
5683 $mailer->Host
= $CFG->smtphosts
;
5684 // Specify secure connection protocol.
5685 $mailer->SMTPSecure
= $CFG->smtpsecure
;
5686 // Use previous keepalive.
5687 $mailer->SMTPKeepAlive
= $prevkeepalive;
5689 if ($CFG->smtpuser
) {
5690 // Use SMTP authentication.
5691 $mailer->SMTPAuth
= true;
5692 $mailer->Username
= $CFG->smtpuser
;
5693 $mailer->Password
= $CFG->smtppass
;
5702 // Keep smtp session open after sending.
5703 if ($action == 'buffer') {
5704 if (!empty($CFG->smtpmaxbulk
)) {
5705 get_mailer('flush');
5707 if ($m->Mailer
== 'smtp') {
5708 $m->SMTPKeepAlive
= true;
5714 // Close smtp session, but continue buffering.
5715 if ($action == 'flush') {
5716 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5717 if (!empty($mailer->SMTPDebug
)) {
5720 $mailer->SmtpClose();
5721 if (!empty($mailer->SMTPDebug
)) {
5728 // Close smtp session, do not buffer anymore.
5729 if ($action == 'close') {
5730 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5731 get_mailer('flush');
5732 $mailer->SMTPKeepAlive
= false;
5734 $mailer = null; // Better force new instance.
5740 * Send an email to a specified user
5742 * @param stdClass $user A {@link $USER} object
5743 * @param stdClass $from A {@link $USER} object
5744 * @param string $subject plain text subject line of the email
5745 * @param string $messagetext plain text version of the message
5746 * @param string $messagehtml complete html version of the message (optional)
5747 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5748 * @param string $attachname the name of the file (extension indicates MIME)
5749 * @param bool $usetrueaddress determines whether $from email address should
5750 * be sent out. Will be overruled by user profile setting for maildisplay
5751 * @param string $replyto Email address to reply to
5752 * @param string $replytoname Name of reply to recipient
5753 * @param int $wordwrapwidth custom word wrap width, default 79
5754 * @return bool Returns true if mail was sent OK and false if there was an error.
5756 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5757 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5761 if (empty($user) or empty($user->id
)) {
5762 debugging('Can not send email to null user', DEBUG_DEVELOPER
);
5766 if (empty($user->email
)) {
5767 debugging('Can not send email to user without email: '.$user->id
, DEBUG_DEVELOPER
);
5771 if (!empty($user->deleted
)) {
5772 debugging('Can not send email to deleted user: '.$user->id
, DEBUG_DEVELOPER
);
5776 if (defined('BEHAT_SITE_RUNNING')) {
5777 // Fake email sending in behat.
5781 if (!empty($CFG->noemailever
)) {
5782 // Hidden setting for development sites, set in config.php if needed.
5783 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL
);
5787 if (!empty($CFG->divertallemailsto
)) {
5788 $subject = "[DIVERTED {$user->email}] $subject";
5789 $user = clone($user);
5790 $user->email
= $CFG->divertallemailsto
;
5793 // Skip mail to suspended users.
5794 if ((isset($user->auth
) && $user->auth
=='nologin') or (isset($user->suspended
) && $user->suspended
)) {
5798 if (!validate_email($user->email
)) {
5799 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5800 $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
5801 error_log($invalidemail);
5803 mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
5808 if (over_bounce_threshold($user)) {
5809 $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
5810 error_log($bouncemsg);
5812 mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
5817 // If the user is a remote mnet user, parse the email text for URL to the
5818 // wwwroot and modify the url to direct the user's browser to login at their
5819 // home site (identity provider - idp) before hitting the link itself.
5820 if (is_mnet_remote_user($user)) {
5821 require_once($CFG->dirroot
.'/mnet/lib.php');
5823 $jumpurl = mnet_get_idp_jump_url($user);
5824 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5826 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5829 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5833 $mail = get_mailer();
5835 if (!empty($mail->SMTPDebug
)) {
5836 echo '<pre>' . "\n";
5839 $temprecipients = array();
5840 $tempreplyto = array();
5842 $supportuser = core_user
::get_support_user();
5844 // Make up an email address for handling bounces.
5845 if (!empty($CFG->handlebounces
)) {
5846 $modargs = 'B'.base64_encode(pack('V', $user->id
)).substr(md5($user->email
), 0, 16);
5847 $mail->Sender
= generate_email_processing_address(0, $modargs);
5849 $mail->Sender
= $supportuser->email
;
5852 if (!empty($CFG->emailonlyfromnoreplyaddress
)) {
5853 $usetrueaddress = false;
5854 if (empty($replyto) && $from->maildisplay
) {
5855 $replyto = $from->email
;
5856 $replytoname = fullname($from);
5860 if (is_string($from)) { // So we can pass whatever we want if there is need.
5861 $mail->From
= $CFG->noreplyaddress
;
5862 $mail->FromName
= $from;
5863 } else if ($usetrueaddress and $from->maildisplay
) {
5864 $mail->From
= $from->email
;
5865 $mail->FromName
= fullname($from);
5867 $mail->From
= $CFG->noreplyaddress
;
5868 $mail->FromName
= fullname($from);
5869 if (empty($replyto)) {
5870 $tempreplyto[] = array($CFG->noreplyaddress
, get_string('noreplyname'));
5874 if (!empty($replyto)) {
5875 $tempreplyto[] = array($replyto, $replytoname);
5878 $mail->Subject
= substr($subject, 0, 900);
5880 $temprecipients[] = array($user->email
, fullname($user));
5883 $mail->WordWrap
= $wordwrapwidth;
5885 if (!empty($from->customheaders
)) {
5886 // Add custom headers.
5887 if (is_array($from->customheaders
)) {
5888 foreach ($from->customheaders
as $customheader) {
5889 $mail->addCustomHeader($customheader);
5892 $mail->addCustomHeader($from->customheaders
);
5896 if (!empty($from->priority
)) {
5897 $mail->Priority
= $from->priority
;
5900 if ($messagehtml && !empty($user->mailformat
) && $user->mailformat
== 1) {
5901 // Don't ever send HTML to users who don't want it.
5902 $mail->isHTML(true);
5903 $mail->Encoding
= 'quoted-printable';
5904 $mail->Body
= $messagehtml;
5905 $mail->AltBody
= "\n$messagetext\n";
5907 $mail->IsHTML(false);
5908 $mail->Body
= "\n$messagetext\n";
5911 if ($attachment && $attachname) {
5912 if (preg_match( "~\\.\\.~" , $attachment )) {
5913 // Security check for ".." in dir path.
5914 $temprecipients[] = array($supportuser->email
, fullname($supportuser, true));
5915 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5917 require_once($CFG->libdir
.'/filelib.php');
5918 $mimetype = mimeinfo('type', $attachname);
5920 $attachmentpath = $attachment;
5922 // If the attachment is a full path to a file in the tempdir, use it as is,
5923 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5924 if (strpos($attachmentpath, $CFG->tempdir
) !== 0) {
5925 $attachmentpath = $CFG->dataroot
. '/' . $attachmentpath;
5928 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5932 // Check if the email should be sent in an other charset then the default UTF-8.
5933 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
5935 // Use the defined site mail charset or eventually the one preferred by the recipient.
5936 $charset = $CFG->sitemailcharset
;
5937 if (!empty($CFG->allowusermailcharset
)) {
5938 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
5939 $charset = $useremailcharset;
5943 // Convert all the necessary strings if the charset is supported.
5944 $charsets = get_list_of_charsets();
5945 unset($charsets['UTF-8']);
5946 if (in_array($charset, $charsets)) {
5947 $mail->CharSet
= $charset;
5948 $mail->FromName
= core_text
::convert($mail->FromName
, 'utf-8', strtolower($charset));
5949 $mail->Subject
= core_text
::convert($mail->Subject
, 'utf-8', strtolower($charset));
5950 $mail->Body
= core_text
::convert($mail->Body
, 'utf-8', strtolower($charset));
5951 $mail->AltBody
= core_text
::convert($mail->AltBody
, 'utf-8', strtolower($charset));
5953 foreach ($temprecipients as $key => $values) {
5954 $temprecipients[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
5956 foreach ($tempreplyto as $key => $values) {
5957 $tempreplyto[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
5962 foreach ($temprecipients as $values) {
5963 $mail->addAddress($values[0], $values[1]);
5965 foreach ($tempreplyto as $values) {
5966 $mail->addReplyTo($values[0], $values[1]);
5969 if ($mail->send()) {
5970 set_send_count($user);
5971 if (!empty($mail->SMTPDebug
)) {
5976 // Trigger event for failing to send email.
5977 $event = \core\event\email_failed
::create(array(
5978 'context' => context_system
::instance(),
5979 'userid' => $from->id
,
5980 'relateduserid' => $user->id
,
5982 'subject' => $subject,
5983 'message' => $messagetext,
5984 'errorinfo' => $mail->ErrorInfo
5989 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo
);
5991 if (!empty($mail->SMTPDebug
)) {
5999 * Generate a signoff for emails based on support settings
6003 function generate_email_signoff() {
6007 if (!empty($CFG->supportname
)) {
6008 $signoff .= $CFG->supportname
."\n";
6010 if (!empty($CFG->supportemail
)) {
6011 $signoff .= $CFG->supportemail
."\n";
6013 if (!empty($CFG->supportpage
)) {
6014 $signoff .= $CFG->supportpage
."\n";
6020 * Sets specified user's password and send the new password to the user via email.
6022 * @param stdClass $user A {@link $USER} object
6023 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6024 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6026 function setnew_password_and_mail($user, $fasthash = false) {
6029 // We try to send the mail in language the user understands,
6030 // unfortunately the filter_string() does not support alternative langs yet
6031 // so multilang will not work properly for site->fullname.
6032 $lang = empty($user->lang
) ?
$CFG->lang
: $user->lang
;
6036 $supportuser = core_user
::get_support_user();
6038 $newpassword = generate_password();
6040 update_internal_user_password($user, $newpassword, $fasthash);
6042 $a = new stdClass();
6043 $a->firstname
= fullname($user, true);
6044 $a->sitename
= format_string($site->fullname
);
6045 $a->username
= $user->username
;
6046 $a->newpassword
= $newpassword;
6047 $a->link
= $CFG->wwwroot
.'/login/';
6048 $a->signoff
= generate_email_signoff();
6050 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6052 $subject = format_string($site->fullname
) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6054 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6055 return email_to_user($user, $supportuser, $subject, $message);
6060 * Resets specified user's password and send the new password to the user via email.
6062 * @param stdClass $user A {@link $USER} object
6063 * @return bool Returns true if mail was sent OK and false if there was an error.
6065 function reset_password_and_mail($user) {
6069 $supportuser = core_user
::get_support_user();
6071 $userauth = get_auth_plugin($user->auth
);
6072 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth
)) {
6073 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6077 $newpassword = generate_password();
6079 if (!$userauth->user_update_password($user, $newpassword)) {
6080 print_error("cannotsetpassword");
6083 $a = new stdClass();
6084 $a->firstname
= $user->firstname
;
6085 $a->lastname
= $user->lastname
;
6086 $a->sitename
= format_string($site->fullname
);
6087 $a->username
= $user->username
;
6088 $a->newpassword
= $newpassword;
6089 $a->link
= $CFG->httpswwwroot
.'/login/change_password.php';
6090 $a->signoff
= generate_email_signoff();
6092 $message = get_string('newpasswordtext', '', $a);
6094 $subject = format_string($site->fullname
) .': '. get_string('changedpassword');
6096 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6098 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6099 return email_to_user($user, $supportuser, $subject, $message);
6103 * Send email to specified user with confirmation text and activation link.
6105 * @param stdClass $user A {@link $USER} object
6106 * @return bool Returns true if mail was sent OK and false if there was an error.
6108 function send_confirmation_email($user) {
6112 $supportuser = core_user
::get_support_user();
6114 $data = new stdClass();
6115 $data->firstname
= fullname($user);
6116 $data->sitename
= format_string($site->fullname
);
6117 $data->admin
= generate_email_signoff();
6119 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname
));
6121 $username = urlencode($user->username
);
6122 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
6123 $data->link
= $CFG->wwwroot
.'/login/confirm.php?data='. $user->secret
.'/'. $username;
6124 $message = get_string('emailconfirmation', '', $data);
6125 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6127 $user->mailformat
= 1; // Always send HTML version as well.
6129 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6130 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6134 * Sends a password change confirmation email.
6136 * @param stdClass $user A {@link $USER} object
6137 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6138 * @return bool Returns true if mail was sent OK and false if there was an error.
6140 function send_password_change_confirmation_email($user, $resetrecord) {
6144 $supportuser = core_user
::get_support_user();
6145 $pwresetmins = isset($CFG->pwresettime
) ?
floor($CFG->pwresettime
/ MINSECS
) : 30;
6147 $data = new stdClass();
6148 $data->firstname
= $user->firstname
;
6149 $data->lastname
= $user->lastname
;
6150 $data->username
= $user->username
;
6151 $data->sitename
= format_string($site->fullname
);
6152 $data->link
= $CFG->httpswwwroot
.'/login/forgot_password.php?token='. $resetrecord->token
;
6153 $data->admin
= generate_email_signoff();
6154 $data->resetminutes
= $pwresetmins;
6156 $message = get_string('emailresetconfirmation', '', $data);
6157 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname
));
6159 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6160 return email_to_user($user, $supportuser, $subject, $message);
6165 * Sends an email containinginformation on how to change your password.
6167 * @param stdClass $user A {@link $USER} object
6168 * @return bool Returns true if mail was sent OK and false if there was an error.
6170 function send_password_change_info($user) {
6174 $supportuser = core_user
::get_support_user();
6175 $systemcontext = context_system
::instance();
6177 $data = new stdClass();
6178 $data->firstname
= $user->firstname
;
6179 $data->lastname
= $user->lastname
;
6180 $data->sitename
= format_string($site->fullname
);
6181 $data->admin
= generate_email_signoff();
6183 $userauth = get_auth_plugin($user->auth
);
6185 if (!is_enabled_auth($user->auth
) or $user->auth
== 'nologin') {
6186 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6187 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6188 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6189 return email_to_user($user, $supportuser, $subject, $message);
6192 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6193 // We have some external url for password changing.
6194 $data->link
.= $userauth->change_password_url();
6197 // No way to change password, sorry.
6201 if (!empty($data->link
) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id
)) {
6202 $message = get_string('emailpasswordchangeinfo', '', $data);
6203 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6205 $message = get_string('emailpasswordchangeinfofail', '', $data);
6206 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6209 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6210 return email_to_user($user, $supportuser, $subject, $message);
6215 * Check that an email is allowed. It returns an error message if there was a problem.
6217 * @param string $email Content of email
6218 * @return string|false
6220 function email_is_not_allowed($email) {
6223 if (!empty($CFG->allowemailaddresses
)) {
6224 $allowed = explode(' ', $CFG->allowemailaddresses
);
6225 foreach ($allowed as $allowedpattern) {
6226 $allowedpattern = trim($allowedpattern);
6227 if (!$allowedpattern) {
6230 if (strpos($allowedpattern, '.') === 0) {
6231 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6232 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6236 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6240 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
6242 } else if (!empty($CFG->denyemailaddresses
)) {
6243 $denied = explode(' ', $CFG->denyemailaddresses
);
6244 foreach ($denied as $deniedpattern) {
6245 $deniedpattern = trim($deniedpattern);
6246 if (!$deniedpattern) {
6249 if (strpos($deniedpattern, '.') === 0) {
6250 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6251 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6252 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6255 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6256 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6267 * Returns local file storage instance
6269 * @return file_storage
6271 function get_file_storage() {
6280 require_once("$CFG->libdir/filelib.php");
6282 if (isset($CFG->filedir
)) {
6283 $filedir = $CFG->filedir
;
6285 $filedir = $CFG->dataroot
.'/filedir';
6288 if (isset($CFG->trashdir
)) {
6289 $trashdirdir = $CFG->trashdir
;
6291 $trashdirdir = $CFG->dataroot
.'/trashdir';
6294 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions
, $CFG->filepermissions
);
6300 * Returns local file storage instance
6302 * @return file_browser
6304 function get_file_browser() {
6313 require_once("$CFG->libdir/filelib.php");
6315 $fb = new file_browser();
6321 * Returns file packer
6323 * @param string $mimetype default application/zip
6324 * @return file_packer
6326 function get_file_packer($mimetype='application/zip') {
6329 static $fp = array();
6331 if (isset($fp[$mimetype])) {
6332 return $fp[$mimetype];
6335 switch ($mimetype) {
6336 case 'application/zip':
6337 case 'application/vnd.moodle.profiling':
6338 $classname = 'zip_packer';
6341 case 'application/x-gzip' :
6342 $classname = 'tgz_packer';
6345 case 'application/vnd.moodle.backup':
6346 $classname = 'mbz_packer';
6353 require_once("$CFG->libdir/filestorage/$classname.php");
6354 $fp[$mimetype] = new $classname();
6356 return $fp[$mimetype];
6360 * Returns current name of file on disk if it exists.
6362 * @param string $newfile File to be verified
6363 * @return string Current name of file on disk if true
6365 function valid_uploaded_file($newfile) {
6366 if (empty($newfile)) {
6369 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6370 return $newfile['tmp_name'];
6377 * Returns the maximum size for uploading files.
6379 * There are seven possible upload limits:
6380 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6381 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6382 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6383 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6384 * 5. by the Moodle admin in $CFG->maxbytes
6385 * 6. by the teacher in the current course $course->maxbytes
6386 * 7. by the teacher for the current module, eg $assignment->maxbytes
6388 * These last two are passed to this function as arguments (in bytes).
6389 * Anything defined as 0 is ignored.
6390 * The smallest of all the non-zero numbers is returned.
6392 * @todo Finish documenting this function
6394 * @param int $sitebytes Set maximum size
6395 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6396 * @param int $modulebytes Current module ->maxbytes (in bytes)
6397 * @return int The maximum size for uploading files.
6399 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6401 if (! $filesize = ini_get('upload_max_filesize')) {
6404 $minimumsize = get_real_size($filesize);
6406 if ($postsize = ini_get('post_max_size')) {
6407 $postsize = get_real_size($postsize);
6408 if ($postsize < $minimumsize) {
6409 $minimumsize = $postsize;
6413 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6414 $minimumsize = $sitebytes;
6417 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6418 $minimumsize = $coursebytes;
6421 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6422 $minimumsize = $modulebytes;
6425 return $minimumsize;
6429 * Returns the maximum size for uploading files for the current user
6431 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6433 * @param context $context The context in which to check user capabilities
6434 * @param int $sitebytes Set maximum size
6435 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6436 * @param int $modulebytes Current module ->maxbytes (in bytes)
6437 * @param stdClass $user The user
6438 * @return int The maximum size for uploading files.
6440 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6447 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6448 return USER_CAN_IGNORE_FILE_SIZE_LIMITS
;
6451 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6455 * Returns an array of possible sizes in local language
6457 * Related to {@link get_max_upload_file_size()} - this function returns an
6458 * array of possible sizes in an array, translated to the
6461 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6463 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6464 * with the value set to 0. This option will be the first in the list.
6466 * @uses SORT_NUMERIC
6467 * @param int $sitebytes Set maximum size
6468 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6469 * @param int $modulebytes Current module ->maxbytes (in bytes)
6470 * @param int|array $custombytes custom upload size/s which will be added to list,
6471 * Only value/s smaller then maxsize will be added to list.
6474 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6477 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6481 if ($sitebytes == 0) {
6482 // Will get the minimum of upload_max_filesize or post_max_size.
6483 $sitebytes = get_max_upload_file_size();
6486 $filesize = array();
6487 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6488 5242880, 10485760, 20971520, 52428800, 104857600);
6490 // If custombytes is given and is valid then add it to the list.
6491 if (is_number($custombytes) and $custombytes > 0) {
6492 $custombytes = (int)$custombytes;
6493 if (!in_array($custombytes, $sizelist)) {
6494 $sizelist[] = $custombytes;
6496 } else if (is_array($custombytes)) {
6497 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6500 // Allow maxbytes to be selected if it falls outside the above boundaries.
6501 if (isset($CFG->maxbytes
) && !in_array(get_real_size($CFG->maxbytes
), $sizelist)) {
6502 // Note: get_real_size() is used in order to prevent problems with invalid values.
6503 $sizelist[] = get_real_size($CFG->maxbytes
);
6506 foreach ($sizelist as $sizebytes) {
6507 if ($sizebytes < $maxsize && $sizebytes > 0) {
6508 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6515 (($modulebytes < $coursebytes ||
$coursebytes == 0) &&
6516 ($modulebytes < $sitebytes ||
$sitebytes == 0))) {
6517 $limitlevel = get_string('activity', 'core');
6518 $displaysize = display_size($modulebytes);
6519 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6521 } else if ($coursebytes && ($coursebytes < $sitebytes ||
$sitebytes == 0)) {
6522 $limitlevel = get_string('course', 'core');
6523 $displaysize = display_size($coursebytes);
6524 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6526 } else if ($sitebytes) {
6527 $limitlevel = get_string('site', 'core');
6528 $displaysize = display_size($sitebytes);
6529 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6532 krsort($filesize, SORT_NUMERIC
);
6534 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6535 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) +
$filesize;
6542 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6544 * If excludefiles is defined, then that file/directory is ignored
6545 * If getdirs is true, then (sub)directories are included in the output
6546 * If getfiles is true, then files are included in the output
6547 * (at least one of these must be true!)
6549 * @todo Finish documenting this function. Add examples of $excludefile usage.
6551 * @param string $rootdir A given root directory to start from
6552 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6553 * @param bool $descend If true then subdirectories are recursed as well
6554 * @param bool $getdirs If true then (sub)directories are included in the output
6555 * @param bool $getfiles If true then files are included in the output
6556 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6558 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6562 if (!$getdirs and !$getfiles) { // Nothing to show.
6566 if (!is_dir($rootdir)) { // Must be a directory.
6570 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6574 if (!is_array($excludefiles)) {
6575 $excludefiles = array($excludefiles);
6578 while (false !== ($file = readdir($dir))) {
6579 $firstchar = substr($file, 0, 1);
6580 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6583 $fullfile = $rootdir .'/'. $file;
6584 if (filetype($fullfile) == 'dir') {
6589 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6590 foreach ($subdirs as $subdir) {
6591 $dirs[] = $file .'/'. $subdir;
6594 } else if ($getfiles) {
6607 * Adds up all the files in a directory and works out the size.
6609 * @param string $rootdir The directory to start from
6610 * @param string $excludefile A file to exclude when summing directory size
6611 * @return int The summed size of all files and subfiles within the root directory
6613 function get_directory_size($rootdir, $excludefile='') {
6616 // Do it this way if we can, it's much faster.
6617 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
6618 $command = trim($CFG->pathtodu
).' -sk '.escapeshellarg($rootdir);
6621 exec($command, $output, $return);
6622 if (is_array($output)) {
6623 // We told it to return k.
6624 return get_real_size(intval($output[0]).'k');
6628 if (!is_dir($rootdir)) {
6629 // Must be a directory.
6633 if (!$dir = @opendir
($rootdir)) {
6634 // Can't open it for some reason.
6640 while (false !== ($file = readdir($dir))) {
6641 $firstchar = substr($file, 0, 1);
6642 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6645 $fullfile = $rootdir .'/'. $file;
6646 if (filetype($fullfile) == 'dir') {
6647 $size +
= get_directory_size($fullfile, $excludefile);
6649 $size +
= filesize($fullfile);
6658 * Converts bytes into display form
6660 * @static string $gb Localized string for size in gigabytes
6661 * @static string $mb Localized string for size in megabytes
6662 * @static string $kb Localized string for size in kilobytes
6663 * @static string $b Localized string for size in bytes
6664 * @param int $size The size to convert to human readable form
6667 function display_size($size) {
6669 static $gb, $mb, $kb, $b;
6671 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS
) {
6672 return get_string('unlimited');
6676 $gb = get_string('sizegb');
6677 $mb = get_string('sizemb');
6678 $kb = get_string('sizekb');
6679 $b = get_string('sizeb');
6682 if ($size >= 1073741824) {
6683 $size = round($size / 1073741824 * 10) / 10 . $gb;
6684 } else if ($size >= 1048576) {
6685 $size = round($size / 1048576 * 10) / 10 . $mb;
6686 } else if ($size >= 1024) {
6687 $size = round($size / 1024 * 10) / 10 . $kb;
6689 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6695 * Cleans a given filename by removing suspicious or troublesome characters
6697 * @see clean_param()
6698 * @param string $string file name
6699 * @return string cleaned file name
6701 function clean_filename($string) {
6702 return clean_param($string, PARAM_FILE
);
6706 // STRING TRANSLATION.
6709 * Returns the code for the current language
6714 function current_language() {
6715 global $CFG, $USER, $SESSION, $COURSE;
6717 if (!empty($SESSION->forcelang
)) {
6718 // Allows overriding course-forced language (useful for admins to check
6719 // issues in courses whose language they don't understand).
6720 // Also used by some code to temporarily get language-related information in a
6721 // specific language (see force_current_language()).
6722 $return = $SESSION->forcelang
;
6724 } else if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) {
6725 // Course language can override all other settings for this page.
6726 $return = $COURSE->lang
;
6728 } else if (!empty($SESSION->lang
)) {
6729 // Session language can override other settings.
6730 $return = $SESSION->lang
;
6732 } else if (!empty($USER->lang
)) {
6733 $return = $USER->lang
;
6735 } else if (isset($CFG->lang
)) {
6736 $return = $CFG->lang
;
6742 // Just in case this slipped in from somewhere by accident.
6743 $return = str_replace('_utf8', '', $return);
6749 * Returns parent language of current active language if defined
6752 * @param string $lang null means current language
6755 function get_parent_language($lang=null) {
6757 // Let's hack around the current language.
6758 if (!empty($lang)) {
6759 $oldforcelang = force_current_language($lang);
6762 $parentlang = get_string('parentlanguage', 'langconfig');
6763 if ($parentlang === 'en') {
6767 // Let's hack around the current language.
6768 if (!empty($lang)) {
6769 force_current_language($oldforcelang);
6776 * Force the current language to get strings and dates localised in the given language.
6778 * After calling this function, all strings will be provided in the given language
6779 * until this function is called again, or equivalent code is run.
6781 * @param string $language
6782 * @return string previous $SESSION->forcelang value
6784 function force_current_language($language) {
6786 $sessionforcelang = isset($SESSION->forcelang
) ?
$SESSION->forcelang
: '';
6787 if ($language !== $sessionforcelang) {
6788 // Seting forcelang to null or an empty string disables it's effect.
6789 if (empty($language) ||
get_string_manager()->translation_exists($language, false)) {
6790 $SESSION->forcelang
= $language;
6794 return $sessionforcelang;
6798 * Returns current string_manager instance.
6800 * The param $forcereload is needed for CLI installer only where the string_manager instance
6801 * must be replaced during the install.php script life time.
6804 * @param bool $forcereload shall the singleton be released and new instance created instead?
6805 * @return core_string_manager
6807 function get_string_manager($forcereload=false) {
6810 static $singleton = null;
6815 if ($singleton === null) {
6816 if (empty($CFG->early_install_lang
)) {
6818 if (empty($CFG->langlist
)) {
6819 $translist = array();
6821 $translist = explode(',', $CFG->langlist
);
6824 $singleton = new core_string_manager_standard($CFG->langotherroot
, $CFG->langlocalroot
, $translist);
6827 $singleton = new core_string_manager_install();
6835 * Returns a localized string.
6837 * Returns the translated string specified by $identifier as
6838 * for $module. Uses the same format files as STphp.
6839 * $a is an object, string or number that can be used
6840 * within translation strings
6842 * eg 'hello {$a->firstname} {$a->lastname}'
6845 * If you would like to directly echo the localized string use
6846 * the function {@link print_string()}
6848 * Example usage of this function involves finding the string you would
6849 * like a local equivalent of and using its identifier and module information
6850 * to retrieve it.<br/>
6851 * If you open moodle/lang/en/moodle.php and look near line 278
6852 * you will find a string to prompt a user for their word for 'course'
6854 * $string['course'] = 'Course';
6856 * So if you want to display the string 'Course'
6857 * in any language that supports it on your site
6858 * you just need to use the identifier 'course'
6860 * $mystring = '<strong>'. get_string('course') .'</strong>';
6863 * If the string you want is in another file you'd take a slightly
6864 * different approach. Looking in moodle/lang/en/calendar.php you find
6867 * $string['typecourse'] = 'Course event';
6869 * If you want to display the string "Course event" in any language
6870 * supported you would use the identifier 'typecourse' and the module 'calendar'
6871 * (because it is in the file calendar.php):
6873 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6876 * As a last resort, should the identifier fail to map to a string
6877 * the returned string will be [[ $identifier ]]
6879 * In Moodle 2.3 there is a new argument to this function $lazyload.
6880 * Setting $lazyload to true causes get_string to return a lang_string object
6881 * rather than the string itself. The fetching of the string is then put off until
6882 * the string object is first used. The object can be used by calling it's out
6883 * method or by casting the object to a string, either directly e.g.
6884 * (string)$stringobject
6885 * or indirectly by using the string within another string or echoing it out e.g.
6886 * echo $stringobject
6887 * return "<p>{$stringobject}</p>";
6888 * It is worth noting that using $lazyload and attempting to use the string as an
6889 * array key will cause a fatal error as objects cannot be used as array keys.
6890 * But you should never do that anyway!
6891 * For more information {@link lang_string}
6894 * @param string $identifier The key identifier for the localized string
6895 * @param string $component The module where the key identifier is stored,
6896 * usually expressed as the filename in the language pack without the
6897 * .php on the end but can also be written as mod/forum or grade/export/xls.
6898 * If none is specified then moodle.php is used.
6899 * @param string|object|array $a An object, string or number that can be used
6900 * within translation strings
6901 * @param bool $lazyload If set to true a string object is returned instead of
6902 * the string itself. The string then isn't calculated until it is first used.
6903 * @return string The localized string.
6904 * @throws coding_exception
6906 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6909 // If the lazy load argument has been supplied return a lang_string object
6911 // We need to make sure it is true (and a bool) as you will see below there
6912 // used to be a forth argument at one point.
6913 if ($lazyload === true) {
6914 return new lang_string($identifier, $component, $a);
6917 if ($CFG->debugdeveloper
&& clean_param($identifier, PARAM_STRINGID
) === '') {
6918 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER
);
6921 // There is now a forth argument again, this time it is a boolean however so
6922 // we can still check for the old extralocations parameter.
6923 if (!is_bool($lazyload) && !empty($lazyload)) {
6924 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6927 if (strpos($component, '/') !== false) {
6928 debugging('The module name you passed to get_string is the deprecated format ' .
6929 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER
);
6930 $componentpath = explode('/', $component);
6932 switch ($componentpath[0]) {
6934 $component = $componentpath[1];
6938 $component = 'block_'.$componentpath[1];
6941 $component = 'enrol_'.$componentpath[1];
6944 $component = 'format_'.$componentpath[1];
6947 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6952 $result = get_string_manager()->get_string($identifier, $component, $a);
6954 // Debugging feature lets you display string identifier and component.
6955 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
6956 $result .= ' {' . $identifier . '/' . $component . '}';
6962 * Converts an array of strings to their localized value.
6964 * @param array $array An array of strings
6965 * @param string $component The language module that these strings can be found in.
6966 * @return stdClass translated strings.
6968 function get_strings($array, $component = '') {
6969 $string = new stdClass
;
6970 foreach ($array as $item) {
6971 $string->$item = get_string($item, $component);
6977 * Prints out a translated string.
6979 * Prints out a translated string using the return value from the {@link get_string()} function.
6981 * Example usage of this function when the string is in the moodle.php file:<br/>
6984 * print_string('course');
6988 * Example usage of this function when the string is not in the moodle.php file:<br/>
6991 * print_string('typecourse', 'calendar');
6996 * @param string $identifier The key identifier for the localized string
6997 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6998 * @param string|object|array $a An object, string or number that can be used within translation strings
7000 function print_string($identifier, $component = '', $a = null) {
7001 echo get_string($identifier, $component, $a);
7005 * Returns a list of charset codes
7007 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7008 * (checking that such charset is supported by the texlib library!)
7010 * @return array And associative array with contents in the form of charset => charset
7012 function get_list_of_charsets() {
7015 'EUC-JP' => 'EUC-JP',
7016 'ISO-2022-JP'=> 'ISO-2022-JP',
7017 'ISO-8859-1' => 'ISO-8859-1',
7018 'SHIFT-JIS' => 'SHIFT-JIS',
7019 'GB2312' => 'GB2312',
7020 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7021 'UTF-8' => 'UTF-8');
7029 * Returns a list of valid and compatible themes
7033 function get_list_of_themes() {
7038 if (!empty($CFG->themelist
)) { // Use admin's list of themes.
7039 $themelist = explode(',', $CFG->themelist
);
7041 $themelist = array_keys(core_component
::get_plugin_list("theme"));
7044 foreach ($themelist as $key => $themename) {
7045 $theme = theme_config
::load($themename);
7046 $themes[$themename] = $theme;
7049 core_collator
::asort_objects_by_method($themes, 'get_theme_name');
7055 * Returns a list of timezones in the current language
7059 function get_list_of_timezones() {
7064 if (!empty($timezones)) { // This function has been called recently.
7068 $timezones = array();
7070 if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
7071 foreach ($rawtimezones as $timezone) {
7072 if (!empty($timezone->name
)) {
7073 if (get_string_manager()->string_exists(strtolower($timezone->name
), 'timezones')) {
7074 $timezones[$timezone->name
] = get_string(strtolower($timezone->name
), 'timezones');
7076 $timezones[$timezone->name
] = $timezone->name
;
7078 if (substr($timezones[$timezone->name
], 0, 1) == '[') { // No translation found.
7079 $timezones[$timezone->name
] = $timezone->name
;
7087 for ($i = -13; $i <= 13; $i +
= .5) {
7090 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
7091 } else if ($i > 0) {
7092 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
7094 $timezones[sprintf("%.1f", $i)] = $tzstring;
7102 * Factory function for emoticon_manager
7104 * @return emoticon_manager singleton
7106 function get_emoticon_manager() {
7107 static $singleton = null;
7109 if (is_null($singleton)) {
7110 $singleton = new emoticon_manager();
7117 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7119 * Whenever this manager mentiones 'emoticon object', the following data
7120 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7121 * altidentifier and altcomponent
7123 * @see admin_setting_emoticons
7125 * @copyright 2010 David Mudrak
7126 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7128 class emoticon_manager
{
7131 * Returns the currently enabled emoticons
7133 * @return array of emoticon objects
7135 public function get_emoticons() {
7138 if (empty($CFG->emoticons
)) {
7142 $emoticons = $this->decode_stored_config($CFG->emoticons
);
7144 if (!is_array($emoticons)) {
7145 // Something is wrong with the format of stored setting.
7146 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL
);
7154 * Converts emoticon object into renderable pix_emoticon object
7156 * @param stdClass $emoticon emoticon object
7157 * @param array $attributes explicit HTML attributes to set
7158 * @return pix_emoticon
7160 public function prepare_renderable_emoticon(stdClass
$emoticon, array $attributes = array()) {
7161 $stringmanager = get_string_manager();
7162 if ($stringmanager->string_exists($emoticon->altidentifier
, $emoticon->altcomponent
)) {
7163 $alt = get_string($emoticon->altidentifier
, $emoticon->altcomponent
);
7165 $alt = s($emoticon->text
);
7167 return new pix_emoticon($emoticon->imagename
, $alt, $emoticon->imagecomponent
, $attributes);
7171 * Encodes the array of emoticon objects into a string storable in config table
7173 * @see self::decode_stored_config()
7174 * @param array $emoticons array of emtocion objects
7177 public function encode_stored_config(array $emoticons) {
7178 return json_encode($emoticons);
7182 * Decodes the string into an array of emoticon objects
7184 * @see self::encode_stored_config()
7185 * @param string $encoded
7186 * @return string|null
7188 public function decode_stored_config($encoded) {
7189 $decoded = json_decode($encoded);
7190 if (!is_array($decoded)) {
7197 * Returns default set of emoticons supported by Moodle
7199 * @return array of sdtClasses
7201 public function default_emoticons() {
7203 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7204 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7205 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7206 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7207 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7208 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7209 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7210 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7211 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7212 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7213 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7214 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7215 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7216 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7217 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7218 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7219 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7220 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7221 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7222 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7223 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7224 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7225 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7226 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7227 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7228 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7229 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7230 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7231 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7232 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7237 * Helper method preparing the stdClass with the emoticon properties
7239 * @param string|array $text or array of strings
7240 * @param string $imagename to be used by {@link pix_emoticon}
7241 * @param string $altidentifier alternative string identifier, null for no alt
7242 * @param string $altcomponent where the alternative string is defined
7243 * @param string $imagecomponent to be used by {@link pix_emoticon}
7246 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7247 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7248 return (object)array(
7250 'imagename' => $imagename,
7251 'imagecomponent' => $imagecomponent,
7252 'altidentifier' => $altidentifier,
7253 'altcomponent' => $altcomponent,
7263 * @param string $data Data to encrypt.
7264 * @return string The now encrypted data.
7266 function rc4encrypt($data) {
7267 return endecrypt(get_site_identifier(), $data, '');
7273 * @param string $data Data to decrypt.
7274 * @return string The now decrypted data.
7276 function rc4decrypt($data) {
7277 return endecrypt(get_site_identifier(), $data, 'de');
7281 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7283 * @todo Finish documenting this function
7285 * @param string $pwd The password to use when encrypting or decrypting
7286 * @param string $data The data to be decrypted/encrypted
7287 * @param string $case Either 'de' for decrypt or '' for encrypt
7290 function endecrypt ($pwd, $data, $case) {
7292 if ($case == 'de') {
7293 $data = urldecode($data);
7298 $pwdlength = strlen($pwd);
7300 for ($i = 0; $i <= 255; $i++
) {
7301 $key[$i] = ord(substr($pwd, ($i %
$pwdlength), 1));
7307 for ($i = 0; $i <= 255; $i++
) {
7308 $x = ($x +
$box[$i] +
$key[$i]) %
256;
7309 $tempswap = $box[$i];
7310 $box[$i] = $box[$x];
7311 $box[$x] = $tempswap;
7319 for ($i = 0; $i < strlen($data); $i++
) {
7320 $a = ($a +
1) %
256;
7321 $j = ($j +
$box[$a]) %
256;
7323 $box[$a] = $box[$j];
7325 $k = $box[(($box[$a] +
$box[$j]) %
256)];
7326 $cipherby = ord(substr($data, $i, 1)) ^
$k;
7327 $cipher .= chr($cipherby);
7330 if ($case == 'de') {
7331 $cipher = urldecode(urlencode($cipher));
7333 $cipher = urlencode($cipher);
7339 // ENVIRONMENT CHECKING.
7342 * This method validates a plug name. It is much faster than calling clean_param.
7344 * @param string $name a string that might be a plugin name.
7345 * @return bool if this string is a valid plugin name.
7347 function is_valid_plugin_name($name) {
7348 // This does not work for 'mod', bad luck, use any other type.
7349 return core_component
::is_valid_plugin_name('tool', $name);
7353 * Get a list of all the plugins of a given type that define a certain API function
7354 * in a certain file. The plugin component names and function names are returned.
7356 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7357 * @param string $function the part of the name of the function after the
7358 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7359 * names like report_courselist_hook.
7360 * @param string $file the name of file within the plugin that defines the
7361 * function. Defaults to lib.php.
7362 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7363 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7365 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7366 $pluginfunctions = array();
7367 $pluginswithfile = core_component
::get_plugin_list_with_file($plugintype, $file, true);
7368 foreach ($pluginswithfile as $plugin => $notused) {
7369 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7371 if (function_exists($fullfunction)) {
7372 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7373 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
7375 } else if ($plugintype === 'mod') {
7376 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7377 $shortfunction = $plugin . '_' . $function;
7378 if (function_exists($shortfunction)) {
7379 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
7383 return $pluginfunctions;
7387 * Lists plugin-like directories within specified directory
7389 * This function was originally used for standard Moodle plugins, please use
7390 * new core_component::get_plugin_list() now.
7392 * This function is used for general directory listing and backwards compatility.
7394 * @param string $directory relative directory from root
7395 * @param string $exclude dir name to exclude from the list (defaults to none)
7396 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7397 * @return array Sorted array of directory names found under the requested parameters
7399 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7404 if (empty($basedir)) {
7405 $basedir = $CFG->dirroot
.'/'. $directory;
7408 $basedir = $basedir .'/'. $directory;
7411 if ($CFG->debugdeveloper
and empty($exclude)) {
7412 // Make sure devs do not use this to list normal plugins,
7413 // this is intended for general directories that are not plugins!
7415 $subtypes = core_component
::get_plugin_types();
7416 if (in_array($basedir, $subtypes)) {
7417 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER
);
7422 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7423 if (!$dirhandle = opendir($basedir)) {
7424 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER
);
7427 while (false !== ($dir = readdir($dirhandle))) {
7428 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7429 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7430 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7433 if (filetype($basedir .'/'. $dir) != 'dir') {
7438 closedir($dirhandle);
7447 * Invoke plugin's callback functions
7449 * @param string $type plugin type e.g. 'mod'
7450 * @param string $name plugin name
7451 * @param string $feature feature name
7452 * @param string $action feature's action
7453 * @param array $params parameters of callback function, should be an array
7454 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7457 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7459 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7460 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7464 * Invoke component's callback functions
7466 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7467 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7468 * @param array $params parameters of callback function
7469 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7472 function component_callback($component, $function, array $params = array(), $default = null) {
7474 $functionname = component_callback_exists($component, $function);
7476 if ($functionname) {
7477 // Function exists, so just return function result.
7478 $ret = call_user_func_array($functionname, $params);
7479 if (is_null($ret)) {
7489 * Determine if a component callback exists and return the function name to call. Note that this
7490 * function will include the required library files so that the functioname returned can be
7493 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7494 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7495 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7496 * @throws coding_exception if invalid component specfied
7498 function component_callback_exists($component, $function) {
7499 global $CFG; // This is needed for the inclusions.
7501 $cleancomponent = clean_param($component, PARAM_COMPONENT
);
7502 if (empty($cleancomponent)) {
7503 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7505 $component = $cleancomponent;
7507 list($type, $name) = core_component
::normalize_component($component);
7508 $component = $type . '_' . $name;
7510 $oldfunction = $name.'_'.$function;
7511 $function = $component.'_'.$function;
7513 $dir = core_component
::get_component_directory($component);
7515 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7518 // Load library and look for function.
7519 if (file_exists($dir.'/lib.php')) {
7520 require_once($dir.'/lib.php');
7523 if (!function_exists($function) and function_exists($oldfunction)) {
7524 if ($type !== 'mod' and $type !== 'core') {
7525 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER
);
7527 $function = $oldfunction;
7530 if (function_exists($function)) {
7537 * Checks whether a plugin supports a specified feature.
7539 * @param string $type Plugin type e.g. 'mod'
7540 * @param string $name Plugin name e.g. 'forum'
7541 * @param string $feature Feature code (FEATURE_xx constant)
7542 * @param mixed $default default value if feature support unknown
7543 * @return mixed Feature result (false if not supported, null if feature is unknown,
7544 * otherwise usually true but may have other feature-specific value such as array)
7545 * @throws coding_exception
7547 function plugin_supports($type, $name, $feature, $default = null) {
7550 if ($type === 'mod' and $name === 'NEWMODULE') {
7551 // Somebody forgot to rename the module template.
7555 $component = clean_param($type . '_' . $name, PARAM_COMPONENT
);
7556 if (empty($component)) {
7557 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7562 if ($type === 'mod') {
7563 // We need this special case because we support subplugins in modules,
7564 // otherwise it would end up in infinite loop.
7565 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7566 include_once("$CFG->dirroot/mod/$name/lib.php");
7567 $function = $component.'_supports';
7568 if (!function_exists($function)) {
7569 // Legacy non-frankenstyle function name.
7570 $function = $name.'_supports';
7575 if (!$path = core_component
::get_plugin_directory($type, $name)) {
7576 // Non existent plugin type.
7579 if (file_exists("$path/lib.php")) {
7580 include_once("$path/lib.php");
7581 $function = $component.'_supports';
7585 if ($function and function_exists($function)) {
7586 $supports = $function($feature);
7587 if (is_null($supports)) {
7588 // Plugin does not know - use default.
7595 // Plugin does not care, so use default.
7600 * Returns true if the current version of PHP is greater that the specified one.
7602 * @todo Check PHP version being required here is it too low?
7604 * @param string $version The version of php being tested.
7607 function check_php_version($version='5.2.4') {
7608 return (version_compare(phpversion(), $version) >= 0);
7612 * Determine if moodle installation requires update.
7614 * Checks version numbers of main code and all plugins to see
7615 * if there are any mismatches.
7619 function moodle_needs_upgrading() {
7622 if (empty($CFG->version
)) {
7626 // There is no need to purge plugininfo caches here because
7627 // these caches are not used during upgrade and they are purged after
7630 if (empty($CFG->allversionshash
)) {
7634 $hash = core_component
::get_all_versions_hash();
7636 return ($hash !== $CFG->allversionshash
);
7640 * Returns the major version of this site
7642 * Moodle version numbers consist of three numbers separated by a dot, for
7643 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7644 * called major version. This function extracts the major version from either
7645 * $CFG->release (default) or eventually from the $release variable defined in
7646 * the main version.php.
7648 * @param bool $fromdisk should the version if source code files be used
7649 * @return string|false the major version like '2.3', false if could not be determined
7651 function moodle_major_version($fromdisk = false) {
7656 require($CFG->dirroot
.'/version.php');
7657 if (empty($release)) {
7662 if (empty($CFG->release
)) {
7665 $release = $CFG->release
;
7668 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7678 * Sets the system locale
7681 * @param string $locale Can be used to force a locale
7683 function moodle_setlocale($locale='') {
7686 static $currentlocale = ''; // Last locale caching.
7688 $oldlocale = $currentlocale;
7690 // Fetch the correct locale based on ostype.
7691 if ($CFG->ostype
== 'WINDOWS') {
7692 $stringtofetch = 'localewin';
7694 $stringtofetch = 'locale';
7697 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7698 if (!empty($locale)) {
7699 $currentlocale = $locale;
7700 } else if (!empty($CFG->locale
)) { // Override locale for all language packs.
7701 $currentlocale = $CFG->locale
;
7703 $currentlocale = get_string($stringtofetch, 'langconfig');
7706 // Do nothing if locale already set up.
7707 if ($oldlocale == $currentlocale) {
7711 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7712 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7713 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7715 // Get current values.
7716 $monetary= setlocale (LC_MONETARY
, 0);
7717 $numeric = setlocale (LC_NUMERIC
, 0);
7718 $ctype = setlocale (LC_CTYPE
, 0);
7719 if ($CFG->ostype
!= 'WINDOWS') {
7720 $messages= setlocale (LC_MESSAGES
, 0);
7722 // Set locale to all.
7723 $result = setlocale (LC_ALL
, $currentlocale);
7724 // If setting of locale fails try the other utf8 or utf-8 variant,
7725 // some operating systems support both (Debian), others just one (OSX).
7726 if ($result === false) {
7727 if (stripos($currentlocale, '.UTF-8') !== false) {
7728 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7729 setlocale (LC_ALL
, $newlocale);
7730 } else if (stripos($currentlocale, '.UTF8') !== false) {
7731 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7732 setlocale (LC_ALL
, $newlocale);
7736 setlocale (LC_MONETARY
, $monetary);
7737 setlocale (LC_NUMERIC
, $numeric);
7738 if ($CFG->ostype
!= 'WINDOWS') {
7739 setlocale (LC_MESSAGES
, $messages);
7741 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7742 // To workaround a well-known PHP problem with Turkish letter Ii.
7743 setlocale (LC_CTYPE
, $ctype);
7748 * Count words in a string.
7750 * Words are defined as things between whitespace.
7753 * @param string $string The text to be searched for words.
7754 * @return int The count of words in the specified string
7756 function count_words($string) {
7757 $string = strip_tags($string);
7758 // Decode HTML entities.
7759 $string = html_entity_decode($string);
7760 // Replace underscores (which are classed as word characters) with spaces.
7761 $string = preg_replace('/_/u', ' ', $string);
7762 // Remove any characters that shouldn't be treated as word boundaries.
7763 $string = preg_replace('/[\'’-]/u', '', $string);
7764 // Remove dots and commas from within numbers only.
7765 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7767 return count(preg_split('/\w\b/u', $string)) - 1;
7771 * Count letters in a string.
7773 * Letters are defined as chars not in tags and different from whitespace.
7776 * @param string $string The text to be searched for letters.
7777 * @return int The count of letters in the specified text.
7779 function count_letters($string) {
7780 $string = strip_tags($string); // Tags are out now.
7781 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7783 return core_text
::strlen($string);
7787 * Generate and return a random string of the specified length.
7789 * @param int $length The length of the string to be created.
7792 function random_string ($length=15) {
7793 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7794 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7795 $pool .= '0123456789';
7796 $poollen = strlen($pool);
7798 for ($i = 0; $i < $length; $i++
) {
7799 $string .= substr($pool, (mt_rand()%
($poollen)), 1);
7805 * Generate a complex random string (useful for md5 salts)
7807 * This function is based on the above {@link random_string()} however it uses a
7808 * larger pool of characters and generates a string between 24 and 32 characters
7810 * @param int $length Optional if set generates a string to exactly this length
7813 function complex_random_string($length=null) {
7814 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7815 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7816 $poollen = strlen($pool);
7817 if ($length===null) {
7818 $length = floor(rand(24, 32));
7821 for ($i = 0; $i < $length; $i++
) {
7822 $string .= $pool[(mt_rand()%
$poollen)];
7828 * Given some text (which may contain HTML) and an ideal length,
7829 * this function truncates the text neatly on a word boundary if possible
7832 * @param string $text text to be shortened
7833 * @param int $ideal ideal string length
7834 * @param boolean $exact if false, $text will not be cut mid-word
7835 * @param string $ending The string to append if the passed string is truncated
7836 * @return string $truncate shortened string
7838 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7839 // If the plain text is shorter than the maximum length, return the whole text.
7840 if (core_text
::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7844 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7845 // and only tag in its 'line'.
7846 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER
);
7848 $totallength = core_text
::strlen($ending);
7851 // This array stores information about open and close tags and their position
7852 // in the truncated string. Each item in the array is an object with fields
7853 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7854 // (byte position in truncated text).
7855 $tagdetails = array();
7857 foreach ($lines as $linematchings) {
7858 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7859 if (!empty($linematchings[1])) {
7860 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7861 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7862 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7863 // Record closing tag.
7864 $tagdetails[] = (object) array(
7866 'tag' => core_text
::strtolower($tagmatchings[1]),
7867 'pos' => core_text
::strlen($truncate),
7870 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7871 // Record opening tag.
7872 $tagdetails[] = (object) array(
7874 'tag' => core_text
::strtolower($tagmatchings[1]),
7875 'pos' => core_text
::strlen($truncate),
7879 // Add html-tag to $truncate'd text.
7880 $truncate .= $linematchings[1];
7883 // Calculate the length of the plain text part of the line; handle entities as one character.
7884 $contentlength = core_text
::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7885 if ($totallength +
$contentlength > $ideal) {
7886 // The number of characters which are left.
7887 $left = $ideal - $totallength;
7888 $entitieslength = 0;
7889 // Search for html entities.
7890 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
)) {
7891 // Calculate the real length of all entities in the legal range.
7892 foreach ($entities[0] as $entity) {
7893 if ($entity[1]+
1-$entitieslength <= $left) {
7895 $entitieslength +
= core_text
::strlen($entity[0]);
7897 // No more characters left.
7902 $breakpos = $left +
$entitieslength;
7904 // If the words shouldn't be cut in the middle...
7906 // Search the last occurence of a space.
7907 for (; $breakpos > 0; $breakpos--) {
7908 if ($char = core_text
::substr($linematchings[2], $breakpos, 1)) {
7909 if ($char === '.' or $char === ' ') {
7912 } else if (strlen($char) > 2) {
7913 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7920 if ($breakpos == 0) {
7921 // This deals with the test_shorten_text_no_spaces case.
7922 $breakpos = $left +
$entitieslength;
7923 } else if ($breakpos > $left +
$entitieslength) {
7924 // This deals with the previous for loop breaking on the first char.
7925 $breakpos = $left +
$entitieslength;
7928 $truncate .= core_text
::substr($linematchings[2], 0, $breakpos);
7929 // Maximum length is reached, so get off the loop.
7932 $truncate .= $linematchings[2];
7933 $totallength +
= $contentlength;
7936 // If the maximum length is reached, get off the loop.
7937 if ($totallength >= $ideal) {
7942 // Add the defined ending to the text.
7943 $truncate .= $ending;
7945 // Now calculate the list of open html tags based on the truncate position.
7946 $opentags = array();
7947 foreach ($tagdetails as $taginfo) {
7948 if ($taginfo->open
) {
7949 // Add tag to the beginning of $opentags list.
7950 array_unshift($opentags, $taginfo->tag
);
7952 // Can have multiple exact same open tags, close the last one.
7953 $pos = array_search($taginfo->tag
, array_reverse($opentags, true));
7954 if ($pos !== false) {
7955 unset($opentags[$pos]);
7960 // Close all unclosed html-tags.
7961 foreach ($opentags as $tag) {
7962 $truncate .= '</' . $tag . '>';
7970 * Given dates in seconds, how many weeks is the date from startdate
7971 * The first week is 1, the second 2 etc ...
7973 * @param int $startdate Timestamp for the start date
7974 * @param int $thedate Timestamp for the end date
7977 function getweek ($startdate, $thedate) {
7978 if ($thedate < $startdate) {
7982 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
7986 * Returns a randomly generated password of length $maxlen. inspired by
7988 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
7989 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
7991 * @param int $maxlen The maximum size of the password being generated.
7994 function generate_password($maxlen=10) {
7997 if (empty($CFG->passwordpolicy
)) {
7998 $fillers = PASSWORD_DIGITS
;
7999 $wordlist = file($CFG->wordlist
);
8000 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8001 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8002 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8003 $password = $word1 . $filler1 . $word2;
8005 $minlen = !empty($CFG->minpasswordlength
) ?
$CFG->minpasswordlength
: 0;
8006 $digits = $CFG->minpassworddigits
;
8007 $lower = $CFG->minpasswordlower
;
8008 $upper = $CFG->minpasswordupper
;
8009 $nonalphanum = $CFG->minpasswordnonalphanum
;
8010 $total = $lower +
$upper +
$digits +
$nonalphanum;
8011 // Var minlength should be the greater one of the two ( $minlen and $total ).
8012 $minlen = $minlen < $total ?
$total : $minlen;
8013 // Var maxlen can never be smaller than minlen.
8014 $maxlen = $minlen > $maxlen ?
$minlen : $maxlen;
8015 $additional = $maxlen - $total;
8017 // Make sure we have enough characters to fulfill
8018 // complexity requirements.
8019 $passworddigits = PASSWORD_DIGITS
;
8020 while ($digits > strlen($passworddigits)) {
8021 $passworddigits .= PASSWORD_DIGITS
;
8023 $passwordlower = PASSWORD_LOWER
;
8024 while ($lower > strlen($passwordlower)) {
8025 $passwordlower .= PASSWORD_LOWER
;
8027 $passwordupper = PASSWORD_UPPER
;
8028 while ($upper > strlen($passwordupper)) {
8029 $passwordupper .= PASSWORD_UPPER
;
8031 $passwordnonalphanum = PASSWORD_NONALPHANUM
;
8032 while ($nonalphanum > strlen($passwordnonalphanum)) {
8033 $passwordnonalphanum .= PASSWORD_NONALPHANUM
;
8036 // Now mix and shuffle it all.
8037 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8038 substr(str_shuffle ($passwordupper), 0, $upper) .
8039 substr(str_shuffle ($passworddigits), 0, $digits) .
8040 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8041 substr(str_shuffle ($passwordlower .
8044 $passwordnonalphanum), 0 , $additional));
8047 return substr ($password, 0, $maxlen);
8051 * Given a float, prints it nicely.
8052 * Localized floats must not be used in calculations!
8054 * The stripzeros feature is intended for making numbers look nicer in small
8055 * areas where it is not necessary to indicate the degree of accuracy by showing
8056 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8057 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8059 * @param float $float The float to print
8060 * @param int $decimalpoints The number of decimal places to print.
8061 * @param bool $localized use localized decimal separator
8062 * @param bool $stripzeros If true, removes final zeros after decimal point
8063 * @return string locale float
8065 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8066 if (is_null($float)) {
8070 $separator = get_string('decsep', 'langconfig');
8074 $result = number_format($float, $decimalpoints, $separator, '');
8076 // Remove zeros and final dot if not needed.
8077 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8083 * Converts locale specific floating point/comma number back to standard PHP float value
8084 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8086 * @param string $localefloat locale aware float representation
8087 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8088 * @return mixed float|bool - false or the parsed float.
8090 function unformat_float($localefloat, $strict = false) {
8091 $localefloat = trim($localefloat);
8093 if ($localefloat == '') {
8097 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8098 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8100 if ($strict && !is_numeric($localefloat)) {
8104 return (float)$localefloat;
8108 * Given a simple array, this shuffles it up just like shuffle()
8109 * Unlike PHP's shuffle() this function works on any machine.
8111 * @param array $array The array to be rearranged
8114 function swapshuffle($array) {
8116 $last = count($array) - 1;
8117 for ($i = 0; $i <= $last; $i++
) {
8118 $from = rand(0, $last);
8120 $array[$i] = $array[$from];
8121 $array[$from] = $curr;
8127 * Like {@link swapshuffle()}, but works on associative arrays
8129 * @param array $array The associative array to be rearranged
8132 function swapshuffle_assoc($array) {
8134 $newarray = array();
8135 $newkeys = swapshuffle(array_keys($array));
8137 foreach ($newkeys as $newkey) {
8138 $newarray[$newkey] = $array[$newkey];
8144 * Given an arbitrary array, and a number of draws,
8145 * this function returns an array with that amount
8146 * of items. The indexes are retained.
8148 * @todo Finish documenting this function
8150 * @param array $array
8154 function draw_rand_array($array, $draws) {
8158 $last = count($array);
8160 if ($draws > $last) {
8164 while ($draws > 0) {
8167 $keys = array_keys($array);
8168 $rand = rand(0, $last);
8170 $return[$keys[$rand]] = $array[$keys[$rand]];
8171 unset($array[$keys[$rand]]);
8180 * Calculate the difference between two microtimes
8182 * @param string $a The first Microtime
8183 * @param string $b The second Microtime
8186 function microtime_diff($a, $b) {
8187 list($adec, $asec) = explode(' ', $a);
8188 list($bdec, $bsec) = explode(' ', $b);
8189 return $bsec - $asec +
$bdec - $adec;
8193 * Given a list (eg a,b,c,d,e) this function returns
8194 * an array of 1->a, 2->b, 3->c etc
8196 * @param string $list The string to explode into array bits
8197 * @param string $separator The separator used within the list string
8198 * @return array The now assembled array
8200 function make_menu_from_list($list, $separator=',') {
8202 $array = array_reverse(explode($separator, $list), true);
8203 foreach ($array as $key => $item) {
8204 $outarray[$key+
1] = trim($item);
8210 * Creates an array that represents all the current grades that
8211 * can be chosen using the given grading type.
8214 * are scales, zero is no grade, and positive numbers are maximum
8217 * @todo Finish documenting this function or better deprecated this completely!
8219 * @param int $gradingtype
8222 function make_grades_menu($gradingtype) {
8226 if ($gradingtype < 0) {
8227 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8228 return make_menu_from_list($scale->scale
);
8230 } else if ($gradingtype > 0) {
8231 for ($i=$gradingtype; $i>=0; $i--) {
8232 $grades[$i] = $i .' / '. $gradingtype;
8240 * This function returns the number of activities using the given scale in the given course.
8242 * @param int $courseid The course ID to check.
8243 * @param int $scaleid The scale ID to check
8246 function course_scale_used($courseid, $scaleid) {
8251 if (!empty($scaleid)) {
8252 if ($cms = get_course_mods($courseid)) {
8253 foreach ($cms as $cm) {
8254 // Check cm->name/lib.php exists.
8255 if (file_exists($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php')) {
8256 include_once($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php');
8257 $functionname = $cm->modname
.'_scale_used';
8258 if (function_exists($functionname)) {
8259 if ($functionname($cm->instance
, $scaleid)) {
8267 // Check if any course grade item makes use of the scale.
8268 $return +
= $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8270 // Check if any outcome in the course makes use of the scale.
8271 $return +
= $DB->count_records_sql("SELECT COUNT('x')
8272 FROM {grade_outcomes_courses} goc,
8274 WHERE go.id = goc.outcomeid
8275 AND go.scaleid = ? AND goc.courseid = ?",
8276 array($scaleid, $courseid));
8282 * This function returns the number of activities using scaleid in the entire site
8284 * @param int $scaleid
8285 * @param array $courses
8288 function site_scale_used($scaleid, &$courses) {
8291 if (!is_array($courses) ||
count($courses) == 0) {
8292 $courses = get_courses("all", false, "c.id, c.shortname");
8295 if (!empty($scaleid)) {
8296 if (is_array($courses) && count($courses) > 0) {
8297 foreach ($courses as $course) {
8298 $return +
= course_scale_used($course->id
, $scaleid);
8306 * make_unique_id_code
8308 * @todo Finish documenting this function
8311 * @param string $extra Extra string to append to the end of the code
8314 function make_unique_id_code($extra = '') {
8316 $hostname = 'unknownhost';
8317 if (!empty($_SERVER['HTTP_HOST'])) {
8318 $hostname = $_SERVER['HTTP_HOST'];
8319 } else if (!empty($_ENV['HTTP_HOST'])) {
8320 $hostname = $_ENV['HTTP_HOST'];
8321 } else if (!empty($_SERVER['SERVER_NAME'])) {
8322 $hostname = $_SERVER['SERVER_NAME'];
8323 } else if (!empty($_ENV['SERVER_NAME'])) {
8324 $hostname = $_ENV['SERVER_NAME'];
8327 $date = gmdate("ymdHis");
8329 $random = random_string(6);
8332 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8334 return $hostname .'+'. $date .'+'. $random;
8340 * Function to check the passed address is within the passed subnet
8342 * The parameter is a comma separated string of subnet definitions.
8343 * Subnet strings can be in one of three formats:
8344 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8345 * 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)
8346 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8347 * Code for type 1 modified from user posted comments by mediator at
8348 * {@link http://au.php.net/manual/en/function.ip2long.php}
8350 * @param string $addr The address you are checking
8351 * @param string $subnetstr The string of subnet addresses
8354 function address_in_subnet($addr, $subnetstr) {
8356 if ($addr == '0.0.0.0') {
8359 $subnets = explode(',', $subnetstr);
8361 $addr = trim($addr);
8362 $addr = cleanremoteaddr($addr, false); // Normalise.
8363 if ($addr === null) {
8366 $addrparts = explode(':', $addr);
8368 $ipv6 = strpos($addr, ':');
8370 foreach ($subnets as $subnet) {
8371 $subnet = trim($subnet);
8372 if ($subnet === '') {
8376 if (strpos($subnet, '/') !== false) {
8377 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8378 list($ip, $mask) = explode('/', $subnet);
8379 $mask = trim($mask);
8380 if (!is_number($mask)) {
8381 continue; // Incorect mask number, eh?
8383 $ip = cleanremoteaddr($ip, false); // Normalise.
8387 if (strpos($ip, ':') !== false) {
8392 if ($mask > 128 or $mask < 0) {
8393 continue; // Nonsense.
8396 return true; // Any address.
8399 if ($ip === $addr) {
8404 $ipparts = explode(':', $ip);
8405 $modulo = $mask %
16;
8406 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8407 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8408 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8412 $pos = ($mask-$modulo)/16;
8413 $ipnet = hexdec($ipparts[$pos]);
8414 $addrnet = hexdec($addrparts[$pos]);
8415 $mask = 0xffff << (16 - $modulo);
8416 if (($addrnet & $mask) == ($ipnet & $mask)) {
8426 if ($mask > 32 or $mask < 0) {
8427 continue; // Nonsense.
8433 if ($ip === $addr) {
8438 $mask = 0xffffffff << (32 - $mask);
8439 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8444 } else if (strpos($subnet, '-') !== false) {
8445 // 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.
8446 $parts = explode('-', $subnet);
8447 if (count($parts) != 2) {
8451 if (strpos($subnet, ':') !== false) {
8456 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8457 if ($ipstart === null) {
8460 $ipparts = explode(':', $ipstart);
8461 $start = hexdec(array_pop($ipparts));
8462 $ipparts[] = trim($parts[1]);
8463 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8464 if ($ipend === null) {
8468 $ipnet = implode(':', $ipparts);
8469 if (strpos($addr, $ipnet) !== 0) {
8472 $ipparts = explode(':', $ipend);
8473 $end = hexdec($ipparts[7]);
8475 $addrend = hexdec($addrparts[7]);
8477 if (($addrend >= $start) and ($addrend <= $end)) {
8486 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8487 if ($ipstart === null) {
8490 $ipparts = explode('.', $ipstart);
8491 $ipparts[3] = trim($parts[1]);
8492 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8493 if ($ipend === null) {
8497 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8503 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8504 if (strpos($subnet, ':') !== false) {
8509 $parts = explode(':', $subnet);
8510 $count = count($parts);
8511 if ($parts[$count-1] === '') {
8512 unset($parts[$count-1]); // Trim trailing :'s.
8514 $subnet = implode('.', $parts);
8516 $isip = cleanremoteaddr($subnet, false); // Normalise.
8517 if ($isip !== null) {
8518 if ($isip === $addr) {
8522 } else if ($count > 8) {
8525 $zeros = array_fill(0, 8-$count, '0');
8526 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8527 if (address_in_subnet($addr, $subnet)) {
8536 $parts = explode('.', $subnet);
8537 $count = count($parts);
8538 if ($parts[$count-1] === '') {
8539 unset($parts[$count-1]); // Trim trailing .
8541 $subnet = implode('.', $parts);
8544 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8545 if ($subnet === $addr) {
8549 } else if ($count > 4) {
8552 $zeros = array_fill(0, 4-$count, '0');
8553 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8554 if (address_in_subnet($addr, $subnet)) {
8565 * For outputting debugging info
8567 * @param string $string The string to write
8568 * @param string $eol The end of line char(s) to use
8569 * @param string $sleep Period to make the application sleep
8570 * This ensures any messages have time to display before redirect
8572 function mtrace($string, $eol="\n", $sleep=0) {
8574 if (defined('STDOUT') and !PHPUNIT_TEST
) {
8575 fwrite(STDOUT
, $string.$eol);
8577 echo $string . $eol;
8582 // Delay to keep message on user's screen in case of subsequent redirect.
8589 * Replace 1 or more slashes or backslashes to 1 slash
8591 * @param string $path The path to strip
8592 * @return string the path with double slashes removed
8594 function cleardoubleslashes ($path) {
8595 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8599 * Is current ip in give list?
8601 * @param string $list
8604 function remoteip_in_list($list) {
8606 $clientip = getremoteaddr(null);
8609 // Ensure access on cli.
8613 $list = explode("\n", $list);
8614 foreach ($list as $subnet) {
8615 $subnet = trim($subnet);
8616 if (address_in_subnet($clientip, $subnet)) {
8625 * Returns most reliable client address
8627 * @param string $default If an address can't be determined, then return this
8628 * @return string The remote IP address
8630 function getremoteaddr($default='0.0.0.0') {
8633 if (empty($CFG->getremoteaddrconf
)) {
8634 // This will happen, for example, before just after the upgrade, as the
8635 // user is redirected to the admin screen.
8636 $variablestoskip = 0;
8638 $variablestoskip = $CFG->getremoteaddrconf
;
8640 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP
)) {
8641 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8642 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8643 return $address ?
$address : $default;
8646 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR
)) {
8647 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8648 $hdr = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8649 $address = cleanremoteaddr($hdr[0]);
8650 return $address ?
$address : $default;
8653 if (!empty($_SERVER['REMOTE_ADDR'])) {
8654 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8655 return $address ?
$address : $default;
8662 * Cleans an ip address. Internal addresses are now allowed.
8663 * (Originally local addresses were not allowed.)
8665 * @param string $addr IPv4 or IPv6 address
8666 * @param bool $compress use IPv6 address compression
8667 * @return string normalised ip address string, null if error
8669 function cleanremoteaddr($addr, $compress=false) {
8670 $addr = trim($addr);
8672 // TODO: maybe add a separate function is_addr_public() or something like this.
8674 if (strpos($addr, ':') !== false) {
8675 // Can be only IPv6.
8676 $parts = explode(':', $addr);
8677 $count = count($parts);
8679 if (strpos($parts[$count-1], '.') !== false) {
8680 // Legacy ipv4 notation.
8681 $last = array_pop($parts);
8682 $ipv4 = cleanremoteaddr($last, true);
8683 if ($ipv4 === null) {
8686 $bits = explode('.', $ipv4);
8687 $parts[] = dechex($bits[0]).dechex($bits[1]);
8688 $parts[] = dechex($bits[2]).dechex($bits[3]);
8689 $count = count($parts);
8690 $addr = implode(':', $parts);
8693 if ($count < 3 or $count > 8) {
8694 return null; // Severly malformed.
8698 if (strpos($addr, '::') === false) {
8699 return null; // Malformed.
8702 $insertat = array_search('', $parts, true);
8703 $missing = array_fill(0, 1 +
8 - $count, '0');
8704 array_splice($parts, $insertat, 1, $missing);
8705 foreach ($parts as $key => $part) {
8712 $adr = implode(':', $parts);
8713 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8714 return null; // Incorrect format - sorry.
8717 // Normalise 0s and case.
8718 $parts = array_map('hexdec', $parts);
8719 $parts = array_map('dechex', $parts);
8721 $result = implode(':', $parts);
8727 if ($result === '0:0:0:0:0:0:0:0') {
8728 return '::'; // All addresses.
8731 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8732 if ($compressed !== $result) {
8736 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8737 if ($compressed !== $result) {
8741 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8742 if ($compressed !== $result) {
8749 // First get all things that look like IPv4 addresses.
8751 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8756 foreach ($parts as $key => $match) {
8760 $parts[$key] = (int)$match; // Normalise 0s.
8763 return implode('.', $parts);
8767 * This function will make a complete copy of anything it's given,
8768 * regardless of whether it's an object or not.
8770 * @param mixed $thing Something you want cloned
8771 * @return mixed What ever it is you passed it
8773 function fullclone($thing) {
8774 return unserialize(serialize($thing));
8778 * If new messages are waiting for the current user, then insert
8779 * JavaScript to pop up the messaging window into the page
8783 function message_popup_window() {
8784 global $USER, $DB, $PAGE, $CFG;
8786 if (!$PAGE->get_popup_notification_allowed() ||
empty($CFG->messaging
)) {
8790 if (!isloggedin() ||
isguestuser()) {
8794 if (!isset($USER->message_lastpopup
)) {
8795 $USER->message_lastpopup
= 0;
8796 } else if ($USER->message_lastpopup
> (time()-120)) {
8797 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8801 // A quick query to check whether the user has new messages.
8802 $messagecount = $DB->count_records('message', array('useridto' => $USER->id
));
8803 if ($messagecount < 1) {
8807 // There are unread messages so now do a more complex but slower query.
8808 $messagesql = "SELECT m.id, c.blocked
8810 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8811 JOIN {message_processors} p ON mw.processorid=p.id
8812 JOIN {user} u ON m.useridfrom=u.id
8813 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8814 AND c.userid = m.useridto
8815 WHERE m.useridto = :userid
8816 AND p.name='popup'";
8818 // If the user was last notified over an hour ago we can re-notify them of old messages
8819 // so don't worry about when the new message was sent.
8820 $lastnotifiedlongago = $USER->message_lastpopup
< (time()-3600);
8821 if (!$lastnotifiedlongago) {
8822 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8825 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id
, 'lastpopuptime' => $USER->message_lastpopup
));
8828 foreach ($waitingmessages as $messageinfo) {
8829 if ($messageinfo->blocked
) {
8830 // Message is from a user who has since been blocked so just mark it read.
8831 // Get the full message to mark as read.
8832 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id
));
8833 message_mark_message_read($messageobject, time());
8839 if ($validmessages > 0) {
8840 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8841 $strgomessage = get_string('gotomessages', 'message');
8842 $strstaymessage = get_string('ignore', 'admin');
8844 $notificationsound = null;
8845 $beep = get_user_preferences('message_beepnewmessage', '');
8846 if (!empty($beep)) {
8847 // Browsers will work down this list until they find something they support.
8848 $sourcetags = html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.wav', 'type' => 'audio/wav'));
8849 $sourcetags .= html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.ogg', 'type' => 'audio/ogg'));
8850 $sourcetags .= html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8851 $sourcetags .= html_writer
::empty_tag('embed', array('src' => $CFG->wwwroot
.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8853 $notificationsound = html_writer
::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8856 $url = $CFG->wwwroot
.'/message/index.php';
8857 $content = html_writer
::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8858 html_writer
::start_tag('div', array('id' => 'newmessagetext')).
8860 html_writer
::end_tag('div').
8863 html_writer
::start_tag('div', array('id' => 'newmessagelinks')).
8864 html_writer
::link($url, $strgomessage, array('id' => 'notificationyes')).' '.
8865 html_writer
::link('', $strstaymessage, array('id' => 'notificationno')).
8866 html_writer
::end_tag('div');
8867 html_writer
::end_tag('div');
8869 $PAGE->requires
->js_init_call('M.core_message.init_notification', array('', $content, $url));
8871 $USER->message_lastpopup
= time();
8876 * Used to make sure that $min <= $value <= $max
8878 * Make sure that value is between min, and max
8880 * @param int $min The minimum value
8881 * @param int $value The value to check
8882 * @param int $max The maximum value
8885 function bounded_number($min, $value, $max) {
8886 if ($value < $min) {
8889 if ($value > $max) {
8896 * Check if there is a nested array within the passed array
8898 * @param array $array
8899 * @return bool true if there is a nested array false otherwise
8901 function array_is_nested($array) {
8902 foreach ($array as $value) {
8903 if (is_array($value)) {
8911 * get_performance_info() pairs up with init_performance_info()
8912 * loaded in setup.php. Returns an array with 'html' and 'txt'
8913 * values ready for use, and each of the individual stats provided
8914 * separately as well.
8918 function get_performance_info() {
8919 global $CFG, $PERF, $DB, $PAGE;
8922 $info['html'] = ''; // Holds userfriendly HTML representation.
8923 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8925 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
8927 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8928 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8930 if (function_exists('memory_get_usage')) {
8931 $info['memory_total'] = memory_get_usage();
8932 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
8933 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8934 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8935 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8938 if (function_exists('memory_get_peak_usage')) {
8939 $info['memory_peak'] = memory_get_peak_usage();
8940 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8941 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8944 $inc = get_included_files();
8945 $info['includecount'] = count($inc);
8946 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8947 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8949 if (!empty($CFG->early_install_lang
) or empty($PAGE)) {
8950 // We can not track more performance before installation or before PAGE init, sorry.
8954 $filtermanager = filter_manager
::instance();
8955 if (method_exists($filtermanager, 'get_performance_summary')) {
8956 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8957 $info = array_merge($filterinfo, $info);
8958 foreach ($filterinfo as $key => $value) {
8959 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8960 $info['txt'] .= "$key: $value ";
8964 $stringmanager = get_string_manager();
8965 if (method_exists($stringmanager, 'get_performance_summary')) {
8966 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8967 $info = array_merge($filterinfo, $info);
8968 foreach ($filterinfo as $key => $value) {
8969 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8970 $info['txt'] .= "$key: $value ";
8974 if (!empty($PERF->logwrites
)) {
8975 $info['logwrites'] = $PERF->logwrites
;
8976 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8977 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8980 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites
);
8981 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
8982 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8984 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
8985 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
8986 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
8988 if (function_exists('posix_times')) {
8989 $ptimes = posix_times();
8990 if (is_array($ptimes)) {
8991 foreach ($ptimes as $key => $val) {
8992 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
8994 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
8995 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8999 // Grab the load average for the last minute.
9000 // /proc will only work under some linux configurations
9001 // while uptime is there under MacOSX/Darwin and other unices.
9002 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
9003 list($serverload) = explode(' ', $loadavg[0]);
9005 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
9006 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9007 $serverload = $matches[1];
9009 trigger_error('Could not parse uptime output!');
9012 if (!empty($serverload)) {
9013 $info['serverload'] = $serverload;
9014 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
9015 $info['txt'] .= "serverload: {$info['serverload']} ";
9018 // Display size of session if session started.
9019 if ($si = \core\session\manager
::get_performance_info()) {
9020 $info['sessionsize'] = $si['size'];
9021 $info['html'] .= $si['html'];
9022 $info['txt'] .= $si['txt'];
9025 if ($stats = cache_helper
::get_stats()) {
9026 $html = '<span class="cachesused">';
9027 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
9028 $text = 'Caches used (hits/misses/sets): ';
9032 foreach ($stats as $definition => $stores) {
9033 $html .= '<span class="cache-definition-stats">';
9034 $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
9035 $text .= "$definition {";
9036 foreach ($stores as $store => $data) {
9037 $hits +
= $data['hits'];
9038 $misses +
= $data['misses'];
9039 $sets +
= $data['sets'];
9040 if ($data['hits'] == 0 and $data['misses'] > 0) {
9041 $cachestoreclass = 'nohits';
9042 } else if ($data['hits'] < $data['misses']) {
9043 $cachestoreclass = 'lowhits';
9045 $cachestoreclass = 'hihits';
9047 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9048 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
9053 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
9054 $html .= '</span> ';
9055 $info['cachesused'] = "$hits / $misses / $sets";
9056 $info['html'] .= $html;
9057 $info['txt'] .= $text.'. ';
9059 $info['cachesused'] = '0 / 0 / 0';
9060 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
9061 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9064 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
9071 * @todo Document this function linux people
9073 function apd_get_profiling() {
9074 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
9078 * Delete directory or only its content
9080 * @param string $dir directory path
9081 * @param bool $contentonly
9082 * @return bool success, true also if dir does not exist
9084 function remove_dir($dir, $contentonly=false) {
9085 if (!file_exists($dir)) {
9089 if (!$handle = opendir($dir)) {
9093 while (false!==($item = readdir($handle))) {
9094 if ($item != '.' && $item != '..') {
9095 if (is_dir($dir.'/'.$item)) {
9096 $result = remove_dir($dir.'/'.$item) && $result;
9098 $result = unlink($dir.'/'.$item) && $result;
9104 clearstatcache(); // Make sure file stat cache is properly invalidated.
9107 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9108 clearstatcache(); // Make sure file stat cache is properly invalidated.
9113 * Detect if an object or a class contains a given property
9114 * will take an actual object or the name of a class
9116 * @param mix $obj Name of class or real object to test
9117 * @param string $property name of property to find
9118 * @return bool true if property exists
9120 function object_property_exists( $obj, $property ) {
9121 if (is_string( $obj )) {
9122 $properties = get_class_vars( $obj );
9124 $properties = get_object_vars( $obj );
9126 return array_key_exists( $property, $properties );
9130 * Converts an object into an associative array
9132 * This function converts an object into an associative array by iterating
9133 * over its public properties. Because this function uses the foreach
9134 * construct, Iterators are respected. It works recursively on arrays of objects.
9135 * Arrays and simple values are returned as is.
9137 * If class has magic properties, it can implement IteratorAggregate
9138 * and return all available properties in getIterator()
9143 function convert_to_array($var) {
9146 // Loop over elements/properties.
9147 foreach ($var as $key => $value) {
9148 // Recursively convert objects.
9149 if (is_object($value) ||
is_array($value)) {
9150 $result[$key] = convert_to_array($value);
9152 // Simple values are untouched.
9153 $result[$key] = $value;
9160 * Detect a custom script replacement in the data directory that will
9161 * replace an existing moodle script
9163 * @return string|bool full path name if a custom script exists, false if no custom script exists
9165 function custom_script_path() {
9166 global $CFG, $SCRIPT;
9168 if ($SCRIPT === null) {
9169 // Probably some weird external script.
9173 $scriptpath = $CFG->customscripts
. $SCRIPT;
9175 // Check the custom script exists.
9176 if (file_exists($scriptpath) and is_file($scriptpath)) {
9184 * Returns whether or not the user object is a remote MNET user. This function
9185 * is in moodlelib because it does not rely on loading any of the MNET code.
9187 * @param object $user A valid user object
9188 * @return bool True if the user is from a remote Moodle.
9190 function is_mnet_remote_user($user) {
9193 if (!isset($CFG->mnet_localhost_id
)) {
9194 include_once($CFG->dirroot
. '/mnet/lib.php');
9195 $env = new mnet_environment();
9200 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
9204 * This function will search for browser prefereed languages, setting Moodle
9205 * to use the best one available if $SESSION->lang is undefined
9207 function setup_lang_from_browser() {
9208 global $CFG, $SESSION, $USER;
9210 if (!empty($SESSION->lang
) or !empty($USER->lang
) or empty($CFG->autolang
)) {
9211 // Lang is defined in session or user profile, nothing to do.
9215 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9219 // Extract and clean langs from headers.
9220 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9221 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9222 $rawlangs = explode(',', $rawlangs); // Convert to array.
9226 foreach ($rawlangs as $lang) {
9227 if (strpos($lang, ';') === false) {
9228 $langs[(string)$order] = $lang;
9229 $order = $order-0.01;
9231 $parts = explode(';', $lang);
9232 $pos = strpos($parts[1], '=');
9233 $langs[substr($parts[1], $pos+
1)] = $parts[0];
9236 krsort($langs, SORT_NUMERIC
);
9238 // Look for such langs under standard locations.
9239 foreach ($langs as $lang) {
9240 // Clean it properly for include.
9241 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR
));
9242 if (get_string_manager()->translation_exists($lang, false)) {
9243 // Lang exists, set it in session.
9244 $SESSION->lang
= $lang;
9245 // We have finished. Go out.
9253 * Check if $url matches anything in proxybypass list
9255 * Any errors just result in the proxy being used (least bad)
9257 * @param string $url url to check
9258 * @return boolean true if we should bypass the proxy
9260 function is_proxybypass( $url ) {
9264 if (empty($CFG->proxyhost
) or empty($CFG->proxybypass
)) {
9268 // Get the host part out of the url.
9269 if (!$host = parse_url( $url, PHP_URL_HOST
)) {
9273 // Get the possible bypass hosts into an array.
9274 $matches = explode( ',', $CFG->proxybypass
);
9276 // Check for a match.
9277 // (IPs need to match the left hand side and hosts the right of the url,
9278 // but we can recklessly check both as there can't be a false +ve).
9279 foreach ($matches as $match) {
9280 $match = trim($match);
9282 // Try for IP match (Left side).
9283 $lhs = substr($host, 0, strlen($match));
9284 if (strcasecmp($match, $lhs)==0) {
9288 // Try for host match (Right side).
9289 $rhs = substr($host, -strlen($match));
9290 if (strcasecmp($match, $rhs)==0) {
9300 * Check if the passed navigation is of the new style
9302 * @param mixed $navigation
9303 * @return bool true for yes false for no
9305 function is_newnav($navigation) {
9306 if (is_array($navigation) && !empty($navigation['newnav'])) {
9314 * Checks whether the given variable name is defined as a variable within the given object.
9316 * This will NOT work with stdClass objects, which have no class variables.
9318 * @param string $var The variable name
9319 * @param object $object The object to check
9322 function in_object_vars($var, $object) {
9323 $classvars = get_class_vars(get_class($object));
9324 $classvars = array_keys($classvars);
9325 return in_array($var, $classvars);
9329 * Returns an array without repeated objects.
9330 * This function is similar to array_unique, but for arrays that have objects as values
9332 * @param array $array
9333 * @param bool $keepkeyassoc
9336 function object_array_unique($array, $keepkeyassoc = true) {
9337 $duplicatekeys = array();
9340 foreach ($array as $key => $val) {
9341 // Convert objects to arrays, in_array() does not support objects.
9342 if (is_object($val)) {
9346 if (!in_array($val, $tmp)) {
9349 $duplicatekeys[] = $key;
9353 foreach ($duplicatekeys as $key) {
9354 unset($array[$key]);
9357 return $keepkeyassoc ?
$array : array_values($array);
9361 * Is a userid the primary administrator?
9363 * @param int $userid int id of user to check
9366 function is_primary_admin($userid) {
9367 $primaryadmin = get_admin();
9369 if ($userid == $primaryadmin->id
) {
9377 * Returns the site identifier
9379 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9381 function get_site_identifier() {
9383 // Check to see if it is missing. If so, initialise it.
9384 if (empty($CFG->siteidentifier
)) {
9385 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9388 return $CFG->siteidentifier
;
9392 * Check whether the given password has no more than the specified
9393 * number of consecutive identical characters.
9395 * @param string $password password to be checked against the password policy
9396 * @param integer $maxchars maximum number of consecutive identical characters
9399 function check_consecutive_identical_characters($password, $maxchars) {
9401 if ($maxchars < 1) {
9402 return true; // Zero 0 is to disable this check.
9404 if (strlen($password) <= $maxchars) {
9405 return true; // Too short to fail this test.
9409 $consecutivecount = 1;
9410 foreach (str_split($password) as $char) {
9411 if ($char != $previouschar) {
9412 $consecutivecount = 1;
9414 $consecutivecount++
;
9415 if ($consecutivecount > $maxchars) {
9416 return false; // Check failed already.
9420 $previouschar = $char;
9427 * Helper function to do partial function binding.
9428 * so we can use it for preg_replace_callback, for example
9429 * this works with php functions, user functions, static methods and class methods
9430 * it returns you a callback that you can pass on like so:
9432 * $callback = partial('somefunction', $arg1, $arg2);
9434 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9436 * $obj = new someclass();
9437 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9439 * and then the arguments that are passed through at calltime are appended to the argument list.
9441 * @param mixed $function a php callback
9442 * @param mixed $arg1,... $argv arguments to partially bind with
9443 * @return array Array callback
9445 function partial() {
9446 if (!class_exists('partial')) {
9448 * Used to manage function binding.
9449 * @copyright 2009 Penny Leach
9450 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9454 public $values = array();
9455 /** @var string The function to call as a callback. */
9459 * @param string $func
9460 * @param array $args
9462 public function __construct($func, $args) {
9463 $this->values
= $args;
9464 $this->func
= $func;
9467 * Calls the callback function.
9470 public function method() {
9471 $args = func_get_args();
9472 return call_user_func_array($this->func
, array_merge($this->values
, $args));
9476 $args = func_get_args();
9477 $func = array_shift($args);
9478 $p = new partial($func, $args);
9479 return array($p, 'method');
9483 * helper function to load up and initialise the mnet environment
9484 * this must be called before you use mnet functions.
9486 * @return mnet_environment the equivalent of old $MNET global
9488 function get_mnet_environment() {
9490 require_once($CFG->dirroot
. '/mnet/lib.php');
9491 static $instance = null;
9492 if (empty($instance)) {
9493 $instance = new mnet_environment();
9500 * during xmlrpc server code execution, any code wishing to access
9501 * information about the remote peer must use this to get it.
9503 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9505 function get_mnet_remote_client() {
9506 if (!defined('MNET_SERVER')) {
9507 debugging(get_string('notinxmlrpcserver', 'mnet'));
9510 global $MNET_REMOTE_CLIENT;
9511 if (isset($MNET_REMOTE_CLIENT)) {
9512 return $MNET_REMOTE_CLIENT;
9518 * during the xmlrpc server code execution, this will be called
9519 * to setup the object returned by {@link get_mnet_remote_client}
9521 * @param mnet_remote_client $client the client to set up
9522 * @throws moodle_exception
9524 function set_mnet_remote_client($client) {
9525 if (!defined('MNET_SERVER')) {
9526 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9528 global $MNET_REMOTE_CLIENT;
9529 $MNET_REMOTE_CLIENT = $client;
9533 * return the jump url for a given remote user
9534 * this is used for rewriting forum post links in emails, etc
9536 * @param stdclass $user the user to get the idp url for
9538 function mnet_get_idp_jump_url($user) {
9541 static $mnetjumps = array();
9542 if (!array_key_exists($user->mnethostid
, $mnetjumps)) {
9543 $idp = mnet_get_peer_host($user->mnethostid
);
9544 $idpjumppath = mnet_get_app_jumppath($idp->applicationid
);
9545 $mnetjumps[$user->mnethostid
] = $idp->wwwroot
. $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot
. '&wantsurl=';
9547 return $mnetjumps[$user->mnethostid
];
9551 * Gets the homepage to use for the current user
9553 * @return int One of HOMEPAGE_*
9555 function get_home_page() {
9558 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage
)) {
9559 if ($CFG->defaulthomepage
== HOMEPAGE_MY
) {
9562 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY
);
9565 return HOMEPAGE_SITE
;
9569 * Gets the name of a course to be displayed when showing a list of courses.
9570 * By default this is just $course->fullname but user can configure it. The
9571 * result of this function should be passed through print_string.
9572 * @param stdClass|course_in_list $course Moodle course object
9573 * @return string Display name of course (either fullname or short + fullname)
9575 function get_course_display_name_for_list($course) {
9577 if (!empty($CFG->courselistshortnames
)) {
9578 if (!($course instanceof stdClass
)) {
9579 $course = (object)convert_to_array($course);
9581 return get_string('courseextendednamedisplay', '', $course);
9583 return $course->fullname
;
9588 * The lang_string class
9590 * This special class is used to create an object representation of a string request.
9591 * It is special because processing doesn't occur until the object is first used.
9592 * The class was created especially to aid performance in areas where strings were
9593 * required to be generated but were not necessarily used.
9594 * As an example the admin tree when generated uses over 1500 strings, of which
9595 * normally only 1/3 are ever actually printed at any time.
9596 * The performance advantage is achieved by not actually processing strings that
9597 * arn't being used, as such reducing the processing required for the page.
9599 * How to use the lang_string class?
9600 * There are two methods of using the lang_string class, first through the
9601 * forth argument of the get_string function, and secondly directly.
9602 * The following are examples of both.
9603 * 1. Through get_string calls e.g.
9604 * $string = get_string($identifier, $component, $a, true);
9605 * $string = get_string('yes', 'moodle', null, true);
9606 * 2. Direct instantiation
9607 * $string = new lang_string($identifier, $component, $a, $lang);
9608 * $string = new lang_string('yes');
9610 * How do I use a lang_string object?
9611 * The lang_string object makes use of a magic __toString method so that you
9612 * are able to use the object exactly as you would use a string in most cases.
9613 * This means you are able to collect it into a variable and then directly
9614 * echo it, or concatenate it into another string, or similar.
9615 * The other thing you can do is manually get the string by calling the
9616 * lang_strings out method e.g.
9617 * $string = new lang_string('yes');
9619 * Also worth noting is that the out method can take one argument, $lang which
9620 * allows the developer to change the language on the fly.
9622 * When should I use a lang_string object?
9623 * The lang_string object is designed to be used in any situation where a
9624 * string may not be needed, but needs to be generated.
9625 * The admin tree is a good example of where lang_string objects should be
9627 * A more practical example would be any class that requries strings that may
9628 * not be printed (after all classes get renderer by renderers and who knows
9629 * what they will do ;))
9631 * When should I not use a lang_string object?
9632 * Don't use lang_strings when you are going to use a string immediately.
9633 * There is no need as it will be processed immediately and there will be no
9634 * advantage, and in fact perhaps a negative hit as a class has to be
9635 * instantiated for a lang_string object, however get_string won't require
9639 * 1. You cannot use a lang_string object as an array offset. Doing so will
9640 * result in PHP throwing an error. (You can use it as an object property!)
9644 * @copyright 2011 Sam Hemelryk
9645 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9649 /** @var string The strings identifier */
9650 protected $identifier;
9651 /** @var string The strings component. Default '' */
9652 protected $component = '';
9653 /** @var array|stdClass Any arguments required for the string. Default null */
9654 protected $a = null;
9655 /** @var string The language to use when processing the string. Default null */
9656 protected $lang = null;
9658 /** @var string The processed string (once processed) */
9659 protected $string = null;
9662 * A special boolean. If set to true then the object has been woken up and
9663 * cannot be regenerated. If this is set then $this->string MUST be used.
9666 protected $forcedstring = false;
9669 * Constructs a lang_string object
9671 * This function should do as little processing as possible to ensure the best
9672 * performance for strings that won't be used.
9674 * @param string $identifier The strings identifier
9675 * @param string $component The strings component
9676 * @param stdClass|array $a Any arguments the string requires
9677 * @param string $lang The language to use when processing the string.
9678 * @throws coding_exception
9680 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9681 if (empty($component)) {
9682 $component = 'moodle';
9685 $this->identifier
= $identifier;
9686 $this->component
= $component;
9687 $this->lang
= $lang;
9689 // We MUST duplicate $a to ensure that it if it changes by reference those
9690 // changes are not carried across.
9691 // To do this we always ensure $a or its properties/values are strings
9692 // and that any properties/values that arn't convertable are forgotten.
9694 if (is_scalar($a)) {
9696 } else if ($a instanceof lang_string
) {
9697 $this->a
= $a->out();
9698 } else if (is_object($a) or is_array($a)) {
9701 foreach ($a as $key => $value) {
9702 // Make sure conversion errors don't get displayed (results in '').
9703 if (is_array($value)) {
9704 $this->a
[$key] = '';
9705 } else if (is_object($value)) {
9706 if (method_exists($value, '__toString')) {
9707 $this->a
[$key] = $value->__toString();
9709 $this->a
[$key] = '';
9712 $this->a
[$key] = (string)$value;
9718 if (debugging(false, DEBUG_DEVELOPER
)) {
9719 if (clean_param($this->identifier
, PARAM_STRINGID
) == '') {
9720 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9722 if (!empty($this->component
) && clean_param($this->component
, PARAM_COMPONENT
) == '') {
9723 throw new coding_exception('Invalid string compontent. Please check your string definition');
9725 if (!get_string_manager()->string_exists($this->identifier
, $this->component
)) {
9726 debugging('String does not exist. Please check your string definition for '.$this->identifier
.'/'.$this->component
, DEBUG_DEVELOPER
);
9732 * Processes the string.
9734 * This function actually processes the string, stores it in the string property
9735 * and then returns it.
9736 * You will notice that this function is VERY similar to the get_string method.
9737 * That is because it is pretty much doing the same thing.
9738 * However as this function is an upgrade it isn't as tolerant to backwards
9742 * @throws coding_exception
9744 protected function get_string() {
9747 // Check if we need to process the string.
9748 if ($this->string === null) {
9749 // Check the quality of the identifier.
9750 if ($CFG->debugdeveloper
&& clean_param($this->identifier
, PARAM_STRINGID
) === '') {
9751 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
);
9754 // Process the string.
9755 $this->string = get_string_manager()->get_string($this->identifier
, $this->component
, $this->a
, $this->lang
);
9756 // Debugging feature lets you display string identifier and component.
9757 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
9758 $this->string .= ' {' . $this->identifier
. '/' . $this->component
. '}';
9761 // Return the string.
9762 return $this->string;
9766 * Returns the string
9768 * @param string $lang The langauge to use when processing the string
9771 public function out($lang = null) {
9772 if ($lang !== null && $lang != $this->lang
&& ($this->lang
== null && $lang != current_language())) {
9773 if ($this->forcedstring
) {
9774 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang
.' used)', DEBUG_DEVELOPER
);
9775 return $this->get_string();
9777 $translatedstring = new lang_string($this->identifier
, $this->component
, $this->a
, $lang);
9778 return $translatedstring->out();
9780 return $this->get_string();
9784 * Magic __toString method for printing a string
9788 public function __toString() {
9789 return $this->get_string();
9793 * Magic __set_state method used for var_export
9797 public function __set_state() {
9798 return $this->get_string();
9802 * Prepares the lang_string for sleep and stores only the forcedstring and
9803 * string properties... the string cannot be regenerated so we need to ensure
9804 * it is generated for this.
9808 public function __sleep() {
9809 $this->get_string();
9810 $this->forcedstring
= true;
9811 return array('forcedstring', 'string', 'lang');