2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') ||
die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 // Parameter constants - every call to optional_param(), required_param()
72 // or clean_param() should have a specified type of parameter.
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
77 define('PARAM_ALPHA', 'alpha');
80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
83 define('PARAM_ALPHAEXT', 'alphaext');
86 * PARAM_ALPHANUM - expected numbers and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
98 define('PARAM_AUTH', 'auth');
101 * PARAM_BASE64 - Base 64 encoded format
103 define('PARAM_BASE64', 'base64');
106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
108 define('PARAM_BOOL', 'bool');
111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112 * checked against the list of capabilities in the database.
114 define('PARAM_CAPABILITY', 'capability');
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
119 * the input (required/optional_param or formslib) and then sanitse the HTML
120 * using format_text on output. This is for the rare cases when you want to
121 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
123 define('PARAM_CLEANHTML', 'cleanhtml');
126 * PARAM_EMAIL - an email address following the RFC
128 define('PARAM_EMAIL', 'email');
131 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
133 define('PARAM_FILE', 'file');
136 * PARAM_FLOAT - a real/floating point number.
138 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139 * It does not work for languages that use , as a decimal separator.
140 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
146 define('PARAM_FLOAT', 'float');
149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
151 define('PARAM_HOST', 'host');
154 * PARAM_INT - integers only, use when expecting only numbers.
156 define('PARAM_INT', 'int');
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
161 define('PARAM_LANG', 'lang');
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
167 define('PARAM_LOCALURL', 'localurl');
170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
172 define('PARAM_NOTAGS', 'notags');
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
178 define('PARAM_PATH', 'path');
181 * PARAM_PEM - Privacy Enhanced Mail format
183 define('PARAM_PEM', 'pem');
186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
188 define('PARAM_PERMISSION', 'permission');
191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
193 define('PARAM_RAW', 'raw');
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
198 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
203 define('PARAM_SAFEDIR', 'safedir');
206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
208 define('PARAM_SAFEPATH', 'safepath');
211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
213 define('PARAM_SEQUENCE', 'sequence');
216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
218 define('PARAM_TAG', 'tag');
221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
223 define('PARAM_TAGLIST', 'taglist');
226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
228 define('PARAM_TEXT', 'text');
231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
233 define('PARAM_THEME', 'theme');
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * http://localhost.localdomain/ is ok.
239 define('PARAM_URL', 'url');
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243 * accounts, do NOT use when syncing with external systems!!
245 define('PARAM_USERNAME', 'username');
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
250 define('PARAM_STRINGID', 'stringid');
252 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
256 * @deprecated since 2.0
258 define('PARAM_CLEAN', 'clean');
261 * PARAM_INTEGER - deprecated alias for PARAM_INT
262 * @deprecated since 2.0
264 define('PARAM_INTEGER', 'int');
267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268 * @deprecated since 2.0
270 define('PARAM_NUMBER', 'float');
273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274 * NOTE: originally alias for PARAM_APLHA
275 * @deprecated since 2.0
277 define('PARAM_ACTION', 'alphanumext');
280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
282 * @deprecated since 2.0
284 define('PARAM_FORMAT', 'alphanumext');
287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288 * @deprecated since 2.0
290 define('PARAM_MULTILANG', 'text');
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295 * America/Port-au-Prince)
297 define('PARAM_TIMEZONE', 'timezone');
300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
302 define('PARAM_CLEANFILE', 'file');
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
310 define('PARAM_COMPONENT', 'component');
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
317 define('PARAM_AREA', 'area');
320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
324 define('PARAM_PLUGIN', 'plugin');
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
332 define('VALUE_REQUIRED', 1);
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
337 define('VALUE_OPTIONAL', 2);
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
342 define('VALUE_DEFAULT', 0);
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
347 define('NULL_NOT_ALLOWED', false);
350 * NULL_ALLOWED - the parameter can be set to null in the database
352 define('NULL_ALLOWED', true);
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
421 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
423 /** Type of module */
424 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425 /** True if module supports intro editor */
426 define('FEATURE_MOD_INTRO', 'mod_intro');
427 /** True if module has default completion */
428 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
430 define('FEATURE_COMMENT', 'comment');
432 define('FEATURE_RATE', 'rate');
433 /** True if module supports backup/restore of moodle2 format */
434 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
436 /** True if module can show description on course main page */
437 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
439 /** True if module uses the question bank */
440 define('FEATURE_USES_QUESTIONS', 'usesquestions');
442 /** Unspecified module archetype */
443 define('MOD_ARCHETYPE_OTHER', 0);
444 /** Resource-like type module */
445 define('MOD_ARCHETYPE_RESOURCE', 1);
446 /** Assignment module archetype */
447 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
448 /** System (not user-addable) module archetype */
449 define('MOD_ARCHETYPE_SYSTEM', 3);
451 /** Return this from modname_get_types callback to use default display in activity chooser */
452 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
455 * Security token used for allowing access
456 * from external application such as web services.
457 * Scripts do not use any session, performance is relatively
458 * low because we need to load access info in each request.
459 * Scripts are executed in parallel.
461 define('EXTERNAL_TOKEN_PERMANENT', 0);
464 * Security token used for allowing access
465 * of embedded applications, the code is executed in the
466 * active user session. Token is invalidated after user logs out.
467 * Scripts are executed serially - normal session locking is used.
469 define('EXTERNAL_TOKEN_EMBEDDED', 1);
472 * The home page should be the site home
474 define('HOMEPAGE_SITE', 0);
476 * The home page should be the users my page
478 define('HOMEPAGE_MY', 1);
480 * The home page can be chosen by the user
482 define('HOMEPAGE_USER', 2);
485 * Hub directory url (should be moodle.org)
487 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
491 * Moodle.org url (should be moodle.org)
493 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
496 * Moodle mobile app service name
498 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
501 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
503 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
506 * Course display settings: display all sections on one page.
508 define('COURSE_DISPLAY_SINGLEPAGE', 0);
510 * Course display settings: split pages into a page per section.
512 define('COURSE_DISPLAY_MULTIPAGE', 1);
515 * Authentication constant: String used in password field when password is not stored.
517 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
519 // PARAMETER HANDLING.
522 * Returns a particular value for the named variable, taken from
523 * POST or GET. If the parameter doesn't exist then an error is
524 * thrown because we require this variable.
526 * This function should be used to initialise all required values
527 * in a script that are based on parameters. Usually it will be
529 * $id = required_param('id', PARAM_INT);
531 * Please note the $type parameter is now required and the value can not be array.
533 * @param string $parname the name of the page parameter we want
534 * @param string $type expected type of parameter
536 * @throws coding_exception
538 function required_param($parname, $type) {
539 if (func_num_args() != 2 or empty($parname) or empty($type)) {
540 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
542 // POST has precedence.
543 if (isset($_POST[$parname])) {
544 $param = $_POST[$parname];
545 } else if (isset($_GET[$parname])) {
546 $param = $_GET[$parname];
548 print_error('missingparam', '', '', $parname);
551 if (is_array($param)) {
552 debugging('Invalid array parameter detected in required_param(): '.$parname);
553 // TODO: switch to fatal error in Moodle 2.3.
554 return required_param_array($parname, $type);
557 return clean_param($param, $type);
561 * Returns a particular array value for the named variable, taken from
562 * POST or GET. If the parameter doesn't exist then an error is
563 * thrown because we require this variable.
565 * This function should be used to initialise all required values
566 * in a script that are based on parameters. Usually it will be
568 * $ids = required_param_array('ids', PARAM_INT);
570 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
572 * @param string $parname the name of the page parameter we want
573 * @param string $type expected type of parameter
575 * @throws coding_exception
577 function required_param_array($parname, $type) {
578 if (func_num_args() != 2 or empty($parname) or empty($type)) {
579 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
581 // POST has precedence.
582 if (isset($_POST[$parname])) {
583 $param = $_POST[$parname];
584 } else if (isset($_GET[$parname])) {
585 $param = $_GET[$parname];
587 print_error('missingparam', '', '', $parname);
589 if (!is_array($param)) {
590 print_error('missingparam', '', '', $parname);
594 foreach ($param as $key => $value) {
595 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
596 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
599 $result[$key] = clean_param($value, $type);
606 * Returns a particular value for the named variable, taken from
607 * POST or GET, otherwise returning a given default.
609 * This function should be used to initialise all optional values
610 * in a script that are based on parameters. Usually it will be
612 * $name = optional_param('name', 'Fred', PARAM_TEXT);
614 * Please note the $type parameter is now required and the value can not be array.
616 * @param string $parname the name of the page parameter we want
617 * @param mixed $default the default value to return if nothing is found
618 * @param string $type expected type of parameter
620 * @throws coding_exception
622 function optional_param($parname, $default, $type) {
623 if (func_num_args() != 3 or empty($parname) or empty($type)) {
624 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
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)) {
1036 // Simulate the HTTPS version of the site.
1037 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot
);
1039 if (preg_match(':^/:', $param)) {
1040 // Root-relative, ok!
1041 } else if (preg_match('/^' . preg_quote($CFG->wwwroot
, '/') . '/i', $param)) {
1042 // Absolute, and matches our wwwroot.
1043 } else if (!empty($CFG->loginhttps
) && preg_match('/^' . preg_quote($httpswwwroot, '/') . '/i', $param)) {
1044 // Absolute, and matches our httpswwwroot.
1046 // Relative - let's make sure there are no tricks.
1047 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1057 $param = trim($param);
1058 // PEM formatted strings may contain letters/numbers and the symbols:
1062 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1063 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1064 list($wholething, $body) = $matches;
1065 unset($wholething, $matches);
1066 $b64 = clean_param($body, PARAM_BASE64
);
1068 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1076 if (!empty($param)) {
1077 // PEM formatted strings may contain letters/numbers and the symbols
1081 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1084 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY
);
1085 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1086 // than (or equal to) 64 characters long.
1087 for ($i=0, $j=count($lines); $i < $j; $i++
) {
1089 if (64 < strlen($lines[$i])) {
1095 if (64 != strlen($lines[$i])) {
1099 return implode("\n", $lines);
1105 $param = fix_utf8($param);
1106 // Please note it is not safe to use the tag name directly anywhere,
1107 // it must be processed with s(), urlencode() before embedding anywhere.
1108 // Remove some nasties.
1109 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1110 // Convert many whitespace chars into one.
1111 $param = preg_replace('/\s+/u', ' ', $param);
1112 $param = core_text
::substr(trim($param), 0, TAG_MAX_LENGTH
);
1116 $param = fix_utf8($param);
1117 $tags = explode(',', $param);
1119 foreach ($tags as $tag) {
1120 $res = clean_param($tag, PARAM_TAG
);
1126 return implode(',', $result);
1131 case PARAM_CAPABILITY
:
1132 if (get_capability_info($param)) {
1138 case PARAM_PERMISSION
:
1139 $param = (int)$param;
1140 if (in_array($param, array(CAP_INHERIT
, CAP_ALLOW
, CAP_PREVENT
, CAP_PROHIBIT
))) {
1147 $param = clean_param($param, PARAM_PLUGIN
);
1148 if (empty($param)) {
1150 } else if (exists_auth_plugin($param)) {
1157 $param = clean_param($param, PARAM_SAFEDIR
);
1158 if (get_string_manager()->translation_exists($param)) {
1161 // Specified language is not installed or param malformed.
1166 $param = clean_param($param, PARAM_PLUGIN
);
1167 if (empty($param)) {
1169 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1171 } else if (!empty($CFG->themedir
) and file_exists("$CFG->themedir/$param/config.php")) {
1174 // Specified theme is not installed.
1178 case PARAM_USERNAME
:
1179 $param = fix_utf8($param);
1180 $param = trim($param);
1181 // Convert uppercase to lowercase MDL-16919.
1182 $param = core_text
::strtolower($param);
1183 if (empty($CFG->extendedusernamechars
)) {
1184 $param = str_replace(" " , "", $param);
1185 // Regular expression, eliminate all chars EXCEPT:
1186 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1187 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1192 $param = fix_utf8($param);
1193 if (validate_email($param)) {
1199 case PARAM_STRINGID
:
1200 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1206 case PARAM_TIMEZONE
:
1207 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1208 $param = fix_utf8($param);
1209 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1210 if (preg_match($timezonepattern, $param)) {
1217 // Doh! throw error, switched parameters in optional_param or another serious problem.
1218 print_error("unknownparamtype", '', '', $type);
1223 * Makes sure the data is using valid utf8, invalid characters are discarded.
1225 * Note: this function is not intended for full objects with methods and private properties.
1227 * @param mixed $value
1228 * @return mixed with proper utf-8 encoding
1230 function fix_utf8($value) {
1231 if (is_null($value) or $value === '') {
1234 } else if (is_string($value)) {
1235 if ((string)(int)$value === $value) {
1239 // No null bytes expected in our data, so let's remove it.
1240 $value = str_replace("\0", '', $value);
1242 // Note: this duplicates min_fix_utf8() intentionally.
1243 static $buggyiconv = null;
1244 if ($buggyiconv === null) {
1245 $buggyiconv = (!function_exists('iconv') or @iconv
('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1249 if (function_exists('mb_convert_encoding')) {
1250 $subst = mb_substitute_character();
1251 mb_substitute_character('');
1252 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1253 mb_substitute_character($subst);
1256 // Warn admins on admin/index.php page.
1261 $result = @iconv
('UTF-8', 'UTF-8//IGNORE', $value);
1266 } else if (is_array($value)) {
1267 foreach ($value as $k => $v) {
1268 $value[$k] = fix_utf8($v);
1272 } else if (is_object($value)) {
1273 // Do not modify original.
1274 $value = clone($value);
1275 foreach ($value as $k => $v) {
1276 $value->$k = fix_utf8($v);
1281 // This is some other type, no utf-8 here.
1287 * Return true if given value is integer or string with integer value
1289 * @param mixed $value String or Int
1290 * @return bool true if number, false if not
1292 function is_number($value) {
1293 if (is_int($value)) {
1295 } else if (is_string($value)) {
1296 return ((string)(int)$value) === $value;
1303 * Returns host part from url.
1305 * @param string $url full url
1306 * @return string host, null if not found
1308 function get_host_from_url($url) {
1309 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1317 * Tests whether anything was returned by text editor
1319 * This function is useful for testing whether something you got back from
1320 * the HTML editor actually contains anything. Sometimes the HTML editor
1321 * appear to be empty, but actually you get back a <br> tag or something.
1323 * @param string $string a string containing HTML.
1324 * @return boolean does the string contain any actual content - that is text,
1325 * images, objects, etc.
1327 function html_is_blank($string) {
1328 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1332 * Set a key in global configuration
1334 * Set a key/value pair in both this session's {@link $CFG} global variable
1335 * and in the 'config' database table for future sessions.
1337 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1338 * In that case it doesn't affect $CFG.
1340 * A NULL value will delete the entry.
1342 * NOTE: this function is called from lib/db/upgrade.php
1344 * @param string $name the key to set
1345 * @param string $value the value to set (without magic quotes)
1346 * @param string $plugin (optional) the plugin scope, default null
1347 * @return bool true or exception
1349 function set_config($name, $value, $plugin=null) {
1352 if (empty($plugin)) {
1353 if (!array_key_exists($name, $CFG->config_php_settings
)) {
1354 // So it's defined for this invocation at least.
1355 if (is_null($value)) {
1358 // Settings from db are always strings.
1359 $CFG->$name = (string)$value;
1363 if ($DB->get_field('config', 'name', array('name' => $name))) {
1364 if ($value === null) {
1365 $DB->delete_records('config', array('name' => $name));
1367 $DB->set_field('config', 'value', $value, array('name' => $name));
1370 if ($value !== null) {
1371 $config = new stdClass();
1372 $config->name
= $name;
1373 $config->value
= $value;
1374 $DB->insert_record('config', $config, false);
1377 if ($name === 'siteidentifier') {
1378 cache_helper
::update_site_identifier($value);
1380 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1383 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1384 if ($value===null) {
1385 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1387 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1390 if ($value !== null) {
1391 $config = new stdClass();
1392 $config->plugin
= $plugin;
1393 $config->name
= $name;
1394 $config->value
= $value;
1395 $DB->insert_record('config_plugins', $config, false);
1398 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
1405 * Get configuration values from the global config table
1406 * or the config_plugins table.
1408 * If called with one parameter, it will load all the config
1409 * variables for one plugin, and return them as an object.
1411 * If called with 2 parameters it will return a string single
1412 * value or false if the value is not found.
1414 * NOTE: this function is called from lib/db/upgrade.php
1416 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1417 * that we need only fetch it once per request.
1418 * @param string $plugin full component name
1419 * @param string $name default null
1420 * @return mixed hash-like object or single value, return false no config found
1421 * @throws dml_exception
1423 function get_config($plugin, $name = null) {
1426 static $siteidentifier = null;
1428 if ($plugin === 'moodle' ||
$plugin === 'core' ||
empty($plugin)) {
1429 $forced =& $CFG->config_php_settings
;
1433 if (array_key_exists($plugin, $CFG->forced_plugin_settings
)) {
1434 $forced =& $CFG->forced_plugin_settings
[$plugin];
1441 if ($siteidentifier === null) {
1443 // This may fail during installation.
1444 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1445 // install the database.
1446 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1447 } catch (dml_exception
$ex) {
1448 // Set siteidentifier to false. We don't want to trip this continually.
1449 $siteidentifier = false;
1454 if (!empty($name)) {
1455 if (array_key_exists($name, $forced)) {
1456 return (string)$forced[$name];
1457 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1458 return $siteidentifier;
1462 $cache = cache
::make('core', 'config');
1463 $result = $cache->get($plugin);
1464 if ($result === false) {
1465 // The user is after a recordset.
1467 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1469 // This part is not really used any more, but anyway...
1470 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1472 $cache->set($plugin, $result);
1475 if (!empty($name)) {
1476 if (array_key_exists($name, $result)) {
1477 return $result[$name];
1482 if ($plugin === 'core') {
1483 $result['siteidentifier'] = $siteidentifier;
1486 foreach ($forced as $key => $value) {
1487 if (is_null($value) or is_array($value) or is_object($value)) {
1488 // We do not want any extra mess here, just real settings that could be saved in db.
1489 unset($result[$key]);
1491 // Convert to string as if it went through the DB.
1492 $result[$key] = (string)$value;
1496 return (object)$result;
1500 * Removes a key from global configuration.
1502 * NOTE: this function is called from lib/db/upgrade.php
1504 * @param string $name the key to set
1505 * @param string $plugin (optional) the plugin scope
1506 * @return boolean whether the operation succeeded.
1508 function unset_config($name, $plugin=null) {
1511 if (empty($plugin)) {
1513 $DB->delete_records('config', array('name' => $name));
1514 cache_helper
::invalidate_by_definition('core', 'config', array(), 'core');
1516 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1517 cache_helper
::invalidate_by_definition('core', 'config', array(), $plugin);
1524 * Remove all the config variables for a given plugin.
1526 * NOTE: this function is called from lib/db/upgrade.php
1528 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1529 * @return boolean whether the operation succeeded.
1531 function unset_all_config_for_plugin($plugin) {
1533 // Delete from the obvious config_plugins first.
1534 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1535 // Next delete any suspect settings from config.
1536 $like = $DB->sql_like('name', '?', true, true, false, '|');
1537 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1538 $DB->delete_records_select('config', $like, $params);
1539 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1540 cache_helper
::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1546 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1548 * All users are verified if they still have the necessary capability.
1550 * @param string $value the value of the config setting.
1551 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1552 * @param bool $includeadmins include administrators.
1553 * @return array of user objects.
1555 function get_users_from_config($value, $capability, $includeadmins = true) {
1556 if (empty($value) or $value === '$@NONE@$') {
1560 // We have to make sure that users still have the necessary capability,
1561 // it should be faster to fetch them all first and then test if they are present
1562 // instead of validating them one-by-one.
1563 $users = get_users_by_capability(context_system
::instance(), $capability);
1564 if ($includeadmins) {
1565 $admins = get_admins();
1566 foreach ($admins as $admin) {
1567 $users[$admin->id
] = $admin;
1571 if ($value === '$@ALL@$') {
1575 $result = array(); // Result in correct order.
1576 $allowed = explode(',', $value);
1577 foreach ($allowed as $uid) {
1578 if (isset($users[$uid])) {
1579 $user = $users[$uid];
1580 $result[$user->id
] = $user;
1589 * Invalidates browser caches and cached data in temp.
1591 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1592 * {@link phpunit_util::reset_dataroot()}
1596 function purge_all_caches() {
1599 reset_text_filters_cache();
1600 js_reset_all_caches();
1601 theme_reset_all_caches();
1602 get_string_manager()->reset_caches();
1603 core_text
::reset_caches();
1604 if (class_exists('core_plugin_manager')) {
1605 core_plugin_manager
::reset_caches();
1608 // Bump up cacherev field for all courses.
1610 increment_revision_number('course', 'cacherev', '');
1611 } catch (moodle_exception
$e) {
1612 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1615 $DB->reset_caches();
1616 cache_helper
::purge_all();
1618 // Purge all other caches: rss, simplepie, etc.
1619 remove_dir($CFG->cachedir
.'', true);
1621 // Make sure cache dir is writable, throws exception if not.
1622 make_cache_directory('');
1624 // This is the only place where we purge local caches, we are only adding files there.
1625 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1626 remove_dir($CFG->localcachedir
, true);
1627 set_config('localcachedirpurged', time());
1628 make_localcache_directory('', true);
1629 \core\task\manager
::clear_static_caches();
1633 * Get volatile flags
1635 * @param string $type
1636 * @param int $changedsince default null
1637 * @return array records array
1639 function get_cache_flags($type, $changedsince = null) {
1642 $params = array('type' => $type, 'expiry' => time());
1643 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1644 if ($changedsince !== null) {
1645 $params['changedsince'] = $changedsince;
1646 $sqlwhere .= " AND timemodified > :changedsince";
1649 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1650 foreach ($flags as $flag) {
1651 $cf[$flag->name
] = $flag->value
;
1658 * Get volatile flags
1660 * @param string $type
1661 * @param string $name
1662 * @param int $changedsince default null
1663 * @return string|false The cache flag value or false
1665 function get_cache_flag($type, $name, $changedsince=null) {
1668 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1670 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1671 if ($changedsince !== null) {
1672 $params['changedsince'] = $changedsince;
1673 $sqlwhere .= " AND timemodified > :changedsince";
1676 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1680 * Set a volatile flag
1682 * @param string $type the "type" namespace for the key
1683 * @param string $name the key to set
1684 * @param string $value the value to set (without magic quotes) - null will remove the flag
1685 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1686 * @return bool Always returns true
1688 function set_cache_flag($type, $name, $value, $expiry = null) {
1691 $timemodified = time();
1692 if ($expiry === null ||
$expiry < $timemodified) {
1693 $expiry = $timemodified +
24 * 60 * 60;
1695 $expiry = (int)$expiry;
1698 if ($value === null) {
1699 unset_cache_flag($type, $name);
1703 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE
)) {
1704 // This is a potential problem in DEBUG_DEVELOPER.
1705 if ($f->value
== $value and $f->expiry
== $expiry and $f->timemodified
== $timemodified) {
1706 return true; // No need to update.
1709 $f->expiry
= $expiry;
1710 $f->timemodified
= $timemodified;
1711 $DB->update_record('cache_flags', $f);
1713 $f = new stdClass();
1714 $f->flagtype
= $type;
1717 $f->expiry
= $expiry;
1718 $f->timemodified
= $timemodified;
1719 $DB->insert_record('cache_flags', $f);
1725 * Removes a single volatile flag
1727 * @param string $type the "type" namespace for the key
1728 * @param string $name the key to set
1731 function unset_cache_flag($type, $name) {
1733 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1738 * Garbage-collect volatile flags
1740 * @return bool Always returns true
1742 function gc_cache_flags() {
1744 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1748 // USER PREFERENCE API.
1751 * Refresh user preference cache. This is used most often for $USER
1752 * object that is stored in session, but it also helps with performance in cron script.
1754 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1757 * @category preference
1759 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1760 * @param int $cachelifetime Cache life time on the current page (in seconds)
1761 * @throws coding_exception
1764 function check_user_preferences_loaded(stdClass
$user, $cachelifetime = 120) {
1766 // Static cache, we need to check on each page load, not only every 2 minutes.
1767 static $loadedusers = array();
1769 if (!isset($user->id
)) {
1770 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1773 if (empty($user->id
) or isguestuser($user->id
)) {
1774 // No permanent storage for not-logged-in users and guest.
1775 if (!isset($user->preference
)) {
1776 $user->preference
= array();
1783 if (isset($loadedusers[$user->id
]) and isset($user->preference
) and isset($user->preference
['_lastloaded'])) {
1784 // Already loaded at least once on this page. Are we up to date?
1785 if ($user->preference
['_lastloaded'] +
$cachelifetime > $timenow) {
1786 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1789 } else if (!get_cache_flag('userpreferenceschanged', $user->id
, $user->preference
['_lastloaded'])) {
1790 // No change since the lastcheck on this page.
1791 $user->preference
['_lastloaded'] = $timenow;
1796 // OK, so we have to reload all preferences.
1797 $loadedusers[$user->id
] = true;
1798 $user->preference
= $DB->get_records_menu('user_preferences', array('userid' => $user->id
), '', 'name,value'); // All values.
1799 $user->preference
['_lastloaded'] = $timenow;
1803 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1805 * NOTE: internal function, do not call from other code.
1809 * @param integer $userid the user whose prefs were changed.
1811 function mark_user_preferences_changed($userid) {
1814 if (empty($userid) or isguestuser($userid)) {
1815 // No cache flags for guest and not-logged-in users.
1819 set_cache_flag('userpreferenceschanged', $userid, 1, time() +
$CFG->sessiontimeout
);
1823 * Sets a preference for the specified user.
1825 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1828 * @category preference
1830 * @param string $name The key to set as preference for the specified user
1831 * @param string $value The value to set for the $name key in the specified user's
1832 * record, null means delete current value.
1833 * @param stdClass|int|null $user A moodle user object or id, null means current user
1834 * @throws coding_exception
1835 * @return bool Always true or exception
1837 function set_user_preference($name, $value, $user = null) {
1840 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1841 throw new coding_exception('Invalid preference name in set_user_preference() call');
1844 if (is_null($value)) {
1845 // Null means delete current.
1846 return unset_user_preference($name, $user);
1847 } else if (is_object($value)) {
1848 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1849 } else if (is_array($value)) {
1850 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1852 // Value column maximum length is 1333 characters.
1853 $value = (string)$value;
1854 if (core_text
::strlen($value) > 1333) {
1855 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1858 if (is_null($user)) {
1860 } else if (isset($user->id
)) {
1861 // It is a valid object.
1862 } else if (is_numeric($user)) {
1863 $user = (object)array('id' => (int)$user);
1865 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1868 check_user_preferences_loaded($user);
1870 if (empty($user->id
) or isguestuser($user->id
)) {
1871 // No permanent storage for not-logged-in users and guest.
1872 $user->preference
[$name] = $value;
1876 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => $name))) {
1877 if ($preference->value
=== $value and isset($user->preference
[$name]) and $user->preference
[$name] === $value) {
1878 // Preference already set to this value.
1881 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id
));
1884 $preference = new stdClass();
1885 $preference->userid
= $user->id
;
1886 $preference->name
= $name;
1887 $preference->value
= $value;
1888 $DB->insert_record('user_preferences', $preference);
1891 // Update value in cache.
1892 $user->preference
[$name] = $value;
1894 // Set reload flag for other sessions.
1895 mark_user_preferences_changed($user->id
);
1901 * Sets a whole array of preferences for the current user
1903 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1906 * @category preference
1908 * @param array $prefarray An array of key/value pairs to be set
1909 * @param stdClass|int|null $user A moodle user object or id, null means current user
1910 * @return bool Always true or exception
1912 function set_user_preferences(array $prefarray, $user = null) {
1913 foreach ($prefarray as $name => $value) {
1914 set_user_preference($name, $value, $user);
1920 * Unsets a preference completely by deleting it from the database
1922 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1925 * @category preference
1927 * @param string $name The key to unset as preference for the specified user
1928 * @param stdClass|int|null $user A moodle user object or id, null means current user
1929 * @throws coding_exception
1930 * @return bool Always true or exception
1932 function unset_user_preference($name, $user = null) {
1935 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1936 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1939 if (is_null($user)) {
1941 } else if (isset($user->id
)) {
1942 // It is a valid object.
1943 } else if (is_numeric($user)) {
1944 $user = (object)array('id' => (int)$user);
1946 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1949 check_user_preferences_loaded($user);
1951 if (empty($user->id
) or isguestuser($user->id
)) {
1952 // No permanent storage for not-logged-in user and guest.
1953 unset($user->preference
[$name]);
1958 $DB->delete_records('user_preferences', array('userid' => $user->id
, 'name' => $name));
1960 // Delete the preference from cache.
1961 unset($user->preference
[$name]);
1963 // Set reload flag for other sessions.
1964 mark_user_preferences_changed($user->id
);
1970 * Used to fetch user preference(s)
1972 * If no arguments are supplied this function will return
1973 * all of the current user preferences as an array.
1975 * If a name is specified then this function
1976 * attempts to return that particular preference value. If
1977 * none is found, then the optional value $default is returned,
1980 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1983 * @category preference
1985 * @param string $name Name of the key to use in finding a preference value
1986 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1987 * @param stdClass|int|null $user A moodle user object or id, null means current user
1988 * @throws coding_exception
1989 * @return string|mixed|null A string containing the value of a single preference. An
1990 * array with all of the preferences or null
1992 function get_user_preferences($name = null, $default = null, $user = null) {
1995 if (is_null($name)) {
1997 } else if (is_numeric($name) or $name === '_lastloaded') {
1998 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2001 if (is_null($user)) {
2003 } else if (isset($user->id
)) {
2004 // Is a valid object.
2005 } else if (is_numeric($user)) {
2006 $user = (object)array('id' => (int)$user);
2008 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2011 check_user_preferences_loaded($user);
2015 return $user->preference
;
2016 } else if (isset($user->preference
[$name])) {
2017 // The single string value.
2018 return $user->preference
[$name];
2020 // Default value (null if not specified).
2025 // FUNCTIONS FOR HANDLING TIME.
2028 * Given date parts in user time produce a GMT timestamp.
2032 * @param int $year The year part to create timestamp of
2033 * @param int $month The month part to create timestamp of
2034 * @param int $day The day part to create timestamp of
2035 * @param int $hour The hour part to create timestamp of
2036 * @param int $minute The minute part to create timestamp of
2037 * @param int $second The second part to create timestamp of
2038 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2039 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2040 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2041 * applied only if timezone is 99 or string.
2042 * @return int GMT timestamp
2044 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2046 // Save input timezone, required for dst offset check.
2047 $passedtimezone = $timezone;
2049 $timezone = get_user_timezone_offset($timezone);
2051 if (abs($timezone) > 13) {
2053 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2055 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2056 $time = usertime($time, $timezone);
2058 // Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
2059 if ($applydst && ((99 == $passedtimezone) ||
!is_numeric($passedtimezone))) {
2060 $time -= dst_offset_on($time, $passedtimezone);
2069 * Format a date/time (seconds) as weeks, days, hours etc as needed
2071 * Given an amount of time in seconds, returns string
2072 * formatted nicely as weeks, days, hours etc as needed
2080 * @param int $totalsecs Time in seconds
2081 * @param stdClass $str Should be a time object
2082 * @return string A nicely formatted date/time string
2084 function format_time($totalsecs, $str = null) {
2086 $totalsecs = abs($totalsecs);
2089 // Create the str structure the slow way.
2090 $str = new stdClass();
2091 $str->day
= get_string('day');
2092 $str->days
= get_string('days');
2093 $str->hour
= get_string('hour');
2094 $str->hours
= get_string('hours');
2095 $str->min
= get_string('min');
2096 $str->mins
= get_string('mins');
2097 $str->sec
= get_string('sec');
2098 $str->secs
= get_string('secs');
2099 $str->year
= get_string('year');
2100 $str->years
= get_string('years');
2103 $years = floor($totalsecs/YEARSECS
);
2104 $remainder = $totalsecs - ($years*YEARSECS
);
2105 $days = floor($remainder/DAYSECS
);
2106 $remainder = $totalsecs - ($days*DAYSECS
);
2107 $hours = floor($remainder/HOURSECS
);
2108 $remainder = $remainder - ($hours*HOURSECS
);
2109 $mins = floor($remainder/MINSECS
);
2110 $secs = $remainder - ($mins*MINSECS
);
2112 $ss = ($secs == 1) ?
$str->sec
: $str->secs
;
2113 $sm = ($mins == 1) ?
$str->min
: $str->mins
;
2114 $sh = ($hours == 1) ?
$str->hour
: $str->hours
;
2115 $sd = ($days == 1) ?
$str->day
: $str->days
;
2116 $sy = ($years == 1) ?
$str->year
: $str->years
;
2125 $oyears = $years .' '. $sy;
2128 $odays = $days .' '. $sd;
2131 $ohours = $hours .' '. $sh;
2134 $omins = $mins .' '. $sm;
2137 $osecs = $secs .' '. $ss;
2141 return trim($oyears .' '. $odays);
2144 return trim($odays .' '. $ohours);
2147 return trim($ohours .' '. $omins);
2150 return trim($omins .' '. $osecs);
2155 return get_string('now');
2159 * Returns a formatted string that represents a date in user time.
2163 * @param int $date the timestamp in UTC, as obtained from the database.
2164 * @param string $format strftime format. You should probably get this using
2165 * get_string('strftime...', 'langconfig');
2166 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2167 * not 99 then daylight saving will not be added.
2168 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2169 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2170 * If false then the leading zero is maintained.
2171 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2172 * @return string the formatted date/time.
2174 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2175 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2176 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2180 * Returns a formatted date ensuring it is UTF-8.
2182 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2183 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2185 * This function does not do any calculation regarding the user preferences and should
2186 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2187 * to differentiate the use of server time or not (strftime() against gmstrftime()).
2189 * @param int $date the timestamp.
2190 * @param string $format strftime format.
2191 * @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2192 * @return string the formatted date/time.
2193 * @since Moodle 2.3.3
2195 function date_format_string($date, $format, $tz = 99) {
2198 $localewincharset = null;
2199 // Get the calendar type user is using.
2200 if ($CFG->ostype
== 'WINDOWS') {
2201 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2202 $localewincharset = $calendartype->locale_win_charset();
2205 if (abs($tz) > 13) {
2206 if ($localewincharset) {
2207 $format = core_text
::convert($format, 'utf-8', $localewincharset);
2208 $datestring = strftime($format, $date);
2209 $datestring = core_text
::convert($datestring, $localewincharset, 'utf-8');
2211 $datestring = strftime($format, $date);
2214 if ($localewincharset) {
2215 $format = core_text
::convert($format, 'utf-8', $localewincharset);
2216 $datestring = gmstrftime($format, $date);
2217 $datestring = core_text
::convert($datestring, $localewincharset, 'utf-8');
2219 $datestring = gmstrftime($format, $date);
2226 * Given a $time timestamp in GMT (seconds since epoch),
2227 * returns an array that represents the date in user time
2232 * @param int $time Timestamp in GMT
2233 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2234 * dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
2235 * @return array An array that represents the date in user time
2237 function usergetdate($time, $timezone=99) {
2239 // Save input timezone, required for dst offset check.
2240 $passedtimezone = $timezone;
2242 $timezone = get_user_timezone_offset($timezone);
2244 if (abs($timezone) > 13) {
2246 return getdate($time);
2249 // Add daylight saving offset for string timezones only, as we can't get dst for
2250 // float values. if timezone is 99 (user default timezone), then try update dst.
2251 if ($passedtimezone == 99 ||
!is_numeric($passedtimezone)) {
2252 $time +
= dst_offset_on($time, $passedtimezone);
2255 $time +
= intval((float)$timezone * HOURSECS
);
2257 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2259 // Be careful to ensure the returned array matches that produced by getdate() above.
2262 $getdate['weekday'],
2269 $getdate['minutes'],
2271 ) = explode('_', $datestring);
2273 // Set correct datatype to match with getdate().
2274 $getdate['seconds'] = (int)$getdate['seconds'];
2275 $getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
2276 $getdate['year'] = (int)$getdate['year'];
2277 $getdate['mon'] = (int)$getdate['mon'];
2278 $getdate['wday'] = (int)$getdate['wday'];
2279 $getdate['mday'] = (int)$getdate['mday'];
2280 $getdate['hours'] = (int)$getdate['hours'];
2281 $getdate['minutes'] = (int)$getdate['minutes'];
2286 * Given a GMT timestamp (seconds since epoch), offsets it by
2287 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2292 * @param int $date Timestamp in GMT
2293 * @param float|int|string $timezone timezone to calculate GMT time offset before
2294 * calculating user time, 99 is default user timezone
2295 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2298 function usertime($date, $timezone=99) {
2300 $timezone = get_user_timezone_offset($timezone);
2302 if (abs($timezone) > 13) {
2305 return $date - (int)($timezone * HOURSECS
);
2309 * Given a time, return the GMT timestamp of the most recent midnight
2310 * for the current user.
2314 * @param int $date Timestamp in GMT
2315 * @param float|int|string $timezone timezone to calculate GMT time offset before
2316 * calculating user midnight time, 99 is default user timezone
2317 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2318 * @return int Returns a GMT timestamp
2320 function usergetmidnight($date, $timezone=99) {
2322 $userdate = usergetdate($date, $timezone);
2324 // Time of midnight of this user's day, in GMT.
2325 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2330 * Returns a string that prints the user's timezone
2334 * @param float|int|string $timezone timezone to calculate GMT time offset before
2335 * calculating user timezone, 99 is default user timezone
2336 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2339 function usertimezone($timezone=99) {
2341 $tz = get_user_timezone($timezone);
2343 if (!is_float($tz)) {
2347 if (abs($tz) > 13) {
2349 return get_string('serverlocaltime');
2352 if ($tz == intval($tz)) {
2353 // Don't show .0 for whole hours.
2359 } else if ($tz > 0) {
2368 * Returns a float which represents the user's timezone difference from GMT in hours
2369 * Checks various settings and picks the most dominant of those which have a value
2373 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2374 * 99 is default user timezone
2375 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2378 function get_user_timezone_offset($tz = 99) {
2379 $tz = get_user_timezone($tz);
2381 if (is_float($tz)) {
2384 $tzrecord = get_timezone_record($tz);
2385 if (empty($tzrecord)) {
2388 return (float)$tzrecord->gmtoff
/ HOURMINS
;
2393 * Returns an int which represents the systems's timezone difference from GMT in seconds
2397 * @param float|int|string $tz timezone for which offset is required.
2398 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2399 * @return int|bool if found, false is timezone 99 or error
2401 function get_timezone_offset($tz) {
2406 if (is_numeric($tz)) {
2407 return intval($tz * 60*60);
2410 if (!$tzrecord = get_timezone_record($tz)) {
2413 return intval($tzrecord->gmtoff
* 60);
2417 * Returns a float or a string which denotes the user's timezone
2418 * 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)
2419 * means that for this timezone there are also DST rules to be taken into account
2420 * Checks various settings and picks the most dominant of those which have a value
2424 * @param float|int|string $tz timezone to calculate GMT time offset before
2425 * calculating user timezone, 99 is default user timezone
2426 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2427 * @return float|string
2429 function get_user_timezone($tz = 99) {
2434 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
2435 isset($USER->timezone
) ?
$USER->timezone
: 99,
2436 isset($CFG->timezone
) ?
$CFG->timezone
: 99,
2441 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2442 while (((empty($tz) && !is_numeric($tz)) ||
$tz == 99) && $next = each($timezones)) {
2443 $tz = $next['value'];
2445 return is_numeric($tz) ?
(float) $tz : $tz;
2449 * Returns cached timezone record for given $timezonename
2452 * @param string $timezonename name of the timezone
2453 * @return stdClass|bool timezonerecord or false
2455 function get_timezone_record($timezonename) {
2457 static $cache = null;
2459 if ($cache === null) {
2463 if (isset($cache[$timezonename])) {
2464 return $cache[$timezonename];
2467 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2468 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE
);
2472 * Build and store the users Daylight Saving Time (DST) table
2475 * @param int $fromyear Start year for the table, defaults to 1971
2476 * @param int $toyear End year for the table, defaults to 2035
2477 * @param int|float|string $strtimezone timezone to check if dst should be applied.
2480 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2481 global $SESSION, $DB;
2483 $usertz = get_user_timezone($strtimezone);
2485 if (is_float($usertz)) {
2486 // Trivial timezone, no DST.
2490 if (!empty($SESSION->dst_offsettz
) && $SESSION->dst_offsettz
!= $usertz) {
2491 // We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
2492 unset($SESSION->dst_offsets
);
2493 unset($SESSION->dst_range
);
2496 if (!empty($SESSION->dst_offsets
) && empty($fromyear) && empty($toyear)) {
2497 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
2498 // This will be the return path most of the time, pretty light computationally.
2502 // Reaching here means we either need to extend our table or create it from scratch.
2504 // Remember which TZ we calculated these changes for.
2505 $SESSION->dst_offsettz
= $usertz;
2507 if (empty($SESSION->dst_offsets
)) {
2508 // If we 're creating from scratch, put the two guard elements in there.
2509 $SESSION->dst_offsets
= array(1 => null, 0 => null);
2511 if (empty($SESSION->dst_range
)) {
2512 // If creating from scratch.
2513 $from = max((empty($fromyear) ?
intval(date('Y')) - 3 : $fromyear), 1971);
2514 $to = min((empty($toyear) ?
intval(date('Y')) +
3 : $toyear), 2035);
2516 // Fill in the array with the extra years we need to process.
2517 $yearstoprocess = array();
2518 for ($i = $from; $i <= $to; ++
$i) {
2519 $yearstoprocess[] = $i;
2522 // Take note of which years we have processed for future calls.
2523 $SESSION->dst_range
= array($from, $to);
2525 // If needing to extend the table, do the same.
2526 $yearstoprocess = array();
2528 $from = max((empty($fromyear) ?
$SESSION->dst_range
[0] : $fromyear), 1971);
2529 $to = min((empty($toyear) ?
$SESSION->dst_range
[1] : $toyear), 2035);
2531 if ($from < $SESSION->dst_range
[0]) {
2532 // Take note of which years we need to process and then note that we have processed them for future calls.
2533 for ($i = $from; $i < $SESSION->dst_range
[0]; ++
$i) {
2534 $yearstoprocess[] = $i;
2536 $SESSION->dst_range
[0] = $from;
2538 if ($to > $SESSION->dst_range
[1]) {
2539 // Take note of which years we need to process and then note that we have processed them for future calls.
2540 for ($i = $SESSION->dst_range
[1] +
1; $i <= $to; ++
$i) {
2541 $yearstoprocess[] = $i;
2543 $SESSION->dst_range
[1] = $to;
2547 if (empty($yearstoprocess)) {
2548 // This means that there was a call requesting a SMALLER range than we have already calculated.
2552 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2553 // Also, the array is sorted in descending timestamp order!
2557 static $presetscache = array();
2558 if (!isset($presetscache[$usertz])) {
2559 $presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
2560 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
2561 'std_startday, std_weekday, std_skipweeks, std_time');
2563 if (empty($presetscache[$usertz])) {
2567 // Remove ending guard (first element of the array).
2568 reset($SESSION->dst_offsets
);
2569 unset($SESSION->dst_offsets
[key($SESSION->dst_offsets
)]);
2571 // Add all required change timestamps.
2572 foreach ($yearstoprocess as $y) {
2573 // Find the record which is in effect for the year $y.
2574 foreach ($presetscache[$usertz] as $year => $preset) {
2580 $changes = dst_changes_for_year($y, $preset);
2582 if ($changes === null) {
2585 if ($changes['dst'] != 0) {
2586 $SESSION->dst_offsets
[$changes['dst']] = $preset->dstoff
* MINSECS
;
2588 if ($changes['std'] != 0) {
2589 $SESSION->dst_offsets
[$changes['std']] = 0;
2593 // Put in a guard element at the top.
2594 $maxtimestamp = max(array_keys($SESSION->dst_offsets
));
2595 $SESSION->dst_offsets
[($maxtimestamp + DAYSECS
)] = null; // DAYSECS is arbitrary, any "small" number will do.
2598 krsort($SESSION->dst_offsets
);
2604 * Calculates the required DST change and returns a Timestamp Array
2610 * @param int|string $year Int or String Year to focus on
2611 * @param object $timezone Instatiated Timezone object
2612 * @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
2614 function dst_changes_for_year($year, $timezone) {
2616 if ($timezone->dst_startday
== 0 && $timezone->dst_weekday
== 0 &&
2617 $timezone->std_startday
== 0 && $timezone->std_weekday
== 0) {
2621 $monthdaydst = find_day_in_month($timezone->dst_startday
, $timezone->dst_weekday
, $timezone->dst_month
, $year);
2622 $monthdaystd = find_day_in_month($timezone->std_startday
, $timezone->std_weekday
, $timezone->std_month
, $year);
2624 list($dsthour, $dstmin) = explode(':', $timezone->dst_time
);
2625 list($stdhour, $stdmin) = explode(':', $timezone->std_time
);
2627 $timedst = make_timestamp($year, $timezone->dst_month
, $monthdaydst, 0, 0, 0, 99, false);
2628 $timestd = make_timestamp($year, $timezone->std_month
, $monthdaystd, 0, 0, 0, 99, false);
2630 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2631 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2632 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2634 $timedst +
= $dsthour * HOURSECS +
$dstmin * MINSECS
;
2635 $timestd +
= $stdhour * HOURSECS +
$stdmin * MINSECS
;
2637 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2641 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2642 * - Note: Daylight saving only works for string timezones and not for float.
2646 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2647 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2648 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2651 function dst_offset_on($time, $strtimezone = null) {
2654 if (!calculate_user_dst_table(null, null, $strtimezone) ||
empty($SESSION->dst_offsets
)) {
2658 reset($SESSION->dst_offsets
);
2659 while (list($from, $offset) = each($SESSION->dst_offsets
)) {
2660 if ($from <= $time) {
2665 // This is the normal return path.
2666 if ($offset !== null) {
2670 // Reaching this point means we haven't calculated far enough, do it now:
2671 // Calculate extra DST changes if needed and recurse. The recursion always
2672 // moves toward the stopping condition, so will always end.
2675 // We need a year smaller than $SESSION->dst_range[0].
2676 if ($SESSION->dst_range
[0] == 1971) {
2679 calculate_user_dst_table($SESSION->dst_range
[0] - 5, null, $strtimezone);
2680 return dst_offset_on($time, $strtimezone);
2682 // We need a year larger than $SESSION->dst_range[1].
2683 if ($SESSION->dst_range
[1] == 2035) {
2686 calculate_user_dst_table(null, $SESSION->dst_range
[1] +
5, $strtimezone);
2687 return dst_offset_on($time, $strtimezone);
2692 * Calculates when the day appears in specific month
2696 * @param int $startday starting day of the month
2697 * @param int $weekday The day when week starts (normally taken from user preferences)
2698 * @param int $month The month whose day is sought
2699 * @param int $year The year of the month whose day is sought
2702 function find_day_in_month($startday, $weekday, $month, $year) {
2703 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2705 $daysinmonth = days_in_month($month, $year);
2706 $daysinweek = count($calendartype->get_weekdays());
2708 if ($weekday == -1) {
2709 // Don't care about weekday, so return:
2710 // abs($startday) if $startday != -1
2711 // $daysinmonth otherwise.
2712 return ($startday == -1) ?
$daysinmonth : abs($startday);
2715 // From now on we 're looking for a specific weekday.
2716 // Give "end of month" its actual value, since we know it.
2717 if ($startday == -1) {
2718 $startday = -1 * $daysinmonth;
2721 // Starting from day $startday, the sign is the direction.
2722 if ($startday < 1) {
2723 $startday = abs($startday);
2724 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2726 // This is the last such weekday of the month.
2727 $lastinmonth = $daysinmonth +
$weekday - $lastmonthweekday;
2728 if ($lastinmonth > $daysinmonth) {
2729 $lastinmonth -= $daysinweek;
2732 // Find the first such weekday <= $startday.
2733 while ($lastinmonth > $startday) {
2734 $lastinmonth -= $daysinweek;
2737 return $lastinmonth;
2739 $indexweekday = dayofweek($startday, $month, $year);
2741 $diff = $weekday - $indexweekday;
2743 $diff +
= $daysinweek;
2746 // This is the first such weekday of the month equal to or after $startday.
2747 $firstfromindex = $startday +
$diff;
2749 return $firstfromindex;
2754 * Calculate the number of days in a given month
2758 * @param int $month The month whose day count is sought
2759 * @param int $year The year of the month whose day count is sought
2762 function days_in_month($month, $year) {
2763 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2764 return $calendartype->get_num_days_in_month($year, $month);
2768 * Calculate the position in the week of a specific calendar day
2772 * @param int $day The day of the date whose position in the week is sought
2773 * @param int $month The month of the date whose position in the week is sought
2774 * @param int $year The year of the date whose position in the week is sought
2777 function dayofweek($day, $month, $year) {
2778 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
2779 return $calendartype->get_weekday($year, $month, $day);
2782 // USER AUTHENTICATION AND LOGIN.
2785 * Returns full login url.
2787 * @return string login url
2789 function get_login_url() {
2792 $url = "$CFG->wwwroot/login/index.php";
2794 if (!empty($CFG->loginhttps
)) {
2795 $url = str_replace('http:', 'https:', $url);
2802 * This function checks that the current user is logged in and has the
2803 * required privileges
2805 * This function checks that the current user is logged in, and optionally
2806 * whether they are allowed to be in a particular course and view a particular
2808 * If they are not logged in, then it redirects them to the site login unless
2809 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2810 * case they are automatically logged in as guests.
2811 * If $courseid is given and the user is not enrolled in that course then the
2812 * user is redirected to the course enrolment page.
2813 * If $cm is given and the course module is hidden and the user is not a teacher
2814 * in the course then the user is redirected to the course home page.
2816 * When $cm parameter specified, this function sets page layout to 'module'.
2817 * You need to change it manually later if some other layout needed.
2819 * @package core_access
2822 * @param mixed $courseorid id of the course or course object
2823 * @param bool $autologinguest default true
2824 * @param object $cm course module object
2825 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2826 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2827 * in order to keep redirects working properly. MDL-14495
2828 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2829 * @return mixed Void, exit, and die depending on path
2830 * @throws coding_exception
2831 * @throws require_login_exception
2833 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2834 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2836 // Must not redirect when byteserving already started.
2837 if (!empty($_SERVER['HTTP_RANGE'])) {
2838 $preventredirect = true;
2841 // Setup global $COURSE, themes, language and locale.
2842 if (!empty($courseorid)) {
2843 if (is_object($courseorid)) {
2844 $course = $courseorid;
2845 } else if ($courseorid == SITEID
) {
2846 $course = clone($SITE);
2848 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST
);
2851 if ($cm->course
!= $course->id
) {
2852 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2854 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2855 if (!($cm instanceof cm_info
)) {
2856 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2857 // db queries so this is not really a performance concern, however it is obviously
2858 // better if you use get_fast_modinfo to get the cm before calling this.
2859 $modinfo = get_fast_modinfo($course);
2860 $cm = $modinfo->get_cm($cm->id
);
2864 // Do not touch global $COURSE via $PAGE->set_course(),
2865 // the reasons is we need to be able to call require_login() at any time!!
2868 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2872 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2873 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2874 // risk leading the user back to the AJAX request URL.
2875 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT
) {
2876 $setwantsurltome = false;
2879 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2880 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out
) && !$preventredirect && !empty($CFG->dbsessions
)) {
2881 if ($setwantsurltome) {
2882 $SESSION->wantsurl
= qualified_me();
2884 redirect(get_login_url());
2887 // If the user is not even logged in yet then make sure they are.
2888 if (!isloggedin()) {
2889 if ($autologinguest and !empty($CFG->guestloginbutton
) and !empty($CFG->autologinguests
)) {
2890 if (!$guest = get_complete_user_data('id', $CFG->siteguest
)) {
2891 // Misconfigured site guest, just redirect to login page.
2892 redirect(get_login_url());
2893 exit; // Never reached.
2895 $lang = isset($SESSION->lang
) ?
$SESSION->lang
: $CFG->lang
;
2896 complete_user_login($guest);
2897 $USER->autologinguest
= true;
2898 $SESSION->lang
= $lang;
2900 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2901 if ($preventredirect) {
2902 throw new require_login_exception('You are not logged in');
2905 if ($setwantsurltome) {
2906 $SESSION->wantsurl
= qualified_me();
2908 if (!empty($_SERVER['HTTP_REFERER'])) {
2909 $SESSION->fromurl
= $_SERVER['HTTP_REFERER'];
2911 redirect(get_login_url());
2912 exit; // Never reached.
2916 // Loginas as redirection if needed.
2917 if ($course->id
!= SITEID
and \core\session\manager
::is_loggedinas()) {
2918 if ($USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
2919 if ($USER->loginascontext
->instanceid
!= $course->id
) {
2920 print_error('loginasonecourse', '', $CFG->wwwroot
.'/course/view.php?id='.$USER->loginascontext
->instanceid
);
2925 // Check whether the user should be changing password (but only if it is REALLY them).
2926 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager
::is_loggedinas()) {
2927 $userauth = get_auth_plugin($USER->auth
);
2928 if ($userauth->can_change_password() and !$preventredirect) {
2929 if ($setwantsurltome) {
2930 $SESSION->wantsurl
= qualified_me();
2932 if ($changeurl = $userauth->change_password_url()) {
2933 // Use plugin custom url.
2934 redirect($changeurl);
2936 // Use moodle internal method.
2937 if (empty($CFG->loginhttps
)) {
2938 redirect($CFG->wwwroot
.'/login/change_password.php');
2940 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot
);
2941 redirect($wwwroot .'/login/change_password.php');
2945 print_error('nopasswordchangeforced', 'auth');
2949 // Check that the user account is properly set up.
2950 if (user_not_fully_set_up($USER)) {
2951 if ($preventredirect) {
2952 throw new require_login_exception('User not fully set-up');
2954 if ($setwantsurltome) {
2955 $SESSION->wantsurl
= qualified_me();
2957 redirect($CFG->wwwroot
.'/user/edit.php?id='. $USER->id
.'&course='. SITEID
);
2960 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2963 // Do not bother admins with any formalities.
2964 if (is_siteadmin()) {
2965 // Set the global $COURSE.
2967 $PAGE->set_cm($cm, $course);
2968 $PAGE->set_pagelayout('incourse');
2969 } else if (!empty($courseorid)) {
2970 $PAGE->set_course($course);
2972 // Set accesstime or the user will appear offline which messes up messaging.
2973 user_accesstime_log($course->id
);
2977 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2978 if (!$USER->policyagreed
and !is_siteadmin()) {
2979 if (!empty($CFG->sitepolicy
) and !isguestuser()) {
2980 if ($preventredirect) {
2981 throw new require_login_exception('Policy not agreed');
2983 if ($setwantsurltome) {
2984 $SESSION->wantsurl
= qualified_me();
2986 redirect($CFG->wwwroot
.'/user/policy.php');
2987 } else if (!empty($CFG->sitepolicyguest
) and isguestuser()) {
2988 if ($preventredirect) {
2989 throw new require_login_exception('Policy not agreed');
2991 if ($setwantsurltome) {
2992 $SESSION->wantsurl
= qualified_me();
2994 redirect($CFG->wwwroot
.'/user/policy.php');
2998 // Fetch the system context, the course context, and prefetch its child contexts.
2999 $sysctx = context_system
::instance();
3000 $coursecontext = context_course
::instance($course->id
, MUST_EXIST
);
3002 $cmcontext = context_module
::instance($cm->id
, MUST_EXIST
);
3007 // If the site is currently under maintenance, then print a message.
3008 if (!empty($CFG->maintenance_enabled
) and !has_capability('moodle/site:config', $sysctx)) {
3009 if ($preventredirect) {
3010 throw new require_login_exception('Maintenance in progress');
3013 print_maintenance_message();
3016 // Make sure the course itself is not hidden.
3017 if ($course->id
== SITEID
) {
3018 // Frontpage can not be hidden.
3020 if (is_role_switched($course->id
)) {
3021 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
3023 if (!$course->visible
and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3024 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
3025 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
3026 if ($preventredirect) {
3027 throw new require_login_exception('Course is hidden');
3029 $PAGE->set_context(null);
3030 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3031 // the navigation will mess up when trying to find it.
3032 navigation_node
::override_active_url(new moodle_url('/'));
3033 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
3038 // Is the user enrolled?
3039 if ($course->id
== SITEID
) {
3040 // Everybody is enrolled on the frontpage.
3042 if (\core\session\manager
::is_loggedinas()) {
3043 // Make sure the REAL person can access this course first.
3044 $realuser = \core\session\manager
::get_realuser();
3045 if (!is_enrolled($coursecontext, $realuser->id
, '', true) and
3046 !is_viewing($coursecontext, $realuser->id
) and !is_siteadmin($realuser->id
)) {
3047 if ($preventredirect) {
3048 throw new require_login_exception('Invalid course login-as access');
3050 $PAGE->set_context(null);
3051 echo $OUTPUT->header();
3052 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot
.'/');
3058 if (is_role_switched($course->id
)) {
3059 // Ok, user had to be inside this course before the switch.
3062 } else if (is_viewing($coursecontext, $USER)) {
3063 // Ok, no need to mess with enrol.
3067 if (isset($USER->enrol
['enrolled'][$course->id
])) {
3068 if ($USER->enrol
['enrolled'][$course->id
] > time()) {
3070 if (isset($USER->enrol
['tempguest'][$course->id
])) {
3071 unset($USER->enrol
['tempguest'][$course->id
]);
3072 remove_temp_course_roles($coursecontext);
3076 unset($USER->enrol
['enrolled'][$course->id
]);
3079 if (isset($USER->enrol
['tempguest'][$course->id
])) {
3080 if ($USER->enrol
['tempguest'][$course->id
] == 0) {
3082 } else if ($USER->enrol
['tempguest'][$course->id
] > time()) {
3086 unset($USER->enrol
['tempguest'][$course->id
]);
3087 remove_temp_course_roles($coursecontext);
3093 $until = enrol_get_enrolment_end($coursecontext->instanceid
, $USER->id
);
3094 if ($until !== false) {
3095 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3097 $until = ENROL_MAX_TIMESTAMP
;
3099 $USER->enrol
['enrolled'][$course->id
] = $until;
3103 $params = array('courseid' => $course->id
, 'status' => ENROL_INSTANCE_ENABLED
);
3104 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3105 $enrols = enrol_get_plugins(true);
3106 // First ask all enabled enrol instances in course if they want to auto enrol user.
3107 foreach ($instances as $instance) {
3108 if (!isset($enrols[$instance->enrol
])) {
3111 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3112 $until = $enrols[$instance->enrol
]->try_autoenrol($instance);
3113 if ($until !== false) {
3115 $until = ENROL_MAX_TIMESTAMP
;
3117 $USER->enrol
['enrolled'][$course->id
] = $until;
3122 // If not enrolled yet try to gain temporary guest access.
3124 foreach ($instances as $instance) {
3125 if (!isset($enrols[$instance->enrol
])) {
3128 // Get a duration for the guest access, a timestamp in the future or false.
3129 $until = $enrols[$instance->enrol
]->try_guestaccess($instance);
3130 if ($until !== false and $until > time()) {
3131 $USER->enrol
['tempguest'][$course->id
] = $until;
3142 if ($preventredirect) {
3143 throw new require_login_exception('Not enrolled');
3145 if ($setwantsurltome) {
3146 $SESSION->wantsurl
= qualified_me();
3148 redirect($CFG->wwwroot
.'/enrol/index.php?id='. $course->id
);
3152 // Set the global $COURSE.
3153 // TODO MDL-49434: setting current course/cm should be after the check $cm->uservisible .
3155 $PAGE->set_cm($cm, $course);
3156 $PAGE->set_pagelayout('incourse');
3157 } else if (!empty($courseorid)) {
3158 $PAGE->set_course($course);
3161 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3162 if ($cm && !$cm->uservisible
) {
3163 if ($preventredirect) {
3164 throw new require_login_exception('Activity is hidden');
3166 if ($course->id
!= SITEID
) {
3167 $url = new moodle_url('/course/view.php', array('id' => $course->id
));
3169 $url = new moodle_url('/');
3171 redirect($url, get_string('activityiscurrentlyhidden'));
3174 // Finally access granted, update lastaccess times.
3175 user_accesstime_log($course->id
);
3180 * This function just makes sure a user is logged out.
3182 * @package core_access
3185 function require_logout() {
3188 if (!isloggedin()) {
3189 // This should not happen often, no need for hooks or events here.
3190 \core\session\manager
::terminate_current();
3194 // Execute hooks before action.
3195 $authplugins = array();
3196 $authsequence = get_enabled_auth_plugins();
3197 foreach ($authsequence as $authname) {
3198 $authplugins[$authname] = get_auth_plugin($authname);
3199 $authplugins[$authname]->prelogout_hook();
3202 // Store info that gets removed during logout.
3203 $sid = session_id();
3204 $event = \core\event\user_loggedout
::create(
3206 'userid' => $USER->id
,
3207 'objectid' => $USER->id
,
3208 'other' => array('sessionid' => $sid),
3211 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3212 $event->add_record_snapshot('sessions', $session);
3215 // Clone of $USER object to be used by auth plugins.
3216 $user = fullclone($USER);
3218 // Delete session record and drop $_SESSION content.
3219 \core\session\manager
::terminate_current();
3221 // Trigger event AFTER action.
3224 // Hook to execute auth plugins redirection after event trigger.
3225 foreach ($authplugins as $authplugin) {
3226 $authplugin->postlogout_hook($user);
3231 * Weaker version of require_login()
3233 * This is a weaker version of {@link require_login()} which only requires login
3234 * when called from within a course rather than the site page, unless
3235 * the forcelogin option is turned on.
3236 * @see require_login()
3238 * @package core_access
3241 * @param mixed $courseorid The course object or id in question
3242 * @param bool $autologinguest Allow autologin guests if that is wanted
3243 * @param object $cm Course activity module if known
3244 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3245 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3246 * in order to keep redirects working properly. MDL-14495
3247 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3249 * @throws coding_exception
3251 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3252 global $CFG, $PAGE, $SITE;
3253 $issite = ((is_object($courseorid) and $courseorid->id
== SITEID
)
3254 or (!is_object($courseorid) and $courseorid == SITEID
));
3255 if ($issite && !empty($cm) && !($cm instanceof cm_info
)) {
3256 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3257 // db queries so this is not really a performance concern, however it is obviously
3258 // better if you use get_fast_modinfo to get the cm before calling this.
3259 if (is_object($courseorid)) {
3260 $course = $courseorid;
3262 $course = clone($SITE);
3264 $modinfo = get_fast_modinfo($course);
3265 $cm = $modinfo->get_cm($cm->id
);
3267 if (!empty($CFG->forcelogin
)) {
3268 // Login required for both SITE and courses.
3269 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3271 } else if ($issite && !empty($cm) and !$cm->uservisible
) {
3272 // Always login for hidden activities.
3273 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3275 } else if ($issite) {
3276 // Login for SITE not required.
3277 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3278 if (!empty($courseorid)) {
3279 if (is_object($courseorid)) {
3280 $course = $courseorid;
3282 $course = clone $SITE;
3285 if ($cm->course
!= $course->id
) {
3286 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3288 $PAGE->set_cm($cm, $course);
3289 $PAGE->set_pagelayout('incourse');
3291 $PAGE->set_course($course);
3294 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3295 $PAGE->set_course($PAGE->course
);
3297 user_accesstime_log(SITEID
);
3301 // Course login always required.
3302 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3307 * Require key login. Function terminates with error if key not found or incorrect.
3309 * @uses NO_MOODLE_COOKIES
3310 * @uses PARAM_ALPHANUM
3311 * @param string $script unique script identifier
3312 * @param int $instance optional instance id
3313 * @return int Instance ID
3315 function require_user_key_login($script, $instance=null) {
3318 if (!NO_MOODLE_COOKIES
) {
3319 print_error('sessioncookiesdisable');
3323 \core\session\manager
::write_close();
3325 $keyvalue = required_param('key', PARAM_ALPHANUM
);
3327 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3328 print_error('invalidkey');
3331 if (!empty($key->validuntil
) and $key->validuntil
< time()) {
3332 print_error('expiredkey');
3335 if ($key->iprestriction
) {
3336 $remoteaddr = getremoteaddr(null);
3337 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction
)) {
3338 print_error('ipmismatch');
3342 if (!$user = $DB->get_record('user', array('id' => $key->userid
))) {
3343 print_error('invaliduserid');
3346 // Emulate normal session.
3347 enrol_check_plugins($user);
3348 \core\session\manager
::set_user($user);
3350 // Note we are not using normal login.
3351 if (!defined('USER_KEY_LOGIN')) {
3352 define('USER_KEY_LOGIN', true);
3355 // Return instance id - it might be empty.
3356 return $key->instance
;
3360 * Creates a new private user access key.
3362 * @param string $script unique target identifier
3363 * @param int $userid
3364 * @param int $instance optional instance id
3365 * @param string $iprestriction optional ip restricted access
3366 * @param timestamp $validuntil key valid only until given data
3367 * @return string access key value
3369 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3372 $key = new stdClass();
3373 $key->script
= $script;
3374 $key->userid
= $userid;
3375 $key->instance
= $instance;
3376 $key->iprestriction
= $iprestriction;
3377 $key->validuntil
= $validuntil;
3378 $key->timecreated
= time();
3380 // Something long and unique.
3381 $key->value
= md5($userid.'_'.time().random_string(40));
3382 while ($DB->record_exists('user_private_key', array('value' => $key->value
))) {
3384 $key->value
= md5($userid.'_'.time().random_string(40));
3386 $DB->insert_record('user_private_key', $key);
3391 * Delete the user's new private user access keys for a particular script.
3393 * @param string $script unique target identifier
3394 * @param int $userid
3397 function delete_user_key($script, $userid) {
3399 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3403 * Gets a private user access key (and creates one if one doesn't exist).
3405 * @param string $script unique target identifier
3406 * @param int $userid
3407 * @param int $instance optional instance id
3408 * @param string $iprestriction optional ip restricted access
3409 * @param timestamp $validuntil key valid only until given data
3410 * @return string access key value
3412 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3415 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3416 'instance' => $instance, 'iprestriction' => $iprestriction,
3417 'validuntil' => $validuntil))) {
3420 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3426 * Modify the user table by setting the currently logged in user's last login to now.
3428 * @return bool Always returns true
3430 function update_user_login_times() {
3433 if (isguestuser()) {
3434 // Do not update guest access times/ips for performance.
3440 $user = new stdClass();
3441 $user->id
= $USER->id
;
3443 // Make sure all users that logged in have some firstaccess.
3444 if ($USER->firstaccess
== 0) {
3445 $USER->firstaccess
= $user->firstaccess
= $now;
3448 // Store the previous current as lastlogin.
3449 $USER->lastlogin
= $user->lastlogin
= $USER->currentlogin
;
3451 $USER->currentlogin
= $user->currentlogin
= $now;
3453 // Function user_accesstime_log() may not update immediately, better do it here.
3454 $USER->lastaccess
= $user->lastaccess
= $now;
3455 $USER->lastip
= $user->lastip
= getremoteaddr();
3457 // Note: do not call user_update_user() here because this is part of the login process,
3458 // the login event means that these fields were updated.
3459 $DB->update_record('user', $user);
3464 * Determines if a user has completed setting up their account.
3466 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3469 function user_not_fully_set_up($user) {
3470 if (isguestuser($user)) {
3473 return (empty($user->firstname
) or empty($user->lastname
) or empty($user->email
) or over_bounce_threshold($user));
3477 * Check whether the user has exceeded the bounce threshold
3479 * @param stdClass $user A {@link $USER} object
3480 * @return bool true => User has exceeded bounce threshold
3482 function over_bounce_threshold($user) {
3485 if (empty($CFG->handlebounces
)) {
3489 if (empty($user->id
)) {
3490 // No real (DB) user, nothing to do here.
3494 // Set sensible defaults.
3495 if (empty($CFG->minbounces
)) {
3496 $CFG->minbounces
= 10;
3498 if (empty($CFG->bounceratio
)) {
3499 $CFG->bounceratio
= .20;
3503 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3504 $bouncecount = $bounce->value
;
3506 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3507 $sendcount = $send->value
;
3509 return ($bouncecount >= $CFG->minbounces
&& $bouncecount/$sendcount >= $CFG->bounceratio
);
3513 * Used to increment or reset email sent count
3515 * @param stdClass $user object containing an id
3516 * @param bool $reset will reset the count to 0
3519 function set_send_count($user, $reset=false) {
3522 if (empty($user->id
)) {
3523 // No real (DB) user, nothing to do here.
3527 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_send_count'))) {
3528 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3529 $DB->update_record('user_preferences', $pref);
3530 } else if (!empty($reset)) {
3531 // If it's not there and we're resetting, don't bother. Make a new one.
3532 $pref = new stdClass();
3533 $pref->name
= 'email_send_count';
3535 $pref->userid
= $user->id
;
3536 $DB->insert_record('user_preferences', $pref, false);
3541 * Increment or reset user's email bounce count
3543 * @param stdClass $user object containing an id
3544 * @param bool $reset will reset the count to 0
3546 function set_bounce_count($user, $reset=false) {
3549 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id
, 'name' => 'email_bounce_count'))) {
3550 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3551 $DB->update_record('user_preferences', $pref);
3552 } else if (!empty($reset)) {
3553 // If it's not there and we're resetting, don't bother. Make a new one.
3554 $pref = new stdClass();
3555 $pref->name
= 'email_bounce_count';
3557 $pref->userid
= $user->id
;
3558 $DB->insert_record('user_preferences', $pref, false);
3563 * Determines if the logged in user is currently moving an activity
3565 * @param int $courseid The id of the course being tested
3568 function ismoving($courseid) {
3571 if (!empty($USER->activitycopy
)) {
3572 return ($USER->activitycopycourse
== $courseid);
3578 * Returns a persons full name
3580 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3581 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3584 * @param stdClass $user A {@link $USER} object to get full name of.
3585 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3588 function fullname($user, $override=false) {
3589 global $CFG, $SESSION;
3591 if (!isset($user->firstname
) and !isset($user->lastname
)) {
3595 // Get all of the name fields.
3596 $allnames = get_all_user_name_fields();
3597 if ($CFG->debugdeveloper
) {
3598 foreach ($allnames as $allname) {
3599 if (!array_key_exists($allname, $user)) {
3600 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3601 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER
);
3602 // Message has been sent, no point in sending the message multiple times.
3609 if (!empty($CFG->forcefirstname
)) {
3610 $user->firstname
= $CFG->forcefirstname
;
3612 if (!empty($CFG->forcelastname
)) {
3613 $user->lastname
= $CFG->forcelastname
;
3617 if (!empty($SESSION->fullnamedisplay
)) {
3618 $CFG->fullnamedisplay
= $SESSION->fullnamedisplay
;
3622 // If the fullnamedisplay setting is available, set the template to that.
3623 if (isset($CFG->fullnamedisplay
)) {
3624 $template = $CFG->fullnamedisplay
;
3626 // If the template is empty, or set to language, return the language string.
3627 if ((empty($template) ||
$template == 'language') && !$override) {
3628 return get_string('fullnamedisplay', null, $user);
3631 // Check to see if we are displaying according to the alternative full name format.
3633 if (empty($CFG->alternativefullnameformat
) ||
$CFG->alternativefullnameformat
== 'language') {
3634 // Default to show just the user names according to the fullnamedisplay string.
3635 return get_string('fullnamedisplay', null, $user);
3637 // If the override is true, then change the template to use the complete name.
3638 $template = $CFG->alternativefullnameformat
;
3642 $requirednames = array();
3643 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3644 foreach ($allnames as $allname) {
3645 if (strpos($template, $allname) !== false) {
3646 $requirednames[] = $allname;
3650 $displayname = $template;
3651 // Switch in the actual data into the template.
3652 foreach ($requirednames as $altname) {
3653 if (isset($user->$altname)) {
3654 // Using empty() on the below if statement causes breakages.
3655 if ((string)$user->$altname == '') {
3656 $displayname = str_replace($altname, 'EMPTY', $displayname);
3658 $displayname = str_replace($altname, $user->$altname, $displayname);
3661 $displayname = str_replace($altname, 'EMPTY', $displayname);
3664 // Tidy up any misc. characters (Not perfect, but gets most characters).
3665 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3666 // katakana and parenthesis.
3667 $patterns = array();
3668 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3669 // filled in by a user.
3670 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3671 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3672 // This regular expression is to remove any double spaces in the display name.
3673 $patterns[] = '/\s{2,}/u';
3674 foreach ($patterns as $pattern) {
3675 $displayname = preg_replace($pattern, ' ', $displayname);
3678 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3679 $displayname = trim($displayname);
3680 if (empty($displayname)) {
3681 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3682 // people in general feel is a good setting to fall back on.
3683 $displayname = $user->firstname
;
3685 return $displayname;
3689 * A centralised location for the all name fields. Returns an array / sql string snippet.
3691 * @param bool $returnsql True for an sql select field snippet.
3692 * @param string $tableprefix table query prefix to use in front of each field.
3693 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3694 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3695 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3696 * @return array|string All name fields.
3698 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3699 // This array is provided in this order because when called by fullname() (above) if firstname is before
3700 // firstnamephonetic str_replace() will change the wrong placeholder.
3701 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3702 'lastnamephonetic' => 'lastnamephonetic',
3703 'middlename' => 'middlename',
3704 'alternatename' => 'alternatename',
3705 'firstname' => 'firstname',
3706 'lastname' => 'lastname');
3708 // Let's add a prefix to the array of user name fields if provided.
3710 foreach ($alternatenames as $key => $altname) {
3711 $alternatenames[$key] = $prefix . $altname;
3715 // If we want the end result to have firstname and lastname at the front / top of the result.
3717 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3718 for ($i = 0; $i < 2; $i++
) {
3719 // Get the last element.
3720 $lastelement = end($alternatenames);
3721 // Remove it from the array.
3722 unset($alternatenames[$lastelement]);
3723 // Put the element back on the top of the array.
3724 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3728 // Create an sql field snippet if requested.
3732 foreach ($alternatenames as $key => $altname) {
3733 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3736 foreach ($alternatenames as $key => $altname) {
3737 $alternatenames[$key] = $tableprefix . '.' . $altname;
3741 $alternatenames = implode(',', $alternatenames);
3743 return $alternatenames;
3747 * Reduces lines of duplicated code for getting user name fields.
3749 * See also {@link user_picture::unalias()}
3751 * @param object $addtoobject Object to add user name fields to.
3752 * @param object $secondobject Object that contains user name field information.
3753 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3754 * @param array $additionalfields Additional fields to be matched with data in the second object.
3755 * The key can be set to the user table field name.
3756 * @return object User name fields.
3758 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3759 $fields = get_all_user_name_fields(false, null, $prefix);
3760 if ($additionalfields) {
3761 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3762 // the key is a number and then sets the key to the array value.
3763 foreach ($additionalfields as $key => $value) {
3764 if (is_numeric($key)) {
3765 $additionalfields[$value] = $prefix . $value;
3766 unset($additionalfields[$key]);
3768 $additionalfields[$key] = $prefix . $value;
3771 $fields = array_merge($fields, $additionalfields);
3773 foreach ($fields as $key => $field) {
3774 // Important that we have all of the user name fields present in the object that we are sending back.
3775 $addtoobject->$key = '';
3776 if (isset($secondobject->$field)) {
3777 $addtoobject->$key = $secondobject->$field;
3780 return $addtoobject;
3784 * Returns an array of values in order of occurance in a provided string.
3785 * The key in the result is the character postion in the string.
3787 * @param array $values Values to be found in the string format
3788 * @param string $stringformat The string which may contain values being searched for.
3789 * @return array An array of values in order according to placement in the string format.
3791 function order_in_string($values, $stringformat) {
3792 $valuearray = array();
3793 foreach ($values as $value) {
3794 $pattern = "/$value\b/";
3795 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3796 if (preg_match($pattern, $stringformat)) {
3797 $replacement = "thing";
3798 // Replace the value with something more unique to ensure we get the right position when using strpos().
3799 $newformat = preg_replace($pattern, $replacement, $stringformat);
3800 $position = strpos($newformat, $replacement);
3801 $valuearray[$position] = $value;
3809 * Checks if current user is shown any extra fields when listing users.
3811 * @param object $context Context
3812 * @param array $already Array of fields that we're going to show anyway
3813 * so don't bother listing them
3814 * @return array Array of field names from user table, not including anything
3815 * listed in $already
3817 function get_extra_user_fields($context, $already = array()) {
3820 // Only users with permission get the extra fields.
3821 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3825 // Split showuseridentity on comma.
3826 if (empty($CFG->showuseridentity
)) {
3827 // Explode gives wrong result with empty string.
3830 $extra = explode(',', $CFG->showuseridentity
);
3833 foreach ($extra as $key => $field) {
3834 if (in_array($field, $already)) {
3835 unset($extra[$key]);
3840 // For consistency, if entries are removed from array, renumber it
3841 // so they are numbered as you would expect.
3842 $extra = array_merge($extra);
3848 * If the current user is to be shown extra user fields when listing or
3849 * selecting users, returns a string suitable for including in an SQL select
3850 * clause to retrieve those fields.
3852 * @param context $context Context
3853 * @param string $alias Alias of user table, e.g. 'u' (default none)
3854 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3855 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3856 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3858 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3859 $fields = get_extra_user_fields($context, $already);
3861 // Add punctuation for alias.
3862 if ($alias !== '') {
3865 foreach ($fields as $field) {
3866 $result .= ', ' . $alias . $field;
3868 $result .= ' AS ' . $prefix . $field;
3875 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3876 * @param string $field Field name, e.g. 'phone1'
3877 * @return string Text description taken from language file, e.g. 'Phone number'
3879 function get_user_field_name($field) {
3880 // Some fields have language strings which are not the same as field name.
3883 return get_string('phone');
3886 return get_string('webpage');
3889 return get_string('icqnumber');
3892 return get_string('skypeid');
3895 return get_string('aimid');
3898 return get_string('yahooid');
3901 return get_string('msnid');
3904 // Otherwise just use the same lang string.
3905 return get_string($field);
3909 * Returns whether a given authentication plugin exists.
3911 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3912 * @return boolean Whether the plugin is available.
3914 function exists_auth_plugin($auth) {
3917 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3918 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3924 * Checks if a given plugin is in the list of enabled authentication plugins.
3926 * @param string $auth Authentication plugin.
3927 * @return boolean Whether the plugin is enabled.
3929 function is_enabled_auth($auth) {
3934 $enabled = get_enabled_auth_plugins();
3936 return in_array($auth, $enabled);
3940 * Returns an authentication plugin instance.
3942 * @param string $auth name of authentication plugin
3943 * @return auth_plugin_base An instance of the required authentication plugin.
3945 function get_auth_plugin($auth) {
3948 // Check the plugin exists first.
3949 if (! exists_auth_plugin($auth)) {
3950 print_error('authpluginnotfound', 'debug', '', $auth);
3953 // Return auth plugin instance.
3954 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3955 $class = "auth_plugin_$auth";
3960 * Returns array of active auth plugins.
3962 * @param bool $fix fix $CFG->auth if needed
3965 function get_enabled_auth_plugins($fix=false) {
3968 $default = array('manual', 'nologin');
3970 if (empty($CFG->auth
)) {
3973 $auths = explode(',', $CFG->auth
);
3977 $auths = array_unique($auths);
3978 foreach ($auths as $k => $authname) {
3979 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3983 $newconfig = implode(',', $auths);
3984 if (!isset($CFG->auth
) or $newconfig != $CFG->auth
) {
3985 set_config('auth', $newconfig);
3989 return (array_merge($default, $auths));
3993 * Returns true if an internal authentication method is being used.
3994 * if method not specified then, global default is assumed
3996 * @param string $auth Form of authentication required
3999 function is_internal_auth($auth) {
4000 // Throws error if bad $auth.
4001 $authplugin = get_auth_plugin($auth);
4002 return $authplugin->is_internal();
4006 * Returns true if the user is a 'restored' one.
4008 * Used in the login process to inform the user and allow him/her to reset the password
4010 * @param string $username username to be checked
4013 function is_restored_user($username) {
4016 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'password' => 'restored'));
4020 * Returns an array of user fields
4022 * @return array User field/column names
4024 function get_user_fieldnames() {
4027 $fieldarray = $DB->get_columns('user');
4028 unset($fieldarray['id']);
4029 $fieldarray = array_keys($fieldarray);
4035 * Creates a bare-bones user record
4037 * @todo Outline auth types and provide code example
4039 * @param string $username New user's username to add to record
4040 * @param string $password New user's password to add to record
4041 * @param string $auth Form of authentication required
4042 * @return stdClass A complete user object
4044 function create_user_record($username, $password, $auth = 'manual') {
4046 require_once($CFG->dirroot
.'/user/profile/lib.php');
4047 require_once($CFG->dirroot
.'/user/lib.php');
4049 // Just in case check text case.
4050 $username = trim(core_text
::strtolower($username));
4052 $authplugin = get_auth_plugin($auth);
4053 $customfields = $authplugin->get_custom_user_profile_fields();
4054 $newuser = new stdClass();
4055 if ($newinfo = $authplugin->get_userinfo($username)) {
4056 $newinfo = truncate_userinfo($newinfo);
4057 foreach ($newinfo as $key => $value) {
4058 if (in_array($key, $authplugin->userfields
) ||
(in_array($key, $customfields))) {
4059 $newuser->$key = $value;
4064 if (!empty($newuser->email
)) {
4065 if (email_is_not_allowed($newuser->email
)) {
4066 unset($newuser->email
);
4070 if (!isset($newuser->city
)) {
4071 $newuser->city
= '';
4074 $newuser->auth
= $auth;
4075 $newuser->username
= $username;
4078 // user CFG lang for user if $newuser->lang is empty
4079 // or $user->lang is not an installed language.
4080 if (empty($newuser->lang
) ||
!get_string_manager()->translation_exists($newuser->lang
)) {
4081 $newuser->lang
= $CFG->lang
;
4083 $newuser->confirmed
= 1;
4084 $newuser->lastip
= getremoteaddr();
4085 $newuser->timecreated
= time();
4086 $newuser->timemodified
= $newuser->timecreated
;
4087 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
4089 $newuser->id
= user_create_user($newuser, false, false);
4091 // Save user profile data.
4092 profile_save_data($newuser);
4094 $user = get_complete_user_data('id', $newuser->id
);
4095 if (!empty($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'})) {
4096 set_user_preference('auth_forcepasswordchange', 1, $user);
4098 // Set the password.
4099 update_internal_user_password($user, $password);
4102 \core\event\user_created
::create_from_userid($newuser->id
)->trigger();
4108 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4110 * @param string $username user's username to update the record
4111 * @return stdClass A complete user object
4113 function update_user_record($username) {
4115 // Just in case check text case.
4116 $username = trim(core_text
::strtolower($username));
4118 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
), '*', MUST_EXIST
);
4119 return update_user_record_by_id($oldinfo->id
);
4123 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4125 * @param int $id user id
4126 * @return stdClass A complete user object
4128 function update_user_record_by_id($id) {
4130 require_once($CFG->dirroot
."/user/profile/lib.php");
4131 require_once($CFG->dirroot
.'/user/lib.php');
4133 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'id' => $id, 'deleted' => 0);
4134 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST
);
4137 $userauth = get_auth_plugin($oldinfo->auth
);
4139 if ($newinfo = $userauth->get_userinfo($oldinfo->username
)) {
4140 $newinfo = truncate_userinfo($newinfo);
4141 $customfields = $userauth->get_custom_user_profile_fields();
4143 foreach ($newinfo as $key => $value) {
4144 $key = strtolower($key);
4145 $iscustom = in_array($key, $customfields);
4146 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4147 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4148 // Unknown or must not be changed.
4151 $confval = $userauth->config
->{'field_updatelocal_' . $key};
4152 $lockval = $userauth->config
->{'field_lock_' . $key};
4153 if (empty($confval) ||
empty($lockval)) {
4156 if ($confval === 'onlogin') {
4157 // MDL-4207 Don't overwrite modified user profile values with
4158 // empty LDAP values when 'unlocked if empty' is set. The purpose
4159 // of the setting 'unlocked if empty' is to allow the user to fill
4160 // in a value for the selected field _if LDAP is giving
4161 // nothing_ for this field. Thus it makes sense to let this value
4162 // stand in until LDAP is giving a value for this field.
4163 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4164 if ($iscustom ||
(in_array($key, $userauth->userfields
) &&
4165 ((string)$oldinfo->$key !== (string)$value))) {
4166 $newuser[$key] = (string)$value;
4172 $newuser['id'] = $oldinfo->id
;
4173 $newuser['timemodified'] = time();
4174 user_update_user((object) $newuser, false, false);
4176 // Save user profile data.
4177 profile_save_data((object) $newuser);
4180 \core\event\user_updated
::create_from_userid($newuser['id'])->trigger();
4184 return get_complete_user_data('id', $oldinfo->id
);
4188 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4190 * @param array $info Array of user properties to truncate if needed
4191 * @return array The now truncated information that was passed in
4193 function truncate_userinfo(array $info) {
4194 // Define the limits.
4204 'institution' => 255,
4205 'department' => 255,
4212 // Apply where needed.
4213 foreach (array_keys($info) as $key) {
4214 if (!empty($limit[$key])) {
4215 $info[$key] = trim(core_text
::substr($info[$key], 0, $limit[$key]));
4223 * Marks user deleted in internal user database and notifies the auth plugin.
4224 * Also unenrols user from all roles and does other cleanup.
4226 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4228 * @param stdClass $user full user object before delete
4229 * @return boolean success
4230 * @throws coding_exception if invalid $user parameter detected
4232 function delete_user(stdClass
$user) {
4234 require_once($CFG->libdir
.'/grouplib.php');
4235 require_once($CFG->libdir
.'/gradelib.php');
4236 require_once($CFG->dirroot
.'/message/lib.php');
4237 require_once($CFG->dirroot
.'/tag/lib.php');
4238 require_once($CFG->dirroot
.'/user/lib.php');
4240 // Make sure nobody sends bogus record type as parameter.
4241 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4242 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4245 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4246 if (!$user = $DB->get_record('user', array('id' => $user->id
))) {
4247 debugging('Attempt to delete unknown user account.');
4251 // There must be always exactly one guest record, originally the guest account was identified by username only,
4252 // now we use $CFG->siteguest for performance reasons.
4253 if ($user->username
=== 'guest' or isguestuser($user)) {
4254 debugging('Guest user account can not be deleted.');
4258 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4259 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4260 if ($user->auth
=== 'manual' and is_siteadmin($user)) {
4261 debugging('Local administrator accounts can not be deleted.');
4265 // Keep user record before updating it, as we have to pass this to user_deleted event.
4266 $olduser = clone $user;
4268 // Keep a copy of user context, we need it for event.
4269 $usercontext = context_user
::instance($user->id
);
4271 // Delete all grades - backup is kept in grade_grades_history table.
4272 grade_user_delete($user->id
);
4274 // Move unread messages from this user to read.
4275 message_move_userfrom_unread2read($user->id
);
4277 // TODO: remove from cohorts using standard API here.
4279 // Remove user tags.
4280 tag_set('user', $user->id
, array(), 'core', $usercontext->id
);
4282 // Unconditionally unenrol from all courses.
4283 enrol_user_delete($user);
4285 // Unenrol from all roles in all contexts.
4286 // This might be slow but it is really needed - modules might do some extra cleanup!
4287 role_unassign_all(array('userid' => $user->id
));
4289 // Now do a brute force cleanup.
4291 // Remove from all cohorts.
4292 $DB->delete_records('cohort_members', array('userid' => $user->id
));
4294 // Remove from all groups.
4295 $DB->delete_records('groups_members', array('userid' => $user->id
));
4297 // Brute force unenrol from all courses.
4298 $DB->delete_records('user_enrolments', array('userid' => $user->id
));
4300 // Purge user preferences.
4301 $DB->delete_records('user_preferences', array('userid' => $user->id
));
4303 // Purge user extra profile info.
4304 $DB->delete_records('user_info_data', array('userid' => $user->id
));
4306 // Last course access not necessary either.
4307 $DB->delete_records('user_lastaccess', array('userid' => $user->id
));
4308 // Remove all user tokens.
4309 $DB->delete_records('external_tokens', array('userid' => $user->id
));
4311 // Unauthorise the user for all services.
4312 $DB->delete_records('external_services_users', array('userid' => $user->id
));
4314 // Remove users private keys.
4315 $DB->delete_records('user_private_key', array('userid' => $user->id
));
4317 // Remove users customised pages.
4318 $DB->delete_records('my_pages', array('userid' => $user->id
, 'private' => 1));
4320 // Force logout - may fail if file based sessions used, sorry.
4321 \core\session\manager
::kill_user_sessions($user->id
);
4323 // Workaround for bulk deletes of users with the same email address.
4324 $delname = clean_param($user->email
. "." . time(), PARAM_USERNAME
);
4325 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4329 // Mark internal user record as "deleted".
4330 $updateuser = new stdClass();
4331 $updateuser->id
= $user->id
;
4332 $updateuser->deleted
= 1;
4333 $updateuser->username
= $delname; // Remember it just in case.
4334 $updateuser->email
= md5($user->username
);// Store hash of username, useful importing/restoring users.
4335 $updateuser->idnumber
= ''; // Clear this field to free it up.
4336 $updateuser->picture
= 0;
4337 $updateuser->timemodified
= time();
4339 // Don't trigger update event, as user is being deleted.
4340 user_update_user($updateuser, false, false);
4342 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4343 context_helper
::delete_instance(CONTEXT_USER
, $user->id
);
4345 // Any plugin that needs to cleanup should register this event.
4347 $event = \core\event\user_deleted
::create(
4349 'objectid' => $user->id
,
4350 'relateduserid' => $user->id
,
4351 'context' => $usercontext,
4353 'username' => $user->username
,
4354 'email' => $user->email
,
4355 'idnumber' => $user->idnumber
,
4356 'picture' => $user->picture
,
4357 'mnethostid' => $user->mnethostid
4361 $event->add_record_snapshot('user', $olduser);
4364 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4365 // should know about this updated property persisted to the user's table.
4366 $user->timemodified
= $updateuser->timemodified
;
4368 // Notify auth plugin - do not block the delete even when plugin fails.
4369 $authplugin = get_auth_plugin($user->auth
);
4370 $authplugin->user_delete($user);
4376 * Retrieve the guest user object.
4378 * @return stdClass A {@link $USER} object
4380 function guest_user() {
4383 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest
))) {
4384 $newuser->confirmed
= 1;
4385 $newuser->lang
= $CFG->lang
;
4386 $newuser->lastip
= getremoteaddr();
4393 * Authenticates a user against the chosen authentication mechanism
4395 * Given a username and password, this function looks them
4396 * up using the currently selected authentication mechanism,
4397 * and if the authentication is successful, it returns a
4398 * valid $user object from the 'user' table.
4400 * Uses auth_ functions from the currently active auth module
4402 * After authenticate_user_login() returns success, you will need to
4403 * log that the user has logged in, and call complete_user_login() to set
4406 * Note: this function works only with non-mnet accounts!
4408 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4409 * @param string $password User's password
4410 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4411 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4412 * @return stdClass|false A {@link $USER} object or false if error
4414 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4416 require_once("$CFG->libdir/authlib.php");
4418 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id
)) {
4419 // we have found the user
4421 } else if (!empty($CFG->authloginviaemail
)) {
4422 if ($email = clean_param($username, PARAM_EMAIL
)) {
4423 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4424 $params = array('mnethostid' => $CFG->mnet_localhost_id
, 'email' => $email);
4425 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4426 if (count($users) === 1) {
4427 // Use email for login only if unique.
4428 $user = reset($users);
4429 $user = get_complete_user_data('id', $user->id
);
4430 $username = $user->username
;
4436 $authsenabled = get_enabled_auth_plugins();
4439 // Use manual if auth not set.
4440 $auth = empty($user->auth
) ?
'manual' : $user->auth
;
4441 if (!empty($user->suspended
)) {
4442 $failurereason = AUTH_LOGIN_SUSPENDED
;
4444 // Trigger login failed event.
4445 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4446 'other' => array('username' => $username, 'reason' => $failurereason)));
4448 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4451 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4452 // Legacy way to suspend user.
4453 $failurereason = AUTH_LOGIN_SUSPENDED
;
4455 // Trigger login failed event.
4456 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4457 'other' => array('username' => $username, 'reason' => $failurereason)));
4459 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4462 $auths = array($auth);
4465 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4466 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id
, 'deleted' => 1))) {
4467 $failurereason = AUTH_LOGIN_NOUSER
;
4469 // Trigger login failed event.
4470 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4471 'reason' => $failurereason)));
4473 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4477 // User does not exist.
4478 $auths = $authsenabled;
4479 $user = new stdClass();
4483 if ($ignorelockout) {
4484 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4485 // or this function is called from a SSO script.
4486 } else if ($user->id
) {
4487 // Verify login lockout after other ways that may prevent user login.
4488 if (login_is_lockedout($user)) {
4489 $failurereason = AUTH_LOGIN_LOCKOUT
;
4491 // Trigger login failed event.
4492 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4493 'other' => array('username' => $username, 'reason' => $failurereason)));
4496 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4500 // We can not lockout non-existing accounts.
4503 foreach ($auths as $auth) {
4504 $authplugin = get_auth_plugin($auth);
4506 // On auth fail fall through to the next plugin.
4507 if (!$authplugin->user_login($username, $password)) {
4511 // Successful authentication.
4513 // User already exists in database.
4514 if (empty($user->auth
)) {
4515 // For some reason auth isn't set yet.
4516 $DB->set_field('user', 'auth', $auth, array('id' => $user->id
));
4517 $user->auth
= $auth;
4520 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4521 // the current hash algorithm while we have access to the user's password.
4522 update_internal_user_password($user, $password);
4524 if ($authplugin->is_synchronised_with_external()) {
4525 // Update user record from external DB.
4526 $user = update_user_record_by_id($user->id
);
4529 // The user is authenticated but user creation may be disabled.
4530 if (!empty($CFG->authpreventaccountcreation
)) {
4531 $failurereason = AUTH_LOGIN_UNAUTHORISED
;
4533 // Trigger login failed event.
4534 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4535 'reason' => $failurereason)));
4538 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4539 $_SERVER['HTTP_USER_AGENT']);
4542 $user = create_user_record($username, $password, $auth);
4546 $authplugin->sync_roles($user);
4548 foreach ($authsenabled as $hau) {
4549 $hauth = get_auth_plugin($hau);
4550 $hauth->user_authenticated_hook($user, $username, $password);
4553 if (empty($user->id
)) {
4554 $failurereason = AUTH_LOGIN_NOUSER
;
4555 // Trigger login failed event.
4556 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4557 'reason' => $failurereason)));
4562 if (!empty($user->suspended
)) {
4563 // Just in case some auth plugin suspended account.
4564 $failurereason = AUTH_LOGIN_SUSPENDED
;
4565 // Trigger login failed event.
4566 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4567 'other' => array('username' => $username, 'reason' => $failurereason)));
4569 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4573 login_attempt_valid($user);
4574 $failurereason = AUTH_LOGIN_OK
;
4578 // Failed if all the plugins have failed.
4579 if (debugging('', DEBUG_ALL
)) {
4580 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4584 login_attempt_failed($user);
4585 $failurereason = AUTH_LOGIN_FAILED
;
4586 // Trigger login failed event.
4587 $event = \core\event\user_login_failed
::create(array('userid' => $user->id
,
4588 'other' => array('username' => $username, 'reason' => $failurereason)));
4591 $failurereason = AUTH_LOGIN_NOUSER
;
4592 // Trigger login failed event.
4593 $event = \core\event\user_login_failed
::create(array('other' => array('username' => $username,
4594 'reason' => $failurereason)));
4602 * Call to complete the user login process after authenticate_user_login()
4603 * has succeeded. It will setup the $USER variable and other required bits
4607 * - It will NOT log anything -- up to the caller to decide what to log.
4608 * - this function does not set any cookies any more!
4610 * @param stdClass $user
4611 * @return stdClass A {@link $USER} object - BC only, do not use
4613 function complete_user_login($user) {
4616 \core\session\manager
::login_user($user);
4618 // Reload preferences from DB.
4619 unset($USER->preference
);
4620 check_user_preferences_loaded($USER);
4622 // Update login times.
4623 update_user_login_times();
4625 // Extra session prefs init.
4626 set_login_session_preferences();
4628 // Trigger login event.
4629 $event = \core\event\user_loggedin
::create(
4631 'userid' => $USER->id
,
4632 'objectid' => $USER->id
,
4633 'other' => array('username' => $USER->username
),
4638 if (isguestuser()) {
4639 // No need to continue when user is THE guest.
4644 // We can redirect to password change URL only in browser.
4648 // Select password change url.
4649 $userauth = get_auth_plugin($USER->auth
);
4651 // Check whether the user should be changing password.
4652 if (get_user_preferences('auth_forcepasswordchange', false)) {
4653 if ($userauth->can_change_password()) {
4654 if ($changeurl = $userauth->change_password_url()) {
4655 redirect($changeurl);
4657 redirect($CFG->httpswwwroot
.'/login/change_password.php');
4660 print_error('nopasswordchangeforced', 'auth');
4667 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4669 * @param string $password String to check.
4670 * @return boolean True if the $password matches the format of an md5 sum.
4672 function password_is_legacy_hash($password) {
4673 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4677 * Compare password against hash stored in user object to determine if it is valid.
4679 * If necessary it also updates the stored hash to the current format.
4681 * @param stdClass $user (Password property may be updated).
4682 * @param string $password Plain text password.
4683 * @return bool True if password is valid.
4685 function validate_internal_user_password($user, $password) {
4687 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4689 if ($user->password
=== AUTH_PASSWORD_NOT_CACHED
) {
4690 // Internal password is not used at all, it can not validate.
4694 // If hash isn't a legacy (md5) hash, validate using the library function.
4695 if (!password_is_legacy_hash($user->password
)) {
4696 return password_verify($password, $user->password
);
4699 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4700 // is valid we can then update it to the new algorithm.
4702 $sitesalt = isset($CFG->passwordsaltmain
) ?
$CFG->passwordsaltmain
: '';
4705 if ($user->password
=== md5($password.$sitesalt)
4706 or $user->password
=== md5($password)
4707 or $user->password
=== md5(addslashes($password).$sitesalt)
4708 or $user->password
=== md5(addslashes($password))) {
4709 // Note: we are intentionally using the addslashes() here because we
4710 // need to accept old password hashes of passwords with magic quotes.
4714 for ($i=1; $i<=20; $i++
) { // 20 alternative salts should be enough, right?
4715 $alt = 'passwordsaltalt'.$i;
4716 if (!empty($CFG->$alt)) {
4717 if ($user->password
=== md5($password.$CFG->$alt) or $user->password
=== md5(addslashes($password).$CFG->$alt)) {
4726 // If the password matches the existing md5 hash, update to the
4727 // current hash algorithm while we have access to the user's password.
4728 update_internal_user_password($user, $password);
4735 * Calculate hash for a plain text password.
4737 * @param string $password Plain text password to be hashed.
4738 * @param bool $fasthash If true, use a low cost factor when generating the hash
4739 * This is much faster to generate but makes the hash
4740 * less secure. It is used when lots of hashes need to
4741 * be generated quickly.
4742 * @return string The hashed password.
4744 * @throws moodle_exception If a problem occurs while generating the hash.
4746 function hash_internal_user_password($password, $fasthash = false) {
4748 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4750 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4751 $options = ($fasthash) ?
array('cost' => 4) : array();
4753 $generatedhash = password_hash($password, PASSWORD_DEFAULT
, $options);
4755 if ($generatedhash === false ||
$generatedhash === null) {
4756 throw new moodle_exception('Failed to generate password hash.');
4759 return $generatedhash;
4763 * Update password hash in user object (if necessary).
4765 * The password is updated if:
4766 * 1. The password has changed (the hash of $user->password is different
4767 * to the hash of $password).
4768 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4771 * Updating the password will modify the $user object and the database
4772 * record to use the current hashing algorithm.
4774 * @param stdClass $user User object (password property may be updated).
4775 * @param string $password Plain text password.
4776 * @param bool $fasthash If true, use a low cost factor when generating the hash
4777 * This is much faster to generate but makes the hash
4778 * less secure. It is used when lots of hashes need to
4779 * be generated quickly.
4780 * @return bool Always returns true.
4782 function update_internal_user_password($user, $password, $fasthash = false) {
4784 require_once($CFG->libdir
.'/password_compat/lib/password.php');
4786 // Figure out what the hashed password should be.
4787 if (!isset($user->auth
)) {
4788 debugging('User record in update_internal_user_password() must include field auth',
4790 $user->auth
= $DB->get_field('user', 'auth', array('id' => $user->id
));
4792 $authplugin = get_auth_plugin($user->auth
);
4793 if ($authplugin->prevent_local_passwords()) {
4794 $hashedpassword = AUTH_PASSWORD_NOT_CACHED
;
4796 $hashedpassword = hash_internal_user_password($password, $fasthash);
4799 $algorithmchanged = false;
4801 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED
) {
4802 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4803 $passwordchanged = ($user->password
!== $hashedpassword);
4805 } else if (isset($user->password
)) {
4806 // If verification fails then it means the password has changed.
4807 $passwordchanged = !password_verify($password, $user->password
);
4808 $algorithmchanged = password_needs_rehash($user->password
, PASSWORD_DEFAULT
);
4810 // While creating new user, password in unset in $user object, to avoid
4811 // saving it with user_create()
4812 $passwordchanged = true;
4815 if ($passwordchanged ||
$algorithmchanged) {
4816 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id
));
4817 $user->password
= $hashedpassword;
4820 $user = $DB->get_record('user', array('id' => $user->id
));
4821 \core\event\user_password_updated
::create_from_user($user)->trigger();
4828 * Get a complete user record, which includes all the info in the user record.
4830 * Intended for setting as $USER session variable
4832 * @param string $field The user field to be checked for a given value.
4833 * @param string $value The value to match for $field.
4834 * @param int $mnethostid
4835 * @return mixed False, or A {@link $USER} object.
4837 function get_complete_user_data($field, $value, $mnethostid = null) {
4840 if (!$field ||
!$value) {
4844 // Build the WHERE clause for an SQL query.
4845 $params = array('fieldval' => $value);
4846 $constraints = "$field = :fieldval AND deleted <> 1";
4848 // If we are loading user data based on anything other than id,
4849 // we must also restrict our search based on mnet host.
4850 if ($field != 'id') {
4851 if (empty($mnethostid)) {
4852 // If empty, we restrict to local users.
4853 $mnethostid = $CFG->mnet_localhost_id
;
4856 if (!empty($mnethostid)) {
4857 $params['mnethostid'] = $mnethostid;
4858 $constraints .= " AND mnethostid = :mnethostid";
4861 // Get all the basic user data.
4862 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4866 // Get various settings and preferences.
4868 // Preload preference cache.
4869 check_user_preferences_loaded($user);
4871 // Load course enrolment related stuff.
4872 $user->lastcourseaccess
= array(); // During last session.
4873 $user->currentcourseaccess
= array(); // During current session.
4874 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id
))) {
4875 foreach ($lastaccesses as $lastaccess) {
4876 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
4880 $sql = "SELECT g.id, g.courseid
4881 FROM {groups} g, {groups_members} gm
4882 WHERE gm.groupid=g.id AND gm.userid=?";
4884 // This is a special hack to speedup calendar display.
4885 $user->groupmember
= array();
4886 if (!isguestuser($user)) {
4887 if ($groups = $DB->get_records_sql($sql, array($user->id
))) {
4888 foreach ($groups as $group) {
4889 if (!array_key_exists($group->courseid
, $user->groupmember
)) {
4890 $user->groupmember
[$group->courseid
] = array();
4892 $user->groupmember
[$group->courseid
][$group->id
] = $group->id
;
4897 // Add the custom profile fields to the user record.
4898 $user->profile
= array();
4899 if (!isguestuser($user)) {
4900 require_once($CFG->dirroot
.'/user/profile/lib.php');
4901 profile_load_custom_fields($user);
4904 // Rewrite some variables if necessary.
4905 if (!empty($user->description
)) {
4906 // No need to cart all of it around.
4907 $user->description
= true;
4909 if (isguestuser($user)) {
4910 // Guest language always same as site.
4911 $user->lang
= $CFG->lang
;
4912 // Name always in current language.
4913 $user->firstname
= get_string('guestuser');
4914 $user->lastname
= ' ';
4921 * Validate a password against the configured password policy
4923 * @param string $password the password to be checked against the password policy
4924 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4925 * @return bool true if the password is valid according to the policy. false otherwise.
4927 function check_password_policy($password, &$errmsg) {
4930 if (empty($CFG->passwordpolicy
)) {
4935 if (core_text
::strlen($password) < $CFG->minpasswordlength
) {
4936 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength
) .'</div>';
4939 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits
) {
4940 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits
) .'</div>';
4943 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower
) {
4944 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower
) .'</div>';
4947 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper
) {
4948 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper
) .'</div>';
4951 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum
) {
4952 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
) .'</div>';
4954 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars
)) {
4955 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars
) .'</div>';
4958 if ($errmsg == '') {
4967 * When logging in, this function is run to set certain preferences for the current SESSION.
4969 function set_login_session_preferences() {
4972 $SESSION->justloggedin
= true;
4974 unset($SESSION->lang
);
4975 unset($SESSION->forcelang
);
4976 unset($SESSION->load_navigation_admin
);
4981 * Delete a course, including all related data from the database, and any associated files.
4983 * @param mixed $courseorid The id of the course or course object to delete.
4984 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4985 * @return bool true if all the removals succeeded. false if there were any failures. If this
4986 * method returns false, some of the removals will probably have succeeded, and others
4987 * failed, but you have no way of knowing which.
4989 function delete_course($courseorid, $showfeedback = true) {
4992 if (is_object($courseorid)) {
4993 $courseid = $courseorid->id
;
4994 $course = $courseorid;
4996 $courseid = $courseorid;
4997 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5001 $context = context_course
::instance($courseid);
5003 // Frontpage course can not be deleted!!
5004 if ($courseid == SITEID
) {
5008 // Make the course completely empty.
5009 remove_course_contents($courseid, $showfeedback);
5011 // Delete the course and related context instance.
5012 context_helper
::delete_instance(CONTEXT_COURSE
, $courseid);
5014 $DB->delete_records("course", array("id" => $courseid));
5015 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5017 // Reset all course related caches here.
5018 if (class_exists('format_base', false)) {
5019 format_base
::reset_course_cache($courseid);
5022 // Trigger a course deleted event.
5023 $event = \core\event\course_deleted
::create(array(
5024 'objectid' => $course->id
,
5025 'context' => $context,
5027 'shortname' => $course->shortname
,
5028 'fullname' => $course->fullname
,
5029 'idnumber' => $course->idnumber
5032 $event->add_record_snapshot('course', $course);
5039 * Clear a course out completely, deleting all content but don't delete the course itself.
5041 * This function does not verify any permissions.
5043 * Please note this function also deletes all user enrolments,
5044 * enrolment instances and role assignments by default.
5047 * - 'keep_roles_and_enrolments' - false by default
5048 * - 'keep_groups_and_groupings' - false by default
5050 * @param int $courseid The id of the course that is being deleted
5051 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5052 * @param array $options extra options
5053 * @return bool true if all the removals succeeded. false if there were any failures. If this
5054 * method returns false, some of the removals will probably have succeeded, and others
5055 * failed, but you have no way of knowing which.
5057 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5058 global $CFG, $DB, $OUTPUT;
5060 require_once($CFG->libdir
.'/badgeslib.php');
5061 require_once($CFG->libdir
.'/completionlib.php');
5062 require_once($CFG->libdir
.'/questionlib.php');
5063 require_once($CFG->libdir
.'/gradelib.php');
5064 require_once($CFG->dirroot
.'/group/lib.php');
5065 require_once($CFG->dirroot
.'/tag/coursetagslib.php');
5066 require_once($CFG->dirroot
.'/comment/lib.php');
5067 require_once($CFG->dirroot
.'/rating/lib.php');
5068 require_once($CFG->dirroot
.'/notes/lib.php');
5070 // Handle course badges.
5071 badges_handle_course_deletion($courseid);
5073 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5074 $strdeleted = get_string('deleted').' - ';
5076 // Some crazy wishlist of stuff we should skip during purging of course content.
5077 $options = (array)$options;
5079 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST
);
5080 $coursecontext = context_course
::instance($courseid);
5081 $fs = get_file_storage();
5083 // Delete course completion information, this has to be done before grades and enrols.
5084 $cc = new completion_info($course);
5085 $cc->clear_criteria();
5086 if ($showfeedback) {
5087 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5090 // Remove all data from gradebook - this needs to be done before course modules
5091 // because while deleting this information, the system may need to reference
5092 // the course modules that own the grades.
5093 remove_course_grades($courseid, $showfeedback);
5094 remove_grade_letters($coursecontext, $showfeedback);
5096 // Delete course blocks in any all child contexts,
5097 // they may depend on modules so delete them first.
5098 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5099 foreach ($childcontexts as $childcontext) {
5100 blocks_delete_all_for_context($childcontext->id
);
5102 unset($childcontexts);
5103 blocks_delete_all_for_context($coursecontext->id
);
5104 if ($showfeedback) {
5105 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5108 // Delete every instance of every module,
5109 // this has to be done before deleting of course level stuff.
5110 $locations = core_component
::get_plugin_list('mod');
5111 foreach ($locations as $modname => $moddir) {
5112 if ($modname === 'NEWMODULE') {
5115 if ($module = $DB->get_record('modules', array('name' => $modname))) {
5116 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5117 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5118 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
5120 if ($instances = $DB->get_records($modname, array('course' => $course->id
))) {
5121 foreach ($instances as $instance) {
5122 if ($cm = get_coursemodule_from_instance($modname, $instance->id
, $course->id
)) {
5123 // Delete activity context questions and question categories.
5124 question_delete_activity($cm, $showfeedback);
5126 if (function_exists($moddelete)) {
5127 // This purges all module data in related tables, extra user prefs, settings, etc.
5128 $moddelete($instance->id
);
5130 // NOTE: we should not allow installation of modules with missing delete support!
5131 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5132 $DB->delete_records($modname, array('id' => $instance->id
));
5136 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5137 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5138 $DB->delete_records('course_modules', array('id' => $cm->id
));
5142 if (function_exists($moddeletecourse)) {
5143 // Execute ptional course cleanup callback.
5144 $moddeletecourse($course, $showfeedback);
5146 if ($instances and $showfeedback) {
5147 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5150 // Ooops, this module is not properly installed, force-delete it in the next block.
5154 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5156 // Remove all data from availability and completion tables that is associated
5157 // with course-modules belonging to this course. Note this is done even if the
5158 // features are not enabled now, in case they were enabled previously.
5159 $DB->delete_records_select('course_modules_completion',
5160 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5163 // Remove course-module data.
5164 $cms = $DB->get_records('course_modules', array('course' => $course->id
));
5165 foreach ($cms as $cm) {
5166 if ($module = $DB->get_record('modules', array('id' => $cm->module
))) {
5168 $DB->delete_records($module->name
, array('id' => $cm->instance
));
5169 } catch (Exception
$e) {
5170 // Ignore weird or missing table problems.
5173 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
5174 $DB->delete_records('course_modules', array('id' => $cm->id
));
5177 if ($showfeedback) {
5178 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5181 // Cleanup the rest of plugins.
5182 $cleanuplugintypes = array('report', 'coursereport', 'format');
5183 foreach ($cleanuplugintypes as $type) {
5184 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
5185 foreach ($plugins as $plugin => $pluginfunction) {
5186 $pluginfunction($course->id
, $showfeedback);
5188 if ($showfeedback) {
5189 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5193 // Delete questions and question categories.
5194 question_delete_course($course, $showfeedback);
5195 if ($showfeedback) {
5196 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5199 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5200 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5201 foreach ($childcontexts as $childcontext) {
5202 $childcontext->delete();
5204 unset($childcontexts);
5206 // Remove all roles and enrolments by default.
5207 if (empty($options['keep_roles_and_enrolments'])) {
5208 // This hack is used in restore when deleting contents of existing course.
5209 role_unassign_all(array('contextid' => $coursecontext->id
, 'component' => ''), true);
5210 enrol_course_delete($course);
5211 if ($showfeedback) {
5212 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5216 // Delete any groups, removing members and grouping/course links first.
5217 if (empty($options['keep_groups_and_groupings'])) {
5218 groups_delete_groupings($course->id
, $showfeedback);
5219 groups_delete_groups($course->id
, $showfeedback);
5223 filter_delete_all_for_context($coursecontext->id
);
5225 // Notes, you shall not pass!
5226 note_delete_all($course->id
);
5229 comment
::delete_comments($coursecontext->id
);
5231 // Ratings are history too.
5232 $delopt = new stdclass();
5233 $delopt->contextid
= $coursecontext->id
;
5234 $rm = new rating_manager();
5235 $rm->delete_ratings($delopt);
5237 // Delete course tags.
5238 coursetag_delete_course_tags($course->id
, $showfeedback);
5240 // Delete calendar events.
5241 $DB->delete_records('event', array('courseid' => $course->id
));
5242 $fs->delete_area_files($coursecontext->id
, 'calendar');
5244 // Delete all related records in other core tables that may have a courseid
5245 // This array stores the tables that need to be cleared, as
5246 // table_name => column_name that contains the course id.
5247 $tablestoclear = array(
5248 'backup_courses' => 'courseid', // Scheduled backup stuff.
5249 'user_lastaccess' => 'courseid', // User access info.
5251 foreach ($tablestoclear as $table => $col) {
5252 $DB->delete_records($table, array($col => $course->id
));
5255 // Delete all course backup files.
5256 $fs->delete_area_files($coursecontext->id
, 'backup');
5258 // Cleanup course record - remove links to deleted stuff.
5259 $oldcourse = new stdClass();
5260 $oldcourse->id
= $course->id
;
5261 $oldcourse->summary
= '';
5262 $oldcourse->cacherev
= 0;
5263 $oldcourse->legacyfiles
= 0;
5264 $oldcourse->enablecompletion
= 0;
5265 if (!empty($options['keep_groups_and_groupings'])) {
5266 $oldcourse->defaultgroupingid
= 0;
5268 $DB->update_record('course', $oldcourse);
5270 // Delete course sections.
5271 $DB->delete_records('course_sections', array('course' => $course->id
));
5273 // Delete legacy, section and any other course files.
5274 $fs->delete_area_files($coursecontext->id
, 'course'); // Files from summary and section.
5276 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5277 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5278 // Easy, do not delete the context itself...
5279 $coursecontext->delete_content();
5282 // We can not drop all context stuff because it would bork enrolments and roles,
5283 // there might be also files used by enrol plugins...
5286 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5287 // also some non-standard unsupported plugins may try to store something there.
5288 fulldelete($CFG->dataroot
.'/'.$course->id
);
5290 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5291 $cachemodinfo = cache
::make('core', 'coursemodinfo');
5292 $cachemodinfo->delete($courseid);
5294 // Trigger a course content deleted event.
5295 $event = \core\event\course_content_deleted
::create(array(
5296 'objectid' => $course->id
,
5297 'context' => $coursecontext,
5298 'other' => array('shortname' => $course->shortname
,
5299 'fullname' => $course->fullname
,
5300 'options' => $options) // Passing this for legacy reasons.
5302 $event->add_record_snapshot('course', $course);
5309 * Change dates in module - used from course reset.
5311 * @param string $modname forum, assignment, etc
5312 * @param array $fields array of date fields from mod table
5313 * @param int $timeshift time difference
5314 * @param int $courseid
5315 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5316 * @return bool success
5318 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5320 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
5323 $params = array($timeshift, $courseid);
5324 foreach ($fields as $field) {
5325 $updatesql = "UPDATE {".$modname."}
5326 SET $field = $field + ?
5327 WHERE course=? AND $field<>0";
5329 $updatesql .= ' AND id=?';
5332 $return = $DB->execute($updatesql, $params) && $return;
5335 $refreshfunction = $modname.'_refresh_events';
5336 if (function_exists($refreshfunction)) {
5337 $refreshfunction($courseid);
5344 * This function will empty a course of user data.
5345 * It will retain the activities and the structure of the course.
5347 * @param object $data an object containing all the settings including courseid (without magic quotes)
5348 * @return array status array of array component, item, error
5350 function reset_course_userdata($data) {
5352 require_once($CFG->libdir
.'/gradelib.php');
5353 require_once($CFG->libdir
.'/completionlib.php');
5354 require_once($CFG->dirroot
.'/group/lib.php');
5356 $data->courseid
= $data->id
;
5357 $context = context_course
::instance($data->courseid
);
5359 $eventparams = array(
5360 'context' => $context,
5361 'courseid' => $data->id
,
5363 'reset_options' => (array) $data
5366 $event = \core\event\course_reset_started
::create($eventparams);
5369 // Calculate the time shift of dates.
5370 if (!empty($data->reset_start_date
)) {
5371 // Time part of course startdate should be zero.
5372 $data->timeshift
= $data->reset_start_date
- usergetmidnight($data->reset_start_date_old
);
5374 $data->timeshift
= 0;
5377 // Result array: component, item, error.
5380 // Start the resetting.
5381 $componentstr = get_string('general');
5383 // Move the course start time.
5384 if (!empty($data->reset_start_date
) and $data->timeshift
) {
5385 // Change course start data.
5386 $DB->set_field('course', 'startdate', $data->reset_start_date
, array('id' => $data->courseid
));
5387 // Update all course and group events - do not move activity events.
5388 $updatesql = "UPDATE {event}
5389 SET timestart = timestart + ?
5390 WHERE courseid=? AND instance=0";
5391 $DB->execute($updatesql, array($data->timeshift
, $data->courseid
));
5393 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5396 if (!empty($data->reset_events
)) {
5397 $DB->delete_records('event', array('courseid' => $data->courseid
));
5398 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5401 if (!empty($data->reset_notes
)) {
5402 require_once($CFG->dirroot
.'/notes/lib.php');
5403 note_delete_all($data->courseid
);
5404 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5407 if (!empty($data->delete_blog_associations
)) {
5408 require_once($CFG->dirroot
.'/blog/lib.php');
5409 blog_remove_associations_for_course($data->courseid
);
5410 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5413 if (!empty($data->reset_completion
)) {
5414 // Delete course and activity completion information.
5415 $course = $DB->get_record('course', array('id' => $data->courseid
));
5416 $cc = new completion_info($course);
5417 $cc->delete_all_completion_data();
5418 $status[] = array('component' => $componentstr,
5419 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5422 $componentstr = get_string('roles');
5424 if (!empty($data->reset_roles_overrides
)) {
5425 $children = $context->get_child_contexts();
5426 foreach ($children as $child) {
5427 $DB->delete_records('role_capabilities', array('contextid' => $child->id
));
5429 $DB->delete_records('role_capabilities', array('contextid' => $context->id
));
5430 // Force refresh for logged in users.
5431 $context->mark_dirty();
5432 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5435 if (!empty($data->reset_roles_local
)) {
5436 $children = $context->get_child_contexts();
5437 foreach ($children as $child) {
5438 role_unassign_all(array('contextid' => $child->id
));
5440 // Force refresh for logged in users.
5441 $context->mark_dirty();
5442 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5445 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5446 $data->unenrolled
= array();
5447 if (!empty($data->unenrol_users
)) {
5448 $plugins = enrol_get_plugins(true);
5449 $instances = enrol_get_instances($data->courseid
, true);
5450 foreach ($instances as $key => $instance) {
5451 if (!isset($plugins[$instance->enrol
])) {
5452 unset($instances[$key]);
5457 foreach ($data->unenrol_users
as $withroleid) {
5460 FROM {user_enrolments} ue
5461 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5462 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5463 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5464 $params = array('courseid' => $data->courseid
, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE
);
5467 // Without any role assigned at course context.
5469 FROM {user_enrolments} ue
5470 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5471 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5472 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5473 WHERE ra.id IS null";
5474 $params = array('courseid' => $data->courseid
, 'courselevel' => CONTEXT_COURSE
);
5477 $rs = $DB->get_recordset_sql($sql, $params);
5478 foreach ($rs as $ue) {
5479 if (!isset($instances[$ue->enrolid
])) {
5482 $instance = $instances[$ue->enrolid
];
5483 $plugin = $plugins[$instance->enrol
];
5484 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5488 $plugin->unenrol_user($instance, $ue->userid
);
5489 $data->unenrolled
[$ue->userid
] = $ue->userid
;
5494 if (!empty($data->unenrolled
)) {
5496 'component' => $componentstr,
5497 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled
).')',
5502 $componentstr = get_string('groups');
5504 // Remove all group members.
5505 if (!empty($data->reset_groups_members
)) {
5506 groups_delete_group_members($data->courseid
);
5507 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5510 // Remove all groups.
5511 if (!empty($data->reset_groups_remove
)) {
5512 groups_delete_groups($data->courseid
, false);
5513 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5516 // Remove all grouping members.
5517 if (!empty($data->reset_groupings_members
)) {
5518 groups_delete_groupings_groups($data->courseid
, false);
5519 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5522 // Remove all groupings.
5523 if (!empty($data->reset_groupings_remove
)) {
5524 groups_delete_groupings($data->courseid
, false);
5525 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5528 // Look in every instance of every module for data to delete.
5529 $unsupportedmods = array();
5530 if ($allmods = $DB->get_records('modules') ) {
5531 foreach ($allmods as $mod) {
5532 $modname = $mod->name
;
5533 $modfile = $CFG->dirroot
.'/mod/'. $modname.'/lib.php';
5534 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5535 if (file_exists($modfile)) {
5536 if (!$DB->count_records($modname, array('course' => $data->courseid
))) {
5537 continue; // Skip mods with no instances.
5539 include_once($modfile);
5540 if (function_exists($moddeleteuserdata)) {
5541 $modstatus = $moddeleteuserdata($data);
5542 if (is_array($modstatus)) {
5543 $status = array_merge($status, $modstatus);
5545 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5548 $unsupportedmods[] = $mod;
5551 debugging('Missing lib.php in '.$modname.' module!');
5556 // Mention unsupported mods.
5557 if (!empty($unsupportedmods)) {
5558 foreach ($unsupportedmods as $mod) {
5560 'component' => get_string('modulenameplural', $mod->name
),
5562 'error' => get_string('resetnotimplemented')
5567 $componentstr = get_string('gradebook', 'grades');
5568 // Reset gradebook,.
5569 if (!empty($data->reset_gradebook_items
)) {
5570 remove_course_grades($data->courseid
, false);
5571 grade_grab_course_grades($data->courseid
);
5572 grade_regrade_final_grades($data->courseid
);
5573 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5575 } else if (!empty($data->reset_gradebook_grades
)) {
5576 grade_course_reset($data->courseid
);
5577 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5580 if (!empty($data->reset_comments
)) {
5581 require_once($CFG->dirroot
.'/comment/lib.php');
5582 comment
::reset_course_page_comments($context);
5585 $event = \core\event\course_reset_ended
::create($eventparams);
5592 * Generate an email processing address.
5595 * @param string $modargs
5596 * @return string Returns email processing address
5598 function generate_email_processing_address($modid, $modargs) {
5601 $header = $CFG->mailprefix
. substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5602 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain
;
5608 * @todo Finish documenting this function
5610 * @param string $modargs
5611 * @param string $body Currently unused
5613 function moodle_process_email($modargs, $body) {
5616 // The first char should be an unencoded letter. We'll take this as an action.
5617 switch ($modargs{0}) {
5618 case 'B': { // Bounce.
5619 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5620 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5621 // Check the half md5 of their email.
5622 $md5check = substr(md5($user->email
), 0, 16);
5623 if ($md5check == substr($modargs, -16)) {
5624 set_bounce_count($user);
5626 // Else maybe they've already changed it?
5630 // Maybe more later?
5637 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5639 * @param string $action 'get', 'buffer', 'close' or 'flush'
5640 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5642 function get_mailer($action='get') {
5645 /** @var moodle_phpmailer $mailer */
5646 static $mailer = null;
5647 static $counter = 0;
5649 if (!isset($CFG->smtpmaxbulk
)) {
5650 $CFG->smtpmaxbulk
= 1;
5653 if ($action == 'get') {
5654 $prevkeepalive = false;
5656 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5657 if ($counter < $CFG->smtpmaxbulk
and !$mailer->isError()) {
5659 // Reset the mailer.
5660 $mailer->Priority
= 3;
5661 $mailer->CharSet
= 'UTF-8'; // Our default.
5662 $mailer->ContentType
= "text/plain";
5663 $mailer->Encoding
= "8bit";
5664 $mailer->From
= "root@localhost";
5665 $mailer->FromName
= "Root User";
5666 $mailer->Sender
= "";
5667 $mailer->Subject
= "";
5669 $mailer->AltBody
= "";
5670 $mailer->ConfirmReadingTo
= "";
5672 $mailer->clearAllRecipients();
5673 $mailer->clearReplyTos();
5674 $mailer->clearAttachments();
5675 $mailer->clearCustomHeaders();
5679 $prevkeepalive = $mailer->SMTPKeepAlive
;
5680 get_mailer('flush');
5683 require_once($CFG->libdir
.'/phpmailer/moodle_phpmailer.php');
5684 $mailer = new moodle_phpmailer();
5688 if ($CFG->smtphosts
== 'qmail') {
5689 // Use Qmail system.
5692 } else if (empty($CFG->smtphosts
)) {
5693 // Use PHP mail() = sendmail.
5697 // Use SMTP directly.
5699 if (!empty($CFG->debugsmtp
)) {
5700 $mailer->SMTPDebug
= true;
5702 // Specify main and backup servers.
5703 $mailer->Host
= $CFG->smtphosts
;
5704 // Specify secure connection protocol.
5705 $mailer->SMTPSecure
= $CFG->smtpsecure
;
5706 // Use previous keepalive.
5707 $mailer->SMTPKeepAlive
= $prevkeepalive;
5709 if ($CFG->smtpuser
) {
5710 // Use SMTP authentication.
5711 $mailer->SMTPAuth
= true;
5712 $mailer->Username
= $CFG->smtpuser
;
5713 $mailer->Password
= $CFG->smtppass
;
5722 // Keep smtp session open after sending.
5723 if ($action == 'buffer') {
5724 if (!empty($CFG->smtpmaxbulk
)) {
5725 get_mailer('flush');
5727 if ($m->Mailer
== 'smtp') {
5728 $m->SMTPKeepAlive
= true;
5734 // Close smtp session, but continue buffering.
5735 if ($action == 'flush') {
5736 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5737 if (!empty($mailer->SMTPDebug
)) {
5740 $mailer->SmtpClose();
5741 if (!empty($mailer->SMTPDebug
)) {
5748 // Close smtp session, do not buffer anymore.
5749 if ($action == 'close') {
5750 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5751 get_mailer('flush');
5752 $mailer->SMTPKeepAlive
= false;
5754 $mailer = null; // Better force new instance.
5760 * Send an email to a specified user
5762 * @param stdClass $user A {@link $USER} object
5763 * @param stdClass $from A {@link $USER} object
5764 * @param string $subject plain text subject line of the email
5765 * @param string $messagetext plain text version of the message
5766 * @param string $messagehtml complete html version of the message (optional)
5767 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5768 * @param string $attachname the name of the file (extension indicates MIME)
5769 * @param bool $usetrueaddress determines whether $from email address should
5770 * be sent out. Will be overruled by user profile setting for maildisplay
5771 * @param string $replyto Email address to reply to
5772 * @param string $replytoname Name of reply to recipient
5773 * @param int $wordwrapwidth custom word wrap width, default 79
5774 * @return bool Returns true if mail was sent OK and false if there was an error.
5776 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5777 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5781 if (empty($user) or empty($user->id
)) {
5782 debugging('Can not send email to null user', DEBUG_DEVELOPER
);
5786 if (empty($user->email
)) {
5787 debugging('Can not send email to user without email: '.$user->id
, DEBUG_DEVELOPER
);
5791 if (!empty($user->deleted
)) {
5792 debugging('Can not send email to deleted user: '.$user->id
, DEBUG_DEVELOPER
);
5796 if (defined('BEHAT_SITE_RUNNING')) {
5797 // Fake email sending in behat.
5801 if (!empty($CFG->noemailever
)) {
5802 // Hidden setting for development sites, set in config.php if needed.
5803 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL
);
5807 if (!empty($CFG->divertallemailsto
)) {
5808 $subject = "[DIVERTED {$user->email}] $subject";
5809 $user = clone($user);
5810 $user->email
= $CFG->divertallemailsto
;
5813 // Skip mail to suspended users.
5814 if ((isset($user->auth
) && $user->auth
=='nologin') or (isset($user->suspended
) && $user->suspended
)) {
5818 if (!validate_email($user->email
)) {
5819 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5820 $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
5821 error_log($invalidemail);
5823 mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
5828 if (over_bounce_threshold($user)) {
5829 $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
5830 error_log($bouncemsg);
5832 mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
5837 // If the user is a remote mnet user, parse the email text for URL to the
5838 // wwwroot and modify the url to direct the user's browser to login at their
5839 // home site (identity provider - idp) before hitting the link itself.
5840 if (is_mnet_remote_user($user)) {
5841 require_once($CFG->dirroot
.'/mnet/lib.php');
5843 $jumpurl = mnet_get_idp_jump_url($user);
5844 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5846 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5849 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5853 $mail = get_mailer();
5855 if (!empty($mail->SMTPDebug
)) {
5856 echo '<pre>' . "\n";
5859 $temprecipients = array();
5860 $tempreplyto = array();
5862 $supportuser = core_user
::get_support_user();
5864 // Make up an email address for handling bounces.
5865 if (!empty($CFG->handlebounces
)) {
5866 $modargs = 'B'.base64_encode(pack('V', $user->id
)).substr(md5($user->email
), 0, 16);
5867 $mail->Sender
= generate_email_processing_address(0, $modargs);
5869 $mail->Sender
= $supportuser->email
;
5872 if (!empty($CFG->emailonlyfromnoreplyaddress
)) {
5873 $usetrueaddress = false;
5874 if (empty($replyto) && $from->maildisplay
) {
5875 $replyto = $from->email
;
5876 $replytoname = fullname($from);
5880 if (is_string($from)) { // So we can pass whatever we want if there is need.
5881 $mail->From
= $CFG->noreplyaddress
;
5882 $mail->FromName
= $from;
5883 } else if ($usetrueaddress and $from->maildisplay
) {
5884 $mail->From
= $from->email
;
5885 $mail->FromName
= fullname($from);
5887 $mail->From
= $CFG->noreplyaddress
;
5888 $mail->FromName
= fullname($from);
5889 if (empty($replyto)) {
5890 $tempreplyto[] = array($CFG->noreplyaddress
, get_string('noreplyname'));
5894 if (!empty($replyto)) {
5895 $tempreplyto[] = array($replyto, $replytoname);
5898 $mail->Subject
= substr($subject, 0, 900);
5900 $temprecipients[] = array($user->email
, fullname($user));
5903 $mail->WordWrap
= $wordwrapwidth;
5905 if (!empty($from->customheaders
)) {
5906 // Add custom headers.
5907 if (is_array($from->customheaders
)) {
5908 foreach ($from->customheaders
as $customheader) {
5909 $mail->addCustomHeader($customheader);
5912 $mail->addCustomHeader($from->customheaders
);
5916 if (!empty($from->priority
)) {
5917 $mail->Priority
= $from->priority
;
5920 if ($messagehtml && !empty($user->mailformat
) && $user->mailformat
== 1) {
5921 // Don't ever send HTML to users who don't want it.
5922 $mail->isHTML(true);
5923 $mail->Encoding
= 'quoted-printable';
5924 $mail->Body
= $messagehtml;
5925 $mail->AltBody
= "\n$messagetext\n";
5927 $mail->IsHTML(false);
5928 $mail->Body
= "\n$messagetext\n";
5931 if ($attachment && $attachname) {
5932 if (preg_match( "~\\.\\.~" , $attachment )) {
5933 // Security check for ".." in dir path.
5934 $temprecipients[] = array($supportuser->email
, fullname($supportuser, true));
5935 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5937 require_once($CFG->libdir
.'/filelib.php');
5938 $mimetype = mimeinfo('type', $attachname);
5940 $attachmentpath = $attachment;
5942 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5943 $attachpath = str_replace('\\', '/', $attachmentpath);
5944 // Make sure both variables are normalised before comparing.
5945 $temppath = str_replace('\\', '/', $CFG->tempdir
);
5947 // If the attachment is a full path to a file in the tempdir, use it as is,
5948 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5949 if (strpos($attachpath, realpath($temppath)) !== 0) {
5950 $attachmentpath = $CFG->dataroot
. '/' . $attachmentpath;
5953 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5957 // Check if the email should be sent in an other charset then the default UTF-8.
5958 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
5960 // Use the defined site mail charset or eventually the one preferred by the recipient.
5961 $charset = $CFG->sitemailcharset
;
5962 if (!empty($CFG->allowusermailcharset
)) {
5963 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
5964 $charset = $useremailcharset;
5968 // Convert all the necessary strings if the charset is supported.
5969 $charsets = get_list_of_charsets();
5970 unset($charsets['UTF-8']);
5971 if (in_array($charset, $charsets)) {
5972 $mail->CharSet
= $charset;
5973 $mail->FromName
= core_text
::convert($mail->FromName
, 'utf-8', strtolower($charset));
5974 $mail->Subject
= core_text
::convert($mail->Subject
, 'utf-8', strtolower($charset));
5975 $mail->Body
= core_text
::convert($mail->Body
, 'utf-8', strtolower($charset));
5976 $mail->AltBody
= core_text
::convert($mail->AltBody
, 'utf-8', strtolower($charset));
5978 foreach ($temprecipients as $key => $values) {
5979 $temprecipients[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
5981 foreach ($tempreplyto as $key => $values) {
5982 $tempreplyto[$key][1] = core_text
::convert($values[1], 'utf-8', strtolower($charset));
5987 foreach ($temprecipients as $values) {
5988 $mail->addAddress($values[0], $values[1]);
5990 foreach ($tempreplyto as $values) {
5991 $mail->addReplyTo($values[0], $values[1]);
5994 if ($mail->send()) {
5995 set_send_count($user);
5996 if (!empty($mail->SMTPDebug
)) {
6001 // Trigger event for failing to send email.
6002 $event = \core\event\email_failed
::create(array(
6003 'context' => context_system
::instance(),
6004 'userid' => $from->id
,
6005 'relateduserid' => $user->id
,
6007 'subject' => $subject,
6008 'message' => $messagetext,
6009 'errorinfo' => $mail->ErrorInfo
6014 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo
);
6016 if (!empty($mail->SMTPDebug
)) {
6024 * Generate a signoff for emails based on support settings
6028 function generate_email_signoff() {
6032 if (!empty($CFG->supportname
)) {
6033 $signoff .= $CFG->supportname
."\n";
6035 if (!empty($CFG->supportemail
)) {
6036 $signoff .= $CFG->supportemail
."\n";
6038 if (!empty($CFG->supportpage
)) {
6039 $signoff .= $CFG->supportpage
."\n";
6045 * Sets specified user's password and send the new password to the user via email.
6047 * @param stdClass $user A {@link $USER} object
6048 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6049 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6051 function setnew_password_and_mail($user, $fasthash = false) {
6054 // We try to send the mail in language the user understands,
6055 // unfortunately the filter_string() does not support alternative langs yet
6056 // so multilang will not work properly for site->fullname.
6057 $lang = empty($user->lang
) ?
$CFG->lang
: $user->lang
;
6061 $supportuser = core_user
::get_support_user();
6063 $newpassword = generate_password();
6065 update_internal_user_password($user, $newpassword, $fasthash);
6067 $a = new stdClass();
6068 $a->firstname
= fullname($user, true);
6069 $a->sitename
= format_string($site->fullname
);
6070 $a->username
= $user->username
;
6071 $a->newpassword
= $newpassword;
6072 $a->link
= $CFG->wwwroot
.'/login/';
6073 $a->signoff
= generate_email_signoff();
6075 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6077 $subject = format_string($site->fullname
) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6079 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6080 return email_to_user($user, $supportuser, $subject, $message);
6085 * Resets specified user's password and send the new password to the user via email.
6087 * @param stdClass $user A {@link $USER} object
6088 * @return bool Returns true if mail was sent OK and false if there was an error.
6090 function reset_password_and_mail($user) {
6094 $supportuser = core_user
::get_support_user();
6096 $userauth = get_auth_plugin($user->auth
);
6097 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth
)) {
6098 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6102 $newpassword = generate_password();
6104 if (!$userauth->user_update_password($user, $newpassword)) {
6105 print_error("cannotsetpassword");
6108 $a = new stdClass();
6109 $a->firstname
= $user->firstname
;
6110 $a->lastname
= $user->lastname
;
6111 $a->sitename
= format_string($site->fullname
);
6112 $a->username
= $user->username
;
6113 $a->newpassword
= $newpassword;
6114 $a->link
= $CFG->httpswwwroot
.'/login/change_password.php';
6115 $a->signoff
= generate_email_signoff();
6117 $message = get_string('newpasswordtext', '', $a);
6119 $subject = format_string($site->fullname
) .': '. get_string('changedpassword');
6121 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6123 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6124 return email_to_user($user, $supportuser, $subject, $message);
6128 * Send email to specified user with confirmation text and activation link.
6130 * @param stdClass $user A {@link $USER} object
6131 * @return bool Returns true if mail was sent OK and false if there was an error.
6133 function send_confirmation_email($user) {
6137 $supportuser = core_user
::get_support_user();
6139 $data = new stdClass();
6140 $data->firstname
= fullname($user);
6141 $data->sitename
= format_string($site->fullname
);
6142 $data->admin
= generate_email_signoff();
6144 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname
));
6146 $username = urlencode($user->username
);
6147 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
6148 $data->link
= $CFG->wwwroot
.'/login/confirm.php?data='. $user->secret
.'/'. $username;
6149 $message = get_string('emailconfirmation', '', $data);
6150 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6152 $user->mailformat
= 1; // Always send HTML version as well.
6154 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6155 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6159 * Sends a password change confirmation email.
6161 * @param stdClass $user A {@link $USER} object
6162 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6163 * @return bool Returns true if mail was sent OK and false if there was an error.
6165 function send_password_change_confirmation_email($user, $resetrecord) {
6169 $supportuser = core_user
::get_support_user();
6170 $pwresetmins = isset($CFG->pwresettime
) ?
floor($CFG->pwresettime
/ MINSECS
) : 30;
6172 $data = new stdClass();
6173 $data->firstname
= $user->firstname
;
6174 $data->lastname
= $user->lastname
;
6175 $data->username
= $user->username
;
6176 $data->sitename
= format_string($site->fullname
);
6177 $data->link
= $CFG->httpswwwroot
.'/login/forgot_password.php?token='. $resetrecord->token
;
6178 $data->admin
= generate_email_signoff();
6179 $data->resetminutes
= $pwresetmins;
6181 $message = get_string('emailresetconfirmation', '', $data);
6182 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname
));
6184 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6185 return email_to_user($user, $supportuser, $subject, $message);
6190 * Sends an email containinginformation on how to change your password.
6192 * @param stdClass $user A {@link $USER} object
6193 * @return bool Returns true if mail was sent OK and false if there was an error.
6195 function send_password_change_info($user) {
6199 $supportuser = core_user
::get_support_user();
6200 $systemcontext = context_system
::instance();
6202 $data = new stdClass();
6203 $data->firstname
= $user->firstname
;
6204 $data->lastname
= $user->lastname
;
6205 $data->sitename
= format_string($site->fullname
);
6206 $data->admin
= generate_email_signoff();
6208 $userauth = get_auth_plugin($user->auth
);
6210 if (!is_enabled_auth($user->auth
) or $user->auth
== 'nologin') {
6211 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6212 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6213 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6214 return email_to_user($user, $supportuser, $subject, $message);
6217 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6218 // We have some external url for password changing.
6219 $data->link
.= $userauth->change_password_url();
6222 // No way to change password, sorry.
6226 if (!empty($data->link
) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id
)) {
6227 $message = get_string('emailpasswordchangeinfo', '', $data);
6228 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6230 $message = get_string('emailpasswordchangeinfofail', '', $data);
6231 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
6234 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6235 return email_to_user($user, $supportuser, $subject, $message);
6240 * Check that an email is allowed. It returns an error message if there was a problem.
6242 * @param string $email Content of email
6243 * @return string|false
6245 function email_is_not_allowed($email) {
6248 if (!empty($CFG->allowemailaddresses
)) {
6249 $allowed = explode(' ', $CFG->allowemailaddresses
);
6250 foreach ($allowed as $allowedpattern) {
6251 $allowedpattern = trim($allowedpattern);
6252 if (!$allowedpattern) {
6255 if (strpos($allowedpattern, '.') === 0) {
6256 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6257 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6261 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6265 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
6267 } else if (!empty($CFG->denyemailaddresses
)) {
6268 $denied = explode(' ', $CFG->denyemailaddresses
);
6269 foreach ($denied as $deniedpattern) {
6270 $deniedpattern = trim($deniedpattern);
6271 if (!$deniedpattern) {
6274 if (strpos($deniedpattern, '.') === 0) {
6275 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6276 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6277 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6280 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6281 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
6292 * Returns local file storage instance
6294 * @return file_storage
6296 function get_file_storage() {
6305 require_once("$CFG->libdir/filelib.php");
6307 if (isset($CFG->filedir
)) {
6308 $filedir = $CFG->filedir
;
6310 $filedir = $CFG->dataroot
.'/filedir';
6313 if (isset($CFG->trashdir
)) {
6314 $trashdirdir = $CFG->trashdir
;
6316 $trashdirdir = $CFG->dataroot
.'/trashdir';
6319 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions
, $CFG->filepermissions
);
6325 * Returns local file storage instance
6327 * @return file_browser
6329 function get_file_browser() {
6338 require_once("$CFG->libdir/filelib.php");
6340 $fb = new file_browser();
6346 * Returns file packer
6348 * @param string $mimetype default application/zip
6349 * @return file_packer
6351 function get_file_packer($mimetype='application/zip') {
6354 static $fp = array();
6356 if (isset($fp[$mimetype])) {
6357 return $fp[$mimetype];
6360 switch ($mimetype) {
6361 case 'application/zip':
6362 case 'application/vnd.moodle.profiling':
6363 $classname = 'zip_packer';
6366 case 'application/x-gzip' :
6367 $classname = 'tgz_packer';
6370 case 'application/vnd.moodle.backup':
6371 $classname = 'mbz_packer';
6378 require_once("$CFG->libdir/filestorage/$classname.php");
6379 $fp[$mimetype] = new $classname();
6381 return $fp[$mimetype];
6385 * Returns current name of file on disk if it exists.
6387 * @param string $newfile File to be verified
6388 * @return string Current name of file on disk if true
6390 function valid_uploaded_file($newfile) {
6391 if (empty($newfile)) {
6394 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6395 return $newfile['tmp_name'];
6402 * Returns the maximum size for uploading files.
6404 * There are seven possible upload limits:
6405 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6406 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6407 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6408 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6409 * 5. by the Moodle admin in $CFG->maxbytes
6410 * 6. by the teacher in the current course $course->maxbytes
6411 * 7. by the teacher for the current module, eg $assignment->maxbytes
6413 * These last two are passed to this function as arguments (in bytes).
6414 * Anything defined as 0 is ignored.
6415 * The smallest of all the non-zero numbers is returned.
6417 * @todo Finish documenting this function
6419 * @param int $sitebytes Set maximum size
6420 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6421 * @param int $modulebytes Current module ->maxbytes (in bytes)
6422 * @return int The maximum size for uploading files.
6424 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6426 if (! $filesize = ini_get('upload_max_filesize')) {
6429 $minimumsize = get_real_size($filesize);
6431 if ($postsize = ini_get('post_max_size')) {
6432 $postsize = get_real_size($postsize);
6433 if ($postsize < $minimumsize) {
6434 $minimumsize = $postsize;
6438 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6439 $minimumsize = $sitebytes;
6442 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6443 $minimumsize = $coursebytes;
6446 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6447 $minimumsize = $modulebytes;
6450 return $minimumsize;
6454 * Returns the maximum size for uploading files for the current user
6456 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6458 * @param context $context The context in which to check user capabilities
6459 * @param int $sitebytes Set maximum size
6460 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6461 * @param int $modulebytes Current module ->maxbytes (in bytes)
6462 * @param stdClass $user The user
6463 * @return int The maximum size for uploading files.
6465 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6472 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6473 return USER_CAN_IGNORE_FILE_SIZE_LIMITS
;
6476 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6480 * Returns an array of possible sizes in local language
6482 * Related to {@link get_max_upload_file_size()} - this function returns an
6483 * array of possible sizes in an array, translated to the
6486 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6488 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6489 * with the value set to 0. This option will be the first in the list.
6491 * @uses SORT_NUMERIC
6492 * @param int $sitebytes Set maximum size
6493 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6494 * @param int $modulebytes Current module ->maxbytes (in bytes)
6495 * @param int|array $custombytes custom upload size/s which will be added to list,
6496 * Only value/s smaller then maxsize will be added to list.
6499 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6502 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6506 if ($sitebytes == 0) {
6507 // Will get the minimum of upload_max_filesize or post_max_size.
6508 $sitebytes = get_max_upload_file_size();
6511 $filesize = array();
6512 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6513 5242880, 10485760, 20971520, 52428800, 104857600);
6515 // If custombytes is given and is valid then add it to the list.
6516 if (is_number($custombytes) and $custombytes > 0) {
6517 $custombytes = (int)$custombytes;
6518 if (!in_array($custombytes, $sizelist)) {
6519 $sizelist[] = $custombytes;
6521 } else if (is_array($custombytes)) {
6522 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6525 // Allow maxbytes to be selected if it falls outside the above boundaries.
6526 if (isset($CFG->maxbytes
) && !in_array(get_real_size($CFG->maxbytes
), $sizelist)) {
6527 // Note: get_real_size() is used in order to prevent problems with invalid values.
6528 $sizelist[] = get_real_size($CFG->maxbytes
);
6531 foreach ($sizelist as $sizebytes) {
6532 if ($sizebytes < $maxsize && $sizebytes > 0) {
6533 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6540 (($modulebytes < $coursebytes ||
$coursebytes == 0) &&
6541 ($modulebytes < $sitebytes ||
$sitebytes == 0))) {
6542 $limitlevel = get_string('activity', 'core');
6543 $displaysize = display_size($modulebytes);
6544 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6546 } else if ($coursebytes && ($coursebytes < $sitebytes ||
$sitebytes == 0)) {
6547 $limitlevel = get_string('course', 'core');
6548 $displaysize = display_size($coursebytes);
6549 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6551 } else if ($sitebytes) {
6552 $limitlevel = get_string('site', 'core');
6553 $displaysize = display_size($sitebytes);
6554 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6557 krsort($filesize, SORT_NUMERIC
);
6559 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6560 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) +
$filesize;
6567 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6569 * If excludefiles is defined, then that file/directory is ignored
6570 * If getdirs is true, then (sub)directories are included in the output
6571 * If getfiles is true, then files are included in the output
6572 * (at least one of these must be true!)
6574 * @todo Finish documenting this function. Add examples of $excludefile usage.
6576 * @param string $rootdir A given root directory to start from
6577 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6578 * @param bool $descend If true then subdirectories are recursed as well
6579 * @param bool $getdirs If true then (sub)directories are included in the output
6580 * @param bool $getfiles If true then files are included in the output
6581 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6583 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6587 if (!$getdirs and !$getfiles) { // Nothing to show.
6591 if (!is_dir($rootdir)) { // Must be a directory.
6595 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6599 if (!is_array($excludefiles)) {
6600 $excludefiles = array($excludefiles);
6603 while (false !== ($file = readdir($dir))) {
6604 $firstchar = substr($file, 0, 1);
6605 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6608 $fullfile = $rootdir .'/'. $file;
6609 if (filetype($fullfile) == 'dir') {
6614 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6615 foreach ($subdirs as $subdir) {
6616 $dirs[] = $file .'/'. $subdir;
6619 } else if ($getfiles) {
6632 * Adds up all the files in a directory and works out the size.
6634 * @param string $rootdir The directory to start from
6635 * @param string $excludefile A file to exclude when summing directory size
6636 * @return int The summed size of all files and subfiles within the root directory
6638 function get_directory_size($rootdir, $excludefile='') {
6641 // Do it this way if we can, it's much faster.
6642 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
6643 $command = trim($CFG->pathtodu
).' -sk '.escapeshellarg($rootdir);
6646 exec($command, $output, $return);
6647 if (is_array($output)) {
6648 // We told it to return k.
6649 return get_real_size(intval($output[0]).'k');
6653 if (!is_dir($rootdir)) {
6654 // Must be a directory.
6658 if (!$dir = @opendir
($rootdir)) {
6659 // Can't open it for some reason.
6665 while (false !== ($file = readdir($dir))) {
6666 $firstchar = substr($file, 0, 1);
6667 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6670 $fullfile = $rootdir .'/'. $file;
6671 if (filetype($fullfile) == 'dir') {
6672 $size +
= get_directory_size($fullfile, $excludefile);
6674 $size +
= filesize($fullfile);
6683 * Converts bytes into display form
6685 * @static string $gb Localized string for size in gigabytes
6686 * @static string $mb Localized string for size in megabytes
6687 * @static string $kb Localized string for size in kilobytes
6688 * @static string $b Localized string for size in bytes
6689 * @param int $size The size to convert to human readable form
6692 function display_size($size) {
6694 static $gb, $mb, $kb, $b;
6696 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS
) {
6697 return get_string('unlimited');
6701 $gb = get_string('sizegb');
6702 $mb = get_string('sizemb');
6703 $kb = get_string('sizekb');
6704 $b = get_string('sizeb');
6707 if ($size >= 1073741824) {
6708 $size = round($size / 1073741824 * 10) / 10 . $gb;
6709 } else if ($size >= 1048576) {
6710 $size = round($size / 1048576 * 10) / 10 . $mb;
6711 } else if ($size >= 1024) {
6712 $size = round($size / 1024 * 10) / 10 . $kb;
6714 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6720 * Cleans a given filename by removing suspicious or troublesome characters
6722 * @see clean_param()
6723 * @param string $string file name
6724 * @return string cleaned file name
6726 function clean_filename($string) {
6727 return clean_param($string, PARAM_FILE
);
6731 // STRING TRANSLATION.
6734 * Returns the code for the current language
6739 function current_language() {
6740 global $CFG, $USER, $SESSION, $COURSE;
6742 if (!empty($SESSION->forcelang
)) {
6743 // Allows overriding course-forced language (useful for admins to check
6744 // issues in courses whose language they don't understand).
6745 // Also used by some code to temporarily get language-related information in a
6746 // specific language (see force_current_language()).
6747 $return = $SESSION->forcelang
;
6749 } else if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) {
6750 // Course language can override all other settings for this page.
6751 $return = $COURSE->lang
;
6753 } else if (!empty($SESSION->lang
)) {
6754 // Session language can override other settings.
6755 $return = $SESSION->lang
;
6757 } else if (!empty($USER->lang
)) {
6758 $return = $USER->lang
;
6760 } else if (isset($CFG->lang
)) {
6761 $return = $CFG->lang
;
6767 // Just in case this slipped in from somewhere by accident.
6768 $return = str_replace('_utf8', '', $return);
6774 * Returns parent language of current active language if defined
6777 * @param string $lang null means current language
6780 function get_parent_language($lang=null) {
6782 // Let's hack around the current language.
6783 if (!empty($lang)) {
6784 $oldforcelang = force_current_language($lang);
6787 $parentlang = get_string('parentlanguage', 'langconfig');
6788 if ($parentlang === 'en') {
6792 // Let's hack around the current language.
6793 if (!empty($lang)) {
6794 force_current_language($oldforcelang);
6801 * Force the current language to get strings and dates localised in the given language.
6803 * After calling this function, all strings will be provided in the given language
6804 * until this function is called again, or equivalent code is run.
6806 * @param string $language
6807 * @return string previous $SESSION->forcelang value
6809 function force_current_language($language) {
6811 $sessionforcelang = isset($SESSION->forcelang
) ?
$SESSION->forcelang
: '';
6812 if ($language !== $sessionforcelang) {
6813 // Seting forcelang to null or an empty string disables it's effect.
6814 if (empty($language) ||
get_string_manager()->translation_exists($language, false)) {
6815 $SESSION->forcelang
= $language;
6819 return $sessionforcelang;
6823 * Returns current string_manager instance.
6825 * The param $forcereload is needed for CLI installer only where the string_manager instance
6826 * must be replaced during the install.php script life time.
6829 * @param bool $forcereload shall the singleton be released and new instance created instead?
6830 * @return core_string_manager
6832 function get_string_manager($forcereload=false) {
6835 static $singleton = null;
6840 if ($singleton === null) {
6841 if (empty($CFG->early_install_lang
)) {
6843 if (empty($CFG->langlist
)) {
6844 $translist = array();
6846 $translist = explode(',', $CFG->langlist
);
6849 $singleton = new core_string_manager_standard($CFG->langotherroot
, $CFG->langlocalroot
, $translist);
6852 $singleton = new core_string_manager_install();
6860 * Returns a localized string.
6862 * Returns the translated string specified by $identifier as
6863 * for $module. Uses the same format files as STphp.
6864 * $a is an object, string or number that can be used
6865 * within translation strings
6867 * eg 'hello {$a->firstname} {$a->lastname}'
6870 * If you would like to directly echo the localized string use
6871 * the function {@link print_string()}
6873 * Example usage of this function involves finding the string you would
6874 * like a local equivalent of and using its identifier and module information
6875 * to retrieve it.<br/>
6876 * If you open moodle/lang/en/moodle.php and look near line 278
6877 * you will find a string to prompt a user for their word for 'course'
6879 * $string['course'] = 'Course';
6881 * So if you want to display the string 'Course'
6882 * in any language that supports it on your site
6883 * you just need to use the identifier 'course'
6885 * $mystring = '<strong>'. get_string('course') .'</strong>';
6888 * If the string you want is in another file you'd take a slightly
6889 * different approach. Looking in moodle/lang/en/calendar.php you find
6892 * $string['typecourse'] = 'Course event';
6894 * If you want to display the string "Course event" in any language
6895 * supported you would use the identifier 'typecourse' and the module 'calendar'
6896 * (because it is in the file calendar.php):
6898 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6901 * As a last resort, should the identifier fail to map to a string
6902 * the returned string will be [[ $identifier ]]
6904 * In Moodle 2.3 there is a new argument to this function $lazyload.
6905 * Setting $lazyload to true causes get_string to return a lang_string object
6906 * rather than the string itself. The fetching of the string is then put off until
6907 * the string object is first used. The object can be used by calling it's out
6908 * method or by casting the object to a string, either directly e.g.
6909 * (string)$stringobject
6910 * or indirectly by using the string within another string or echoing it out e.g.
6911 * echo $stringobject
6912 * return "<p>{$stringobject}</p>";
6913 * It is worth noting that using $lazyload and attempting to use the string as an
6914 * array key will cause a fatal error as objects cannot be used as array keys.
6915 * But you should never do that anyway!
6916 * For more information {@link lang_string}
6919 * @param string $identifier The key identifier for the localized string
6920 * @param string $component The module where the key identifier is stored,
6921 * usually expressed as the filename in the language pack without the
6922 * .php on the end but can also be written as mod/forum or grade/export/xls.
6923 * If none is specified then moodle.php is used.
6924 * @param string|object|array $a An object, string or number that can be used
6925 * within translation strings
6926 * @param bool $lazyload If set to true a string object is returned instead of
6927 * the string itself. The string then isn't calculated until it is first used.
6928 * @return string The localized string.
6929 * @throws coding_exception
6931 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6934 // If the lazy load argument has been supplied return a lang_string object
6936 // We need to make sure it is true (and a bool) as you will see below there
6937 // used to be a forth argument at one point.
6938 if ($lazyload === true) {
6939 return new lang_string($identifier, $component, $a);
6942 if ($CFG->debugdeveloper
&& clean_param($identifier, PARAM_STRINGID
) === '') {
6943 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER
);
6946 // There is now a forth argument again, this time it is a boolean however so
6947 // we can still check for the old extralocations parameter.
6948 if (!is_bool($lazyload) && !empty($lazyload)) {
6949 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6952 if (strpos($component, '/') !== false) {
6953 debugging('The module name you passed to get_string is the deprecated format ' .
6954 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER
);
6955 $componentpath = explode('/', $component);
6957 switch ($componentpath[0]) {
6959 $component = $componentpath[1];
6963 $component = 'block_'.$componentpath[1];
6966 $component = 'enrol_'.$componentpath[1];
6969 $component = 'format_'.$componentpath[1];
6972 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6977 $result = get_string_manager()->get_string($identifier, $component, $a);
6979 // Debugging feature lets you display string identifier and component.
6980 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
6981 $result .= ' {' . $identifier . '/' . $component . '}';
6987 * Converts an array of strings to their localized value.
6989 * @param array $array An array of strings
6990 * @param string $component The language module that these strings can be found in.
6991 * @return stdClass translated strings.
6993 function get_strings($array, $component = '') {
6994 $string = new stdClass
;
6995 foreach ($array as $item) {
6996 $string->$item = get_string($item, $component);
7002 * Prints out a translated string.
7004 * Prints out a translated string using the return value from the {@link get_string()} function.
7006 * Example usage of this function when the string is in the moodle.php file:<br/>
7009 * print_string('course');
7013 * Example usage of this function when the string is not in the moodle.php file:<br/>
7016 * print_string('typecourse', 'calendar');
7021 * @param string $identifier The key identifier for the localized string
7022 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7023 * @param string|object|array $a An object, string or number that can be used within translation strings
7025 function print_string($identifier, $component = '', $a = null) {
7026 echo get_string($identifier, $component, $a);
7030 * Returns a list of charset codes
7032 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7033 * (checking that such charset is supported by the texlib library!)
7035 * @return array And associative array with contents in the form of charset => charset
7037 function get_list_of_charsets() {
7040 'EUC-JP' => 'EUC-JP',
7041 'ISO-2022-JP'=> 'ISO-2022-JP',
7042 'ISO-8859-1' => 'ISO-8859-1',
7043 'SHIFT-JIS' => 'SHIFT-JIS',
7044 'GB2312' => 'GB2312',
7045 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7046 'UTF-8' => 'UTF-8');
7054 * Returns a list of valid and compatible themes
7058 function get_list_of_themes() {
7063 if (!empty($CFG->themelist
)) { // Use admin's list of themes.
7064 $themelist = explode(',', $CFG->themelist
);
7066 $themelist = array_keys(core_component
::get_plugin_list("theme"));
7069 foreach ($themelist as $key => $themename) {
7070 $theme = theme_config
::load($themename);
7071 $themes[$themename] = $theme;
7074 core_collator
::asort_objects_by_method($themes, 'get_theme_name');
7080 * Returns a list of timezones in the current language
7084 function get_list_of_timezones() {
7089 if (!empty($timezones)) { // This function has been called recently.
7093 $timezones = array();
7095 if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
7096 foreach ($rawtimezones as $timezone) {
7097 if (!empty($timezone->name
)) {
7098 if (get_string_manager()->string_exists(strtolower($timezone->name
), 'timezones')) {
7099 $timezones[$timezone->name
] = get_string(strtolower($timezone->name
), 'timezones');
7101 $timezones[$timezone->name
] = $timezone->name
;
7103 if (substr($timezones[$timezone->name
], 0, 1) == '[') { // No translation found.
7104 $timezones[$timezone->name
] = $timezone->name
;
7112 for ($i = -13; $i <= 13; $i +
= .5) {
7115 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
7116 } else if ($i > 0) {
7117 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
7119 $timezones[sprintf("%.1f", $i)] = $tzstring;
7127 * Factory function for emoticon_manager
7129 * @return emoticon_manager singleton
7131 function get_emoticon_manager() {
7132 static $singleton = null;
7134 if (is_null($singleton)) {
7135 $singleton = new emoticon_manager();
7142 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7144 * Whenever this manager mentiones 'emoticon object', the following data
7145 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7146 * altidentifier and altcomponent
7148 * @see admin_setting_emoticons
7150 * @copyright 2010 David Mudrak
7151 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7153 class emoticon_manager
{
7156 * Returns the currently enabled emoticons
7158 * @return array of emoticon objects
7160 public function get_emoticons() {
7163 if (empty($CFG->emoticons
)) {
7167 $emoticons = $this->decode_stored_config($CFG->emoticons
);
7169 if (!is_array($emoticons)) {
7170 // Something is wrong with the format of stored setting.
7171 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL
);
7179 * Converts emoticon object into renderable pix_emoticon object
7181 * @param stdClass $emoticon emoticon object
7182 * @param array $attributes explicit HTML attributes to set
7183 * @return pix_emoticon
7185 public function prepare_renderable_emoticon(stdClass
$emoticon, array $attributes = array()) {
7186 $stringmanager = get_string_manager();
7187 if ($stringmanager->string_exists($emoticon->altidentifier
, $emoticon->altcomponent
)) {
7188 $alt = get_string($emoticon->altidentifier
, $emoticon->altcomponent
);
7190 $alt = s($emoticon->text
);
7192 return new pix_emoticon($emoticon->imagename
, $alt, $emoticon->imagecomponent
, $attributes);
7196 * Encodes the array of emoticon objects into a string storable in config table
7198 * @see self::decode_stored_config()
7199 * @param array $emoticons array of emtocion objects
7202 public function encode_stored_config(array $emoticons) {
7203 return json_encode($emoticons);
7207 * Decodes the string into an array of emoticon objects
7209 * @see self::encode_stored_config()
7210 * @param string $encoded
7211 * @return string|null
7213 public function decode_stored_config($encoded) {
7214 $decoded = json_decode($encoded);
7215 if (!is_array($decoded)) {
7222 * Returns default set of emoticons supported by Moodle
7224 * @return array of sdtClasses
7226 public function default_emoticons() {
7228 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7229 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7230 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7231 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7232 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7233 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7234 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7235 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7236 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7237 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7238 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7239 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7240 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7241 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7242 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7243 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7244 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7245 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7246 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7247 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7248 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7249 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7250 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7251 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7252 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7253 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7254 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7255 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7256 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7257 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7262 * Helper method preparing the stdClass with the emoticon properties
7264 * @param string|array $text or array of strings
7265 * @param string $imagename to be used by {@link pix_emoticon}
7266 * @param string $altidentifier alternative string identifier, null for no alt
7267 * @param string $altcomponent where the alternative string is defined
7268 * @param string $imagecomponent to be used by {@link pix_emoticon}
7271 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7272 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7273 return (object)array(
7275 'imagename' => $imagename,
7276 'imagecomponent' => $imagecomponent,
7277 'altidentifier' => $altidentifier,
7278 'altcomponent' => $altcomponent,
7288 * @param string $data Data to encrypt.
7289 * @return string The now encrypted data.
7291 function rc4encrypt($data) {
7292 return endecrypt(get_site_identifier(), $data, '');
7298 * @param string $data Data to decrypt.
7299 * @return string The now decrypted data.
7301 function rc4decrypt($data) {
7302 return endecrypt(get_site_identifier(), $data, 'de');
7306 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7308 * @todo Finish documenting this function
7310 * @param string $pwd The password to use when encrypting or decrypting
7311 * @param string $data The data to be decrypted/encrypted
7312 * @param string $case Either 'de' for decrypt or '' for encrypt
7315 function endecrypt ($pwd, $data, $case) {
7317 if ($case == 'de') {
7318 $data = urldecode($data);
7323 $pwdlength = strlen($pwd);
7325 for ($i = 0; $i <= 255; $i++
) {
7326 $key[$i] = ord(substr($pwd, ($i %
$pwdlength), 1));
7332 for ($i = 0; $i <= 255; $i++
) {
7333 $x = ($x +
$box[$i] +
$key[$i]) %
256;
7334 $tempswap = $box[$i];
7335 $box[$i] = $box[$x];
7336 $box[$x] = $tempswap;
7344 for ($i = 0; $i < strlen($data); $i++
) {
7345 $a = ($a +
1) %
256;
7346 $j = ($j +
$box[$a]) %
256;
7348 $box[$a] = $box[$j];
7350 $k = $box[(($box[$a] +
$box[$j]) %
256)];
7351 $cipherby = ord(substr($data, $i, 1)) ^
$k;
7352 $cipher .= chr($cipherby);
7355 if ($case == 'de') {
7356 $cipher = urldecode(urlencode($cipher));
7358 $cipher = urlencode($cipher);
7364 // ENVIRONMENT CHECKING.
7367 * This method validates a plug name. It is much faster than calling clean_param.
7369 * @param string $name a string that might be a plugin name.
7370 * @return bool if this string is a valid plugin name.
7372 function is_valid_plugin_name($name) {
7373 // This does not work for 'mod', bad luck, use any other type.
7374 return core_component
::is_valid_plugin_name('tool', $name);
7378 * Get a list of all the plugins of a given type that define a certain API function
7379 * in a certain file. The plugin component names and function names are returned.
7381 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7382 * @param string $function the part of the name of the function after the
7383 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7384 * names like report_courselist_hook.
7385 * @param string $file the name of file within the plugin that defines the
7386 * function. Defaults to lib.php.
7387 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7388 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7390 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7391 $pluginfunctions = array();
7392 $pluginswithfile = core_component
::get_plugin_list_with_file($plugintype, $file, true);
7393 foreach ($pluginswithfile as $plugin => $notused) {
7394 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7396 if (function_exists($fullfunction)) {
7397 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7398 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
7400 } else if ($plugintype === 'mod') {
7401 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7402 $shortfunction = $plugin . '_' . $function;
7403 if (function_exists($shortfunction)) {
7404 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
7408 return $pluginfunctions;
7412 * Lists plugin-like directories within specified directory
7414 * This function was originally used for standard Moodle plugins, please use
7415 * new core_component::get_plugin_list() now.
7417 * This function is used for general directory listing and backwards compatility.
7419 * @param string $directory relative directory from root
7420 * @param string $exclude dir name to exclude from the list (defaults to none)
7421 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7422 * @return array Sorted array of directory names found under the requested parameters
7424 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7429 if (empty($basedir)) {
7430 $basedir = $CFG->dirroot
.'/'. $directory;
7433 $basedir = $basedir .'/'. $directory;
7436 if ($CFG->debugdeveloper
and empty($exclude)) {
7437 // Make sure devs do not use this to list normal plugins,
7438 // this is intended for general directories that are not plugins!
7440 $subtypes = core_component
::get_plugin_types();
7441 if (in_array($basedir, $subtypes)) {
7442 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER
);
7447 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7448 if (!$dirhandle = opendir($basedir)) {
7449 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER
);
7452 while (false !== ($dir = readdir($dirhandle))) {
7453 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7454 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7455 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7458 if (filetype($basedir .'/'. $dir) != 'dir') {
7463 closedir($dirhandle);
7472 * Invoke plugin's callback functions
7474 * @param string $type plugin type e.g. 'mod'
7475 * @param string $name plugin name
7476 * @param string $feature feature name
7477 * @param string $action feature's action
7478 * @param array $params parameters of callback function, should be an array
7479 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7482 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7484 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7485 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7489 * Invoke component's callback functions
7491 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7492 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7493 * @param array $params parameters of callback function
7494 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7497 function component_callback($component, $function, array $params = array(), $default = null) {
7499 $functionname = component_callback_exists($component, $function);
7501 if ($functionname) {
7502 // Function exists, so just return function result.
7503 $ret = call_user_func_array($functionname, $params);
7504 if (is_null($ret)) {
7514 * Determine if a component callback exists and return the function name to call. Note that this
7515 * function will include the required library files so that the functioname returned can be
7518 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7519 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7520 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7521 * @throws coding_exception if invalid component specfied
7523 function component_callback_exists($component, $function) {
7524 global $CFG; // This is needed for the inclusions.
7526 $cleancomponent = clean_param($component, PARAM_COMPONENT
);
7527 if (empty($cleancomponent)) {
7528 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7530 $component = $cleancomponent;
7532 list($type, $name) = core_component
::normalize_component($component);
7533 $component = $type . '_' . $name;
7535 $oldfunction = $name.'_'.$function;
7536 $function = $component.'_'.$function;
7538 $dir = core_component
::get_component_directory($component);
7540 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7543 // Load library and look for function.
7544 if (file_exists($dir.'/lib.php')) {
7545 require_once($dir.'/lib.php');
7548 if (!function_exists($function) and function_exists($oldfunction)) {
7549 if ($type !== 'mod' and $type !== 'core') {
7550 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER
);
7552 $function = $oldfunction;
7555 if (function_exists($function)) {
7562 * Checks whether a plugin supports a specified feature.
7564 * @param string $type Plugin type e.g. 'mod'
7565 * @param string $name Plugin name e.g. 'forum'
7566 * @param string $feature Feature code (FEATURE_xx constant)
7567 * @param mixed $default default value if feature support unknown
7568 * @return mixed Feature result (false if not supported, null if feature is unknown,
7569 * otherwise usually true but may have other feature-specific value such as array)
7570 * @throws coding_exception
7572 function plugin_supports($type, $name, $feature, $default = null) {
7575 if ($type === 'mod' and $name === 'NEWMODULE') {
7576 // Somebody forgot to rename the module template.
7580 $component = clean_param($type . '_' . $name, PARAM_COMPONENT
);
7581 if (empty($component)) {
7582 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7587 if ($type === 'mod') {
7588 // We need this special case because we support subplugins in modules,
7589 // otherwise it would end up in infinite loop.
7590 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7591 include_once("$CFG->dirroot/mod/$name/lib.php");
7592 $function = $component.'_supports';
7593 if (!function_exists($function)) {
7594 // Legacy non-frankenstyle function name.
7595 $function = $name.'_supports';
7600 if (!$path = core_component
::get_plugin_directory($type, $name)) {
7601 // Non existent plugin type.
7604 if (file_exists("$path/lib.php")) {
7605 include_once("$path/lib.php");
7606 $function = $component.'_supports';
7610 if ($function and function_exists($function)) {
7611 $supports = $function($feature);
7612 if (is_null($supports)) {
7613 // Plugin does not know - use default.
7620 // Plugin does not care, so use default.
7625 * Returns true if the current version of PHP is greater that the specified one.
7627 * @todo Check PHP version being required here is it too low?
7629 * @param string $version The version of php being tested.
7632 function check_php_version($version='5.2.4') {
7633 return (version_compare(phpversion(), $version) >= 0);
7637 * Determine if moodle installation requires update.
7639 * Checks version numbers of main code and all plugins to see
7640 * if there are any mismatches.
7644 function moodle_needs_upgrading() {
7647 if (empty($CFG->version
)) {
7651 // There is no need to purge plugininfo caches here because
7652 // these caches are not used during upgrade and they are purged after
7655 if (empty($CFG->allversionshash
)) {
7659 $hash = core_component
::get_all_versions_hash();
7661 return ($hash !== $CFG->allversionshash
);
7665 * Returns the major version of this site
7667 * Moodle version numbers consist of three numbers separated by a dot, for
7668 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7669 * called major version. This function extracts the major version from either
7670 * $CFG->release (default) or eventually from the $release variable defined in
7671 * the main version.php.
7673 * @param bool $fromdisk should the version if source code files be used
7674 * @return string|false the major version like '2.3', false if could not be determined
7676 function moodle_major_version($fromdisk = false) {
7681 require($CFG->dirroot
.'/version.php');
7682 if (empty($release)) {
7687 if (empty($CFG->release
)) {
7690 $release = $CFG->release
;
7693 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7703 * Sets the system locale
7706 * @param string $locale Can be used to force a locale
7708 function moodle_setlocale($locale='') {
7711 static $currentlocale = ''; // Last locale caching.
7713 $oldlocale = $currentlocale;
7715 // Fetch the correct locale based on ostype.
7716 if ($CFG->ostype
== 'WINDOWS') {
7717 $stringtofetch = 'localewin';
7719 $stringtofetch = 'locale';
7722 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7723 if (!empty($locale)) {
7724 $currentlocale = $locale;
7725 } else if (!empty($CFG->locale
)) { // Override locale for all language packs.
7726 $currentlocale = $CFG->locale
;
7728 $currentlocale = get_string($stringtofetch, 'langconfig');
7731 // Do nothing if locale already set up.
7732 if ($oldlocale == $currentlocale) {
7736 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7737 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7738 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7740 // Get current values.
7741 $monetary= setlocale (LC_MONETARY
, 0);
7742 $numeric = setlocale (LC_NUMERIC
, 0);
7743 $ctype = setlocale (LC_CTYPE
, 0);
7744 if ($CFG->ostype
!= 'WINDOWS') {
7745 $messages= setlocale (LC_MESSAGES
, 0);
7747 // Set locale to all.
7748 $result = setlocale (LC_ALL
, $currentlocale);
7749 // If setting of locale fails try the other utf8 or utf-8 variant,
7750 // some operating systems support both (Debian), others just one (OSX).
7751 if ($result === false) {
7752 if (stripos($currentlocale, '.UTF-8') !== false) {
7753 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7754 setlocale (LC_ALL
, $newlocale);
7755 } else if (stripos($currentlocale, '.UTF8') !== false) {
7756 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7757 setlocale (LC_ALL
, $newlocale);
7761 setlocale (LC_MONETARY
, $monetary);
7762 setlocale (LC_NUMERIC
, $numeric);
7763 if ($CFG->ostype
!= 'WINDOWS') {
7764 setlocale (LC_MESSAGES
, $messages);
7766 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7767 // To workaround a well-known PHP problem with Turkish letter Ii.
7768 setlocale (LC_CTYPE
, $ctype);
7773 * Count words in a string.
7775 * Words are defined as things between whitespace.
7778 * @param string $string The text to be searched for words.
7779 * @return int The count of words in the specified string
7781 function count_words($string) {
7782 $string = strip_tags($string);
7783 // Decode HTML entities.
7784 $string = html_entity_decode($string);
7785 // Replace underscores (which are classed as word characters) with spaces.
7786 $string = preg_replace('/_/u', ' ', $string);
7787 // Remove any characters that shouldn't be treated as word boundaries.
7788 $string = preg_replace('/[\'’-]/u', '', $string);
7789 // Remove dots and commas from within numbers only.
7790 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7792 return count(preg_split('/\w\b/u', $string)) - 1;
7796 * Count letters in a string.
7798 * Letters are defined as chars not in tags and different from whitespace.
7801 * @param string $string The text to be searched for letters.
7802 * @return int The count of letters in the specified text.
7804 function count_letters($string) {
7805 $string = strip_tags($string); // Tags are out now.
7806 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7808 return core_text
::strlen($string);
7812 * Generate and return a random string of the specified length.
7814 * @param int $length The length of the string to be created.
7817 function random_string ($length=15) {
7818 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7819 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7820 $pool .= '0123456789';
7821 $poollen = strlen($pool);
7823 for ($i = 0; $i < $length; $i++
) {
7824 $string .= substr($pool, (mt_rand()%
($poollen)), 1);
7830 * Generate a complex random string (useful for md5 salts)
7832 * This function is based on the above {@link random_string()} however it uses a
7833 * larger pool of characters and generates a string between 24 and 32 characters
7835 * @param int $length Optional if set generates a string to exactly this length
7838 function complex_random_string($length=null) {
7839 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7840 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7841 $poollen = strlen($pool);
7842 if ($length===null) {
7843 $length = floor(rand(24, 32));
7846 for ($i = 0; $i < $length; $i++
) {
7847 $string .= $pool[(mt_rand()%
$poollen)];
7853 * Given some text (which may contain HTML) and an ideal length,
7854 * this function truncates the text neatly on a word boundary if possible
7857 * @param string $text text to be shortened
7858 * @param int $ideal ideal string length
7859 * @param boolean $exact if false, $text will not be cut mid-word
7860 * @param string $ending The string to append if the passed string is truncated
7861 * @return string $truncate shortened string
7863 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7864 // If the plain text is shorter than the maximum length, return the whole text.
7865 if (core_text
::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7869 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7870 // and only tag in its 'line'.
7871 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER
);
7873 $totallength = core_text
::strlen($ending);
7876 // This array stores information about open and close tags and their position
7877 // in the truncated string. Each item in the array is an object with fields
7878 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7879 // (byte position in truncated text).
7880 $tagdetails = array();
7882 foreach ($lines as $linematchings) {
7883 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7884 if (!empty($linematchings[1])) {
7885 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7886 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7887 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7888 // Record closing tag.
7889 $tagdetails[] = (object) array(
7891 'tag' => core_text
::strtolower($tagmatchings[1]),
7892 'pos' => core_text
::strlen($truncate),
7895 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7896 // Record opening tag.
7897 $tagdetails[] = (object) array(
7899 'tag' => core_text
::strtolower($tagmatchings[1]),
7900 'pos' => core_text
::strlen($truncate),
7904 // Add html-tag to $truncate'd text.
7905 $truncate .= $linematchings[1];
7908 // Calculate the length of the plain text part of the line; handle entities as one character.
7909 $contentlength = core_text
::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7910 if ($totallength +
$contentlength > $ideal) {
7911 // The number of characters which are left.
7912 $left = $ideal - $totallength;
7913 $entitieslength = 0;
7914 // Search for html entities.
7915 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
)) {
7916 // Calculate the real length of all entities in the legal range.
7917 foreach ($entities[0] as $entity) {
7918 if ($entity[1]+
1-$entitieslength <= $left) {
7920 $entitieslength +
= core_text
::strlen($entity[0]);
7922 // No more characters left.
7927 $breakpos = $left +
$entitieslength;
7929 // If the words shouldn't be cut in the middle...
7931 // Search the last occurence of a space.
7932 for (; $breakpos > 0; $breakpos--) {
7933 if ($char = core_text
::substr($linematchings[2], $breakpos, 1)) {
7934 if ($char === '.' or $char === ' ') {
7937 } else if (strlen($char) > 2) {
7938 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7945 if ($breakpos == 0) {
7946 // This deals with the test_shorten_text_no_spaces case.
7947 $breakpos = $left +
$entitieslength;
7948 } else if ($breakpos > $left +
$entitieslength) {
7949 // This deals with the previous for loop breaking on the first char.
7950 $breakpos = $left +
$entitieslength;
7953 $truncate .= core_text
::substr($linematchings[2], 0, $breakpos);
7954 // Maximum length is reached, so get off the loop.
7957 $truncate .= $linematchings[2];
7958 $totallength +
= $contentlength;
7961 // If the maximum length is reached, get off the loop.
7962 if ($totallength >= $ideal) {
7967 // Add the defined ending to the text.
7968 $truncate .= $ending;
7970 // Now calculate the list of open html tags based on the truncate position.
7971 $opentags = array();
7972 foreach ($tagdetails as $taginfo) {
7973 if ($taginfo->open
) {
7974 // Add tag to the beginning of $opentags list.
7975 array_unshift($opentags, $taginfo->tag
);
7977 // Can have multiple exact same open tags, close the last one.
7978 $pos = array_search($taginfo->tag
, array_reverse($opentags, true));
7979 if ($pos !== false) {
7980 unset($opentags[$pos]);
7985 // Close all unclosed html-tags.
7986 foreach ($opentags as $tag) {
7987 $truncate .= '</' . $tag . '>';
7995 * Given dates in seconds, how many weeks is the date from startdate
7996 * The first week is 1, the second 2 etc ...
7998 * @param int $startdate Timestamp for the start date
7999 * @param int $thedate Timestamp for the end date
8002 function getweek ($startdate, $thedate) {
8003 if ($thedate < $startdate) {
8007 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
8011 * Returns a randomly generated password of length $maxlen. inspired by
8013 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8014 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8016 * @param int $maxlen The maximum size of the password being generated.
8019 function generate_password($maxlen=10) {
8022 if (empty($CFG->passwordpolicy
)) {
8023 $fillers = PASSWORD_DIGITS
;
8024 $wordlist = file($CFG->wordlist
);
8025 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8026 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8027 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8028 $password = $word1 . $filler1 . $word2;
8030 $minlen = !empty($CFG->minpasswordlength
) ?
$CFG->minpasswordlength
: 0;
8031 $digits = $CFG->minpassworddigits
;
8032 $lower = $CFG->minpasswordlower
;
8033 $upper = $CFG->minpasswordupper
;
8034 $nonalphanum = $CFG->minpasswordnonalphanum
;
8035 $total = $lower +
$upper +
$digits +
$nonalphanum;
8036 // Var minlength should be the greater one of the two ( $minlen and $total ).
8037 $minlen = $minlen < $total ?
$total : $minlen;
8038 // Var maxlen can never be smaller than minlen.
8039 $maxlen = $minlen > $maxlen ?
$minlen : $maxlen;
8040 $additional = $maxlen - $total;
8042 // Make sure we have enough characters to fulfill
8043 // complexity requirements.
8044 $passworddigits = PASSWORD_DIGITS
;
8045 while ($digits > strlen($passworddigits)) {
8046 $passworddigits .= PASSWORD_DIGITS
;
8048 $passwordlower = PASSWORD_LOWER
;
8049 while ($lower > strlen($passwordlower)) {
8050 $passwordlower .= PASSWORD_LOWER
;
8052 $passwordupper = PASSWORD_UPPER
;
8053 while ($upper > strlen($passwordupper)) {
8054 $passwordupper .= PASSWORD_UPPER
;
8056 $passwordnonalphanum = PASSWORD_NONALPHANUM
;
8057 while ($nonalphanum > strlen($passwordnonalphanum)) {
8058 $passwordnonalphanum .= PASSWORD_NONALPHANUM
;
8061 // Now mix and shuffle it all.
8062 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8063 substr(str_shuffle ($passwordupper), 0, $upper) .
8064 substr(str_shuffle ($passworddigits), 0, $digits) .
8065 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8066 substr(str_shuffle ($passwordlower .
8069 $passwordnonalphanum), 0 , $additional));
8072 return substr ($password, 0, $maxlen);
8076 * Given a float, prints it nicely.
8077 * Localized floats must not be used in calculations!
8079 * The stripzeros feature is intended for making numbers look nicer in small
8080 * areas where it is not necessary to indicate the degree of accuracy by showing
8081 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8082 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8084 * @param float $float The float to print
8085 * @param int $decimalpoints The number of decimal places to print.
8086 * @param bool $localized use localized decimal separator
8087 * @param bool $stripzeros If true, removes final zeros after decimal point
8088 * @return string locale float
8090 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8091 if (is_null($float)) {
8095 $separator = get_string('decsep', 'langconfig');
8099 $result = number_format($float, $decimalpoints, $separator, '');
8101 // Remove zeros and final dot if not needed.
8102 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8108 * Converts locale specific floating point/comma number back to standard PHP float value
8109 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8111 * @param string $localefloat locale aware float representation
8112 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8113 * @return mixed float|bool - false or the parsed float.
8115 function unformat_float($localefloat, $strict = false) {
8116 $localefloat = trim($localefloat);
8118 if ($localefloat == '') {
8122 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8123 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8125 if ($strict && !is_numeric($localefloat)) {
8129 return (float)$localefloat;
8133 * Given a simple array, this shuffles it up just like shuffle()
8134 * Unlike PHP's shuffle() this function works on any machine.
8136 * @param array $array The array to be rearranged
8139 function swapshuffle($array) {
8141 $last = count($array) - 1;
8142 for ($i = 0; $i <= $last; $i++
) {
8143 $from = rand(0, $last);
8145 $array[$i] = $array[$from];
8146 $array[$from] = $curr;
8152 * Like {@link swapshuffle()}, but works on associative arrays
8154 * @param array $array The associative array to be rearranged
8157 function swapshuffle_assoc($array) {
8159 $newarray = array();
8160 $newkeys = swapshuffle(array_keys($array));
8162 foreach ($newkeys as $newkey) {
8163 $newarray[$newkey] = $array[$newkey];
8169 * Given an arbitrary array, and a number of draws,
8170 * this function returns an array with that amount
8171 * of items. The indexes are retained.
8173 * @todo Finish documenting this function
8175 * @param array $array
8179 function draw_rand_array($array, $draws) {
8183 $last = count($array);
8185 if ($draws > $last) {
8189 while ($draws > 0) {
8192 $keys = array_keys($array);
8193 $rand = rand(0, $last);
8195 $return[$keys[$rand]] = $array[$keys[$rand]];
8196 unset($array[$keys[$rand]]);
8205 * Calculate the difference between two microtimes
8207 * @param string $a The first Microtime
8208 * @param string $b The second Microtime
8211 function microtime_diff($a, $b) {
8212 list($adec, $asec) = explode(' ', $a);
8213 list($bdec, $bsec) = explode(' ', $b);
8214 return $bsec - $asec +
$bdec - $adec;
8218 * Given a list (eg a,b,c,d,e) this function returns
8219 * an array of 1->a, 2->b, 3->c etc
8221 * @param string $list The string to explode into array bits
8222 * @param string $separator The separator used within the list string
8223 * @return array The now assembled array
8225 function make_menu_from_list($list, $separator=',') {
8227 $array = array_reverse(explode($separator, $list), true);
8228 foreach ($array as $key => $item) {
8229 $outarray[$key+
1] = trim($item);
8235 * Creates an array that represents all the current grades that
8236 * can be chosen using the given grading type.
8239 * are scales, zero is no grade, and positive numbers are maximum
8242 * @todo Finish documenting this function or better deprecated this completely!
8244 * @param int $gradingtype
8247 function make_grades_menu($gradingtype) {
8251 if ($gradingtype < 0) {
8252 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8253 return make_menu_from_list($scale->scale
);
8255 } else if ($gradingtype > 0) {
8256 for ($i=$gradingtype; $i>=0; $i--) {
8257 $grades[$i] = $i .' / '. $gradingtype;
8265 * This function returns the number of activities using the given scale in the given course.
8267 * @param int $courseid The course ID to check.
8268 * @param int $scaleid The scale ID to check
8271 function course_scale_used($courseid, $scaleid) {
8276 if (!empty($scaleid)) {
8277 if ($cms = get_course_mods($courseid)) {
8278 foreach ($cms as $cm) {
8279 // Check cm->name/lib.php exists.
8280 if (file_exists($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php')) {
8281 include_once($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php');
8282 $functionname = $cm->modname
.'_scale_used';
8283 if (function_exists($functionname)) {
8284 if ($functionname($cm->instance
, $scaleid)) {
8292 // Check if any course grade item makes use of the scale.
8293 $return +
= $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8295 // Check if any outcome in the course makes use of the scale.
8296 $return +
= $DB->count_records_sql("SELECT COUNT('x')
8297 FROM {grade_outcomes_courses} goc,
8299 WHERE go.id = goc.outcomeid
8300 AND go.scaleid = ? AND goc.courseid = ?",
8301 array($scaleid, $courseid));
8307 * This function returns the number of activities using scaleid in the entire site
8309 * @param int $scaleid
8310 * @param array $courses
8313 function site_scale_used($scaleid, &$courses) {
8316 if (!is_array($courses) ||
count($courses) == 0) {
8317 $courses = get_courses("all", false, "c.id, c.shortname");
8320 if (!empty($scaleid)) {
8321 if (is_array($courses) && count($courses) > 0) {
8322 foreach ($courses as $course) {
8323 $return +
= course_scale_used($course->id
, $scaleid);
8331 * make_unique_id_code
8333 * @todo Finish documenting this function
8336 * @param string $extra Extra string to append to the end of the code
8339 function make_unique_id_code($extra = '') {
8341 $hostname = 'unknownhost';
8342 if (!empty($_SERVER['HTTP_HOST'])) {
8343 $hostname = $_SERVER['HTTP_HOST'];
8344 } else if (!empty($_ENV['HTTP_HOST'])) {
8345 $hostname = $_ENV['HTTP_HOST'];
8346 } else if (!empty($_SERVER['SERVER_NAME'])) {
8347 $hostname = $_SERVER['SERVER_NAME'];
8348 } else if (!empty($_ENV['SERVER_NAME'])) {
8349 $hostname = $_ENV['SERVER_NAME'];
8352 $date = gmdate("ymdHis");
8354 $random = random_string(6);
8357 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8359 return $hostname .'+'. $date .'+'. $random;
8365 * Function to check the passed address is within the passed subnet
8367 * The parameter is a comma separated string of subnet definitions.
8368 * Subnet strings can be in one of three formats:
8369 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8370 * 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)
8371 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8372 * Code for type 1 modified from user posted comments by mediator at
8373 * {@link http://au.php.net/manual/en/function.ip2long.php}
8375 * @param string $addr The address you are checking
8376 * @param string $subnetstr The string of subnet addresses
8379 function address_in_subnet($addr, $subnetstr) {
8381 if ($addr == '0.0.0.0') {
8384 $subnets = explode(',', $subnetstr);
8386 $addr = trim($addr);
8387 $addr = cleanremoteaddr($addr, false); // Normalise.
8388 if ($addr === null) {
8391 $addrparts = explode(':', $addr);
8393 $ipv6 = strpos($addr, ':');
8395 foreach ($subnets as $subnet) {
8396 $subnet = trim($subnet);
8397 if ($subnet === '') {
8401 if (strpos($subnet, '/') !== false) {
8402 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8403 list($ip, $mask) = explode('/', $subnet);
8404 $mask = trim($mask);
8405 if (!is_number($mask)) {
8406 continue; // Incorect mask number, eh?
8408 $ip = cleanremoteaddr($ip, false); // Normalise.
8412 if (strpos($ip, ':') !== false) {
8417 if ($mask > 128 or $mask < 0) {
8418 continue; // Nonsense.
8421 return true; // Any address.
8424 if ($ip === $addr) {
8429 $ipparts = explode(':', $ip);
8430 $modulo = $mask %
16;
8431 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8432 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8433 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8437 $pos = ($mask-$modulo)/16;
8438 $ipnet = hexdec($ipparts[$pos]);
8439 $addrnet = hexdec($addrparts[$pos]);
8440 $mask = 0xffff << (16 - $modulo);
8441 if (($addrnet & $mask) == ($ipnet & $mask)) {
8451 if ($mask > 32 or $mask < 0) {
8452 continue; // Nonsense.
8458 if ($ip === $addr) {
8463 $mask = 0xffffffff << (32 - $mask);
8464 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8469 } else if (strpos($subnet, '-') !== false) {
8470 // 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.
8471 $parts = explode('-', $subnet);
8472 if (count($parts) != 2) {
8476 if (strpos($subnet, ':') !== false) {
8481 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8482 if ($ipstart === null) {
8485 $ipparts = explode(':', $ipstart);
8486 $start = hexdec(array_pop($ipparts));
8487 $ipparts[] = trim($parts[1]);
8488 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8489 if ($ipend === null) {
8493 $ipnet = implode(':', $ipparts);
8494 if (strpos($addr, $ipnet) !== 0) {
8497 $ipparts = explode(':', $ipend);
8498 $end = hexdec($ipparts[7]);
8500 $addrend = hexdec($addrparts[7]);
8502 if (($addrend >= $start) and ($addrend <= $end)) {
8511 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8512 if ($ipstart === null) {
8515 $ipparts = explode('.', $ipstart);
8516 $ipparts[3] = trim($parts[1]);
8517 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8518 if ($ipend === null) {
8522 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8528 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8529 if (strpos($subnet, ':') !== false) {
8534 $parts = explode(':', $subnet);
8535 $count = count($parts);
8536 if ($parts[$count-1] === '') {
8537 unset($parts[$count-1]); // Trim trailing :'s.
8539 $subnet = implode('.', $parts);
8541 $isip = cleanremoteaddr($subnet, false); // Normalise.
8542 if ($isip !== null) {
8543 if ($isip === $addr) {
8547 } else if ($count > 8) {
8550 $zeros = array_fill(0, 8-$count, '0');
8551 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8552 if (address_in_subnet($addr, $subnet)) {
8561 $parts = explode('.', $subnet);
8562 $count = count($parts);
8563 if ($parts[$count-1] === '') {
8564 unset($parts[$count-1]); // Trim trailing .
8566 $subnet = implode('.', $parts);
8569 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8570 if ($subnet === $addr) {
8574 } else if ($count > 4) {
8577 $zeros = array_fill(0, 4-$count, '0');
8578 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8579 if (address_in_subnet($addr, $subnet)) {
8590 * For outputting debugging info
8592 * @param string $string The string to write
8593 * @param string $eol The end of line char(s) to use
8594 * @param string $sleep Period to make the application sleep
8595 * This ensures any messages have time to display before redirect
8597 function mtrace($string, $eol="\n", $sleep=0) {
8599 if (defined('STDOUT') and !PHPUNIT_TEST
) {
8600 fwrite(STDOUT
, $string.$eol);
8602 echo $string . $eol;
8607 // Delay to keep message on user's screen in case of subsequent redirect.
8614 * Replace 1 or more slashes or backslashes to 1 slash
8616 * @param string $path The path to strip
8617 * @return string the path with double slashes removed
8619 function cleardoubleslashes ($path) {
8620 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8624 * Is current ip in give list?
8626 * @param string $list
8629 function remoteip_in_list($list) {
8631 $clientip = getremoteaddr(null);
8634 // Ensure access on cli.
8638 $list = explode("\n", $list);
8639 foreach ($list as $subnet) {
8640 $subnet = trim($subnet);
8641 if (address_in_subnet($clientip, $subnet)) {
8650 * Returns most reliable client address
8652 * @param string $default If an address can't be determined, then return this
8653 * @return string The remote IP address
8655 function getremoteaddr($default='0.0.0.0') {
8658 if (empty($CFG->getremoteaddrconf
)) {
8659 // This will happen, for example, before just after the upgrade, as the
8660 // user is redirected to the admin screen.
8661 $variablestoskip = 0;
8663 $variablestoskip = $CFG->getremoteaddrconf
;
8665 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP
)) {
8666 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8667 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8668 return $address ?
$address : $default;
8671 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR
)) {
8672 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8673 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8674 $address = $forwardedaddresses[0];
8676 if (substr_count($address, ":") > 1) {
8677 // Remove port and brackets from IPv6.
8678 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8679 $address = $matches[1];
8682 // Remove port from IPv4.
8683 if (substr_count($address, ":") == 1) {
8684 $parts = explode(":", $address);
8685 $address = $parts[0];
8689 $address = cleanremoteaddr($address);
8690 return $address ?
$address : $default;
8693 if (!empty($_SERVER['REMOTE_ADDR'])) {
8694 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8695 return $address ?
$address : $default;
8702 * Cleans an ip address. Internal addresses are now allowed.
8703 * (Originally local addresses were not allowed.)
8705 * @param string $addr IPv4 or IPv6 address
8706 * @param bool $compress use IPv6 address compression
8707 * @return string normalised ip address string, null if error
8709 function cleanremoteaddr($addr, $compress=false) {
8710 $addr = trim($addr);
8712 // TODO: maybe add a separate function is_addr_public() or something like this.
8714 if (strpos($addr, ':') !== false) {
8715 // Can be only IPv6.
8716 $parts = explode(':', $addr);
8717 $count = count($parts);
8719 if (strpos($parts[$count-1], '.') !== false) {
8720 // Legacy ipv4 notation.
8721 $last = array_pop($parts);
8722 $ipv4 = cleanremoteaddr($last, true);
8723 if ($ipv4 === null) {
8726 $bits = explode('.', $ipv4);
8727 $parts[] = dechex($bits[0]).dechex($bits[1]);
8728 $parts[] = dechex($bits[2]).dechex($bits[3]);
8729 $count = count($parts);
8730 $addr = implode(':', $parts);
8733 if ($count < 3 or $count > 8) {
8734 return null; // Severly malformed.
8738 if (strpos($addr, '::') === false) {
8739 return null; // Malformed.
8742 $insertat = array_search('', $parts, true);
8743 $missing = array_fill(0, 1 +
8 - $count, '0');
8744 array_splice($parts, $insertat, 1, $missing);
8745 foreach ($parts as $key => $part) {
8752 $adr = implode(':', $parts);
8753 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8754 return null; // Incorrect format - sorry.
8757 // Normalise 0s and case.
8758 $parts = array_map('hexdec', $parts);
8759 $parts = array_map('dechex', $parts);
8761 $result = implode(':', $parts);
8767 if ($result === '0:0:0:0:0:0:0:0') {
8768 return '::'; // All addresses.
8771 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8772 if ($compressed !== $result) {
8776 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8777 if ($compressed !== $result) {
8781 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8782 if ($compressed !== $result) {
8789 // First get all things that look like IPv4 addresses.
8791 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8796 foreach ($parts as $key => $match) {
8800 $parts[$key] = (int)$match; // Normalise 0s.
8803 return implode('.', $parts);
8807 * This function will make a complete copy of anything it's given,
8808 * regardless of whether it's an object or not.
8810 * @param mixed $thing Something you want cloned
8811 * @return mixed What ever it is you passed it
8813 function fullclone($thing) {
8814 return unserialize(serialize($thing));
8818 * If new messages are waiting for the current user, then insert
8819 * JavaScript to pop up the messaging window into the page
8823 function message_popup_window() {
8824 global $USER, $DB, $PAGE, $CFG;
8826 if (!$PAGE->get_popup_notification_allowed() ||
empty($CFG->messaging
)) {
8830 if (!isloggedin() ||
isguestuser()) {
8834 if (!isset($USER->message_lastpopup
)) {
8835 $USER->message_lastpopup
= 0;
8836 } else if ($USER->message_lastpopup
> (time()-120)) {
8837 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8841 // A quick query to check whether the user has new messages.
8842 $messagecount = $DB->count_records('message', array('useridto' => $USER->id
));
8843 if ($messagecount < 1) {
8847 // There are unread messages so now do a more complex but slower query.
8848 $messagesql = "SELECT m.id, c.blocked
8850 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8851 JOIN {message_processors} p ON mw.processorid=p.id
8852 JOIN {user} u ON m.useridfrom=u.id
8853 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8854 AND c.userid = m.useridto
8855 WHERE m.useridto = :userid
8856 AND p.name='popup'";
8858 // If the user was last notified over an hour ago we can re-notify them of old messages
8859 // so don't worry about when the new message was sent.
8860 $lastnotifiedlongago = $USER->message_lastpopup
< (time()-3600);
8861 if (!$lastnotifiedlongago) {
8862 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8865 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id
, 'lastpopuptime' => $USER->message_lastpopup
));
8868 foreach ($waitingmessages as $messageinfo) {
8869 if ($messageinfo->blocked
) {
8870 // Message is from a user who has since been blocked so just mark it read.
8871 // Get the full message to mark as read.
8872 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id
));
8873 message_mark_message_read($messageobject, time());
8879 if ($validmessages > 0) {
8880 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8881 $strgomessage = get_string('gotomessages', 'message');
8882 $strstaymessage = get_string('ignore', 'admin');
8884 $notificationsound = null;
8885 $beep = get_user_preferences('message_beepnewmessage', '');
8886 if (!empty($beep)) {
8887 // Browsers will work down this list until they find something they support.
8888 $sourcetags = html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.wav', 'type' => 'audio/wav'));
8889 $sourcetags .= html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.ogg', 'type' => 'audio/ogg'));
8890 $sourcetags .= html_writer
::empty_tag('source', array('src' => $CFG->wwwroot
.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8891 $sourcetags .= html_writer
::empty_tag('embed', array('src' => $CFG->wwwroot
.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8893 $notificationsound = html_writer
::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8896 $url = $CFG->wwwroot
.'/message/index.php';
8897 $content = html_writer
::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8898 html_writer
::start_tag('div', array('id' => 'newmessagetext')).
8900 html_writer
::end_tag('div').
8903 html_writer
::start_tag('div', array('id' => 'newmessagelinks')).
8904 html_writer
::link($url, $strgomessage, array('id' => 'notificationyes')).' '.
8905 html_writer
::link('', $strstaymessage, array('id' => 'notificationno')).
8906 html_writer
::end_tag('div');
8907 html_writer
::end_tag('div');
8909 $PAGE->requires
->js_init_call('M.core_message.init_notification', array('', $content, $url));
8911 $USER->message_lastpopup
= time();
8916 * Used to make sure that $min <= $value <= $max
8918 * Make sure that value is between min, and max
8920 * @param int $min The minimum value
8921 * @param int $value The value to check
8922 * @param int $max The maximum value
8925 function bounded_number($min, $value, $max) {
8926 if ($value < $min) {
8929 if ($value > $max) {
8936 * Check if there is a nested array within the passed array
8938 * @param array $array
8939 * @return bool true if there is a nested array false otherwise
8941 function array_is_nested($array) {
8942 foreach ($array as $value) {
8943 if (is_array($value)) {
8951 * get_performance_info() pairs up with init_performance_info()
8952 * loaded in setup.php. Returns an array with 'html' and 'txt'
8953 * values ready for use, and each of the individual stats provided
8954 * separately as well.
8958 function get_performance_info() {
8959 global $CFG, $PERF, $DB, $PAGE;
8962 $info['html'] = ''; // Holds userfriendly HTML representation.
8963 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8965 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
8967 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8968 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8970 if (function_exists('memory_get_usage')) {
8971 $info['memory_total'] = memory_get_usage();
8972 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
8973 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8974 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8975 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8978 if (function_exists('memory_get_peak_usage')) {
8979 $info['memory_peak'] = memory_get_peak_usage();
8980 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8981 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8984 $inc = get_included_files();
8985 $info['includecount'] = count($inc);
8986 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8987 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8989 if (!empty($CFG->early_install_lang
) or empty($PAGE)) {
8990 // We can not track more performance before installation or before PAGE init, sorry.
8994 $filtermanager = filter_manager
::instance();
8995 if (method_exists($filtermanager, 'get_performance_summary')) {
8996 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8997 $info = array_merge($filterinfo, $info);
8998 foreach ($filterinfo as $key => $value) {
8999 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
9000 $info['txt'] .= "$key: $value ";
9004 $stringmanager = get_string_manager();
9005 if (method_exists($stringmanager, 'get_performance_summary')) {
9006 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9007 $info = array_merge($filterinfo, $info);
9008 foreach ($filterinfo as $key => $value) {
9009 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
9010 $info['txt'] .= "$key: $value ";
9014 if (!empty($PERF->logwrites
)) {
9015 $info['logwrites'] = $PERF->logwrites
;
9016 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
9017 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9020 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites
);
9021 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
9022 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9024 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9025 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
9026 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9028 if (function_exists('posix_times')) {
9029 $ptimes = posix_times();
9030 if (is_array($ptimes)) {
9031 foreach ($ptimes as $key => $val) {
9032 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
9034 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
9035 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9039 // Grab the load average for the last minute.
9040 // /proc will only work under some linux configurations
9041 // while uptime is there under MacOSX/Darwin and other unices.
9042 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
9043 list($serverload) = explode(' ', $loadavg[0]);
9045 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
9046 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9047 $serverload = $matches[1];
9049 trigger_error('Could not parse uptime output!');
9052 if (!empty($serverload)) {
9053 $info['serverload'] = $serverload;
9054 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
9055 $info['txt'] .= "serverload: {$info['serverload']} ";
9058 // Display size of session if session started.
9059 if ($si = \core\session\manager
::get_performance_info()) {
9060 $info['sessionsize'] = $si['size'];
9061 $info['html'] .= $si['html'];
9062 $info['txt'] .= $si['txt'];
9065 if ($stats = cache_helper
::get_stats()) {
9066 $html = '<span class="cachesused">';
9067 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
9068 $text = 'Caches used (hits/misses/sets): ';
9072 foreach ($stats as $definition => $stores) {
9073 $html .= '<span class="cache-definition-stats">';
9074 $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
9075 $text .= "$definition {";
9076 foreach ($stores as $store => $data) {
9077 $hits +
= $data['hits'];
9078 $misses +
= $data['misses'];
9079 $sets +
= $data['sets'];
9080 if ($data['hits'] == 0 and $data['misses'] > 0) {
9081 $cachestoreclass = 'nohits';
9082 } else if ($data['hits'] < $data['misses']) {
9083 $cachestoreclass = 'lowhits';
9085 $cachestoreclass = 'hihits';
9087 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9088 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
9093 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
9094 $html .= '</span> ';
9095 $info['cachesused'] = "$hits / $misses / $sets";
9096 $info['html'] .= $html;
9097 $info['txt'] .= $text.'. ';
9099 $info['cachesused'] = '0 / 0 / 0';
9100 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
9101 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9104 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
9111 * @todo Document this function linux people
9113 function apd_get_profiling() {
9114 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
9118 * Delete directory or only its content
9120 * @param string $dir directory path
9121 * @param bool $contentonly
9122 * @return bool success, true also if dir does not exist
9124 function remove_dir($dir, $contentonly=false) {
9125 if (!file_exists($dir)) {
9129 if (!$handle = opendir($dir)) {
9133 while (false!==($item = readdir($handle))) {
9134 if ($item != '.' && $item != '..') {
9135 if (is_dir($dir.'/'.$item)) {
9136 $result = remove_dir($dir.'/'.$item) && $result;
9138 $result = unlink($dir.'/'.$item) && $result;
9144 clearstatcache(); // Make sure file stat cache is properly invalidated.
9147 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9148 clearstatcache(); // Make sure file stat cache is properly invalidated.
9153 * Detect if an object or a class contains a given property
9154 * will take an actual object or the name of a class
9156 * @param mix $obj Name of class or real object to test
9157 * @param string $property name of property to find
9158 * @return bool true if property exists
9160 function object_property_exists( $obj, $property ) {
9161 if (is_string( $obj )) {
9162 $properties = get_class_vars( $obj );
9164 $properties = get_object_vars( $obj );
9166 return array_key_exists( $property, $properties );
9170 * Converts an object into an associative array
9172 * This function converts an object into an associative array by iterating
9173 * over its public properties. Because this function uses the foreach
9174 * construct, Iterators are respected. It works recursively on arrays of objects.
9175 * Arrays and simple values are returned as is.
9177 * If class has magic properties, it can implement IteratorAggregate
9178 * and return all available properties in getIterator()
9183 function convert_to_array($var) {
9186 // Loop over elements/properties.
9187 foreach ($var as $key => $value) {
9188 // Recursively convert objects.
9189 if (is_object($value) ||
is_array($value)) {
9190 $result[$key] = convert_to_array($value);
9192 // Simple values are untouched.
9193 $result[$key] = $value;
9200 * Detect a custom script replacement in the data directory that will
9201 * replace an existing moodle script
9203 * @return string|bool full path name if a custom script exists, false if no custom script exists
9205 function custom_script_path() {
9206 global $CFG, $SCRIPT;
9208 if ($SCRIPT === null) {
9209 // Probably some weird external script.
9213 $scriptpath = $CFG->customscripts
. $SCRIPT;
9215 // Check the custom script exists.
9216 if (file_exists($scriptpath) and is_file($scriptpath)) {
9224 * Returns whether or not the user object is a remote MNET user. This function
9225 * is in moodlelib because it does not rely on loading any of the MNET code.
9227 * @param object $user A valid user object
9228 * @return bool True if the user is from a remote Moodle.
9230 function is_mnet_remote_user($user) {
9233 if (!isset($CFG->mnet_localhost_id
)) {
9234 include_once($CFG->dirroot
. '/mnet/lib.php');
9235 $env = new mnet_environment();
9240 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
9244 * This function will search for browser prefereed languages, setting Moodle
9245 * to use the best one available if $SESSION->lang is undefined
9247 function setup_lang_from_browser() {
9248 global $CFG, $SESSION, $USER;
9250 if (!empty($SESSION->lang
) or !empty($USER->lang
) or empty($CFG->autolang
)) {
9251 // Lang is defined in session or user profile, nothing to do.
9255 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9259 // Extract and clean langs from headers.
9260 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9261 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9262 $rawlangs = explode(',', $rawlangs); // Convert to array.
9266 foreach ($rawlangs as $lang) {
9267 if (strpos($lang, ';') === false) {
9268 $langs[(string)$order] = $lang;
9269 $order = $order-0.01;
9271 $parts = explode(';', $lang);
9272 $pos = strpos($parts[1], '=');
9273 $langs[substr($parts[1], $pos+
1)] = $parts[0];
9276 krsort($langs, SORT_NUMERIC
);
9278 // Look for such langs under standard locations.
9279 foreach ($langs as $lang) {
9280 // Clean it properly for include.
9281 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR
));
9282 if (get_string_manager()->translation_exists($lang, false)) {
9283 // Lang exists, set it in session.
9284 $SESSION->lang
= $lang;
9285 // We have finished. Go out.
9293 * Check if $url matches anything in proxybypass list
9295 * Any errors just result in the proxy being used (least bad)
9297 * @param string $url url to check
9298 * @return boolean true if we should bypass the proxy
9300 function is_proxybypass( $url ) {
9304 if (empty($CFG->proxyhost
) or empty($CFG->proxybypass
)) {
9308 // Get the host part out of the url.
9309 if (!$host = parse_url( $url, PHP_URL_HOST
)) {
9313 // Get the possible bypass hosts into an array.
9314 $matches = explode( ',', $CFG->proxybypass
);
9316 // Check for a match.
9317 // (IPs need to match the left hand side and hosts the right of the url,
9318 // but we can recklessly check both as there can't be a false +ve).
9319 foreach ($matches as $match) {
9320 $match = trim($match);
9322 // Try for IP match (Left side).
9323 $lhs = substr($host, 0, strlen($match));
9324 if (strcasecmp($match, $lhs)==0) {
9328 // Try for host match (Right side).
9329 $rhs = substr($host, -strlen($match));
9330 if (strcasecmp($match, $rhs)==0) {
9340 * Check if the passed navigation is of the new style
9342 * @param mixed $navigation
9343 * @return bool true for yes false for no
9345 function is_newnav($navigation) {
9346 if (is_array($navigation) && !empty($navigation['newnav'])) {
9354 * Checks whether the given variable name is defined as a variable within the given object.
9356 * This will NOT work with stdClass objects, which have no class variables.
9358 * @param string $var The variable name
9359 * @param object $object The object to check
9362 function in_object_vars($var, $object) {
9363 $classvars = get_class_vars(get_class($object));
9364 $classvars = array_keys($classvars);
9365 return in_array($var, $classvars);
9369 * Returns an array without repeated objects.
9370 * This function is similar to array_unique, but for arrays that have objects as values
9372 * @param array $array
9373 * @param bool $keepkeyassoc
9376 function object_array_unique($array, $keepkeyassoc = true) {
9377 $duplicatekeys = array();
9380 foreach ($array as $key => $val) {
9381 // Convert objects to arrays, in_array() does not support objects.
9382 if (is_object($val)) {
9386 if (!in_array($val, $tmp)) {
9389 $duplicatekeys[] = $key;
9393 foreach ($duplicatekeys as $key) {
9394 unset($array[$key]);
9397 return $keepkeyassoc ?
$array : array_values($array);
9401 * Is a userid the primary administrator?
9403 * @param int $userid int id of user to check
9406 function is_primary_admin($userid) {
9407 $primaryadmin = get_admin();
9409 if ($userid == $primaryadmin->id
) {
9417 * Returns the site identifier
9419 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9421 function get_site_identifier() {
9423 // Check to see if it is missing. If so, initialise it.
9424 if (empty($CFG->siteidentifier
)) {
9425 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9428 return $CFG->siteidentifier
;
9432 * Check whether the given password has no more than the specified
9433 * number of consecutive identical characters.
9435 * @param string $password password to be checked against the password policy
9436 * @param integer $maxchars maximum number of consecutive identical characters
9439 function check_consecutive_identical_characters($password, $maxchars) {
9441 if ($maxchars < 1) {
9442 return true; // Zero 0 is to disable this check.
9444 if (strlen($password) <= $maxchars) {
9445 return true; // Too short to fail this test.
9449 $consecutivecount = 1;
9450 foreach (str_split($password) as $char) {
9451 if ($char != $previouschar) {
9452 $consecutivecount = 1;
9454 $consecutivecount++
;
9455 if ($consecutivecount > $maxchars) {
9456 return false; // Check failed already.
9460 $previouschar = $char;
9467 * Helper function to do partial function binding.
9468 * so we can use it for preg_replace_callback, for example
9469 * this works with php functions, user functions, static methods and class methods
9470 * it returns you a callback that you can pass on like so:
9472 * $callback = partial('somefunction', $arg1, $arg2);
9474 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9476 * $obj = new someclass();
9477 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9479 * and then the arguments that are passed through at calltime are appended to the argument list.
9481 * @param mixed $function a php callback
9482 * @param mixed $arg1,... $argv arguments to partially bind with
9483 * @return array Array callback
9485 function partial() {
9486 if (!class_exists('partial')) {
9488 * Used to manage function binding.
9489 * @copyright 2009 Penny Leach
9490 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9494 public $values = array();
9495 /** @var string The function to call as a callback. */
9499 * @param string $func
9500 * @param array $args
9502 public function __construct($func, $args) {
9503 $this->values
= $args;
9504 $this->func
= $func;
9507 * Calls the callback function.
9510 public function method() {
9511 $args = func_get_args();
9512 return call_user_func_array($this->func
, array_merge($this->values
, $args));
9516 $args = func_get_args();
9517 $func = array_shift($args);
9518 $p = new partial($func, $args);
9519 return array($p, 'method');
9523 * helper function to load up and initialise the mnet environment
9524 * this must be called before you use mnet functions.
9526 * @return mnet_environment the equivalent of old $MNET global
9528 function get_mnet_environment() {
9530 require_once($CFG->dirroot
. '/mnet/lib.php');
9531 static $instance = null;
9532 if (empty($instance)) {
9533 $instance = new mnet_environment();
9540 * during xmlrpc server code execution, any code wishing to access
9541 * information about the remote peer must use this to get it.
9543 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9545 function get_mnet_remote_client() {
9546 if (!defined('MNET_SERVER')) {
9547 debugging(get_string('notinxmlrpcserver', 'mnet'));
9550 global $MNET_REMOTE_CLIENT;
9551 if (isset($MNET_REMOTE_CLIENT)) {
9552 return $MNET_REMOTE_CLIENT;
9558 * during the xmlrpc server code execution, this will be called
9559 * to setup the object returned by {@link get_mnet_remote_client}
9561 * @param mnet_remote_client $client the client to set up
9562 * @throws moodle_exception
9564 function set_mnet_remote_client($client) {
9565 if (!defined('MNET_SERVER')) {
9566 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9568 global $MNET_REMOTE_CLIENT;
9569 $MNET_REMOTE_CLIENT = $client;
9573 * return the jump url for a given remote user
9574 * this is used for rewriting forum post links in emails, etc
9576 * @param stdclass $user the user to get the idp url for
9578 function mnet_get_idp_jump_url($user) {
9581 static $mnetjumps = array();
9582 if (!array_key_exists($user->mnethostid
, $mnetjumps)) {
9583 $idp = mnet_get_peer_host($user->mnethostid
);
9584 $idpjumppath = mnet_get_app_jumppath($idp->applicationid
);
9585 $mnetjumps[$user->mnethostid
] = $idp->wwwroot
. $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot
. '&wantsurl=';
9587 return $mnetjumps[$user->mnethostid
];
9591 * Gets the homepage to use for the current user
9593 * @return int One of HOMEPAGE_*
9595 function get_home_page() {
9598 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage
)) {
9599 if ($CFG->defaulthomepage
== HOMEPAGE_MY
) {
9602 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY
);
9605 return HOMEPAGE_SITE
;
9609 * Gets the name of a course to be displayed when showing a list of courses.
9610 * By default this is just $course->fullname but user can configure it. The
9611 * result of this function should be passed through print_string.
9612 * @param stdClass|course_in_list $course Moodle course object
9613 * @return string Display name of course (either fullname or short + fullname)
9615 function get_course_display_name_for_list($course) {
9617 if (!empty($CFG->courselistshortnames
)) {
9618 if (!($course instanceof stdClass
)) {
9619 $course = (object)convert_to_array($course);
9621 return get_string('courseextendednamedisplay', '', $course);
9623 return $course->fullname
;
9628 * The lang_string class
9630 * This special class is used to create an object representation of a string request.
9631 * It is special because processing doesn't occur until the object is first used.
9632 * The class was created especially to aid performance in areas where strings were
9633 * required to be generated but were not necessarily used.
9634 * As an example the admin tree when generated uses over 1500 strings, of which
9635 * normally only 1/3 are ever actually printed at any time.
9636 * The performance advantage is achieved by not actually processing strings that
9637 * arn't being used, as such reducing the processing required for the page.
9639 * How to use the lang_string class?
9640 * There are two methods of using the lang_string class, first through the
9641 * forth argument of the get_string function, and secondly directly.
9642 * The following are examples of both.
9643 * 1. Through get_string calls e.g.
9644 * $string = get_string($identifier, $component, $a, true);
9645 * $string = get_string('yes', 'moodle', null, true);
9646 * 2. Direct instantiation
9647 * $string = new lang_string($identifier, $component, $a, $lang);
9648 * $string = new lang_string('yes');
9650 * How do I use a lang_string object?
9651 * The lang_string object makes use of a magic __toString method so that you
9652 * are able to use the object exactly as you would use a string in most cases.
9653 * This means you are able to collect it into a variable and then directly
9654 * echo it, or concatenate it into another string, or similar.
9655 * The other thing you can do is manually get the string by calling the
9656 * lang_strings out method e.g.
9657 * $string = new lang_string('yes');
9659 * Also worth noting is that the out method can take one argument, $lang which
9660 * allows the developer to change the language on the fly.
9662 * When should I use a lang_string object?
9663 * The lang_string object is designed to be used in any situation where a
9664 * string may not be needed, but needs to be generated.
9665 * The admin tree is a good example of where lang_string objects should be
9667 * A more practical example would be any class that requries strings that may
9668 * not be printed (after all classes get renderer by renderers and who knows
9669 * what they will do ;))
9671 * When should I not use a lang_string object?
9672 * Don't use lang_strings when you are going to use a string immediately.
9673 * There is no need as it will be processed immediately and there will be no
9674 * advantage, and in fact perhaps a negative hit as a class has to be
9675 * instantiated for a lang_string object, however get_string won't require
9679 * 1. You cannot use a lang_string object as an array offset. Doing so will
9680 * result in PHP throwing an error. (You can use it as an object property!)
9684 * @copyright 2011 Sam Hemelryk
9685 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9689 /** @var string The strings identifier */
9690 protected $identifier;
9691 /** @var string The strings component. Default '' */
9692 protected $component = '';
9693 /** @var array|stdClass Any arguments required for the string. Default null */
9694 protected $a = null;
9695 /** @var string The language to use when processing the string. Default null */
9696 protected $lang = null;
9698 /** @var string The processed string (once processed) */
9699 protected $string = null;
9702 * A special boolean. If set to true then the object has been woken up and
9703 * cannot be regenerated. If this is set then $this->string MUST be used.
9706 protected $forcedstring = false;
9709 * Constructs a lang_string object
9711 * This function should do as little processing as possible to ensure the best
9712 * performance for strings that won't be used.
9714 * @param string $identifier The strings identifier
9715 * @param string $component The strings component
9716 * @param stdClass|array $a Any arguments the string requires
9717 * @param string $lang The language to use when processing the string.
9718 * @throws coding_exception
9720 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9721 if (empty($component)) {
9722 $component = 'moodle';
9725 $this->identifier
= $identifier;
9726 $this->component
= $component;
9727 $this->lang
= $lang;
9729 // We MUST duplicate $a to ensure that it if it changes by reference those
9730 // changes are not carried across.
9731 // To do this we always ensure $a or its properties/values are strings
9732 // and that any properties/values that arn't convertable are forgotten.
9734 if (is_scalar($a)) {
9736 } else if ($a instanceof lang_string
) {
9737 $this->a
= $a->out();
9738 } else if (is_object($a) or is_array($a)) {
9741 foreach ($a as $key => $value) {
9742 // Make sure conversion errors don't get displayed (results in '').
9743 if (is_array($value)) {
9744 $this->a
[$key] = '';
9745 } else if (is_object($value)) {
9746 if (method_exists($value, '__toString')) {
9747 $this->a
[$key] = $value->__toString();
9749 $this->a
[$key] = '';
9752 $this->a
[$key] = (string)$value;
9758 if (debugging(false, DEBUG_DEVELOPER
)) {
9759 if (clean_param($this->identifier
, PARAM_STRINGID
) == '') {
9760 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9762 if (!empty($this->component
) && clean_param($this->component
, PARAM_COMPONENT
) == '') {
9763 throw new coding_exception('Invalid string compontent. Please check your string definition');
9765 if (!get_string_manager()->string_exists($this->identifier
, $this->component
)) {
9766 debugging('String does not exist. Please check your string definition for '.$this->identifier
.'/'.$this->component
, DEBUG_DEVELOPER
);
9772 * Processes the string.
9774 * This function actually processes the string, stores it in the string property
9775 * and then returns it.
9776 * You will notice that this function is VERY similar to the get_string method.
9777 * That is because it is pretty much doing the same thing.
9778 * However as this function is an upgrade it isn't as tolerant to backwards
9782 * @throws coding_exception
9784 protected function get_string() {
9787 // Check if we need to process the string.
9788 if ($this->string === null) {
9789 // Check the quality of the identifier.
9790 if ($CFG->debugdeveloper
&& clean_param($this->identifier
, PARAM_STRINGID
) === '') {
9791 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
);
9794 // Process the string.
9795 $this->string = get_string_manager()->get_string($this->identifier
, $this->component
, $this->a
, $this->lang
);
9796 // Debugging feature lets you display string identifier and component.
9797 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
9798 $this->string .= ' {' . $this->identifier
. '/' . $this->component
. '}';
9801 // Return the string.
9802 return $this->string;
9806 * Returns the string
9808 * @param string $lang The langauge to use when processing the string
9811 public function out($lang = null) {
9812 if ($lang !== null && $lang != $this->lang
&& ($this->lang
== null && $lang != current_language())) {
9813 if ($this->forcedstring
) {
9814 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang
.' used)', DEBUG_DEVELOPER
);
9815 return $this->get_string();
9817 $translatedstring = new lang_string($this->identifier
, $this->component
, $this->a
, $lang);
9818 return $translatedstring->out();
9820 return $this->get_string();
9824 * Magic __toString method for printing a string
9828 public function __toString() {
9829 return $this->get_string();
9833 * Magic __set_state method used for var_export
9837 public function __set_state() {
9838 return $this->get_string();
9842 * Prepares the lang_string for sleep and stores only the forcedstring and
9843 * string properties... the string cannot be regenerated so we need to ensure
9844 * it is generated for this.
9848 public function __sleep() {
9849 $this->get_string();
9850 $this->forcedstring
= true;
9851 return array('forcedstring', 'string', 'lang');