MDL-31936 workshop: Delete attachments on record removal
[moodle.git] / lib / moodlelib.php
blobe44954f90c002a38ad6eb87b999a6cad85ea90e4
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
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
25 * @package core
26 * @subpackage lib
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.
36 /**
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
41 /**
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
46 /**
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
51 /**
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
56 /**
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
61 /**
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
66 /**
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.
74 /**
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
77 define('PARAM_ALPHA', 'alpha');
79 /**
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');
85 /**
86 * PARAM_ALPHANUM - expected numbers and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
90 /**
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
95 /**
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');
327 // Web Services.
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);
354 // Page types.
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);
374 // Tag constants.
376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True if module supports outcomes */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
421 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
423 /** Type of module */
424 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425 /** True if module supports intro editor */
426 define('FEATURE_MOD_INTRO', 'mod_intro');
427 /** True if module has default completion */
428 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
430 define('FEATURE_COMMENT', 'comment');
432 define('FEATURE_RATE', 'rate');
433 /** True if module supports backup/restore of moodle2 format */
434 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
436 /** True if module can show description on course main page */
437 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
439 /** True if module uses the question bank */
440 define('FEATURE_USES_QUESTIONS', 'usesquestions');
442 /** Unspecified module archetype */
443 define('MOD_ARCHETYPE_OTHER', 0);
444 /** Resource-like type module */
445 define('MOD_ARCHETYPE_RESOURCE', 1);
446 /** Assignment module archetype */
447 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
448 /** System (not user-addable) module archetype */
449 define('MOD_ARCHETYPE_SYSTEM', 3);
451 /** Return this from modname_get_types callback to use default display in activity chooser */
452 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
455 * Security token used for allowing access
456 * from external application such as web services.
457 * Scripts do not use any session, performance is relatively
458 * low because we need to load access info in each request.
459 * Scripts are executed in parallel.
461 define('EXTERNAL_TOKEN_PERMANENT', 0);
464 * Security token used for allowing access
465 * of embedded applications, the code is executed in the
466 * active user session. Token is invalidated after user logs out.
467 * Scripts are executed serially - normal session locking is used.
469 define('EXTERNAL_TOKEN_EMBEDDED', 1);
472 * The home page should be the site home
474 define('HOMEPAGE_SITE', 0);
476 * The home page should be the users my page
478 define('HOMEPAGE_MY', 1);
480 * The home page can be chosen by the user
482 define('HOMEPAGE_USER', 2);
485 * Hub directory url (should be moodle.org)
487 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
491 * Moodle.org url (should be moodle.org)
493 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
496 * Moodle mobile app service name
498 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
501 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
503 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
506 * Course display settings: display all sections on one page.
508 define('COURSE_DISPLAY_SINGLEPAGE', 0);
510 * Course display settings: split pages into a page per section.
512 define('COURSE_DISPLAY_MULTIPAGE', 1);
515 * Authentication constant: String used in password field when password is not stored.
517 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
519 // PARAMETER HANDLING.
522 * Returns a particular value for the named variable, taken from
523 * POST or GET. If the parameter doesn't exist then an error is
524 * thrown because we require this variable.
526 * This function should be used to initialise all required values
527 * in a script that are based on parameters. Usually it will be
528 * used like this:
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
535 * @return mixed
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];
547 } else {
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
567 * used like this:
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
574 * @return array
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];
586 } else {
587 print_error('missingparam', '', '', $parname);
589 if (!is_array($param)) {
590 print_error('missingparam', '', '', $parname);
593 $result = array();
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);
597 continue;
599 $result[$key] = clean_param($value, $type);
602 return $result;
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
611 * used like this:
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
619 * @return mixed
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)) {
627 $default = null;
630 // POST has precedence.
631 if (isset($_POST[$parname])) {
632 $param = $_POST[$parname];
633 } else if (isset($_GET[$parname])) {
634 $param = $_GET[$parname];
635 } else {
636 return $default;
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
654 * used like this:
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
662 * @return array
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];
675 } else {
676 return $default;
678 if (!is_array($param)) {
679 debugging('optional_param_array() expects array parameters only: '.$parname);
680 return $default;
683 $result = array();
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);
687 continue;
689 $result[$key] = clean_param($value, $type);
692 return $result;
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) {
712 return null;
713 } else {
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)) {
726 // These always fit.
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);
735 return $cleaned;
739 * Makes sure array contains only the allowed types, this function does not validate array key names!
741 * <code>
742 * $options = clean_param($options, PARAM_INT);
743 * </code>
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
748 * @return array
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)) {
756 if ($recursive) {
757 $param[$key] = clean_param_array($value, $type, true);
758 } else {
759 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
761 } else {
762 $param[$key] = clean_param($value, $type);
765 return $param;
769 * Used by {@link optional_param()} and {@link required_param()} to
770 * clean the variables and/or cast to specific types, based on
771 * an options field.
772 * <code>
773 * $course->format = clean_param($course->format, PARAM_ALPHA);
774 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
775 * </code>
777 * @param mixed $param the variable we are cleaning
778 * @param string $type expected format of param after cleaning.
779 * @return mixed
780 * @throws coding_exception
782 function clean_param($param, $type) {
783 global $CFG;
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();
790 } else {
791 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
795 switch ($type) {
796 case PARAM_RAW:
797 // No cleaning at all.
798 $param = fix_utf8($param);
799 return $param;
801 case PARAM_RAW_TRIMMED:
802 // No cleaning, but strip leading and trailing whitespace.
803 $param = fix_utf8($param);
804 return trim($param);
806 case PARAM_CLEAN:
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)) {
810 return $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);
821 return trim($param);
823 case PARAM_INT:
824 // Convert to integer.
825 return (int)$param;
827 case PARAM_FLOAT:
828 // Convert to float.
829 return (float)$param;
831 case PARAM_ALPHA:
832 // Remove everything not `a-z`.
833 return preg_replace('/[^a-zA-Z]/i', '', $param);
835 case PARAM_ALPHAEXT:
836 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
837 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
839 case PARAM_ALPHANUM:
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);
847 case PARAM_SEQUENCE:
848 // Remove everything not `0-9,`.
849 return preg_replace('/[^0-9,]/i', '', $param);
851 case PARAM_BOOL:
852 // Convert to 1 or 0.
853 $tempstr = strtolower($param);
854 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
855 $param = 1;
856 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
857 $param = 0;
858 } else {
859 $param = empty($param) ? 0 : 1;
861 return $param;
863 case PARAM_NOTAGS:
864 // Strip all tags.
865 $param = fix_utf8($param);
866 return strip_tags($param);
868 case PARAM_TEXT:
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.
873 do {
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)) {
878 break;
880 $open = false;
881 foreach ($matches[0] as $match) {
882 if ($match === '</lang>') {
883 if ($open) {
884 $open = false;
885 continue;
886 } else {
887 break 2;
890 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
891 break 2;
892 } else {
893 $open = true;
896 if ($open) {
897 break;
899 return $param;
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)) {
905 break;
907 $open = false;
908 foreach ($matches[0] as $match) {
909 if ($match === '</span>') {
910 if ($open) {
911 $open = false;
912 continue;
913 } else {
914 break 2;
917 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
918 break 2;
919 } else {
920 $open = true;
923 if ($open) {
924 break;
926 return $param;
928 } while (false);
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)) {
936 return '';
938 if (strpos($param, '__') !== false) {
939 return '';
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) {
944 return '';
947 return $param;
949 case PARAM_PLUGIN:
950 case PARAM_AREA:
951 // We do not want any guessing here, either the name is correct or not.
952 if (!is_valid_plugin_name($param)) {
953 return '';
955 return $param;
957 case PARAM_SAFEDIR:
958 // Remove everything not a-zA-Z0-9_- .
959 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
961 case PARAM_SAFEPATH:
962 // Remove everything not a-zA-Z0-9/_- .
963 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
965 case PARAM_FILE:
966 // Strip all suspicious characters from filename.
967 $param = fix_utf8($param);
968 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
969 if ($param === '.' || $param === '..') {
970 $param = '';
972 return $param;
974 case PARAM_PATH:
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.
984 } else {
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);
994 return $param;
996 case PARAM_HOST:
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
1003 || $match[1] > 255
1004 || $match[3] > 255
1005 || $match[4] > 255 ) {
1006 // Hmmm, what kind of dotted quad is this?
1007 $param = '';
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.
1014 } else {
1015 // All is not ok...
1016 $param='';
1018 return $param;
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.
1025 } else {
1026 // Not really ok.
1027 $param ='';
1029 return $param;
1031 case PARAM_LOCALURL:
1032 // Allow http absolute, root relative and relative URLs within wwwroot.
1033 $param = clean_param($param, PARAM_URL);
1034 if (!empty($param)) {
1035 if (preg_match(':^/:', $param)) {
1036 // Root-relative, ok!
1037 } else if (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i', $param)) {
1038 // Absolute, and matches our wwwroot.
1039 } else {
1040 // Relative - let's make sure there are no tricks.
1041 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1042 // Looks ok.
1043 } else {
1044 $param = '';
1048 return $param;
1050 case PARAM_PEM:
1051 $param = trim($param);
1052 // PEM formatted strings may contain letters/numbers and the symbols:
1053 // forward slash: /
1054 // plus sign: +
1055 // equal sign: =
1056 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1057 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1058 list($wholething, $body) = $matches;
1059 unset($wholething, $matches);
1060 $b64 = clean_param($body, PARAM_BASE64);
1061 if (!empty($b64)) {
1062 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1063 } else {
1064 return '';
1067 return '';
1069 case PARAM_BASE64:
1070 if (!empty($param)) {
1071 // PEM formatted strings may contain letters/numbers and the symbols
1072 // forward slash: /
1073 // plus sign: +
1074 // equal sign: =.
1075 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1076 return '';
1078 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1079 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1080 // than (or equal to) 64 characters long.
1081 for ($i=0, $j=count($lines); $i < $j; $i++) {
1082 if ($i + 1 == $j) {
1083 if (64 < strlen($lines[$i])) {
1084 return '';
1086 continue;
1089 if (64 != strlen($lines[$i])) {
1090 return '';
1093 return implode("\n", $lines);
1094 } else {
1095 return '';
1098 case PARAM_TAG:
1099 $param = fix_utf8($param);
1100 // Please note it is not safe to use the tag name directly anywhere,
1101 // it must be processed with s(), urlencode() before embedding anywhere.
1102 // Remove some nasties.
1103 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1104 // Convert many whitespace chars into one.
1105 $param = preg_replace('/\s+/', ' ', $param);
1106 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1107 return $param;
1109 case PARAM_TAGLIST:
1110 $param = fix_utf8($param);
1111 $tags = explode(',', $param);
1112 $result = array();
1113 foreach ($tags as $tag) {
1114 $res = clean_param($tag, PARAM_TAG);
1115 if ($res !== '') {
1116 $result[] = $res;
1119 if ($result) {
1120 return implode(',', $result);
1121 } else {
1122 return '';
1125 case PARAM_CAPABILITY:
1126 if (get_capability_info($param)) {
1127 return $param;
1128 } else {
1129 return '';
1132 case PARAM_PERMISSION:
1133 $param = (int)$param;
1134 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1135 return $param;
1136 } else {
1137 return CAP_INHERIT;
1140 case PARAM_AUTH:
1141 $param = clean_param($param, PARAM_PLUGIN);
1142 if (empty($param)) {
1143 return '';
1144 } else if (exists_auth_plugin($param)) {
1145 return $param;
1146 } else {
1147 return '';
1150 case PARAM_LANG:
1151 $param = clean_param($param, PARAM_SAFEDIR);
1152 if (get_string_manager()->translation_exists($param)) {
1153 return $param;
1154 } else {
1155 // Specified language is not installed or param malformed.
1156 return '';
1159 case PARAM_THEME:
1160 $param = clean_param($param, PARAM_PLUGIN);
1161 if (empty($param)) {
1162 return '';
1163 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1164 return $param;
1165 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1166 return $param;
1167 } else {
1168 // Specified theme is not installed.
1169 return '';
1172 case PARAM_USERNAME:
1173 $param = fix_utf8($param);
1174 $param = trim($param);
1175 // Convert uppercase to lowercase MDL-16919.
1176 $param = core_text::strtolower($param);
1177 if (empty($CFG->extendedusernamechars)) {
1178 $param = str_replace(" " , "", $param);
1179 // Regular expression, eliminate all chars EXCEPT:
1180 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1181 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1183 return $param;
1185 case PARAM_EMAIL:
1186 $param = fix_utf8($param);
1187 if (validate_email($param)) {
1188 return $param;
1189 } else {
1190 return '';
1193 case PARAM_STRINGID:
1194 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1195 return $param;
1196 } else {
1197 return '';
1200 case PARAM_TIMEZONE:
1201 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1202 $param = fix_utf8($param);
1203 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1204 if (preg_match($timezonepattern, $param)) {
1205 return $param;
1206 } else {
1207 return '';
1210 default:
1211 // Doh! throw error, switched parameters in optional_param or another serious problem.
1212 print_error("unknownparamtype", '', '', $type);
1217 * Makes sure the data is using valid utf8, invalid characters are discarded.
1219 * Note: this function is not intended for full objects with methods and private properties.
1221 * @param mixed $value
1222 * @return mixed with proper utf-8 encoding
1224 function fix_utf8($value) {
1225 if (is_null($value) or $value === '') {
1226 return $value;
1228 } else if (is_string($value)) {
1229 if ((string)(int)$value === $value) {
1230 // Shortcut.
1231 return $value;
1233 // No null bytes expected in our data, so let's remove it.
1234 $value = str_replace("\0", '', $value);
1236 // Note: this duplicates min_fix_utf8() intentionally.
1237 static $buggyiconv = null;
1238 if ($buggyiconv === null) {
1239 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1242 if ($buggyiconv) {
1243 if (function_exists('mb_convert_encoding')) {
1244 $subst = mb_substitute_character();
1245 mb_substitute_character('');
1246 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1247 mb_substitute_character($subst);
1249 } else {
1250 // Warn admins on admin/index.php page.
1251 $result = $value;
1254 } else {
1255 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1258 return $result;
1260 } else if (is_array($value)) {
1261 foreach ($value as $k => $v) {
1262 $value[$k] = fix_utf8($v);
1264 return $value;
1266 } else if (is_object($value)) {
1267 // Do not modify original.
1268 $value = clone($value);
1269 foreach ($value as $k => $v) {
1270 $value->$k = fix_utf8($v);
1272 return $value;
1274 } else {
1275 // This is some other type, no utf-8 here.
1276 return $value;
1281 * Return true if given value is integer or string with integer value
1283 * @param mixed $value String or Int
1284 * @return bool true if number, false if not
1286 function is_number($value) {
1287 if (is_int($value)) {
1288 return true;
1289 } else if (is_string($value)) {
1290 return ((string)(int)$value) === $value;
1291 } else {
1292 return false;
1297 * Returns host part from url.
1299 * @param string $url full url
1300 * @return string host, null if not found
1302 function get_host_from_url($url) {
1303 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1304 if ($matches) {
1305 return $matches[1];
1307 return null;
1311 * Tests whether anything was returned by text editor
1313 * This function is useful for testing whether something you got back from
1314 * the HTML editor actually contains anything. Sometimes the HTML editor
1315 * appear to be empty, but actually you get back a <br> tag or something.
1317 * @param string $string a string containing HTML.
1318 * @return boolean does the string contain any actual content - that is text,
1319 * images, objects, etc.
1321 function html_is_blank($string) {
1322 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1326 * Set a key in global configuration
1328 * Set a key/value pair in both this session's {@link $CFG} global variable
1329 * and in the 'config' database table for future sessions.
1331 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1332 * In that case it doesn't affect $CFG.
1334 * A NULL value will delete the entry.
1336 * NOTE: this function is called from lib/db/upgrade.php
1338 * @param string $name the key to set
1339 * @param string $value the value to set (without magic quotes)
1340 * @param string $plugin (optional) the plugin scope, default null
1341 * @return bool true or exception
1343 function set_config($name, $value, $plugin=null) {
1344 global $CFG, $DB;
1346 if (empty($plugin)) {
1347 if (!array_key_exists($name, $CFG->config_php_settings)) {
1348 // So it's defined for this invocation at least.
1349 if (is_null($value)) {
1350 unset($CFG->$name);
1351 } else {
1352 // Settings from db are always strings.
1353 $CFG->$name = (string)$value;
1357 if ($DB->get_field('config', 'name', array('name' => $name))) {
1358 if ($value === null) {
1359 $DB->delete_records('config', array('name' => $name));
1360 } else {
1361 $DB->set_field('config', 'value', $value, array('name' => $name));
1363 } else {
1364 if ($value !== null) {
1365 $config = new stdClass();
1366 $config->name = $name;
1367 $config->value = $value;
1368 $DB->insert_record('config', $config, false);
1371 if ($name === 'siteidentifier') {
1372 cache_helper::update_site_identifier($value);
1374 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1375 } else {
1376 // Plugin scope.
1377 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1378 if ($value===null) {
1379 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1380 } else {
1381 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1383 } else {
1384 if ($value !== null) {
1385 $config = new stdClass();
1386 $config->plugin = $plugin;
1387 $config->name = $name;
1388 $config->value = $value;
1389 $DB->insert_record('config_plugins', $config, false);
1392 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1395 return true;
1399 * Get configuration values from the global config table
1400 * or the config_plugins table.
1402 * If called with one parameter, it will load all the config
1403 * variables for one plugin, and return them as an object.
1405 * If called with 2 parameters it will return a string single
1406 * value or false if the value is not found.
1408 * NOTE: this function is called from lib/db/upgrade.php
1410 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1411 * that we need only fetch it once per request.
1412 * @param string $plugin full component name
1413 * @param string $name default null
1414 * @return mixed hash-like object or single value, return false no config found
1415 * @throws dml_exception
1417 function get_config($plugin, $name = null) {
1418 global $CFG, $DB;
1420 static $siteidentifier = null;
1422 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1423 $forced =& $CFG->config_php_settings;
1424 $iscore = true;
1425 $plugin = 'core';
1426 } else {
1427 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1428 $forced =& $CFG->forced_plugin_settings[$plugin];
1429 } else {
1430 $forced = array();
1432 $iscore = false;
1435 if ($siteidentifier === null) {
1436 try {
1437 // This may fail during installation.
1438 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1439 // install the database.
1440 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1441 } catch (dml_exception $ex) {
1442 // Set siteidentifier to false. We don't want to trip this continually.
1443 $siteidentifier = false;
1444 throw $ex;
1448 if (!empty($name)) {
1449 if (array_key_exists($name, $forced)) {
1450 return (string)$forced[$name];
1451 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1452 return $siteidentifier;
1456 $cache = cache::make('core', 'config');
1457 $result = $cache->get($plugin);
1458 if ($result === false) {
1459 // The user is after a recordset.
1460 if (!$iscore) {
1461 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1462 } else {
1463 // This part is not really used any more, but anyway...
1464 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1466 $cache->set($plugin, $result);
1469 if (!empty($name)) {
1470 if (array_key_exists($name, $result)) {
1471 return $result[$name];
1473 return false;
1476 if ($plugin === 'core') {
1477 $result['siteidentifier'] = $siteidentifier;
1480 foreach ($forced as $key => $value) {
1481 if (is_null($value) or is_array($value) or is_object($value)) {
1482 // We do not want any extra mess here, just real settings that could be saved in db.
1483 unset($result[$key]);
1484 } else {
1485 // Convert to string as if it went through the DB.
1486 $result[$key] = (string)$value;
1490 return (object)$result;
1494 * Removes a key from global configuration.
1496 * NOTE: this function is called from lib/db/upgrade.php
1498 * @param string $name the key to set
1499 * @param string $plugin (optional) the plugin scope
1500 * @return boolean whether the operation succeeded.
1502 function unset_config($name, $plugin=null) {
1503 global $CFG, $DB;
1505 if (empty($plugin)) {
1506 unset($CFG->$name);
1507 $DB->delete_records('config', array('name' => $name));
1508 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1509 } else {
1510 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1511 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1514 return true;
1518 * Remove all the config variables for a given plugin.
1520 * NOTE: this function is called from lib/db/upgrade.php
1522 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1523 * @return boolean whether the operation succeeded.
1525 function unset_all_config_for_plugin($plugin) {
1526 global $DB;
1527 // Delete from the obvious config_plugins first.
1528 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1529 // Next delete any suspect settings from config.
1530 $like = $DB->sql_like('name', '?', true, true, false, '|');
1531 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1532 $DB->delete_records_select('config', $like, $params);
1533 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1534 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1536 return true;
1540 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1542 * All users are verified if they still have the necessary capability.
1544 * @param string $value the value of the config setting.
1545 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1546 * @param bool $includeadmins include administrators.
1547 * @return array of user objects.
1549 function get_users_from_config($value, $capability, $includeadmins = true) {
1550 if (empty($value) or $value === '$@NONE@$') {
1551 return array();
1554 // We have to make sure that users still have the necessary capability,
1555 // it should be faster to fetch them all first and then test if they are present
1556 // instead of validating them one-by-one.
1557 $users = get_users_by_capability(context_system::instance(), $capability);
1558 if ($includeadmins) {
1559 $admins = get_admins();
1560 foreach ($admins as $admin) {
1561 $users[$admin->id] = $admin;
1565 if ($value === '$@ALL@$') {
1566 return $users;
1569 $result = array(); // Result in correct order.
1570 $allowed = explode(',', $value);
1571 foreach ($allowed as $uid) {
1572 if (isset($users[$uid])) {
1573 $user = $users[$uid];
1574 $result[$user->id] = $user;
1578 return $result;
1583 * Invalidates browser caches and cached data in temp.
1585 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1586 * {@link phpunit_util::reset_dataroot()}
1588 * @return void
1590 function purge_all_caches() {
1591 global $CFG, $DB;
1593 reset_text_filters_cache();
1594 js_reset_all_caches();
1595 theme_reset_all_caches();
1596 get_string_manager()->reset_caches();
1597 core_text::reset_caches();
1598 if (class_exists('core_plugin_manager')) {
1599 core_plugin_manager::reset_caches();
1602 // Bump up cacherev field for all courses.
1603 try {
1604 increment_revision_number('course', 'cacherev', '');
1605 } catch (moodle_exception $e) {
1606 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1609 $DB->reset_caches();
1610 cache_helper::purge_all();
1612 // Purge all other caches: rss, simplepie, etc.
1613 remove_dir($CFG->cachedir.'', true);
1615 // Make sure cache dir is writable, throws exception if not.
1616 make_cache_directory('');
1618 // This is the only place where we purge local caches, we are only adding files there.
1619 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1620 remove_dir($CFG->localcachedir, true);
1621 set_config('localcachedirpurged', time());
1622 make_localcache_directory('', true);
1623 \core\task\manager::clear_static_caches();
1627 * Get volatile flags
1629 * @param string $type
1630 * @param int $changedsince default null
1631 * @return array records array
1633 function get_cache_flags($type, $changedsince = null) {
1634 global $DB;
1636 $params = array('type' => $type, 'expiry' => time());
1637 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1638 if ($changedsince !== null) {
1639 $params['changedsince'] = $changedsince;
1640 $sqlwhere .= " AND timemodified > :changedsince";
1642 $cf = array();
1643 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1644 foreach ($flags as $flag) {
1645 $cf[$flag->name] = $flag->value;
1648 return $cf;
1652 * Get volatile flags
1654 * @param string $type
1655 * @param string $name
1656 * @param int $changedsince default null
1657 * @return string|false The cache flag value or false
1659 function get_cache_flag($type, $name, $changedsince=null) {
1660 global $DB;
1662 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1664 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1665 if ($changedsince !== null) {
1666 $params['changedsince'] = $changedsince;
1667 $sqlwhere .= " AND timemodified > :changedsince";
1670 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1674 * Set a volatile flag
1676 * @param string $type the "type" namespace for the key
1677 * @param string $name the key to set
1678 * @param string $value the value to set (without magic quotes) - null will remove the flag
1679 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1680 * @return bool Always returns true
1682 function set_cache_flag($type, $name, $value, $expiry = null) {
1683 global $DB;
1685 $timemodified = time();
1686 if ($expiry === null || $expiry < $timemodified) {
1687 $expiry = $timemodified + 24 * 60 * 60;
1688 } else {
1689 $expiry = (int)$expiry;
1692 if ($value === null) {
1693 unset_cache_flag($type, $name);
1694 return true;
1697 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1698 // This is a potential problem in DEBUG_DEVELOPER.
1699 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1700 return true; // No need to update.
1702 $f->value = $value;
1703 $f->expiry = $expiry;
1704 $f->timemodified = $timemodified;
1705 $DB->update_record('cache_flags', $f);
1706 } else {
1707 $f = new stdClass();
1708 $f->flagtype = $type;
1709 $f->name = $name;
1710 $f->value = $value;
1711 $f->expiry = $expiry;
1712 $f->timemodified = $timemodified;
1713 $DB->insert_record('cache_flags', $f);
1715 return true;
1719 * Removes a single volatile flag
1721 * @param string $type the "type" namespace for the key
1722 * @param string $name the key to set
1723 * @return bool
1725 function unset_cache_flag($type, $name) {
1726 global $DB;
1727 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1728 return true;
1732 * Garbage-collect volatile flags
1734 * @return bool Always returns true
1736 function gc_cache_flags() {
1737 global $DB;
1738 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1739 return true;
1742 // USER PREFERENCE API.
1745 * Refresh user preference cache. This is used most often for $USER
1746 * object that is stored in session, but it also helps with performance in cron script.
1748 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1750 * @package core
1751 * @category preference
1752 * @access public
1753 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1754 * @param int $cachelifetime Cache life time on the current page (in seconds)
1755 * @throws coding_exception
1756 * @return null
1758 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1759 global $DB;
1760 // Static cache, we need to check on each page load, not only every 2 minutes.
1761 static $loadedusers = array();
1763 if (!isset($user->id)) {
1764 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1767 if (empty($user->id) or isguestuser($user->id)) {
1768 // No permanent storage for not-logged-in users and guest.
1769 if (!isset($user->preference)) {
1770 $user->preference = array();
1772 return;
1775 $timenow = time();
1777 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1778 // Already loaded at least once on this page. Are we up to date?
1779 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1780 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1781 return;
1783 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1784 // No change since the lastcheck on this page.
1785 $user->preference['_lastloaded'] = $timenow;
1786 return;
1790 // OK, so we have to reload all preferences.
1791 $loadedusers[$user->id] = true;
1792 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1793 $user->preference['_lastloaded'] = $timenow;
1797 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1799 * NOTE: internal function, do not call from other code.
1801 * @package core
1802 * @access private
1803 * @param integer $userid the user whose prefs were changed.
1805 function mark_user_preferences_changed($userid) {
1806 global $CFG;
1808 if (empty($userid) or isguestuser($userid)) {
1809 // No cache flags for guest and not-logged-in users.
1810 return;
1813 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1817 * Sets a preference for the specified user.
1819 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1821 * @package core
1822 * @category preference
1823 * @access public
1824 * @param string $name The key to set as preference for the specified user
1825 * @param string $value The value to set for the $name key in the specified user's
1826 * record, null means delete current value.
1827 * @param stdClass|int|null $user A moodle user object or id, null means current user
1828 * @throws coding_exception
1829 * @return bool Always true or exception
1831 function set_user_preference($name, $value, $user = null) {
1832 global $USER, $DB;
1834 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1835 throw new coding_exception('Invalid preference name in set_user_preference() call');
1838 if (is_null($value)) {
1839 // Null means delete current.
1840 return unset_user_preference($name, $user);
1841 } else if (is_object($value)) {
1842 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1843 } else if (is_array($value)) {
1844 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1846 // Value column maximum length is 1333 characters.
1847 $value = (string)$value;
1848 if (core_text::strlen($value) > 1333) {
1849 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1852 if (is_null($user)) {
1853 $user = $USER;
1854 } else if (isset($user->id)) {
1855 // It is a valid object.
1856 } else if (is_numeric($user)) {
1857 $user = (object)array('id' => (int)$user);
1858 } else {
1859 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1862 check_user_preferences_loaded($user);
1864 if (empty($user->id) or isguestuser($user->id)) {
1865 // No permanent storage for not-logged-in users and guest.
1866 $user->preference[$name] = $value;
1867 return true;
1870 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1871 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1872 // Preference already set to this value.
1873 return true;
1875 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1877 } else {
1878 $preference = new stdClass();
1879 $preference->userid = $user->id;
1880 $preference->name = $name;
1881 $preference->value = $value;
1882 $DB->insert_record('user_preferences', $preference);
1885 // Update value in cache.
1886 $user->preference[$name] = $value;
1888 // Set reload flag for other sessions.
1889 mark_user_preferences_changed($user->id);
1891 return true;
1895 * Sets a whole array of preferences for the current user
1897 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1899 * @package core
1900 * @category preference
1901 * @access public
1902 * @param array $prefarray An array of key/value pairs to be set
1903 * @param stdClass|int|null $user A moodle user object or id, null means current user
1904 * @return bool Always true or exception
1906 function set_user_preferences(array $prefarray, $user = null) {
1907 foreach ($prefarray as $name => $value) {
1908 set_user_preference($name, $value, $user);
1910 return true;
1914 * Unsets a preference completely by deleting it from the database
1916 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1918 * @package core
1919 * @category preference
1920 * @access public
1921 * @param string $name The key to unset as preference for the specified user
1922 * @param stdClass|int|null $user A moodle user object or id, null means current user
1923 * @throws coding_exception
1924 * @return bool Always true or exception
1926 function unset_user_preference($name, $user = null) {
1927 global $USER, $DB;
1929 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1930 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1933 if (is_null($user)) {
1934 $user = $USER;
1935 } else if (isset($user->id)) {
1936 // It is a valid object.
1937 } else if (is_numeric($user)) {
1938 $user = (object)array('id' => (int)$user);
1939 } else {
1940 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1943 check_user_preferences_loaded($user);
1945 if (empty($user->id) or isguestuser($user->id)) {
1946 // No permanent storage for not-logged-in user and guest.
1947 unset($user->preference[$name]);
1948 return true;
1951 // Delete from DB.
1952 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1954 // Delete the preference from cache.
1955 unset($user->preference[$name]);
1957 // Set reload flag for other sessions.
1958 mark_user_preferences_changed($user->id);
1960 return true;
1964 * Used to fetch user preference(s)
1966 * If no arguments are supplied this function will return
1967 * all of the current user preferences as an array.
1969 * If a name is specified then this function
1970 * attempts to return that particular preference value. If
1971 * none is found, then the optional value $default is returned,
1972 * otherwise null.
1974 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1976 * @package core
1977 * @category preference
1978 * @access public
1979 * @param string $name Name of the key to use in finding a preference value
1980 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1981 * @param stdClass|int|null $user A moodle user object or id, null means current user
1982 * @throws coding_exception
1983 * @return string|mixed|null A string containing the value of a single preference. An
1984 * array with all of the preferences or null
1986 function get_user_preferences($name = null, $default = null, $user = null) {
1987 global $USER;
1989 if (is_null($name)) {
1990 // All prefs.
1991 } else if (is_numeric($name) or $name === '_lastloaded') {
1992 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1995 if (is_null($user)) {
1996 $user = $USER;
1997 } else if (isset($user->id)) {
1998 // Is a valid object.
1999 } else if (is_numeric($user)) {
2000 $user = (object)array('id' => (int)$user);
2001 } else {
2002 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2005 check_user_preferences_loaded($user);
2007 if (empty($name)) {
2008 // All values.
2009 return $user->preference;
2010 } else if (isset($user->preference[$name])) {
2011 // The single string value.
2012 return $user->preference[$name];
2013 } else {
2014 // Default value (null if not specified).
2015 return $default;
2019 // FUNCTIONS FOR HANDLING TIME.
2022 * Given date parts in user time produce a GMT timestamp.
2024 * @package core
2025 * @category time
2026 * @param int $year The year part to create timestamp of
2027 * @param int $month The month part to create timestamp of
2028 * @param int $day The day part to create timestamp of
2029 * @param int $hour The hour part to create timestamp of
2030 * @param int $minute The minute part to create timestamp of
2031 * @param int $second The second part to create timestamp of
2032 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2033 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2034 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2035 * applied only if timezone is 99 or string.
2036 * @return int GMT timestamp
2038 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2040 // Save input timezone, required for dst offset check.
2041 $passedtimezone = $timezone;
2043 $timezone = get_user_timezone_offset($timezone);
2045 if (abs($timezone) > 13) {
2046 // Server time.
2047 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2048 } else {
2049 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2050 $time = usertime($time, $timezone);
2052 // Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
2053 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
2054 $time -= dst_offset_on($time, $passedtimezone);
2058 return $time;
2063 * Format a date/time (seconds) as weeks, days, hours etc as needed
2065 * Given an amount of time in seconds, returns string
2066 * formatted nicely as weeks, days, hours etc as needed
2068 * @package core
2069 * @category time
2070 * @uses MINSECS
2071 * @uses HOURSECS
2072 * @uses DAYSECS
2073 * @uses YEARSECS
2074 * @param int $totalsecs Time in seconds
2075 * @param stdClass $str Should be a time object
2076 * @return string A nicely formatted date/time string
2078 function format_time($totalsecs, $str = null) {
2080 $totalsecs = abs($totalsecs);
2082 if (!$str) {
2083 // Create the str structure the slow way.
2084 $str = new stdClass();
2085 $str->day = get_string('day');
2086 $str->days = get_string('days');
2087 $str->hour = get_string('hour');
2088 $str->hours = get_string('hours');
2089 $str->min = get_string('min');
2090 $str->mins = get_string('mins');
2091 $str->sec = get_string('sec');
2092 $str->secs = get_string('secs');
2093 $str->year = get_string('year');
2094 $str->years = get_string('years');
2097 $years = floor($totalsecs/YEARSECS);
2098 $remainder = $totalsecs - ($years*YEARSECS);
2099 $days = floor($remainder/DAYSECS);
2100 $remainder = $totalsecs - ($days*DAYSECS);
2101 $hours = floor($remainder/HOURSECS);
2102 $remainder = $remainder - ($hours*HOURSECS);
2103 $mins = floor($remainder/MINSECS);
2104 $secs = $remainder - ($mins*MINSECS);
2106 $ss = ($secs == 1) ? $str->sec : $str->secs;
2107 $sm = ($mins == 1) ? $str->min : $str->mins;
2108 $sh = ($hours == 1) ? $str->hour : $str->hours;
2109 $sd = ($days == 1) ? $str->day : $str->days;
2110 $sy = ($years == 1) ? $str->year : $str->years;
2112 $oyears = '';
2113 $odays = '';
2114 $ohours = '';
2115 $omins = '';
2116 $osecs = '';
2118 if ($years) {
2119 $oyears = $years .' '. $sy;
2121 if ($days) {
2122 $odays = $days .' '. $sd;
2124 if ($hours) {
2125 $ohours = $hours .' '. $sh;
2127 if ($mins) {
2128 $omins = $mins .' '. $sm;
2130 if ($secs) {
2131 $osecs = $secs .' '. $ss;
2134 if ($years) {
2135 return trim($oyears .' '. $odays);
2137 if ($days) {
2138 return trim($odays .' '. $ohours);
2140 if ($hours) {
2141 return trim($ohours .' '. $omins);
2143 if ($mins) {
2144 return trim($omins .' '. $osecs);
2146 if ($secs) {
2147 return $osecs;
2149 return get_string('now');
2153 * Returns a formatted string that represents a date in user time.
2155 * @package core
2156 * @category time
2157 * @param int $date the timestamp in UTC, as obtained from the database.
2158 * @param string $format strftime format. You should probably get this using
2159 * get_string('strftime...', 'langconfig');
2160 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2161 * not 99 then daylight saving will not be added.
2162 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2163 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2164 * If false then the leading zero is maintained.
2165 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2166 * @return string the formatted date/time.
2168 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2169 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2170 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2174 * Returns a formatted date ensuring it is UTF-8.
2176 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2177 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2179 * This function does not do any calculation regarding the user preferences and should
2180 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2181 * to differentiate the use of server time or not (strftime() against gmstrftime()).
2183 * @param int $date the timestamp.
2184 * @param string $format strftime format.
2185 * @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2186 * @return string the formatted date/time.
2187 * @since Moodle 2.3.3
2189 function date_format_string($date, $format, $tz = 99) {
2190 global $CFG;
2192 $localewincharset = null;
2193 // Get the calendar type user is using.
2194 if ($CFG->ostype == 'WINDOWS') {
2195 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2196 $localewincharset = $calendartype->locale_win_charset();
2199 if (abs($tz) > 13) {
2200 if ($localewincharset) {
2201 $format = core_text::convert($format, 'utf-8', $localewincharset);
2202 $datestring = strftime($format, $date);
2203 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2204 } else {
2205 $datestring = strftime($format, $date);
2207 } else {
2208 if ($localewincharset) {
2209 $format = core_text::convert($format, 'utf-8', $localewincharset);
2210 $datestring = gmstrftime($format, $date);
2211 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2212 } else {
2213 $datestring = gmstrftime($format, $date);
2216 return $datestring;
2220 * Given a $time timestamp in GMT (seconds since epoch),
2221 * returns an array that represents the date in user time
2223 * @package core
2224 * @category time
2225 * @uses HOURSECS
2226 * @param int $time Timestamp in GMT
2227 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2228 * dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
2229 * @return array An array that represents the date in user time
2231 function usergetdate($time, $timezone=99) {
2233 // Save input timezone, required for dst offset check.
2234 $passedtimezone = $timezone;
2236 $timezone = get_user_timezone_offset($timezone);
2238 if (abs($timezone) > 13) {
2239 // Server time.
2240 return getdate($time);
2243 // Add daylight saving offset for string timezones only, as we can't get dst for
2244 // float values. if timezone is 99 (user default timezone), then try update dst.
2245 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2246 $time += dst_offset_on($time, $passedtimezone);
2249 $time += intval((float)$timezone * HOURSECS);
2251 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2253 // Be careful to ensure the returned array matches that produced by getdate() above.
2254 list(
2255 $getdate['month'],
2256 $getdate['weekday'],
2257 $getdate['yday'],
2258 $getdate['year'],
2259 $getdate['mon'],
2260 $getdate['wday'],
2261 $getdate['mday'],
2262 $getdate['hours'],
2263 $getdate['minutes'],
2264 $getdate['seconds']
2265 ) = explode('_', $datestring);
2267 // Set correct datatype to match with getdate().
2268 $getdate['seconds'] = (int)$getdate['seconds'];
2269 $getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
2270 $getdate['year'] = (int)$getdate['year'];
2271 $getdate['mon'] = (int)$getdate['mon'];
2272 $getdate['wday'] = (int)$getdate['wday'];
2273 $getdate['mday'] = (int)$getdate['mday'];
2274 $getdate['hours'] = (int)$getdate['hours'];
2275 $getdate['minutes'] = (int)$getdate['minutes'];
2276 return $getdate;
2280 * Given a GMT timestamp (seconds since epoch), offsets it by
2281 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2283 * @package core
2284 * @category time
2285 * @uses HOURSECS
2286 * @param int $date Timestamp in GMT
2287 * @param float|int|string $timezone timezone to calculate GMT time offset before
2288 * calculating user time, 99 is default user timezone
2289 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2290 * @return int
2292 function usertime($date, $timezone=99) {
2294 $timezone = get_user_timezone_offset($timezone);
2296 if (abs($timezone) > 13) {
2297 return $date;
2299 return $date - (int)($timezone * HOURSECS);
2303 * Given a time, return the GMT timestamp of the most recent midnight
2304 * for the current user.
2306 * @package core
2307 * @category time
2308 * @param int $date Timestamp in GMT
2309 * @param float|int|string $timezone timezone to calculate GMT time offset before
2310 * calculating user midnight time, 99 is default user timezone
2311 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2312 * @return int Returns a GMT timestamp
2314 function usergetmidnight($date, $timezone=99) {
2316 $userdate = usergetdate($date, $timezone);
2318 // Time of midnight of this user's day, in GMT.
2319 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2324 * Returns a string that prints the user's timezone
2326 * @package core
2327 * @category time
2328 * @param float|int|string $timezone timezone to calculate GMT time offset before
2329 * calculating user timezone, 99 is default user timezone
2330 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2331 * @return string
2333 function usertimezone($timezone=99) {
2335 $tz = get_user_timezone($timezone);
2337 if (!is_float($tz)) {
2338 return $tz;
2341 if (abs($tz) > 13) {
2342 // Server time.
2343 return get_string('serverlocaltime');
2346 if ($tz == intval($tz)) {
2347 // Don't show .0 for whole hours.
2348 $tz = intval($tz);
2351 if ($tz == 0) {
2352 return 'UTC';
2353 } else if ($tz > 0) {
2354 return 'UTC+'.$tz;
2355 } else {
2356 return 'UTC'.$tz;
2362 * Returns a float which represents the user's timezone difference from GMT in hours
2363 * Checks various settings and picks the most dominant of those which have a value
2365 * @package core
2366 * @category time
2367 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2368 * 99 is default user timezone
2369 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2370 * @return float
2372 function get_user_timezone_offset($tz = 99) {
2373 $tz = get_user_timezone($tz);
2375 if (is_float($tz)) {
2376 return $tz;
2377 } else {
2378 $tzrecord = get_timezone_record($tz);
2379 if (empty($tzrecord)) {
2380 return 99.0;
2382 return (float)$tzrecord->gmtoff / HOURMINS;
2387 * Returns an int which represents the systems's timezone difference from GMT in seconds
2389 * @package core
2390 * @category time
2391 * @param float|int|string $tz timezone for which offset is required.
2392 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2393 * @return int|bool if found, false is timezone 99 or error
2395 function get_timezone_offset($tz) {
2396 if ($tz == 99) {
2397 return false;
2400 if (is_numeric($tz)) {
2401 return intval($tz * 60*60);
2404 if (!$tzrecord = get_timezone_record($tz)) {
2405 return false;
2407 return intval($tzrecord->gmtoff * 60);
2411 * Returns a float or a string which denotes the user's timezone
2412 * A float value means that a simple offset from GMT is used, while a string (it will be the name of a timezone in the database)
2413 * means that for this timezone there are also DST rules to be taken into account
2414 * Checks various settings and picks the most dominant of those which have a value
2416 * @package core
2417 * @category time
2418 * @param float|int|string $tz timezone to calculate GMT time offset before
2419 * calculating user timezone, 99 is default user timezone
2420 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2421 * @return float|string
2423 function get_user_timezone($tz = 99) {
2424 global $USER, $CFG;
2426 $timezones = array(
2427 $tz,
2428 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2429 isset($USER->timezone) ? $USER->timezone : 99,
2430 isset($CFG->timezone) ? $CFG->timezone : 99,
2433 $tz = 99;
2435 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2436 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2437 $tz = $next['value'];
2439 return is_numeric($tz) ? (float) $tz : $tz;
2443 * Returns cached timezone record for given $timezonename
2445 * @package core
2446 * @param string $timezonename name of the timezone
2447 * @return stdClass|bool timezonerecord or false
2449 function get_timezone_record($timezonename) {
2450 global $DB;
2451 static $cache = null;
2453 if ($cache === null) {
2454 $cache = array();
2457 if (isset($cache[$timezonename])) {
2458 return $cache[$timezonename];
2461 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2462 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2466 * Build and store the users Daylight Saving Time (DST) table
2468 * @package core
2469 * @param int $fromyear Start year for the table, defaults to 1971
2470 * @param int $toyear End year for the table, defaults to 2035
2471 * @param int|float|string $strtimezone timezone to check if dst should be applied.
2472 * @return bool
2474 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2475 global $SESSION, $DB;
2477 $usertz = get_user_timezone($strtimezone);
2479 if (is_float($usertz)) {
2480 // Trivial timezone, no DST.
2481 return false;
2484 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2485 // We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
2486 unset($SESSION->dst_offsets);
2487 unset($SESSION->dst_range);
2490 if (!empty($SESSION->dst_offsets) && empty($fromyear) && empty($toyear)) {
2491 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
2492 // This will be the return path most of the time, pretty light computationally.
2493 return true;
2496 // Reaching here means we either need to extend our table or create it from scratch.
2498 // Remember which TZ we calculated these changes for.
2499 $SESSION->dst_offsettz = $usertz;
2501 if (empty($SESSION->dst_offsets)) {
2502 // If we 're creating from scratch, put the two guard elements in there.
2503 $SESSION->dst_offsets = array(1 => null, 0 => null);
2505 if (empty($SESSION->dst_range)) {
2506 // If creating from scratch.
2507 $from = max((empty($fromyear) ? intval(date('Y')) - 3 : $fromyear), 1971);
2508 $to = min((empty($toyear) ? intval(date('Y')) + 3 : $toyear), 2035);
2510 // Fill in the array with the extra years we need to process.
2511 $yearstoprocess = array();
2512 for ($i = $from; $i <= $to; ++$i) {
2513 $yearstoprocess[] = $i;
2516 // Take note of which years we have processed for future calls.
2517 $SESSION->dst_range = array($from, $to);
2518 } else {
2519 // If needing to extend the table, do the same.
2520 $yearstoprocess = array();
2522 $from = max((empty($fromyear) ? $SESSION->dst_range[0] : $fromyear), 1971);
2523 $to = min((empty($toyear) ? $SESSION->dst_range[1] : $toyear), 2035);
2525 if ($from < $SESSION->dst_range[0]) {
2526 // Take note of which years we need to process and then note that we have processed them for future calls.
2527 for ($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2528 $yearstoprocess[] = $i;
2530 $SESSION->dst_range[0] = $from;
2532 if ($to > $SESSION->dst_range[1]) {
2533 // Take note of which years we need to process and then note that we have processed them for future calls.
2534 for ($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2535 $yearstoprocess[] = $i;
2537 $SESSION->dst_range[1] = $to;
2541 if (empty($yearstoprocess)) {
2542 // This means that there was a call requesting a SMALLER range than we have already calculated.
2543 return true;
2546 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2547 // Also, the array is sorted in descending timestamp order!
2549 // Get DB data.
2551 static $presetscache = array();
2552 if (!isset($presetscache[$usertz])) {
2553 $presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
2554 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
2555 'std_startday, std_weekday, std_skipweeks, std_time');
2557 if (empty($presetscache[$usertz])) {
2558 return false;
2561 // Remove ending guard (first element of the array).
2562 reset($SESSION->dst_offsets);
2563 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2565 // Add all required change timestamps.
2566 foreach ($yearstoprocess as $y) {
2567 // Find the record which is in effect for the year $y.
2568 foreach ($presetscache[$usertz] as $year => $preset) {
2569 if ($year <= $y) {
2570 break;
2574 $changes = dst_changes_for_year($y, $preset);
2576 if ($changes === null) {
2577 continue;
2579 if ($changes['dst'] != 0) {
2580 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2582 if ($changes['std'] != 0) {
2583 $SESSION->dst_offsets[$changes['std']] = 0;
2587 // Put in a guard element at the top.
2588 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2589 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = null; // DAYSECS is arbitrary, any "small" number will do.
2591 // Sort again.
2592 krsort($SESSION->dst_offsets);
2594 return true;
2598 * Calculates the required DST change and returns a Timestamp Array
2600 * @package core
2601 * @category time
2602 * @uses HOURSECS
2603 * @uses MINSECS
2604 * @param int|string $year Int or String Year to focus on
2605 * @param object $timezone Instatiated Timezone object
2606 * @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
2608 function dst_changes_for_year($year, $timezone) {
2610 if ($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 &&
2611 $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2612 return null;
2615 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2616 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2618 list($dsthour, $dstmin) = explode(':', $timezone->dst_time);
2619 list($stdhour, $stdmin) = explode(':', $timezone->std_time);
2621 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2622 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2624 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2625 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2626 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2628 $timedst += $dsthour * HOURSECS + $dstmin * MINSECS;
2629 $timestd += $stdhour * HOURSECS + $stdmin * MINSECS;
2631 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2635 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2636 * - Note: Daylight saving only works for string timezones and not for float.
2638 * @package core
2639 * @category time
2640 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2641 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2642 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2643 * @return int
2645 function dst_offset_on($time, $strtimezone = null) {
2646 global $SESSION;
2648 if (!calculate_user_dst_table(null, null, $strtimezone) || empty($SESSION->dst_offsets)) {
2649 return 0;
2652 reset($SESSION->dst_offsets);
2653 while (list($from, $offset) = each($SESSION->dst_offsets)) {
2654 if ($from <= $time) {
2655 break;
2659 // This is the normal return path.
2660 if ($offset !== null) {
2661 return $offset;
2664 // Reaching this point means we haven't calculated far enough, do it now:
2665 // Calculate extra DST changes if needed and recurse. The recursion always
2666 // moves toward the stopping condition, so will always end.
2668 if ($from == 0) {
2669 // We need a year smaller than $SESSION->dst_range[0].
2670 if ($SESSION->dst_range[0] == 1971) {
2671 return 0;
2673 calculate_user_dst_table($SESSION->dst_range[0] - 5, null, $strtimezone);
2674 return dst_offset_on($time, $strtimezone);
2675 } else {
2676 // We need a year larger than $SESSION->dst_range[1].
2677 if ($SESSION->dst_range[1] == 2035) {
2678 return 0;
2680 calculate_user_dst_table(null, $SESSION->dst_range[1] + 5, $strtimezone);
2681 return dst_offset_on($time, $strtimezone);
2686 * Calculates when the day appears in specific month
2688 * @package core
2689 * @category time
2690 * @param int $startday starting day of the month
2691 * @param int $weekday The day when week starts (normally taken from user preferences)
2692 * @param int $month The month whose day is sought
2693 * @param int $year The year of the month whose day is sought
2694 * @return int
2696 function find_day_in_month($startday, $weekday, $month, $year) {
2697 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2699 $daysinmonth = days_in_month($month, $year);
2700 $daysinweek = count($calendartype->get_weekdays());
2702 if ($weekday == -1) {
2703 // Don't care about weekday, so return:
2704 // abs($startday) if $startday != -1
2705 // $daysinmonth otherwise.
2706 return ($startday == -1) ? $daysinmonth : abs($startday);
2709 // From now on we 're looking for a specific weekday.
2710 // Give "end of month" its actual value, since we know it.
2711 if ($startday == -1) {
2712 $startday = -1 * $daysinmonth;
2715 // Starting from day $startday, the sign is the direction.
2716 if ($startday < 1) {
2717 $startday = abs($startday);
2718 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2720 // This is the last such weekday of the month.
2721 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2722 if ($lastinmonth > $daysinmonth) {
2723 $lastinmonth -= $daysinweek;
2726 // Find the first such weekday <= $startday.
2727 while ($lastinmonth > $startday) {
2728 $lastinmonth -= $daysinweek;
2731 return $lastinmonth;
2732 } else {
2733 $indexweekday = dayofweek($startday, $month, $year);
2735 $diff = $weekday - $indexweekday;
2736 if ($diff < 0) {
2737 $diff += $daysinweek;
2740 // This is the first such weekday of the month equal to or after $startday.
2741 $firstfromindex = $startday + $diff;
2743 return $firstfromindex;
2748 * Calculate the number of days in a given month
2750 * @package core
2751 * @category time
2752 * @param int $month The month whose day count is sought
2753 * @param int $year The year of the month whose day count is sought
2754 * @return int
2756 function days_in_month($month, $year) {
2757 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2758 return $calendartype->get_num_days_in_month($year, $month);
2762 * Calculate the position in the week of a specific calendar day
2764 * @package core
2765 * @category time
2766 * @param int $day The day of the date whose position in the week is sought
2767 * @param int $month The month of the date whose position in the week is sought
2768 * @param int $year The year of the date whose position in the week is sought
2769 * @return int
2771 function dayofweek($day, $month, $year) {
2772 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2773 return $calendartype->get_weekday($year, $month, $day);
2776 // USER AUTHENTICATION AND LOGIN.
2779 * Returns full login url.
2781 * @return string login url
2783 function get_login_url() {
2784 global $CFG;
2786 $url = "$CFG->wwwroot/login/index.php";
2788 if (!empty($CFG->loginhttps)) {
2789 $url = str_replace('http:', 'https:', $url);
2792 return $url;
2796 * This function checks that the current user is logged in and has the
2797 * required privileges
2799 * This function checks that the current user is logged in, and optionally
2800 * whether they are allowed to be in a particular course and view a particular
2801 * course module.
2802 * If they are not logged in, then it redirects them to the site login unless
2803 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2804 * case they are automatically logged in as guests.
2805 * If $courseid is given and the user is not enrolled in that course then the
2806 * user is redirected to the course enrolment page.
2807 * If $cm is given and the course module is hidden and the user is not a teacher
2808 * in the course then the user is redirected to the course home page.
2810 * When $cm parameter specified, this function sets page layout to 'module'.
2811 * You need to change it manually later if some other layout needed.
2813 * @package core_access
2814 * @category access
2816 * @param mixed $courseorid id of the course or course object
2817 * @param bool $autologinguest default true
2818 * @param object $cm course module object
2819 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2820 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2821 * in order to keep redirects working properly. MDL-14495
2822 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2823 * @return mixed Void, exit, and die depending on path
2824 * @throws coding_exception
2825 * @throws require_login_exception
2827 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2828 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2830 // Must not redirect when byteserving already started.
2831 if (!empty($_SERVER['HTTP_RANGE'])) {
2832 $preventredirect = true;
2835 // Setup global $COURSE, themes, language and locale.
2836 if (!empty($courseorid)) {
2837 if (is_object($courseorid)) {
2838 $course = $courseorid;
2839 } else if ($courseorid == SITEID) {
2840 $course = clone($SITE);
2841 } else {
2842 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2844 if ($cm) {
2845 if ($cm->course != $course->id) {
2846 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2848 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2849 if (!($cm instanceof cm_info)) {
2850 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2851 // db queries so this is not really a performance concern, however it is obviously
2852 // better if you use get_fast_modinfo to get the cm before calling this.
2853 $modinfo = get_fast_modinfo($course);
2854 $cm = $modinfo->get_cm($cm->id);
2856 $PAGE->set_cm($cm, $course); // Set's up global $COURSE.
2857 $PAGE->set_pagelayout('incourse');
2858 } else {
2859 $PAGE->set_course($course); // Set's up global $COURSE.
2861 } else {
2862 // Do not touch global $COURSE via $PAGE->set_course(),
2863 // the reasons is we need to be able to call require_login() at any time!!
2864 $course = $SITE;
2865 if ($cm) {
2866 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2870 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2871 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2872 // risk leading the user back to the AJAX request URL.
2873 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2874 $setwantsurltome = false;
2877 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2878 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
2879 if ($setwantsurltome) {
2880 $SESSION->wantsurl = qualified_me();
2882 redirect(get_login_url());
2885 // If the user is not even logged in yet then make sure they are.
2886 if (!isloggedin()) {
2887 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2888 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2889 // Misconfigured site guest, just redirect to login page.
2890 redirect(get_login_url());
2891 exit; // Never reached.
2893 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2894 complete_user_login($guest);
2895 $USER->autologinguest = true;
2896 $SESSION->lang = $lang;
2897 } else {
2898 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2899 if ($preventredirect) {
2900 throw new require_login_exception('You are not logged in');
2903 if ($setwantsurltome) {
2904 $SESSION->wantsurl = qualified_me();
2906 if (!empty($_SERVER['HTTP_REFERER'])) {
2907 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2909 redirect(get_login_url());
2910 exit; // Never reached.
2914 // Loginas as redirection if needed.
2915 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2916 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2917 if ($USER->loginascontext->instanceid != $course->id) {
2918 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2923 // Check whether the user should be changing password (but only if it is REALLY them).
2924 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2925 $userauth = get_auth_plugin($USER->auth);
2926 if ($userauth->can_change_password() and !$preventredirect) {
2927 if ($setwantsurltome) {
2928 $SESSION->wantsurl = qualified_me();
2930 if ($changeurl = $userauth->change_password_url()) {
2931 // Use plugin custom url.
2932 redirect($changeurl);
2933 } else {
2934 // Use moodle internal method.
2935 if (empty($CFG->loginhttps)) {
2936 redirect($CFG->wwwroot .'/login/change_password.php');
2937 } else {
2938 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2939 redirect($wwwroot .'/login/change_password.php');
2942 } else {
2943 print_error('nopasswordchangeforced', 'auth');
2947 // Check that the user account is properly set up.
2948 if (user_not_fully_set_up($USER)) {
2949 if ($preventredirect) {
2950 throw new require_login_exception('User not fully set-up');
2952 if ($setwantsurltome) {
2953 $SESSION->wantsurl = qualified_me();
2955 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2958 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2959 sesskey();
2961 // Do not bother admins with any formalities.
2962 if (is_siteadmin()) {
2963 // Set accesstime or the user will appear offline which messes up messaging.
2964 user_accesstime_log($course->id);
2965 return;
2968 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2969 if (!$USER->policyagreed and !is_siteadmin()) {
2970 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2971 if ($preventredirect) {
2972 throw new require_login_exception('Policy not agreed');
2974 if ($setwantsurltome) {
2975 $SESSION->wantsurl = qualified_me();
2977 redirect($CFG->wwwroot .'/user/policy.php');
2978 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2979 if ($preventredirect) {
2980 throw new require_login_exception('Policy not agreed');
2982 if ($setwantsurltome) {
2983 $SESSION->wantsurl = qualified_me();
2985 redirect($CFG->wwwroot .'/user/policy.php');
2989 // Fetch the system context, the course context, and prefetch its child contexts.
2990 $sysctx = context_system::instance();
2991 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2992 if ($cm) {
2993 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2994 } else {
2995 $cmcontext = null;
2998 // If the site is currently under maintenance, then print a message.
2999 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
3000 if ($preventredirect) {
3001 throw new require_login_exception('Maintenance in progress');
3004 print_maintenance_message();
3007 // Make sure the course itself is not hidden.
3008 if ($course->id == SITEID) {
3009 // Frontpage can not be hidden.
3010 } else {
3011 if (is_role_switched($course->id)) {
3012 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
3013 } else {
3014 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3015 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
3016 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
3017 if ($preventredirect) {
3018 throw new require_login_exception('Course is hidden');
3020 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3021 // the navigation will mess up when trying to find it.
3022 navigation_node::override_active_url(new moodle_url('/'));
3023 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3028 // Is the user enrolled?
3029 if ($course->id == SITEID) {
3030 // Everybody is enrolled on the frontpage.
3031 } else {
3032 if (\core\session\manager::is_loggedinas()) {
3033 // Make sure the REAL person can access this course first.
3034 $realuser = \core\session\manager::get_realuser();
3035 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
3036 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
3037 if ($preventredirect) {
3038 throw new require_login_exception('Invalid course login-as access');
3040 echo $OUTPUT->header();
3041 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
3045 $access = false;
3047 if (is_role_switched($course->id)) {
3048 // Ok, user had to be inside this course before the switch.
3049 $access = true;
3051 } else if (is_viewing($coursecontext, $USER)) {
3052 // Ok, no need to mess with enrol.
3053 $access = true;
3055 } else {
3056 if (isset($USER->enrol['enrolled'][$course->id])) {
3057 if ($USER->enrol['enrolled'][$course->id] > time()) {
3058 $access = true;
3059 if (isset($USER->enrol['tempguest'][$course->id])) {
3060 unset($USER->enrol['tempguest'][$course->id]);
3061 remove_temp_course_roles($coursecontext);
3063 } else {
3064 // Expired.
3065 unset($USER->enrol['enrolled'][$course->id]);
3068 if (isset($USER->enrol['tempguest'][$course->id])) {
3069 if ($USER->enrol['tempguest'][$course->id] == 0) {
3070 $access = true;
3071 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3072 $access = true;
3073 } else {
3074 // Expired.
3075 unset($USER->enrol['tempguest'][$course->id]);
3076 remove_temp_course_roles($coursecontext);
3080 if (!$access) {
3081 // Cache not ok.
3082 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3083 if ($until !== false) {
3084 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3085 if ($until == 0) {
3086 $until = ENROL_MAX_TIMESTAMP;
3088 $USER->enrol['enrolled'][$course->id] = $until;
3089 $access = true;
3091 } else {
3092 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3093 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3094 $enrols = enrol_get_plugins(true);
3095 // First ask all enabled enrol instances in course if they want to auto enrol user.
3096 foreach ($instances as $instance) {
3097 if (!isset($enrols[$instance->enrol])) {
3098 continue;
3100 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3101 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3102 if ($until !== false) {
3103 if ($until == 0) {
3104 $until = ENROL_MAX_TIMESTAMP;
3106 $USER->enrol['enrolled'][$course->id] = $until;
3107 $access = true;
3108 break;
3111 // If not enrolled yet try to gain temporary guest access.
3112 if (!$access) {
3113 foreach ($instances as $instance) {
3114 if (!isset($enrols[$instance->enrol])) {
3115 continue;
3117 // Get a duration for the guest access, a timestamp in the future or false.
3118 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3119 if ($until !== false and $until > time()) {
3120 $USER->enrol['tempguest'][$course->id] = $until;
3121 $access = true;
3122 break;
3130 if (!$access) {
3131 if ($preventredirect) {
3132 throw new require_login_exception('Not enrolled');
3134 if ($setwantsurltome) {
3135 $SESSION->wantsurl = qualified_me();
3137 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3141 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3142 if ($cm && !$cm->uservisible) {
3143 if ($preventredirect) {
3144 throw new require_login_exception('Activity is hidden');
3146 if ($course->id != SITEID) {
3147 $url = new moodle_url('/course/view.php', array('id' => $course->id));
3148 } else {
3149 $url = new moodle_url('/');
3151 redirect($url, get_string('activityiscurrentlyhidden'));
3154 // Finally access granted, update lastaccess times.
3155 user_accesstime_log($course->id);
3160 * This function just makes sure a user is logged out.
3162 * @package core_access
3163 * @category access
3165 function require_logout() {
3166 global $USER, $DB;
3168 if (!isloggedin()) {
3169 // This should not happen often, no need for hooks or events here.
3170 \core\session\manager::terminate_current();
3171 return;
3174 // Execute hooks before action.
3175 $authplugins = array();
3176 $authsequence = get_enabled_auth_plugins();
3177 foreach ($authsequence as $authname) {
3178 $authplugins[$authname] = get_auth_plugin($authname);
3179 $authplugins[$authname]->prelogout_hook();
3182 // Store info that gets removed during logout.
3183 $sid = session_id();
3184 $event = \core\event\user_loggedout::create(
3185 array(
3186 'userid' => $USER->id,
3187 'objectid' => $USER->id,
3188 'other' => array('sessionid' => $sid),
3191 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3192 $event->add_record_snapshot('sessions', $session);
3195 // Clone of $USER object to be used by auth plugins.
3196 $user = fullclone($USER);
3198 // Delete session record and drop $_SESSION content.
3199 \core\session\manager::terminate_current();
3201 // Trigger event AFTER action.
3202 $event->trigger();
3204 // Hook to execute auth plugins redirection after event trigger.
3205 foreach ($authplugins as $authplugin) {
3206 $authplugin->postlogout_hook($user);
3211 * Weaker version of require_login()
3213 * This is a weaker version of {@link require_login()} which only requires login
3214 * when called from within a course rather than the site page, unless
3215 * the forcelogin option is turned on.
3216 * @see require_login()
3218 * @package core_access
3219 * @category access
3221 * @param mixed $courseorid The course object or id in question
3222 * @param bool $autologinguest Allow autologin guests if that is wanted
3223 * @param object $cm Course activity module if known
3224 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3225 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3226 * in order to keep redirects working properly. MDL-14495
3227 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3228 * @return void
3229 * @throws coding_exception
3231 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3232 global $CFG, $PAGE, $SITE;
3233 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3234 or (!is_object($courseorid) and $courseorid == SITEID));
3235 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3236 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3237 // db queries so this is not really a performance concern, however it is obviously
3238 // better if you use get_fast_modinfo to get the cm before calling this.
3239 if (is_object($courseorid)) {
3240 $course = $courseorid;
3241 } else {
3242 $course = clone($SITE);
3244 $modinfo = get_fast_modinfo($course);
3245 $cm = $modinfo->get_cm($cm->id);
3247 if (!empty($CFG->forcelogin)) {
3248 // Login required for both SITE and courses.
3249 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3251 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3252 // Always login for hidden activities.
3253 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3255 } else if ($issite) {
3256 // Login for SITE not required.
3257 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3258 if (!empty($courseorid)) {
3259 if (is_object($courseorid)) {
3260 $course = $courseorid;
3261 } else {
3262 $course = clone $SITE;
3264 if ($cm) {
3265 if ($cm->course != $course->id) {
3266 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3268 $PAGE->set_cm($cm, $course);
3269 $PAGE->set_pagelayout('incourse');
3270 } else {
3271 $PAGE->set_course($course);
3273 } else {
3274 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3275 $PAGE->set_course($PAGE->course);
3277 user_accesstime_log(SITEID);
3278 return;
3280 } else {
3281 // Course login always required.
3282 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3287 * Require key login. Function terminates with error if key not found or incorrect.
3289 * @uses NO_MOODLE_COOKIES
3290 * @uses PARAM_ALPHANUM
3291 * @param string $script unique script identifier
3292 * @param int $instance optional instance id
3293 * @return int Instance ID
3295 function require_user_key_login($script, $instance=null) {
3296 global $DB;
3298 if (!NO_MOODLE_COOKIES) {
3299 print_error('sessioncookiesdisable');
3302 // Extra safety.
3303 \core\session\manager::write_close();
3305 $keyvalue = required_param('key', PARAM_ALPHANUM);
3307 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3308 print_error('invalidkey');
3311 if (!empty($key->validuntil) and $key->validuntil < time()) {
3312 print_error('expiredkey');
3315 if ($key->iprestriction) {
3316 $remoteaddr = getremoteaddr(null);
3317 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3318 print_error('ipmismatch');
3322 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3323 print_error('invaliduserid');
3326 // Emulate normal session.
3327 enrol_check_plugins($user);
3328 \core\session\manager::set_user($user);
3330 // Note we are not using normal login.
3331 if (!defined('USER_KEY_LOGIN')) {
3332 define('USER_KEY_LOGIN', true);
3335 // Return instance id - it might be empty.
3336 return $key->instance;
3340 * Creates a new private user access key.
3342 * @param string $script unique target identifier
3343 * @param int $userid
3344 * @param int $instance optional instance id
3345 * @param string $iprestriction optional ip restricted access
3346 * @param timestamp $validuntil key valid only until given data
3347 * @return string access key value
3349 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3350 global $DB;
3352 $key = new stdClass();
3353 $key->script = $script;
3354 $key->userid = $userid;
3355 $key->instance = $instance;
3356 $key->iprestriction = $iprestriction;
3357 $key->validuntil = $validuntil;
3358 $key->timecreated = time();
3360 // Something long and unique.
3361 $key->value = md5($userid.'_'.time().random_string(40));
3362 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3363 // Must be unique.
3364 $key->value = md5($userid.'_'.time().random_string(40));
3366 $DB->insert_record('user_private_key', $key);
3367 return $key->value;
3371 * Delete the user's new private user access keys for a particular script.
3373 * @param string $script unique target identifier
3374 * @param int $userid
3375 * @return void
3377 function delete_user_key($script, $userid) {
3378 global $DB;
3379 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3383 * Gets a private user access key (and creates one if one doesn't exist).
3385 * @param string $script unique target identifier
3386 * @param int $userid
3387 * @param int $instance optional instance id
3388 * @param string $iprestriction optional ip restricted access
3389 * @param timestamp $validuntil key valid only until given data
3390 * @return string access key value
3392 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3393 global $DB;
3395 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3396 'instance' => $instance, 'iprestriction' => $iprestriction,
3397 'validuntil' => $validuntil))) {
3398 return $key->value;
3399 } else {
3400 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3406 * Modify the user table by setting the currently logged in user's last login to now.
3408 * @return bool Always returns true
3410 function update_user_login_times() {
3411 global $USER, $DB;
3413 if (isguestuser()) {
3414 // Do not update guest access times/ips for performance.
3415 return true;
3418 $now = time();
3420 $user = new stdClass();
3421 $user->id = $USER->id;
3423 // Make sure all users that logged in have some firstaccess.
3424 if ($USER->firstaccess == 0) {
3425 $USER->firstaccess = $user->firstaccess = $now;
3428 // Store the previous current as lastlogin.
3429 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3431 $USER->currentlogin = $user->currentlogin = $now;
3433 // Function user_accesstime_log() may not update immediately, better do it here.
3434 $USER->lastaccess = $user->lastaccess = $now;
3435 $USER->lastip = $user->lastip = getremoteaddr();
3437 // Note: do not call user_update_user() here because this is part of the login process,
3438 // the login event means that these fields were updated.
3439 $DB->update_record('user', $user);
3440 return true;
3444 * Determines if a user has completed setting up their account.
3446 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3447 * @return bool
3449 function user_not_fully_set_up($user) {
3450 if (isguestuser($user)) {
3451 return false;
3453 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3457 * Check whether the user has exceeded the bounce threshold
3459 * @param stdClass $user A {@link $USER} object
3460 * @return bool true => User has exceeded bounce threshold
3462 function over_bounce_threshold($user) {
3463 global $CFG, $DB;
3465 if (empty($CFG->handlebounces)) {
3466 return false;
3469 if (empty($user->id)) {
3470 // No real (DB) user, nothing to do here.
3471 return false;
3474 // Set sensible defaults.
3475 if (empty($CFG->minbounces)) {
3476 $CFG->minbounces = 10;
3478 if (empty($CFG->bounceratio)) {
3479 $CFG->bounceratio = .20;
3481 $bouncecount = 0;
3482 $sendcount = 0;
3483 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3484 $bouncecount = $bounce->value;
3486 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3487 $sendcount = $send->value;
3489 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3493 * Used to increment or reset email sent count
3495 * @param stdClass $user object containing an id
3496 * @param bool $reset will reset the count to 0
3497 * @return void
3499 function set_send_count($user, $reset=false) {
3500 global $DB;
3502 if (empty($user->id)) {
3503 // No real (DB) user, nothing to do here.
3504 return;
3507 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3508 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3509 $DB->update_record('user_preferences', $pref);
3510 } else if (!empty($reset)) {
3511 // If it's not there and we're resetting, don't bother. Make a new one.
3512 $pref = new stdClass();
3513 $pref->name = 'email_send_count';
3514 $pref->value = 1;
3515 $pref->userid = $user->id;
3516 $DB->insert_record('user_preferences', $pref, false);
3521 * Increment or reset user's email bounce count
3523 * @param stdClass $user object containing an id
3524 * @param bool $reset will reset the count to 0
3526 function set_bounce_count($user, $reset=false) {
3527 global $DB;
3529 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3530 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3531 $DB->update_record('user_preferences', $pref);
3532 } else if (!empty($reset)) {
3533 // If it's not there and we're resetting, don't bother. Make a new one.
3534 $pref = new stdClass();
3535 $pref->name = 'email_bounce_count';
3536 $pref->value = 1;
3537 $pref->userid = $user->id;
3538 $DB->insert_record('user_preferences', $pref, false);
3543 * Determines if the logged in user is currently moving an activity
3545 * @param int $courseid The id of the course being tested
3546 * @return bool
3548 function ismoving($courseid) {
3549 global $USER;
3551 if (!empty($USER->activitycopy)) {
3552 return ($USER->activitycopycourse == $courseid);
3554 return false;
3558 * Returns a persons full name
3560 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3561 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3562 * specify one.
3564 * @param stdClass $user A {@link $USER} object to get full name of.
3565 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3566 * @return string
3568 function fullname($user, $override=false) {
3569 global $CFG, $SESSION;
3571 if (!isset($user->firstname) and !isset($user->lastname)) {
3572 return '';
3575 // Get all of the name fields.
3576 $allnames = get_all_user_name_fields();
3577 if ($CFG->debugdeveloper) {
3578 foreach ($allnames as $allname) {
3579 if (!array_key_exists($allname, $user)) {
3580 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3581 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3582 // Message has been sent, no point in sending the message multiple times.
3583 break;
3588 if (!$override) {
3589 if (!empty($CFG->forcefirstname)) {
3590 $user->firstname = $CFG->forcefirstname;
3592 if (!empty($CFG->forcelastname)) {
3593 $user->lastname = $CFG->forcelastname;
3597 if (!empty($SESSION->fullnamedisplay)) {
3598 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3601 $template = null;
3602 // If the fullnamedisplay setting is available, set the template to that.
3603 if (isset($CFG->fullnamedisplay)) {
3604 $template = $CFG->fullnamedisplay;
3606 // If the template is empty, or set to language, return the language string.
3607 if ((empty($template) || $template == 'language') && !$override) {
3608 return get_string('fullnamedisplay', null, $user);
3611 // Check to see if we are displaying according to the alternative full name format.
3612 if ($override) {
3613 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3614 // Default to show just the user names according to the fullnamedisplay string.
3615 return get_string('fullnamedisplay', null, $user);
3616 } else {
3617 // If the override is true, then change the template to use the complete name.
3618 $template = $CFG->alternativefullnameformat;
3622 $requirednames = array();
3623 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3624 foreach ($allnames as $allname) {
3625 if (strpos($template, $allname) !== false) {
3626 $requirednames[] = $allname;
3630 $displayname = $template;
3631 // Switch in the actual data into the template.
3632 foreach ($requirednames as $altname) {
3633 if (isset($user->$altname)) {
3634 // Using empty() on the below if statement causes breakages.
3635 if ((string)$user->$altname == '') {
3636 $displayname = str_replace($altname, 'EMPTY', $displayname);
3637 } else {
3638 $displayname = str_replace($altname, $user->$altname, $displayname);
3640 } else {
3641 $displayname = str_replace($altname, 'EMPTY', $displayname);
3644 // Tidy up any misc. characters (Not perfect, but gets most characters).
3645 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3646 // katakana and parenthesis.
3647 $patterns = array();
3648 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3649 // filled in by a user.
3650 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3651 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3652 // This regular expression is to remove any double spaces in the display name.
3653 $patterns[] = '/\s{2,}/u';
3654 foreach ($patterns as $pattern) {
3655 $displayname = preg_replace($pattern, ' ', $displayname);
3658 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3659 $displayname = trim($displayname);
3660 if (empty($displayname)) {
3661 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3662 // people in general feel is a good setting to fall back on.
3663 $displayname = $user->firstname;
3665 return $displayname;
3669 * A centralised location for the all name fields. Returns an array / sql string snippet.
3671 * @param bool $returnsql True for an sql select field snippet.
3672 * @param string $tableprefix table query prefix to use in front of each field.
3673 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3674 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3675 * @return array|string All name fields.
3677 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null) {
3678 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3679 'lastnamephonetic' => 'lastnamephonetic',
3680 'middlename' => 'middlename',
3681 'alternatename' => 'alternatename',
3682 'firstname' => 'firstname',
3683 'lastname' => 'lastname');
3685 // Let's add a prefix to the array of user name fields if provided.
3686 if ($prefix) {
3687 foreach ($alternatenames as $key => $altname) {
3688 $alternatenames[$key] = $prefix . $altname;
3692 // Create an sql field snippet if requested.
3693 if ($returnsql) {
3694 if ($tableprefix) {
3695 if ($fieldprefix) {
3696 foreach ($alternatenames as $key => $altname) {
3697 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3699 } else {
3700 foreach ($alternatenames as $key => $altname) {
3701 $alternatenames[$key] = $tableprefix . '.' . $altname;
3705 $alternatenames = implode(',', $alternatenames);
3707 return $alternatenames;
3711 * Reduces lines of duplicated code for getting user name fields.
3713 * See also {@link user_picture::unalias()}
3715 * @param object $addtoobject Object to add user name fields to.
3716 * @param object $secondobject Object that contains user name field information.
3717 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3718 * @param array $additionalfields Additional fields to be matched with data in the second object.
3719 * The key can be set to the user table field name.
3720 * @return object User name fields.
3722 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3723 $fields = get_all_user_name_fields(false, null, $prefix);
3724 if ($additionalfields) {
3725 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3726 // the key is a number and then sets the key to the array value.
3727 foreach ($additionalfields as $key => $value) {
3728 if (is_numeric($key)) {
3729 $additionalfields[$value] = $prefix . $value;
3730 unset($additionalfields[$key]);
3731 } else {
3732 $additionalfields[$key] = $prefix . $value;
3735 $fields = array_merge($fields, $additionalfields);
3737 foreach ($fields as $key => $field) {
3738 // Important that we have all of the user name fields present in the object that we are sending back.
3739 $addtoobject->$key = '';
3740 if (isset($secondobject->$field)) {
3741 $addtoobject->$key = $secondobject->$field;
3744 return $addtoobject;
3748 * Returns an array of values in order of occurance in a provided string.
3749 * The key in the result is the character postion in the string.
3751 * @param array $values Values to be found in the string format
3752 * @param string $stringformat The string which may contain values being searched for.
3753 * @return array An array of values in order according to placement in the string format.
3755 function order_in_string($values, $stringformat) {
3756 $valuearray = array();
3757 foreach ($values as $value) {
3758 $pattern = "/$value\b/";
3759 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3760 if (preg_match($pattern, $stringformat)) {
3761 $replacement = "thing";
3762 // Replace the value with something more unique to ensure we get the right position when using strpos().
3763 $newformat = preg_replace($pattern, $replacement, $stringformat);
3764 $position = strpos($newformat, $replacement);
3765 $valuearray[$position] = $value;
3768 ksort($valuearray);
3769 return $valuearray;
3773 * Checks if current user is shown any extra fields when listing users.
3775 * @param object $context Context
3776 * @param array $already Array of fields that we're going to show anyway
3777 * so don't bother listing them
3778 * @return array Array of field names from user table, not including anything
3779 * listed in $already
3781 function get_extra_user_fields($context, $already = array()) {
3782 global $CFG;
3784 // Only users with permission get the extra fields.
3785 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3786 return array();
3789 // Split showuseridentity on comma.
3790 if (empty($CFG->showuseridentity)) {
3791 // Explode gives wrong result with empty string.
3792 $extra = array();
3793 } else {
3794 $extra = explode(',', $CFG->showuseridentity);
3796 $renumber = false;
3797 foreach ($extra as $key => $field) {
3798 if (in_array($field, $already)) {
3799 unset($extra[$key]);
3800 $renumber = true;
3803 if ($renumber) {
3804 // For consistency, if entries are removed from array, renumber it
3805 // so they are numbered as you would expect.
3806 $extra = array_merge($extra);
3808 return $extra;
3812 * If the current user is to be shown extra user fields when listing or
3813 * selecting users, returns a string suitable for including in an SQL select
3814 * clause to retrieve those fields.
3816 * @param context $context Context
3817 * @param string $alias Alias of user table, e.g. 'u' (default none)
3818 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3819 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3820 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3822 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3823 $fields = get_extra_user_fields($context, $already);
3824 $result = '';
3825 // Add punctuation for alias.
3826 if ($alias !== '') {
3827 $alias .= '.';
3829 foreach ($fields as $field) {
3830 $result .= ', ' . $alias . $field;
3831 if ($prefix) {
3832 $result .= ' AS ' . $prefix . $field;
3835 return $result;
3839 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3840 * @param string $field Field name, e.g. 'phone1'
3841 * @return string Text description taken from language file, e.g. 'Phone number'
3843 function get_user_field_name($field) {
3844 // Some fields have language strings which are not the same as field name.
3845 switch ($field) {
3846 case 'phone1' : {
3847 return get_string('phone');
3849 case 'url' : {
3850 return get_string('webpage');
3852 case 'icq' : {
3853 return get_string('icqnumber');
3855 case 'skype' : {
3856 return get_string('skypeid');
3858 case 'aim' : {
3859 return get_string('aimid');
3861 case 'yahoo' : {
3862 return get_string('yahooid');
3864 case 'msn' : {
3865 return get_string('msnid');
3868 // Otherwise just use the same lang string.
3869 return get_string($field);
3873 * Returns whether a given authentication plugin exists.
3875 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3876 * @return boolean Whether the plugin is available.
3878 function exists_auth_plugin($auth) {
3879 global $CFG;
3881 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3882 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3884 return false;
3888 * Checks if a given plugin is in the list of enabled authentication plugins.
3890 * @param string $auth Authentication plugin.
3891 * @return boolean Whether the plugin is enabled.
3893 function is_enabled_auth($auth) {
3894 if (empty($auth)) {
3895 return false;
3898 $enabled = get_enabled_auth_plugins();
3900 return in_array($auth, $enabled);
3904 * Returns an authentication plugin instance.
3906 * @param string $auth name of authentication plugin
3907 * @return auth_plugin_base An instance of the required authentication plugin.
3909 function get_auth_plugin($auth) {
3910 global $CFG;
3912 // Check the plugin exists first.
3913 if (! exists_auth_plugin($auth)) {
3914 print_error('authpluginnotfound', 'debug', '', $auth);
3917 // Return auth plugin instance.
3918 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3919 $class = "auth_plugin_$auth";
3920 return new $class;
3924 * Returns array of active auth plugins.
3926 * @param bool $fix fix $CFG->auth if needed
3927 * @return array
3929 function get_enabled_auth_plugins($fix=false) {
3930 global $CFG;
3932 $default = array('manual', 'nologin');
3934 if (empty($CFG->auth)) {
3935 $auths = array();
3936 } else {
3937 $auths = explode(',', $CFG->auth);
3940 if ($fix) {
3941 $auths = array_unique($auths);
3942 foreach ($auths as $k => $authname) {
3943 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3944 unset($auths[$k]);
3947 $newconfig = implode(',', $auths);
3948 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3949 set_config('auth', $newconfig);
3953 return (array_merge($default, $auths));
3957 * Returns true if an internal authentication method is being used.
3958 * if method not specified then, global default is assumed
3960 * @param string $auth Form of authentication required
3961 * @return bool
3963 function is_internal_auth($auth) {
3964 // Throws error if bad $auth.
3965 $authplugin = get_auth_plugin($auth);
3966 return $authplugin->is_internal();
3970 * Returns true if the user is a 'restored' one.
3972 * Used in the login process to inform the user and allow him/her to reset the password
3974 * @param string $username username to be checked
3975 * @return bool
3977 function is_restored_user($username) {
3978 global $CFG, $DB;
3980 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3984 * Returns an array of user fields
3986 * @return array User field/column names
3988 function get_user_fieldnames() {
3989 global $DB;
3991 $fieldarray = $DB->get_columns('user');
3992 unset($fieldarray['id']);
3993 $fieldarray = array_keys($fieldarray);
3995 return $fieldarray;
3999 * Creates a bare-bones user record
4001 * @todo Outline auth types and provide code example
4003 * @param string $username New user's username to add to record
4004 * @param string $password New user's password to add to record
4005 * @param string $auth Form of authentication required
4006 * @return stdClass A complete user object
4008 function create_user_record($username, $password, $auth = 'manual') {
4009 global $CFG, $DB;
4010 require_once($CFG->dirroot.'/user/profile/lib.php');
4011 require_once($CFG->dirroot.'/user/lib.php');
4013 // Just in case check text case.
4014 $username = trim(core_text::strtolower($username));
4016 $authplugin = get_auth_plugin($auth);
4017 $customfields = $authplugin->get_custom_user_profile_fields();
4018 $newuser = new stdClass();
4019 if ($newinfo = $authplugin->get_userinfo($username)) {
4020 $newinfo = truncate_userinfo($newinfo);
4021 foreach ($newinfo as $key => $value) {
4022 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
4023 $newuser->$key = $value;
4028 if (!empty($newuser->email)) {
4029 if (email_is_not_allowed($newuser->email)) {
4030 unset($newuser->email);
4034 if (!isset($newuser->city)) {
4035 $newuser->city = '';
4038 $newuser->auth = $auth;
4039 $newuser->username = $username;
4041 // Fix for MDL-8480
4042 // user CFG lang for user if $newuser->lang is empty
4043 // or $user->lang is not an installed language.
4044 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
4045 $newuser->lang = $CFG->lang;
4047 $newuser->confirmed = 1;
4048 $newuser->lastip = getremoteaddr();
4049 $newuser->timecreated = time();
4050 $newuser->timemodified = $newuser->timecreated;
4051 $newuser->mnethostid = $CFG->mnet_localhost_id;
4053 $newuser->id = user_create_user($newuser, false, false);
4055 // Save user profile data.
4056 profile_save_data($newuser);
4058 $user = get_complete_user_data('id', $newuser->id);
4059 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
4060 set_user_preference('auth_forcepasswordchange', 1, $user);
4062 // Set the password.
4063 update_internal_user_password($user, $password);
4065 // Trigger event.
4066 \core\event\user_created::create_from_userid($newuser->id)->trigger();
4068 return $user;
4072 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4074 * @param string $username user's username to update the record
4075 * @return stdClass A complete user object
4077 function update_user_record($username) {
4078 global $DB, $CFG;
4079 // Just in case check text case.
4080 $username = trim(core_text::strtolower($username));
4082 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
4083 return update_user_record_by_id($oldinfo->id);
4087 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4089 * @param int $id user id
4090 * @return stdClass A complete user object
4092 function update_user_record_by_id($id) {
4093 global $DB, $CFG;
4094 require_once($CFG->dirroot."/user/profile/lib.php");
4095 require_once($CFG->dirroot.'/user/lib.php');
4097 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
4098 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
4100 $newuser = array();
4101 $userauth = get_auth_plugin($oldinfo->auth);
4103 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
4104 $newinfo = truncate_userinfo($newinfo);
4105 $customfields = $userauth->get_custom_user_profile_fields();
4107 foreach ($newinfo as $key => $value) {
4108 $key = strtolower($key);
4109 $iscustom = in_array($key, $customfields);
4110 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4111 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4112 // Unknown or must not be changed.
4113 continue;
4115 $confval = $userauth->config->{'field_updatelocal_' . $key};
4116 $lockval = $userauth->config->{'field_lock_' . $key};
4117 if (empty($confval) || empty($lockval)) {
4118 continue;
4120 if ($confval === 'onlogin') {
4121 // MDL-4207 Don't overwrite modified user profile values with
4122 // empty LDAP values when 'unlocked if empty' is set. The purpose
4123 // of the setting 'unlocked if empty' is to allow the user to fill
4124 // in a value for the selected field _if LDAP is giving
4125 // nothing_ for this field. Thus it makes sense to let this value
4126 // stand in until LDAP is giving a value for this field.
4127 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4128 if ($iscustom || (in_array($key, $userauth->userfields) &&
4129 ((string)$oldinfo->$key !== (string)$value))) {
4130 $newuser[$key] = (string)$value;
4135 if ($newuser) {
4136 $newuser['id'] = $oldinfo->id;
4137 $newuser['timemodified'] = time();
4138 user_update_user((object) $newuser, false, false);
4140 // Save user profile data.
4141 profile_save_data((object) $newuser);
4143 // Trigger event.
4144 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4148 return get_complete_user_data('id', $oldinfo->id);
4152 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4154 * @param array $info Array of user properties to truncate if needed
4155 * @return array The now truncated information that was passed in
4157 function truncate_userinfo(array $info) {
4158 // Define the limits.
4159 $limit = array(
4160 'username' => 100,
4161 'idnumber' => 255,
4162 'firstname' => 100,
4163 'lastname' => 100,
4164 'email' => 100,
4165 'icq' => 15,
4166 'phone1' => 20,
4167 'phone2' => 20,
4168 'institution' => 255,
4169 'department' => 255,
4170 'address' => 255,
4171 'city' => 120,
4172 'country' => 2,
4173 'url' => 255,
4176 // Apply where needed.
4177 foreach (array_keys($info) as $key) {
4178 if (!empty($limit[$key])) {
4179 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4183 return $info;
4187 * Marks user deleted in internal user database and notifies the auth plugin.
4188 * Also unenrols user from all roles and does other cleanup.
4190 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4192 * @param stdClass $user full user object before delete
4193 * @return boolean success
4194 * @throws coding_exception if invalid $user parameter detected
4196 function delete_user(stdClass $user) {
4197 global $CFG, $DB;
4198 require_once($CFG->libdir.'/grouplib.php');
4199 require_once($CFG->libdir.'/gradelib.php');
4200 require_once($CFG->dirroot.'/message/lib.php');
4201 require_once($CFG->dirroot.'/tag/lib.php');
4202 require_once($CFG->dirroot.'/user/lib.php');
4204 // Make sure nobody sends bogus record type as parameter.
4205 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4206 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4209 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4210 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4211 debugging('Attempt to delete unknown user account.');
4212 return false;
4215 // There must be always exactly one guest record, originally the guest account was identified by username only,
4216 // now we use $CFG->siteguest for performance reasons.
4217 if ($user->username === 'guest' or isguestuser($user)) {
4218 debugging('Guest user account can not be deleted.');
4219 return false;
4222 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4223 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4224 if ($user->auth === 'manual' and is_siteadmin($user)) {
4225 debugging('Local administrator accounts can not be deleted.');
4226 return false;
4229 // Keep user record before updating it, as we have to pass this to user_deleted event.
4230 $olduser = clone $user;
4232 // Keep a copy of user context, we need it for event.
4233 $usercontext = context_user::instance($user->id);
4235 // Delete all grades - backup is kept in grade_grades_history table.
4236 grade_user_delete($user->id);
4238 // Move unread messages from this user to read.
4239 message_move_userfrom_unread2read($user->id);
4241 // TODO: remove from cohorts using standard API here.
4243 // Remove user tags.
4244 tag_set('user', $user->id, array(), 'core', $usercontext->id);
4246 // Unconditionally unenrol from all courses.
4247 enrol_user_delete($user);
4249 // Unenrol from all roles in all contexts.
4250 // This might be slow but it is really needed - modules might do some extra cleanup!
4251 role_unassign_all(array('userid' => $user->id));
4253 // Now do a brute force cleanup.
4255 // Remove from all cohorts.
4256 $DB->delete_records('cohort_members', array('userid' => $user->id));
4258 // Remove from all groups.
4259 $DB->delete_records('groups_members', array('userid' => $user->id));
4261 // Brute force unenrol from all courses.
4262 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4264 // Purge user preferences.
4265 $DB->delete_records('user_preferences', array('userid' => $user->id));
4267 // Purge user extra profile info.
4268 $DB->delete_records('user_info_data', array('userid' => $user->id));
4270 // Last course access not necessary either.
4271 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4272 // Remove all user tokens.
4273 $DB->delete_records('external_tokens', array('userid' => $user->id));
4275 // Unauthorise the user for all services.
4276 $DB->delete_records('external_services_users', array('userid' => $user->id));
4278 // Remove users private keys.
4279 $DB->delete_records('user_private_key', array('userid' => $user->id));
4281 // Remove users customised pages.
4282 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4284 // Force logout - may fail if file based sessions used, sorry.
4285 \core\session\manager::kill_user_sessions($user->id);
4287 // Workaround for bulk deletes of users with the same email address.
4288 $delname = clean_param($user->email . "." . time(), PARAM_USERNAME);
4289 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4290 $delname++;
4293 // Mark internal user record as "deleted".
4294 $updateuser = new stdClass();
4295 $updateuser->id = $user->id;
4296 $updateuser->deleted = 1;
4297 $updateuser->username = $delname; // Remember it just in case.
4298 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4299 $updateuser->idnumber = ''; // Clear this field to free it up.
4300 $updateuser->picture = 0;
4301 $updateuser->timemodified = time();
4303 // Don't trigger update event, as user is being deleted.
4304 user_update_user($updateuser, false, false);
4306 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4307 context_helper::delete_instance(CONTEXT_USER, $user->id);
4309 // Any plugin that needs to cleanup should register this event.
4310 // Trigger event.
4311 $event = \core\event\user_deleted::create(
4312 array(
4313 'objectid' => $user->id,
4314 'relateduserid' => $user->id,
4315 'context' => $usercontext,
4316 'other' => array(
4317 'username' => $user->username,
4318 'email' => $user->email,
4319 'idnumber' => $user->idnumber,
4320 'picture' => $user->picture,
4321 'mnethostid' => $user->mnethostid
4325 $event->add_record_snapshot('user', $olduser);
4326 $event->trigger();
4328 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4329 // should know about this updated property persisted to the user's table.
4330 $user->timemodified = $updateuser->timemodified;
4332 // Notify auth plugin - do not block the delete even when plugin fails.
4333 $authplugin = get_auth_plugin($user->auth);
4334 $authplugin->user_delete($user);
4336 return true;
4340 * Retrieve the guest user object.
4342 * @return stdClass A {@link $USER} object
4344 function guest_user() {
4345 global $CFG, $DB;
4347 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4348 $newuser->confirmed = 1;
4349 $newuser->lang = $CFG->lang;
4350 $newuser->lastip = getremoteaddr();
4353 return $newuser;
4357 * Authenticates a user against the chosen authentication mechanism
4359 * Given a username and password, this function looks them
4360 * up using the currently selected authentication mechanism,
4361 * and if the authentication is successful, it returns a
4362 * valid $user object from the 'user' table.
4364 * Uses auth_ functions from the currently active auth module
4366 * After authenticate_user_login() returns success, you will need to
4367 * log that the user has logged in, and call complete_user_login() to set
4368 * the session up.
4370 * Note: this function works only with non-mnet accounts!
4372 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4373 * @param string $password User's password
4374 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4375 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4376 * @return stdClass|false A {@link $USER} object or false if error
4378 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4379 global $CFG, $DB;
4380 require_once("$CFG->libdir/authlib.php");
4382 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4383 // we have found the user
4385 } else if (!empty($CFG->authloginviaemail)) {
4386 if ($email = clean_param($username, PARAM_EMAIL)) {
4387 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4388 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4389 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4390 if (count($users) === 1) {
4391 // Use email for login only if unique.
4392 $user = reset($users);
4393 $user = get_complete_user_data('id', $user->id);
4394 $username = $user->username;
4396 unset($users);
4400 $authsenabled = get_enabled_auth_plugins();
4402 if ($user) {
4403 // Use manual if auth not set.
4404 $auth = empty($user->auth) ? 'manual' : $user->auth;
4405 if (!empty($user->suspended)) {
4406 $failurereason = AUTH_LOGIN_SUSPENDED;
4408 // Trigger login failed event.
4409 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4410 'other' => array('username' => $username, 'reason' => $failurereason)));
4411 $event->trigger();
4412 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4413 return false;
4415 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4416 // Legacy way to suspend user.
4417 $failurereason = AUTH_LOGIN_SUSPENDED;
4419 // Trigger login failed event.
4420 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4421 'other' => array('username' => $username, 'reason' => $failurereason)));
4422 $event->trigger();
4423 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4424 return false;
4426 $auths = array($auth);
4428 } else {
4429 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4430 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4431 $failurereason = AUTH_LOGIN_NOUSER;
4433 // Trigger login failed event.
4434 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4435 'reason' => $failurereason)));
4436 $event->trigger();
4437 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4438 return false;
4441 // User does not exist.
4442 $auths = $authsenabled;
4443 $user = new stdClass();
4444 $user->id = 0;
4447 if ($ignorelockout) {
4448 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4449 // or this function is called from a SSO script.
4450 } else if ($user->id) {
4451 // Verify login lockout after other ways that may prevent user login.
4452 if (login_is_lockedout($user)) {
4453 $failurereason = AUTH_LOGIN_LOCKOUT;
4455 // Trigger login failed event.
4456 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4457 'other' => array('username' => $username, 'reason' => $failurereason)));
4458 $event->trigger();
4460 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4461 return false;
4463 } else {
4464 // We can not lockout non-existing accounts.
4467 foreach ($auths as $auth) {
4468 $authplugin = get_auth_plugin($auth);
4470 // On auth fail fall through to the next plugin.
4471 if (!$authplugin->user_login($username, $password)) {
4472 continue;
4475 // Successful authentication.
4476 if ($user->id) {
4477 // User already exists in database.
4478 if (empty($user->auth)) {
4479 // For some reason auth isn't set yet.
4480 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4481 $user->auth = $auth;
4484 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4485 // the current hash algorithm while we have access to the user's password.
4486 update_internal_user_password($user, $password);
4488 if ($authplugin->is_synchronised_with_external()) {
4489 // Update user record from external DB.
4490 $user = update_user_record_by_id($user->id);
4492 } else {
4493 // The user is authenticated but user creation may be disabled.
4494 if (!empty($CFG->authpreventaccountcreation)) {
4495 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4497 // Trigger login failed event.
4498 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4499 'reason' => $failurereason)));
4500 $event->trigger();
4502 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4503 $_SERVER['HTTP_USER_AGENT']);
4504 return false;
4505 } else {
4506 $user = create_user_record($username, $password, $auth);
4510 $authplugin->sync_roles($user);
4512 foreach ($authsenabled as $hau) {
4513 $hauth = get_auth_plugin($hau);
4514 $hauth->user_authenticated_hook($user, $username, $password);
4517 if (empty($user->id)) {
4518 $failurereason = AUTH_LOGIN_NOUSER;
4519 // Trigger login failed event.
4520 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4521 'reason' => $failurereason)));
4522 $event->trigger();
4523 return false;
4526 if (!empty($user->suspended)) {
4527 // Just in case some auth plugin suspended account.
4528 $failurereason = AUTH_LOGIN_SUSPENDED;
4529 // Trigger login failed event.
4530 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4531 'other' => array('username' => $username, 'reason' => $failurereason)));
4532 $event->trigger();
4533 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4534 return false;
4537 login_attempt_valid($user);
4538 $failurereason = AUTH_LOGIN_OK;
4539 return $user;
4542 // Failed if all the plugins have failed.
4543 if (debugging('', DEBUG_ALL)) {
4544 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4547 if ($user->id) {
4548 login_attempt_failed($user);
4549 $failurereason = AUTH_LOGIN_FAILED;
4550 // Trigger login failed event.
4551 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4552 'other' => array('username' => $username, 'reason' => $failurereason)));
4553 $event->trigger();
4554 } else {
4555 $failurereason = AUTH_LOGIN_NOUSER;
4556 // Trigger login failed event.
4557 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4558 'reason' => $failurereason)));
4559 $event->trigger();
4562 return false;
4566 * Call to complete the user login process after authenticate_user_login()
4567 * has succeeded. It will setup the $USER variable and other required bits
4568 * and pieces.
4570 * NOTE:
4571 * - It will NOT log anything -- up to the caller to decide what to log.
4572 * - this function does not set any cookies any more!
4574 * @param stdClass $user
4575 * @return stdClass A {@link $USER} object - BC only, do not use
4577 function complete_user_login($user) {
4578 global $CFG, $USER;
4580 \core\session\manager::login_user($user);
4582 // Reload preferences from DB.
4583 unset($USER->preference);
4584 check_user_preferences_loaded($USER);
4586 // Update login times.
4587 update_user_login_times();
4589 // Extra session prefs init.
4590 set_login_session_preferences();
4592 // Trigger login event.
4593 $event = \core\event\user_loggedin::create(
4594 array(
4595 'userid' => $USER->id,
4596 'objectid' => $USER->id,
4597 'other' => array('username' => $USER->username),
4600 $event->trigger();
4602 if (isguestuser()) {
4603 // No need to continue when user is THE guest.
4604 return $USER;
4607 if (CLI_SCRIPT) {
4608 // We can redirect to password change URL only in browser.
4609 return $USER;
4612 // Select password change url.
4613 $userauth = get_auth_plugin($USER->auth);
4615 // Check whether the user should be changing password.
4616 if (get_user_preferences('auth_forcepasswordchange', false)) {
4617 if ($userauth->can_change_password()) {
4618 if ($changeurl = $userauth->change_password_url()) {
4619 redirect($changeurl);
4620 } else {
4621 redirect($CFG->httpswwwroot.'/login/change_password.php');
4623 } else {
4624 print_error('nopasswordchangeforced', 'auth');
4627 return $USER;
4631 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4633 * @param string $password String to check.
4634 * @return boolean True if the $password matches the format of an md5 sum.
4636 function password_is_legacy_hash($password) {
4637 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4641 * Compare password against hash stored in user object to determine if it is valid.
4643 * If necessary it also updates the stored hash to the current format.
4645 * @param stdClass $user (Password property may be updated).
4646 * @param string $password Plain text password.
4647 * @return bool True if password is valid.
4649 function validate_internal_user_password($user, $password) {
4650 global $CFG;
4651 require_once($CFG->libdir.'/password_compat/lib/password.php');
4653 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4654 // Internal password is not used at all, it can not validate.
4655 return false;
4658 // If hash isn't a legacy (md5) hash, validate using the library function.
4659 if (!password_is_legacy_hash($user->password)) {
4660 return password_verify($password, $user->password);
4663 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4664 // is valid we can then update it to the new algorithm.
4666 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4667 $validated = false;
4669 if ($user->password === md5($password.$sitesalt)
4670 or $user->password === md5($password)
4671 or $user->password === md5(addslashes($password).$sitesalt)
4672 or $user->password === md5(addslashes($password))) {
4673 // Note: we are intentionally using the addslashes() here because we
4674 // need to accept old password hashes of passwords with magic quotes.
4675 $validated = true;
4677 } else {
4678 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4679 $alt = 'passwordsaltalt'.$i;
4680 if (!empty($CFG->$alt)) {
4681 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4682 $validated = true;
4683 break;
4689 if ($validated) {
4690 // If the password matches the existing md5 hash, update to the
4691 // current hash algorithm while we have access to the user's password.
4692 update_internal_user_password($user, $password);
4695 return $validated;
4699 * Calculate hash for a plain text password.
4701 * @param string $password Plain text password to be hashed.
4702 * @param bool $fasthash If true, use a low cost factor when generating the hash
4703 * This is much faster to generate but makes the hash
4704 * less secure. It is used when lots of hashes need to
4705 * be generated quickly.
4706 * @return string The hashed password.
4708 * @throws moodle_exception If a problem occurs while generating the hash.
4710 function hash_internal_user_password($password, $fasthash = false) {
4711 global $CFG;
4712 require_once($CFG->libdir.'/password_compat/lib/password.php');
4714 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4715 $options = ($fasthash) ? array('cost' => 4) : array();
4717 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4719 if ($generatedhash === false || $generatedhash === null) {
4720 throw new moodle_exception('Failed to generate password hash.');
4723 return $generatedhash;
4727 * Update password hash in user object (if necessary).
4729 * The password is updated if:
4730 * 1. The password has changed (the hash of $user->password is different
4731 * to the hash of $password).
4732 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4733 * md5 algorithm).
4735 * Updating the password will modify the $user object and the database
4736 * record to use the current hashing algorithm.
4738 * @param stdClass $user User object (password property may be updated).
4739 * @param string $password Plain text password.
4740 * @param bool $fasthash If true, use a low cost factor when generating the hash
4741 * This is much faster to generate but makes the hash
4742 * less secure. It is used when lots of hashes need to
4743 * be generated quickly.
4744 * @return bool Always returns true.
4746 function update_internal_user_password($user, $password, $fasthash = false) {
4747 global $CFG, $DB;
4748 require_once($CFG->libdir.'/password_compat/lib/password.php');
4750 // Figure out what the hashed password should be.
4751 if (!isset($user->auth)) {
4752 debugging('User record in update_internal_user_password() must include field auth',
4753 DEBUG_DEVELOPER);
4754 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4756 $authplugin = get_auth_plugin($user->auth);
4757 if ($authplugin->prevent_local_passwords()) {
4758 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4759 } else {
4760 $hashedpassword = hash_internal_user_password($password, $fasthash);
4763 $algorithmchanged = false;
4765 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4766 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4767 $passwordchanged = ($user->password !== $hashedpassword);
4769 } else if (isset($user->password)) {
4770 // If verification fails then it means the password has changed.
4771 $passwordchanged = !password_verify($password, $user->password);
4772 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4773 } else {
4774 // While creating new user, password in unset in $user object, to avoid
4775 // saving it with user_create()
4776 $passwordchanged = true;
4779 if ($passwordchanged || $algorithmchanged) {
4780 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4781 $user->password = $hashedpassword;
4783 // Trigger event.
4784 $user = $DB->get_record('user', array('id' => $user->id));
4785 \core\event\user_password_updated::create_from_user($user)->trigger();
4788 return true;
4792 * Get a complete user record, which includes all the info in the user record.
4794 * Intended for setting as $USER session variable
4796 * @param string $field The user field to be checked for a given value.
4797 * @param string $value The value to match for $field.
4798 * @param int $mnethostid
4799 * @return mixed False, or A {@link $USER} object.
4801 function get_complete_user_data($field, $value, $mnethostid = null) {
4802 global $CFG, $DB;
4804 if (!$field || !$value) {
4805 return false;
4808 // Build the WHERE clause for an SQL query.
4809 $params = array('fieldval' => $value);
4810 $constraints = "$field = :fieldval AND deleted <> 1";
4812 // If we are loading user data based on anything other than id,
4813 // we must also restrict our search based on mnet host.
4814 if ($field != 'id') {
4815 if (empty($mnethostid)) {
4816 // If empty, we restrict to local users.
4817 $mnethostid = $CFG->mnet_localhost_id;
4820 if (!empty($mnethostid)) {
4821 $params['mnethostid'] = $mnethostid;
4822 $constraints .= " AND mnethostid = :mnethostid";
4825 // Get all the basic user data.
4826 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4827 return false;
4830 // Get various settings and preferences.
4832 // Preload preference cache.
4833 check_user_preferences_loaded($user);
4835 // Load course enrolment related stuff.
4836 $user->lastcourseaccess = array(); // During last session.
4837 $user->currentcourseaccess = array(); // During current session.
4838 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4839 foreach ($lastaccesses as $lastaccess) {
4840 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4844 $sql = "SELECT g.id, g.courseid
4845 FROM {groups} g, {groups_members} gm
4846 WHERE gm.groupid=g.id AND gm.userid=?";
4848 // This is a special hack to speedup calendar display.
4849 $user->groupmember = array();
4850 if (!isguestuser($user)) {
4851 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4852 foreach ($groups as $group) {
4853 if (!array_key_exists($group->courseid, $user->groupmember)) {
4854 $user->groupmember[$group->courseid] = array();
4856 $user->groupmember[$group->courseid][$group->id] = $group->id;
4861 // Add the custom profile fields to the user record.
4862 $user->profile = array();
4863 if (!isguestuser($user)) {
4864 require_once($CFG->dirroot.'/user/profile/lib.php');
4865 profile_load_custom_fields($user);
4868 // Rewrite some variables if necessary.
4869 if (!empty($user->description)) {
4870 // No need to cart all of it around.
4871 $user->description = true;
4873 if (isguestuser($user)) {
4874 // Guest language always same as site.
4875 $user->lang = $CFG->lang;
4876 // Name always in current language.
4877 $user->firstname = get_string('guestuser');
4878 $user->lastname = ' ';
4881 return $user;
4885 * Validate a password against the configured password policy
4887 * @param string $password the password to be checked against the password policy
4888 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4889 * @return bool true if the password is valid according to the policy. false otherwise.
4891 function check_password_policy($password, &$errmsg) {
4892 global $CFG;
4894 if (empty($CFG->passwordpolicy)) {
4895 return true;
4898 $errmsg = '';
4899 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4900 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4903 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4904 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4907 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4908 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4911 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4912 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4915 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4916 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4918 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4919 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4922 if ($errmsg == '') {
4923 return true;
4924 } else {
4925 return false;
4931 * When logging in, this function is run to set certain preferences for the current SESSION.
4933 function set_login_session_preferences() {
4934 global $SESSION;
4936 $SESSION->justloggedin = true;
4938 unset($SESSION->lang);
4939 unset($SESSION->forcelang);
4940 unset($SESSION->load_navigation_admin);
4945 * Delete a course, including all related data from the database, and any associated files.
4947 * @param mixed $courseorid The id of the course or course object to delete.
4948 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4949 * @return bool true if all the removals succeeded. false if there were any failures. If this
4950 * method returns false, some of the removals will probably have succeeded, and others
4951 * failed, but you have no way of knowing which.
4953 function delete_course($courseorid, $showfeedback = true) {
4954 global $DB;
4956 if (is_object($courseorid)) {
4957 $courseid = $courseorid->id;
4958 $course = $courseorid;
4959 } else {
4960 $courseid = $courseorid;
4961 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4962 return false;
4965 $context = context_course::instance($courseid);
4967 // Frontpage course can not be deleted!!
4968 if ($courseid == SITEID) {
4969 return false;
4972 // Make the course completely empty.
4973 remove_course_contents($courseid, $showfeedback);
4975 // Delete the course and related context instance.
4976 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4978 $DB->delete_records("course", array("id" => $courseid));
4979 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4981 // Reset all course related caches here.
4982 if (class_exists('format_base', false)) {
4983 format_base::reset_course_cache($courseid);
4986 // Trigger a course deleted event.
4987 $event = \core\event\course_deleted::create(array(
4988 'objectid' => $course->id,
4989 'context' => $context,
4990 'other' => array(
4991 'shortname' => $course->shortname,
4992 'fullname' => $course->fullname,
4993 'idnumber' => $course->idnumber
4996 $event->add_record_snapshot('course', $course);
4997 $event->trigger();
4999 return true;
5003 * Clear a course out completely, deleting all content but don't delete the course itself.
5005 * This function does not verify any permissions.
5007 * Please note this function also deletes all user enrolments,
5008 * enrolment instances and role assignments by default.
5010 * $options:
5011 * - 'keep_roles_and_enrolments' - false by default
5012 * - 'keep_groups_and_groupings' - false by default
5014 * @param int $courseid The id of the course that is being deleted
5015 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5016 * @param array $options extra options
5017 * @return bool true if all the removals succeeded. false if there were any failures. If this
5018 * method returns false, some of the removals will probably have succeeded, and others
5019 * failed, but you have no way of knowing which.
5021 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5022 global $CFG, $DB, $OUTPUT;
5024 require_once($CFG->libdir.'/badgeslib.php');
5025 require_once($CFG->libdir.'/completionlib.php');
5026 require_once($CFG->libdir.'/questionlib.php');
5027 require_once($CFG->libdir.'/gradelib.php');
5028 require_once($CFG->dirroot.'/group/lib.php');
5029 require_once($CFG->dirroot.'/tag/coursetagslib.php');
5030 require_once($CFG->dirroot.'/comment/lib.php');
5031 require_once($CFG->dirroot.'/rating/lib.php');
5032 require_once($CFG->dirroot.'/notes/lib.php');
5034 // Handle course badges.
5035 badges_handle_course_deletion($courseid);
5037 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5038 $strdeleted = get_string('deleted').' - ';
5040 // Some crazy wishlist of stuff we should skip during purging of course content.
5041 $options = (array)$options;
5043 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5044 $coursecontext = context_course::instance($courseid);
5045 $fs = get_file_storage();
5047 // Delete course completion information, this has to be done before grades and enrols.
5048 $cc = new completion_info($course);
5049 $cc->clear_criteria();
5050 if ($showfeedback) {
5051 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5054 // Remove all data from gradebook - this needs to be done before course modules
5055 // because while deleting this information, the system may need to reference
5056 // the course modules that own the grades.
5057 remove_course_grades($courseid, $showfeedback);
5058 remove_grade_letters($coursecontext, $showfeedback);
5060 // Delete course blocks in any all child contexts,
5061 // they may depend on modules so delete them first.
5062 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5063 foreach ($childcontexts as $childcontext) {
5064 blocks_delete_all_for_context($childcontext->id);
5066 unset($childcontexts);
5067 blocks_delete_all_for_context($coursecontext->id);
5068 if ($showfeedback) {
5069 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5072 // Delete every instance of every module,
5073 // this has to be done before deleting of course level stuff.
5074 $locations = core_component::get_plugin_list('mod');
5075 foreach ($locations as $modname => $moddir) {
5076 if ($modname === 'NEWMODULE') {
5077 continue;
5079 if ($module = $DB->get_record('modules', array('name' => $modname))) {
5080 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5081 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5082 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
5084 if ($instances = $DB->get_records($modname, array('course' => $course->id))) {
5085 foreach ($instances as $instance) {
5086 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
5087 // Delete activity context questions and question categories.
5088 question_delete_activity($cm, $showfeedback);
5090 if (function_exists($moddelete)) {
5091 // This purges all module data in related tables, extra user prefs, settings, etc.
5092 $moddelete($instance->id);
5093 } else {
5094 // NOTE: we should not allow installation of modules with missing delete support!
5095 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5096 $DB->delete_records($modname, array('id' => $instance->id));
5099 if ($cm) {
5100 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5101 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5102 $DB->delete_records('course_modules', array('id' => $cm->id));
5106 if (function_exists($moddeletecourse)) {
5107 // Execute ptional course cleanup callback.
5108 $moddeletecourse($course, $showfeedback);
5110 if ($instances and $showfeedback) {
5111 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5113 } else {
5114 // Ooops, this module is not properly installed, force-delete it in the next block.
5118 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5120 // Remove all data from availability and completion tables that is associated
5121 // with course-modules belonging to this course. Note this is done even if the
5122 // features are not enabled now, in case they were enabled previously.
5123 $DB->delete_records_select('course_modules_completion',
5124 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5125 array($courseid));
5127 // Remove course-module data.
5128 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5129 foreach ($cms as $cm) {
5130 if ($module = $DB->get_record('modules', array('id' => $cm->module))) {
5131 try {
5132 $DB->delete_records($module->name, array('id' => $cm->instance));
5133 } catch (Exception $e) {
5134 // Ignore weird or missing table problems.
5137 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5138 $DB->delete_records('course_modules', array('id' => $cm->id));
5141 if ($showfeedback) {
5142 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5145 // Cleanup the rest of plugins.
5146 $cleanuplugintypes = array('report', 'coursereport', 'format');
5147 foreach ($cleanuplugintypes as $type) {
5148 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
5149 foreach ($plugins as $plugin => $pluginfunction) {
5150 $pluginfunction($course->id, $showfeedback);
5152 if ($showfeedback) {
5153 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5157 // Delete questions and question categories.
5158 question_delete_course($course, $showfeedback);
5159 if ($showfeedback) {
5160 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5163 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5164 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5165 foreach ($childcontexts as $childcontext) {
5166 $childcontext->delete();
5168 unset($childcontexts);
5170 // Remove all roles and enrolments by default.
5171 if (empty($options['keep_roles_and_enrolments'])) {
5172 // This hack is used in restore when deleting contents of existing course.
5173 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5174 enrol_course_delete($course);
5175 if ($showfeedback) {
5176 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5180 // Delete any groups, removing members and grouping/course links first.
5181 if (empty($options['keep_groups_and_groupings'])) {
5182 groups_delete_groupings($course->id, $showfeedback);
5183 groups_delete_groups($course->id, $showfeedback);
5186 // Filters be gone!
5187 filter_delete_all_for_context($coursecontext->id);
5189 // Notes, you shall not pass!
5190 note_delete_all($course->id);
5192 // Die comments!
5193 comment::delete_comments($coursecontext->id);
5195 // Ratings are history too.
5196 $delopt = new stdclass();
5197 $delopt->contextid = $coursecontext->id;
5198 $rm = new rating_manager();
5199 $rm->delete_ratings($delopt);
5201 // Delete course tags.
5202 coursetag_delete_course_tags($course->id, $showfeedback);
5204 // Delete calendar events.
5205 $DB->delete_records('event', array('courseid' => $course->id));
5206 $fs->delete_area_files($coursecontext->id, 'calendar');
5208 // Delete all related records in other core tables that may have a courseid
5209 // This array stores the tables that need to be cleared, as
5210 // table_name => column_name that contains the course id.
5211 $tablestoclear = array(
5212 'backup_courses' => 'courseid', // Scheduled backup stuff.
5213 'user_lastaccess' => 'courseid', // User access info.
5215 foreach ($tablestoclear as $table => $col) {
5216 $DB->delete_records($table, array($col => $course->id));
5219 // Delete all course backup files.
5220 $fs->delete_area_files($coursecontext->id, 'backup');
5222 // Cleanup course record - remove links to deleted stuff.
5223 $oldcourse = new stdClass();
5224 $oldcourse->id = $course->id;
5225 $oldcourse->summary = '';
5226 $oldcourse->cacherev = 0;
5227 $oldcourse->legacyfiles = 0;
5228 $oldcourse->enablecompletion = 0;
5229 if (!empty($options['keep_groups_and_groupings'])) {
5230 $oldcourse->defaultgroupingid = 0;
5232 $DB->update_record('course', $oldcourse);
5234 // Delete course sections.
5235 $DB->delete_records('course_sections', array('course' => $course->id));
5237 // Delete legacy, section and any other course files.
5238 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5240 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5241 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5242 // Easy, do not delete the context itself...
5243 $coursecontext->delete_content();
5244 } else {
5245 // Hack alert!!!!
5246 // We can not drop all context stuff because it would bork enrolments and roles,
5247 // there might be also files used by enrol plugins...
5250 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5251 // also some non-standard unsupported plugins may try to store something there.
5252 fulldelete($CFG->dataroot.'/'.$course->id);
5254 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5255 $cachemodinfo = cache::make('core', 'coursemodinfo');
5256 $cachemodinfo->delete($courseid);
5258 // Trigger a course content deleted event.
5259 $event = \core\event\course_content_deleted::create(array(
5260 'objectid' => $course->id,
5261 'context' => $coursecontext,
5262 'other' => array('shortname' => $course->shortname,
5263 'fullname' => $course->fullname,
5264 'options' => $options) // Passing this for legacy reasons.
5266 $event->add_record_snapshot('course', $course);
5267 $event->trigger();
5269 return true;
5273 * Change dates in module - used from course reset.
5275 * @param string $modname forum, assignment, etc
5276 * @param array $fields array of date fields from mod table
5277 * @param int $timeshift time difference
5278 * @param int $courseid
5279 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5280 * @return bool success
5282 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5283 global $CFG, $DB;
5284 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5286 $return = true;
5287 $params = array($timeshift, $courseid);
5288 foreach ($fields as $field) {
5289 $updatesql = "UPDATE {".$modname."}
5290 SET $field = $field + ?
5291 WHERE course=? AND $field<>0";
5292 if ($modid) {
5293 $updatesql .= ' AND id=?';
5294 $params[] = $modid;
5296 $return = $DB->execute($updatesql, $params) && $return;
5299 $refreshfunction = $modname.'_refresh_events';
5300 if (function_exists($refreshfunction)) {
5301 $refreshfunction($courseid);
5304 return $return;
5308 * This function will empty a course of user data.
5309 * It will retain the activities and the structure of the course.
5311 * @param object $data an object containing all the settings including courseid (without magic quotes)
5312 * @return array status array of array component, item, error
5314 function reset_course_userdata($data) {
5315 global $CFG, $DB;
5316 require_once($CFG->libdir.'/gradelib.php');
5317 require_once($CFG->libdir.'/completionlib.php');
5318 require_once($CFG->dirroot.'/group/lib.php');
5320 $data->courseid = $data->id;
5321 $context = context_course::instance($data->courseid);
5323 $eventparams = array(
5324 'context' => $context,
5325 'courseid' => $data->id,
5326 'other' => array(
5327 'reset_options' => (array) $data
5330 $event = \core\event\course_reset_started::create($eventparams);
5331 $event->trigger();
5333 // Calculate the time shift of dates.
5334 if (!empty($data->reset_start_date)) {
5335 // Time part of course startdate should be zero.
5336 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5337 } else {
5338 $data->timeshift = 0;
5341 // Result array: component, item, error.
5342 $status = array();
5344 // Start the resetting.
5345 $componentstr = get_string('general');
5347 // Move the course start time.
5348 if (!empty($data->reset_start_date) and $data->timeshift) {
5349 // Change course start data.
5350 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5351 // Update all course and group events - do not move activity events.
5352 $updatesql = "UPDATE {event}
5353 SET timestart = timestart + ?
5354 WHERE courseid=? AND instance=0";
5355 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5357 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5360 if (!empty($data->reset_events)) {
5361 $DB->delete_records('event', array('courseid' => $data->courseid));
5362 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5365 if (!empty($data->reset_notes)) {
5366 require_once($CFG->dirroot.'/notes/lib.php');
5367 note_delete_all($data->courseid);
5368 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5371 if (!empty($data->delete_blog_associations)) {
5372 require_once($CFG->dirroot.'/blog/lib.php');
5373 blog_remove_associations_for_course($data->courseid);
5374 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5377 if (!empty($data->reset_completion)) {
5378 // Delete course and activity completion information.
5379 $course = $DB->get_record('course', array('id' => $data->courseid));
5380 $cc = new completion_info($course);
5381 $cc->delete_all_completion_data();
5382 $status[] = array('component' => $componentstr,
5383 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5386 $componentstr = get_string('roles');
5388 if (!empty($data->reset_roles_overrides)) {
5389 $children = $context->get_child_contexts();
5390 foreach ($children as $child) {
5391 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5393 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5394 // Force refresh for logged in users.
5395 $context->mark_dirty();
5396 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5399 if (!empty($data->reset_roles_local)) {
5400 $children = $context->get_child_contexts();
5401 foreach ($children as $child) {
5402 role_unassign_all(array('contextid' => $child->id));
5404 // Force refresh for logged in users.
5405 $context->mark_dirty();
5406 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5409 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5410 $data->unenrolled = array();
5411 if (!empty($data->unenrol_users)) {
5412 $plugins = enrol_get_plugins(true);
5413 $instances = enrol_get_instances($data->courseid, true);
5414 foreach ($instances as $key => $instance) {
5415 if (!isset($plugins[$instance->enrol])) {
5416 unset($instances[$key]);
5417 continue;
5421 foreach ($data->unenrol_users as $withroleid) {
5422 if ($withroleid) {
5423 $sql = "SELECT ue.*
5424 FROM {user_enrolments} ue
5425 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5426 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5427 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5428 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5430 } else {
5431 // Without any role assigned at course context.
5432 $sql = "SELECT ue.*
5433 FROM {user_enrolments} ue
5434 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5435 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5436 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5437 WHERE ra.id IS null";
5438 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5441 $rs = $DB->get_recordset_sql($sql, $params);
5442 foreach ($rs as $ue) {
5443 if (!isset($instances[$ue->enrolid])) {
5444 continue;
5446 $instance = $instances[$ue->enrolid];
5447 $plugin = $plugins[$instance->enrol];
5448 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5449 continue;
5452 $plugin->unenrol_user($instance, $ue->userid);
5453 $data->unenrolled[$ue->userid] = $ue->userid;
5455 $rs->close();
5458 if (!empty($data->unenrolled)) {
5459 $status[] = array(
5460 'component' => $componentstr,
5461 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5462 'error' => false
5466 $componentstr = get_string('groups');
5468 // Remove all group members.
5469 if (!empty($data->reset_groups_members)) {
5470 groups_delete_group_members($data->courseid);
5471 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5474 // Remove all groups.
5475 if (!empty($data->reset_groups_remove)) {
5476 groups_delete_groups($data->courseid, false);
5477 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5480 // Remove all grouping members.
5481 if (!empty($data->reset_groupings_members)) {
5482 groups_delete_groupings_groups($data->courseid, false);
5483 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5486 // Remove all groupings.
5487 if (!empty($data->reset_groupings_remove)) {
5488 groups_delete_groupings($data->courseid, false);
5489 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5492 // Look in every instance of every module for data to delete.
5493 $unsupportedmods = array();
5494 if ($allmods = $DB->get_records('modules') ) {
5495 foreach ($allmods as $mod) {
5496 $modname = $mod->name;
5497 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5498 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5499 if (file_exists($modfile)) {
5500 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5501 continue; // Skip mods with no instances.
5503 include_once($modfile);
5504 if (function_exists($moddeleteuserdata)) {
5505 $modstatus = $moddeleteuserdata($data);
5506 if (is_array($modstatus)) {
5507 $status = array_merge($status, $modstatus);
5508 } else {
5509 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5511 } else {
5512 $unsupportedmods[] = $mod;
5514 } else {
5515 debugging('Missing lib.php in '.$modname.' module!');
5520 // Mention unsupported mods.
5521 if (!empty($unsupportedmods)) {
5522 foreach ($unsupportedmods as $mod) {
5523 $status[] = array(
5524 'component' => get_string('modulenameplural', $mod->name),
5525 'item' => '',
5526 'error' => get_string('resetnotimplemented')
5531 $componentstr = get_string('gradebook', 'grades');
5532 // Reset gradebook,.
5533 if (!empty($data->reset_gradebook_items)) {
5534 remove_course_grades($data->courseid, false);
5535 grade_grab_course_grades($data->courseid);
5536 grade_regrade_final_grades($data->courseid);
5537 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5539 } else if (!empty($data->reset_gradebook_grades)) {
5540 grade_course_reset($data->courseid);
5541 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5543 // Reset comments.
5544 if (!empty($data->reset_comments)) {
5545 require_once($CFG->dirroot.'/comment/lib.php');
5546 comment::reset_course_page_comments($context);
5549 $event = \core\event\course_reset_ended::create($eventparams);
5550 $event->trigger();
5552 return $status;
5556 * Generate an email processing address.
5558 * @param int $modid
5559 * @param string $modargs
5560 * @return string Returns email processing address
5562 function generate_email_processing_address($modid, $modargs) {
5563 global $CFG;
5565 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5566 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5572 * @todo Finish documenting this function
5574 * @param string $modargs
5575 * @param string $body Currently unused
5577 function moodle_process_email($modargs, $body) {
5578 global $DB;
5580 // The first char should be an unencoded letter. We'll take this as an action.
5581 switch ($modargs{0}) {
5582 case 'B': { // Bounce.
5583 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5584 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5585 // Check the half md5 of their email.
5586 $md5check = substr(md5($user->email), 0, 16);
5587 if ($md5check == substr($modargs, -16)) {
5588 set_bounce_count($user);
5590 // Else maybe they've already changed it?
5593 break;
5594 // Maybe more later?
5598 // CORRESPONDENCE.
5601 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5603 * @param string $action 'get', 'buffer', 'close' or 'flush'
5604 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5606 function get_mailer($action='get') {
5607 global $CFG;
5609 /** @var moodle_phpmailer $mailer */
5610 static $mailer = null;
5611 static $counter = 0;
5613 if (!isset($CFG->smtpmaxbulk)) {
5614 $CFG->smtpmaxbulk = 1;
5617 if ($action == 'get') {
5618 $prevkeepalive = false;
5620 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5621 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5622 $counter++;
5623 // Reset the mailer.
5624 $mailer->Priority = 3;
5625 $mailer->CharSet = 'UTF-8'; // Our default.
5626 $mailer->ContentType = "text/plain";
5627 $mailer->Encoding = "8bit";
5628 $mailer->From = "root@localhost";
5629 $mailer->FromName = "Root User";
5630 $mailer->Sender = "";
5631 $mailer->Subject = "";
5632 $mailer->Body = "";
5633 $mailer->AltBody = "";
5634 $mailer->ConfirmReadingTo = "";
5636 $mailer->clearAllRecipients();
5637 $mailer->clearReplyTos();
5638 $mailer->clearAttachments();
5639 $mailer->clearCustomHeaders();
5640 return $mailer;
5643 $prevkeepalive = $mailer->SMTPKeepAlive;
5644 get_mailer('flush');
5647 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5648 $mailer = new moodle_phpmailer();
5650 $counter = 1;
5652 if ($CFG->smtphosts == 'qmail') {
5653 // Use Qmail system.
5654 $mailer->isQmail();
5656 } else if (empty($CFG->smtphosts)) {
5657 // Use PHP mail() = sendmail.
5658 $mailer->isMail();
5660 } else {
5661 // Use SMTP directly.
5662 $mailer->isSMTP();
5663 if (!empty($CFG->debugsmtp)) {
5664 $mailer->SMTPDebug = true;
5666 // Specify main and backup servers.
5667 $mailer->Host = $CFG->smtphosts;
5668 // Specify secure connection protocol.
5669 $mailer->SMTPSecure = $CFG->smtpsecure;
5670 // Use previous keepalive.
5671 $mailer->SMTPKeepAlive = $prevkeepalive;
5673 if ($CFG->smtpuser) {
5674 // Use SMTP authentication.
5675 $mailer->SMTPAuth = true;
5676 $mailer->Username = $CFG->smtpuser;
5677 $mailer->Password = $CFG->smtppass;
5681 return $mailer;
5684 $nothing = null;
5686 // Keep smtp session open after sending.
5687 if ($action == 'buffer') {
5688 if (!empty($CFG->smtpmaxbulk)) {
5689 get_mailer('flush');
5690 $m = get_mailer();
5691 if ($m->Mailer == 'smtp') {
5692 $m->SMTPKeepAlive = true;
5695 return $nothing;
5698 // Close smtp session, but continue buffering.
5699 if ($action == 'flush') {
5700 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5701 if (!empty($mailer->SMTPDebug)) {
5702 echo '<pre>'."\n";
5704 $mailer->SmtpClose();
5705 if (!empty($mailer->SMTPDebug)) {
5706 echo '</pre>';
5709 return $nothing;
5712 // Close smtp session, do not buffer anymore.
5713 if ($action == 'close') {
5714 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5715 get_mailer('flush');
5716 $mailer->SMTPKeepAlive = false;
5718 $mailer = null; // Better force new instance.
5719 return $nothing;
5724 * Send an email to a specified user
5726 * @param stdClass $user A {@link $USER} object
5727 * @param stdClass $from A {@link $USER} object
5728 * @param string $subject plain text subject line of the email
5729 * @param string $messagetext plain text version of the message
5730 * @param string $messagehtml complete html version of the message (optional)
5731 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5732 * @param string $attachname the name of the file (extension indicates MIME)
5733 * @param bool $usetrueaddress determines whether $from email address should
5734 * be sent out. Will be overruled by user profile setting for maildisplay
5735 * @param string $replyto Email address to reply to
5736 * @param string $replytoname Name of reply to recipient
5737 * @param int $wordwrapwidth custom word wrap width, default 79
5738 * @return bool Returns true if mail was sent OK and false if there was an error.
5740 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5741 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5743 global $CFG;
5745 if (empty($user) or empty($user->id)) {
5746 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5747 return false;
5750 if (empty($user->email)) {
5751 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5752 return false;
5755 if (!empty($user->deleted)) {
5756 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5757 return false;
5760 if (defined('BEHAT_SITE_RUNNING')) {
5761 // Fake email sending in behat.
5762 return true;
5765 if (!empty($CFG->noemailever)) {
5766 // Hidden setting for development sites, set in config.php if needed.
5767 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5768 return true;
5771 if (!empty($CFG->divertallemailsto)) {
5772 $subject = "[DIVERTED {$user->email}] $subject";
5773 $user = clone($user);
5774 $user->email = $CFG->divertallemailsto;
5777 // Skip mail to suspended users.
5778 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5779 return true;
5782 if (!validate_email($user->email)) {
5783 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5784 $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
5785 error_log($invalidemail);
5786 if (CLI_SCRIPT) {
5787 mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
5789 return false;
5792 if (over_bounce_threshold($user)) {
5793 $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
5794 error_log($bouncemsg);
5795 if (CLI_SCRIPT) {
5796 mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
5798 return false;
5801 // If the user is a remote mnet user, parse the email text for URL to the
5802 // wwwroot and modify the url to direct the user's browser to login at their
5803 // home site (identity provider - idp) before hitting the link itself.
5804 if (is_mnet_remote_user($user)) {
5805 require_once($CFG->dirroot.'/mnet/lib.php');
5807 $jumpurl = mnet_get_idp_jump_url($user);
5808 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5810 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5811 $callback,
5812 $messagetext);
5813 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5814 $callback,
5815 $messagehtml);
5817 $mail = get_mailer();
5819 if (!empty($mail->SMTPDebug)) {
5820 echo '<pre>' . "\n";
5823 $temprecipients = array();
5824 $tempreplyto = array();
5826 $supportuser = core_user::get_support_user();
5828 // Make up an email address for handling bounces.
5829 if (!empty($CFG->handlebounces)) {
5830 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5831 $mail->Sender = generate_email_processing_address(0, $modargs);
5832 } else {
5833 $mail->Sender = $supportuser->email;
5836 if (!empty($CFG->emailonlyfromnoreplyaddress)) {
5837 $usetrueaddress = false;
5838 if (empty($replyto) && $from->maildisplay) {
5839 $replyto = $from->email;
5840 $replytoname = fullname($from);
5844 if (is_string($from)) { // So we can pass whatever we want if there is need.
5845 $mail->From = $CFG->noreplyaddress;
5846 $mail->FromName = $from;
5847 } else if ($usetrueaddress and $from->maildisplay) {
5848 $mail->From = $from->email;
5849 $mail->FromName = fullname($from);
5850 } else {
5851 $mail->From = $CFG->noreplyaddress;
5852 $mail->FromName = fullname($from);
5853 if (empty($replyto)) {
5854 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5858 if (!empty($replyto)) {
5859 $tempreplyto[] = array($replyto, $replytoname);
5862 $mail->Subject = substr($subject, 0, 900);
5864 $temprecipients[] = array($user->email, fullname($user));
5866 // Set word wrap.
5867 $mail->WordWrap = $wordwrapwidth;
5869 if (!empty($from->customheaders)) {
5870 // Add custom headers.
5871 if (is_array($from->customheaders)) {
5872 foreach ($from->customheaders as $customheader) {
5873 $mail->addCustomHeader($customheader);
5875 } else {
5876 $mail->addCustomHeader($from->customheaders);
5880 if (!empty($from->priority)) {
5881 $mail->Priority = $from->priority;
5884 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5885 // Don't ever send HTML to users who don't want it.
5886 $mail->isHTML(true);
5887 $mail->Encoding = 'quoted-printable';
5888 $mail->Body = $messagehtml;
5889 $mail->AltBody = "\n$messagetext\n";
5890 } else {
5891 $mail->IsHTML(false);
5892 $mail->Body = "\n$messagetext\n";
5895 if ($attachment && $attachname) {
5896 if (preg_match( "~\\.\\.~" , $attachment )) {
5897 // Security check for ".." in dir path.
5898 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5899 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5900 } else {
5901 require_once($CFG->libdir.'/filelib.php');
5902 $mimetype = mimeinfo('type', $attachname);
5904 $attachmentpath = $attachment;
5906 // If the attachment is a full path to a file in the tempdir, use it as is,
5907 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5908 if (strpos($attachmentpath, $CFG->tempdir) !== 0) {
5909 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5912 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5916 // Check if the email should be sent in an other charset then the default UTF-8.
5917 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5919 // Use the defined site mail charset or eventually the one preferred by the recipient.
5920 $charset = $CFG->sitemailcharset;
5921 if (!empty($CFG->allowusermailcharset)) {
5922 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5923 $charset = $useremailcharset;
5927 // Convert all the necessary strings if the charset is supported.
5928 $charsets = get_list_of_charsets();
5929 unset($charsets['UTF-8']);
5930 if (in_array($charset, $charsets)) {
5931 $mail->CharSet = $charset;
5932 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5933 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5934 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5935 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5937 foreach ($temprecipients as $key => $values) {
5938 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5940 foreach ($tempreplyto as $key => $values) {
5941 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5946 foreach ($temprecipients as $values) {
5947 $mail->addAddress($values[0], $values[1]);
5949 foreach ($tempreplyto as $values) {
5950 $mail->addReplyTo($values[0], $values[1]);
5953 if ($mail->send()) {
5954 set_send_count($user);
5955 if (!empty($mail->SMTPDebug)) {
5956 echo '</pre>';
5958 return true;
5959 } else {
5960 // Trigger event for failing to send email.
5961 $event = \core\event\email_failed::create(array(
5962 'context' => context_system::instance(),
5963 'userid' => $from->id,
5964 'relateduserid' => $user->id,
5965 'other' => array(
5966 'subject' => $subject,
5967 'message' => $messagetext,
5968 'errorinfo' => $mail->ErrorInfo
5971 $event->trigger();
5972 if (CLI_SCRIPT) {
5973 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5975 if (!empty($mail->SMTPDebug)) {
5976 echo '</pre>';
5978 return false;
5983 * Generate a signoff for emails based on support settings
5985 * @return string
5987 function generate_email_signoff() {
5988 global $CFG;
5990 $signoff = "\n";
5991 if (!empty($CFG->supportname)) {
5992 $signoff .= $CFG->supportname."\n";
5994 if (!empty($CFG->supportemail)) {
5995 $signoff .= $CFG->supportemail."\n";
5997 if (!empty($CFG->supportpage)) {
5998 $signoff .= $CFG->supportpage."\n";
6000 return $signoff;
6004 * Sets specified user's password and send the new password to the user via email.
6006 * @param stdClass $user A {@link $USER} object
6007 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6008 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6010 function setnew_password_and_mail($user, $fasthash = false) {
6011 global $CFG, $DB;
6013 // We try to send the mail in language the user understands,
6014 // unfortunately the filter_string() does not support alternative langs yet
6015 // so multilang will not work properly for site->fullname.
6016 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6018 $site = get_site();
6020 $supportuser = core_user::get_support_user();
6022 $newpassword = generate_password();
6024 update_internal_user_password($user, $newpassword, $fasthash);
6026 $a = new stdClass();
6027 $a->firstname = fullname($user, true);
6028 $a->sitename = format_string($site->fullname);
6029 $a->username = $user->username;
6030 $a->newpassword = $newpassword;
6031 $a->link = $CFG->wwwroot .'/login/';
6032 $a->signoff = generate_email_signoff();
6034 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6036 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6038 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6039 return email_to_user($user, $supportuser, $subject, $message);
6044 * Resets specified user's password and send the new password to the user via email.
6046 * @param stdClass $user A {@link $USER} object
6047 * @return bool Returns true if mail was sent OK and false if there was an error.
6049 function reset_password_and_mail($user) {
6050 global $CFG;
6052 $site = get_site();
6053 $supportuser = core_user::get_support_user();
6055 $userauth = get_auth_plugin($user->auth);
6056 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6057 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6058 return false;
6061 $newpassword = generate_password();
6063 if (!$userauth->user_update_password($user, $newpassword)) {
6064 print_error("cannotsetpassword");
6067 $a = new stdClass();
6068 $a->firstname = $user->firstname;
6069 $a->lastname = $user->lastname;
6070 $a->sitename = format_string($site->fullname);
6071 $a->username = $user->username;
6072 $a->newpassword = $newpassword;
6073 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
6074 $a->signoff = generate_email_signoff();
6076 $message = get_string('newpasswordtext', '', $a);
6078 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6080 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6082 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6083 return email_to_user($user, $supportuser, $subject, $message);
6087 * Send email to specified user with confirmation text and activation link.
6089 * @param stdClass $user A {@link $USER} object
6090 * @return bool Returns true if mail was sent OK and false if there was an error.
6092 function send_confirmation_email($user) {
6093 global $CFG;
6095 $site = get_site();
6096 $supportuser = core_user::get_support_user();
6098 $data = new stdClass();
6099 $data->firstname = fullname($user);
6100 $data->sitename = format_string($site->fullname);
6101 $data->admin = generate_email_signoff();
6103 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6105 $username = urlencode($user->username);
6106 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
6107 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
6108 $message = get_string('emailconfirmation', '', $data);
6109 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6111 $user->mailformat = 1; // Always send HTML version as well.
6113 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6114 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6118 * Sends a password change confirmation email.
6120 * @param stdClass $user A {@link $USER} object
6121 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6122 * @return bool Returns true if mail was sent OK and false if there was an error.
6124 function send_password_change_confirmation_email($user, $resetrecord) {
6125 global $CFG;
6127 $site = get_site();
6128 $supportuser = core_user::get_support_user();
6129 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6131 $data = new stdClass();
6132 $data->firstname = $user->firstname;
6133 $data->lastname = $user->lastname;
6134 $data->username = $user->username;
6135 $data->sitename = format_string($site->fullname);
6136 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6137 $data->admin = generate_email_signoff();
6138 $data->resetminutes = $pwresetmins;
6140 $message = get_string('emailresetconfirmation', '', $data);
6141 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6143 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6144 return email_to_user($user, $supportuser, $subject, $message);
6149 * Sends an email containinginformation on how to change your password.
6151 * @param stdClass $user A {@link $USER} object
6152 * @return bool Returns true if mail was sent OK and false if there was an error.
6154 function send_password_change_info($user) {
6155 global $CFG;
6157 $site = get_site();
6158 $supportuser = core_user::get_support_user();
6159 $systemcontext = context_system::instance();
6161 $data = new stdClass();
6162 $data->firstname = $user->firstname;
6163 $data->lastname = $user->lastname;
6164 $data->sitename = format_string($site->fullname);
6165 $data->admin = generate_email_signoff();
6167 $userauth = get_auth_plugin($user->auth);
6169 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6170 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6171 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6172 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6173 return email_to_user($user, $supportuser, $subject, $message);
6176 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6177 // We have some external url for password changing.
6178 $data->link .= $userauth->change_password_url();
6180 } else {
6181 // No way to change password, sorry.
6182 $data->link = '';
6185 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6186 $message = get_string('emailpasswordchangeinfo', '', $data);
6187 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6188 } else {
6189 $message = get_string('emailpasswordchangeinfofail', '', $data);
6190 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6193 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6194 return email_to_user($user, $supportuser, $subject, $message);
6199 * Check that an email is allowed. It returns an error message if there was a problem.
6201 * @param string $email Content of email
6202 * @return string|false
6204 function email_is_not_allowed($email) {
6205 global $CFG;
6207 if (!empty($CFG->allowemailaddresses)) {
6208 $allowed = explode(' ', $CFG->allowemailaddresses);
6209 foreach ($allowed as $allowedpattern) {
6210 $allowedpattern = trim($allowedpattern);
6211 if (!$allowedpattern) {
6212 continue;
6214 if (strpos($allowedpattern, '.') === 0) {
6215 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6216 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6217 return false;
6220 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6221 return false;
6224 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6226 } else if (!empty($CFG->denyemailaddresses)) {
6227 $denied = explode(' ', $CFG->denyemailaddresses);
6228 foreach ($denied as $deniedpattern) {
6229 $deniedpattern = trim($deniedpattern);
6230 if (!$deniedpattern) {
6231 continue;
6233 if (strpos($deniedpattern, '.') === 0) {
6234 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6235 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6236 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6239 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6240 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6245 return false;
6248 // FILE HANDLING.
6251 * Returns local file storage instance
6253 * @return file_storage
6255 function get_file_storage() {
6256 global $CFG;
6258 static $fs = null;
6260 if ($fs) {
6261 return $fs;
6264 require_once("$CFG->libdir/filelib.php");
6266 if (isset($CFG->filedir)) {
6267 $filedir = $CFG->filedir;
6268 } else {
6269 $filedir = $CFG->dataroot.'/filedir';
6272 if (isset($CFG->trashdir)) {
6273 $trashdirdir = $CFG->trashdir;
6274 } else {
6275 $trashdirdir = $CFG->dataroot.'/trashdir';
6278 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6280 return $fs;
6284 * Returns local file storage instance
6286 * @return file_browser
6288 function get_file_browser() {
6289 global $CFG;
6291 static $fb = null;
6293 if ($fb) {
6294 return $fb;
6297 require_once("$CFG->libdir/filelib.php");
6299 $fb = new file_browser();
6301 return $fb;
6305 * Returns file packer
6307 * @param string $mimetype default application/zip
6308 * @return file_packer
6310 function get_file_packer($mimetype='application/zip') {
6311 global $CFG;
6313 static $fp = array();
6315 if (isset($fp[$mimetype])) {
6316 return $fp[$mimetype];
6319 switch ($mimetype) {
6320 case 'application/zip':
6321 case 'application/vnd.moodle.profiling':
6322 $classname = 'zip_packer';
6323 break;
6325 case 'application/x-gzip' :
6326 $classname = 'tgz_packer';
6327 break;
6329 case 'application/vnd.moodle.backup':
6330 $classname = 'mbz_packer';
6331 break;
6333 default:
6334 return false;
6337 require_once("$CFG->libdir/filestorage/$classname.php");
6338 $fp[$mimetype] = new $classname();
6340 return $fp[$mimetype];
6344 * Returns current name of file on disk if it exists.
6346 * @param string $newfile File to be verified
6347 * @return string Current name of file on disk if true
6349 function valid_uploaded_file($newfile) {
6350 if (empty($newfile)) {
6351 return '';
6353 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6354 return $newfile['tmp_name'];
6355 } else {
6356 return '';
6361 * Returns the maximum size for uploading files.
6363 * There are seven possible upload limits:
6364 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6365 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6366 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6367 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6368 * 5. by the Moodle admin in $CFG->maxbytes
6369 * 6. by the teacher in the current course $course->maxbytes
6370 * 7. by the teacher for the current module, eg $assignment->maxbytes
6372 * These last two are passed to this function as arguments (in bytes).
6373 * Anything defined as 0 is ignored.
6374 * The smallest of all the non-zero numbers is returned.
6376 * @todo Finish documenting this function
6378 * @param int $sitebytes Set maximum size
6379 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6380 * @param int $modulebytes Current module ->maxbytes (in bytes)
6381 * @return int The maximum size for uploading files.
6383 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6385 if (! $filesize = ini_get('upload_max_filesize')) {
6386 $filesize = '5M';
6388 $minimumsize = get_real_size($filesize);
6390 if ($postsize = ini_get('post_max_size')) {
6391 $postsize = get_real_size($postsize);
6392 if ($postsize < $minimumsize) {
6393 $minimumsize = $postsize;
6397 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6398 $minimumsize = $sitebytes;
6401 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6402 $minimumsize = $coursebytes;
6405 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6406 $minimumsize = $modulebytes;
6409 return $minimumsize;
6413 * Returns the maximum size for uploading files for the current user
6415 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6417 * @param context $context The context in which to check user capabilities
6418 * @param int $sitebytes Set maximum size
6419 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6420 * @param int $modulebytes Current module ->maxbytes (in bytes)
6421 * @param stdClass $user The user
6422 * @return int The maximum size for uploading files.
6424 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6425 global $USER;
6427 if (empty($user)) {
6428 $user = $USER;
6431 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6432 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6435 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6439 * Returns an array of possible sizes in local language
6441 * Related to {@link get_max_upload_file_size()} - this function returns an
6442 * array of possible sizes in an array, translated to the
6443 * local language.
6445 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6447 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6448 * with the value set to 0. This option will be the first in the list.
6450 * @uses SORT_NUMERIC
6451 * @param int $sitebytes Set maximum size
6452 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6453 * @param int $modulebytes Current module ->maxbytes (in bytes)
6454 * @param int|array $custombytes custom upload size/s which will be added to list,
6455 * Only value/s smaller then maxsize will be added to list.
6456 * @return array
6458 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6459 global $CFG;
6461 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6462 return array();
6465 if ($sitebytes == 0) {
6466 // Will get the minimum of upload_max_filesize or post_max_size.
6467 $sitebytes = get_max_upload_file_size();
6470 $filesize = array();
6471 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6472 5242880, 10485760, 20971520, 52428800, 104857600);
6474 // If custombytes is given and is valid then add it to the list.
6475 if (is_number($custombytes) and $custombytes > 0) {
6476 $custombytes = (int)$custombytes;
6477 if (!in_array($custombytes, $sizelist)) {
6478 $sizelist[] = $custombytes;
6480 } else if (is_array($custombytes)) {
6481 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6484 // Allow maxbytes to be selected if it falls outside the above boundaries.
6485 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6486 // Note: get_real_size() is used in order to prevent problems with invalid values.
6487 $sizelist[] = get_real_size($CFG->maxbytes);
6490 foreach ($sizelist as $sizebytes) {
6491 if ($sizebytes < $maxsize && $sizebytes > 0) {
6492 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6496 $limitlevel = '';
6497 $displaysize = '';
6498 if ($modulebytes &&
6499 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6500 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6501 $limitlevel = get_string('activity', 'core');
6502 $displaysize = display_size($modulebytes);
6503 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6505 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6506 $limitlevel = get_string('course', 'core');
6507 $displaysize = display_size($coursebytes);
6508 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6510 } else if ($sitebytes) {
6511 $limitlevel = get_string('site', 'core');
6512 $displaysize = display_size($sitebytes);
6513 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6516 krsort($filesize, SORT_NUMERIC);
6517 if ($limitlevel) {
6518 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6519 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6522 return $filesize;
6526 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6528 * If excludefiles is defined, then that file/directory is ignored
6529 * If getdirs is true, then (sub)directories are included in the output
6530 * If getfiles is true, then files are included in the output
6531 * (at least one of these must be true!)
6533 * @todo Finish documenting this function. Add examples of $excludefile usage.
6535 * @param string $rootdir A given root directory to start from
6536 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6537 * @param bool $descend If true then subdirectories are recursed as well
6538 * @param bool $getdirs If true then (sub)directories are included in the output
6539 * @param bool $getfiles If true then files are included in the output
6540 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6542 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6544 $dirs = array();
6546 if (!$getdirs and !$getfiles) { // Nothing to show.
6547 return $dirs;
6550 if (!is_dir($rootdir)) { // Must be a directory.
6551 return $dirs;
6554 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6555 return $dirs;
6558 if (!is_array($excludefiles)) {
6559 $excludefiles = array($excludefiles);
6562 while (false !== ($file = readdir($dir))) {
6563 $firstchar = substr($file, 0, 1);
6564 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6565 continue;
6567 $fullfile = $rootdir .'/'. $file;
6568 if (filetype($fullfile) == 'dir') {
6569 if ($getdirs) {
6570 $dirs[] = $file;
6572 if ($descend) {
6573 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6574 foreach ($subdirs as $subdir) {
6575 $dirs[] = $file .'/'. $subdir;
6578 } else if ($getfiles) {
6579 $dirs[] = $file;
6582 closedir($dir);
6584 asort($dirs);
6586 return $dirs;
6591 * Adds up all the files in a directory and works out the size.
6593 * @param string $rootdir The directory to start from
6594 * @param string $excludefile A file to exclude when summing directory size
6595 * @return int The summed size of all files and subfiles within the root directory
6597 function get_directory_size($rootdir, $excludefile='') {
6598 global $CFG;
6600 // Do it this way if we can, it's much faster.
6601 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6602 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6603 $output = null;
6604 $return = null;
6605 exec($command, $output, $return);
6606 if (is_array($output)) {
6607 // We told it to return k.
6608 return get_real_size(intval($output[0]).'k');
6612 if (!is_dir($rootdir)) {
6613 // Must be a directory.
6614 return 0;
6617 if (!$dir = @opendir($rootdir)) {
6618 // Can't open it for some reason.
6619 return 0;
6622 $size = 0;
6624 while (false !== ($file = readdir($dir))) {
6625 $firstchar = substr($file, 0, 1);
6626 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6627 continue;
6629 $fullfile = $rootdir .'/'. $file;
6630 if (filetype($fullfile) == 'dir') {
6631 $size += get_directory_size($fullfile, $excludefile);
6632 } else {
6633 $size += filesize($fullfile);
6636 closedir($dir);
6638 return $size;
6642 * Converts bytes into display form
6644 * @static string $gb Localized string for size in gigabytes
6645 * @static string $mb Localized string for size in megabytes
6646 * @static string $kb Localized string for size in kilobytes
6647 * @static string $b Localized string for size in bytes
6648 * @param int $size The size to convert to human readable form
6649 * @return string
6651 function display_size($size) {
6653 static $gb, $mb, $kb, $b;
6655 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6656 return get_string('unlimited');
6659 if (empty($gb)) {
6660 $gb = get_string('sizegb');
6661 $mb = get_string('sizemb');
6662 $kb = get_string('sizekb');
6663 $b = get_string('sizeb');
6666 if ($size >= 1073741824) {
6667 $size = round($size / 1073741824 * 10) / 10 . $gb;
6668 } else if ($size >= 1048576) {
6669 $size = round($size / 1048576 * 10) / 10 . $mb;
6670 } else if ($size >= 1024) {
6671 $size = round($size / 1024 * 10) / 10 . $kb;
6672 } else {
6673 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6675 return $size;
6679 * Cleans a given filename by removing suspicious or troublesome characters
6681 * @see clean_param()
6682 * @param string $string file name
6683 * @return string cleaned file name
6685 function clean_filename($string) {
6686 return clean_param($string, PARAM_FILE);
6690 // STRING TRANSLATION.
6693 * Returns the code for the current language
6695 * @category string
6696 * @return string
6698 function current_language() {
6699 global $CFG, $USER, $SESSION, $COURSE;
6701 if (!empty($SESSION->forcelang)) {
6702 // Allows overriding course-forced language (useful for admins to check
6703 // issues in courses whose language they don't understand).
6704 // Also used by some code to temporarily get language-related information in a
6705 // specific language (see force_current_language()).
6706 $return = $SESSION->forcelang;
6708 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6709 // Course language can override all other settings for this page.
6710 $return = $COURSE->lang;
6712 } else if (!empty($SESSION->lang)) {
6713 // Session language can override other settings.
6714 $return = $SESSION->lang;
6716 } else if (!empty($USER->lang)) {
6717 $return = $USER->lang;
6719 } else if (isset($CFG->lang)) {
6720 $return = $CFG->lang;
6722 } else {
6723 $return = 'en';
6726 // Just in case this slipped in from somewhere by accident.
6727 $return = str_replace('_utf8', '', $return);
6729 return $return;
6733 * Returns parent language of current active language if defined
6735 * @category string
6736 * @param string $lang null means current language
6737 * @return string
6739 function get_parent_language($lang=null) {
6741 // Let's hack around the current language.
6742 if (!empty($lang)) {
6743 $oldforcelang = force_current_language($lang);
6746 $parentlang = get_string('parentlanguage', 'langconfig');
6747 if ($parentlang === 'en') {
6748 $parentlang = '';
6751 // Let's hack around the current language.
6752 if (!empty($lang)) {
6753 force_current_language($oldforcelang);
6756 return $parentlang;
6760 * Force the current language to get strings and dates localised in the given language.
6762 * After calling this function, all strings will be provided in the given language
6763 * until this function is called again, or equivalent code is run.
6765 * @param string $language
6766 * @return string previous $SESSION->forcelang value
6768 function force_current_language($language) {
6769 global $SESSION;
6770 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6771 if ($language !== $sessionforcelang) {
6772 // Seting forcelang to null or an empty string disables it's effect.
6773 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6774 $SESSION->forcelang = $language;
6775 moodle_setlocale();
6778 return $sessionforcelang;
6782 * Returns current string_manager instance.
6784 * The param $forcereload is needed for CLI installer only where the string_manager instance
6785 * must be replaced during the install.php script life time.
6787 * @category string
6788 * @param bool $forcereload shall the singleton be released and new instance created instead?
6789 * @return core_string_manager
6791 function get_string_manager($forcereload=false) {
6792 global $CFG;
6794 static $singleton = null;
6796 if ($forcereload) {
6797 $singleton = null;
6799 if ($singleton === null) {
6800 if (empty($CFG->early_install_lang)) {
6802 if (empty($CFG->langlist)) {
6803 $translist = array();
6804 } else {
6805 $translist = explode(',', $CFG->langlist);
6808 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6810 } else {
6811 $singleton = new core_string_manager_install();
6815 return $singleton;
6819 * Returns a localized string.
6821 * Returns the translated string specified by $identifier as
6822 * for $module. Uses the same format files as STphp.
6823 * $a is an object, string or number that can be used
6824 * within translation strings
6826 * eg 'hello {$a->firstname} {$a->lastname}'
6827 * or 'hello {$a}'
6829 * If you would like to directly echo the localized string use
6830 * the function {@link print_string()}
6832 * Example usage of this function involves finding the string you would
6833 * like a local equivalent of and using its identifier and module information
6834 * to retrieve it.<br/>
6835 * If you open moodle/lang/en/moodle.php and look near line 278
6836 * you will find a string to prompt a user for their word for 'course'
6837 * <code>
6838 * $string['course'] = 'Course';
6839 * </code>
6840 * So if you want to display the string 'Course'
6841 * in any language that supports it on your site
6842 * you just need to use the identifier 'course'
6843 * <code>
6844 * $mystring = '<strong>'. get_string('course') .'</strong>';
6845 * or
6846 * </code>
6847 * If the string you want is in another file you'd take a slightly
6848 * different approach. Looking in moodle/lang/en/calendar.php you find
6849 * around line 75:
6850 * <code>
6851 * $string['typecourse'] = 'Course event';
6852 * </code>
6853 * If you want to display the string "Course event" in any language
6854 * supported you would use the identifier 'typecourse' and the module 'calendar'
6855 * (because it is in the file calendar.php):
6856 * <code>
6857 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6858 * </code>
6860 * As a last resort, should the identifier fail to map to a string
6861 * the returned string will be [[ $identifier ]]
6863 * In Moodle 2.3 there is a new argument to this function $lazyload.
6864 * Setting $lazyload to true causes get_string to return a lang_string object
6865 * rather than the string itself. The fetching of the string is then put off until
6866 * the string object is first used. The object can be used by calling it's out
6867 * method or by casting the object to a string, either directly e.g.
6868 * (string)$stringobject
6869 * or indirectly by using the string within another string or echoing it out e.g.
6870 * echo $stringobject
6871 * return "<p>{$stringobject}</p>";
6872 * It is worth noting that using $lazyload and attempting to use the string as an
6873 * array key will cause a fatal error as objects cannot be used as array keys.
6874 * But you should never do that anyway!
6875 * For more information {@link lang_string}
6877 * @category string
6878 * @param string $identifier The key identifier for the localized string
6879 * @param string $component The module where the key identifier is stored,
6880 * usually expressed as the filename in the language pack without the
6881 * .php on the end but can also be written as mod/forum or grade/export/xls.
6882 * If none is specified then moodle.php is used.
6883 * @param string|object|array $a An object, string or number that can be used
6884 * within translation strings
6885 * @param bool $lazyload If set to true a string object is returned instead of
6886 * the string itself. The string then isn't calculated until it is first used.
6887 * @return string The localized string.
6888 * @throws coding_exception
6890 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6891 global $CFG;
6893 // If the lazy load argument has been supplied return a lang_string object
6894 // instead.
6895 // We need to make sure it is true (and a bool) as you will see below there
6896 // used to be a forth argument at one point.
6897 if ($lazyload === true) {
6898 return new lang_string($identifier, $component, $a);
6901 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6902 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6905 // There is now a forth argument again, this time it is a boolean however so
6906 // we can still check for the old extralocations parameter.
6907 if (!is_bool($lazyload) && !empty($lazyload)) {
6908 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6911 if (strpos($component, '/') !== false) {
6912 debugging('The module name you passed to get_string is the deprecated format ' .
6913 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6914 $componentpath = explode('/', $component);
6916 switch ($componentpath[0]) {
6917 case 'mod':
6918 $component = $componentpath[1];
6919 break;
6920 case 'blocks':
6921 case 'block':
6922 $component = 'block_'.$componentpath[1];
6923 break;
6924 case 'enrol':
6925 $component = 'enrol_'.$componentpath[1];
6926 break;
6927 case 'format':
6928 $component = 'format_'.$componentpath[1];
6929 break;
6930 case 'grade':
6931 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6932 break;
6936 $result = get_string_manager()->get_string($identifier, $component, $a);
6938 // Debugging feature lets you display string identifier and component.
6939 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6940 $result .= ' {' . $identifier . '/' . $component . '}';
6942 return $result;
6946 * Converts an array of strings to their localized value.
6948 * @param array $array An array of strings
6949 * @param string $component The language module that these strings can be found in.
6950 * @return stdClass translated strings.
6952 function get_strings($array, $component = '') {
6953 $string = new stdClass;
6954 foreach ($array as $item) {
6955 $string->$item = get_string($item, $component);
6957 return $string;
6961 * Prints out a translated string.
6963 * Prints out a translated string using the return value from the {@link get_string()} function.
6965 * Example usage of this function when the string is in the moodle.php file:<br/>
6966 * <code>
6967 * echo '<strong>';
6968 * print_string('course');
6969 * echo '</strong>';
6970 * </code>
6972 * Example usage of this function when the string is not in the moodle.php file:<br/>
6973 * <code>
6974 * echo '<h1>';
6975 * print_string('typecourse', 'calendar');
6976 * echo '</h1>';
6977 * </code>
6979 * @category string
6980 * @param string $identifier The key identifier for the localized string
6981 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6982 * @param string|object|array $a An object, string or number that can be used within translation strings
6984 function print_string($identifier, $component = '', $a = null) {
6985 echo get_string($identifier, $component, $a);
6989 * Returns a list of charset codes
6991 * Returns a list of charset codes. It's hardcoded, so they should be added manually
6992 * (checking that such charset is supported by the texlib library!)
6994 * @return array And associative array with contents in the form of charset => charset
6996 function get_list_of_charsets() {
6998 $charsets = array(
6999 'EUC-JP' => 'EUC-JP',
7000 'ISO-2022-JP'=> 'ISO-2022-JP',
7001 'ISO-8859-1' => 'ISO-8859-1',
7002 'SHIFT-JIS' => 'SHIFT-JIS',
7003 'GB2312' => 'GB2312',
7004 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7005 'UTF-8' => 'UTF-8');
7007 asort($charsets);
7009 return $charsets;
7013 * Returns a list of valid and compatible themes
7015 * @return array
7017 function get_list_of_themes() {
7018 global $CFG;
7020 $themes = array();
7022 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7023 $themelist = explode(',', $CFG->themelist);
7024 } else {
7025 $themelist = array_keys(core_component::get_plugin_list("theme"));
7028 foreach ($themelist as $key => $themename) {
7029 $theme = theme_config::load($themename);
7030 $themes[$themename] = $theme;
7033 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7035 return $themes;
7039 * Returns a list of timezones in the current language
7041 * @return array
7043 function get_list_of_timezones() {
7044 global $DB;
7046 static $timezones;
7048 if (!empty($timezones)) { // This function has been called recently.
7049 return $timezones;
7052 $timezones = array();
7054 if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
7055 foreach ($rawtimezones as $timezone) {
7056 if (!empty($timezone->name)) {
7057 if (get_string_manager()->string_exists(strtolower($timezone->name), 'timezones')) {
7058 $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
7059 } else {
7060 $timezones[$timezone->name] = $timezone->name;
7062 if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found.
7063 $timezones[$timezone->name] = $timezone->name;
7069 asort($timezones);
7071 for ($i = -13; $i <= 13; $i += .5) {
7072 $tzstring = 'UTC';
7073 if ($i < 0) {
7074 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
7075 } else if ($i > 0) {
7076 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
7077 } else {
7078 $timezones[sprintf("%.1f", $i)] = $tzstring;
7082 return $timezones;
7086 * Factory function for emoticon_manager
7088 * @return emoticon_manager singleton
7090 function get_emoticon_manager() {
7091 static $singleton = null;
7093 if (is_null($singleton)) {
7094 $singleton = new emoticon_manager();
7097 return $singleton;
7101 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7103 * Whenever this manager mentiones 'emoticon object', the following data
7104 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7105 * altidentifier and altcomponent
7107 * @see admin_setting_emoticons
7109 * @copyright 2010 David Mudrak
7110 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7112 class emoticon_manager {
7115 * Returns the currently enabled emoticons
7117 * @return array of emoticon objects
7119 public function get_emoticons() {
7120 global $CFG;
7122 if (empty($CFG->emoticons)) {
7123 return array();
7126 $emoticons = $this->decode_stored_config($CFG->emoticons);
7128 if (!is_array($emoticons)) {
7129 // Something is wrong with the format of stored setting.
7130 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7131 return array();
7134 return $emoticons;
7138 * Converts emoticon object into renderable pix_emoticon object
7140 * @param stdClass $emoticon emoticon object
7141 * @param array $attributes explicit HTML attributes to set
7142 * @return pix_emoticon
7144 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7145 $stringmanager = get_string_manager();
7146 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7147 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7148 } else {
7149 $alt = s($emoticon->text);
7151 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7155 * Encodes the array of emoticon objects into a string storable in config table
7157 * @see self::decode_stored_config()
7158 * @param array $emoticons array of emtocion objects
7159 * @return string
7161 public function encode_stored_config(array $emoticons) {
7162 return json_encode($emoticons);
7166 * Decodes the string into an array of emoticon objects
7168 * @see self::encode_stored_config()
7169 * @param string $encoded
7170 * @return string|null
7172 public function decode_stored_config($encoded) {
7173 $decoded = json_decode($encoded);
7174 if (!is_array($decoded)) {
7175 return null;
7177 return $decoded;
7181 * Returns default set of emoticons supported by Moodle
7183 * @return array of sdtClasses
7185 public function default_emoticons() {
7186 return array(
7187 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7188 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7189 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7190 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7191 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7192 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7193 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7194 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7195 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7196 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7197 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7198 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7199 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7200 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7201 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7202 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7203 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7204 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7205 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7206 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7207 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7208 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7209 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7210 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7211 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7212 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7213 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7214 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7215 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7216 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7221 * Helper method preparing the stdClass with the emoticon properties
7223 * @param string|array $text or array of strings
7224 * @param string $imagename to be used by {@link pix_emoticon}
7225 * @param string $altidentifier alternative string identifier, null for no alt
7226 * @param string $altcomponent where the alternative string is defined
7227 * @param string $imagecomponent to be used by {@link pix_emoticon}
7228 * @return stdClass
7230 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7231 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7232 return (object)array(
7233 'text' => $text,
7234 'imagename' => $imagename,
7235 'imagecomponent' => $imagecomponent,
7236 'altidentifier' => $altidentifier,
7237 'altcomponent' => $altcomponent,
7242 // ENCRYPTION.
7245 * rc4encrypt
7247 * @param string $data Data to encrypt.
7248 * @return string The now encrypted data.
7250 function rc4encrypt($data) {
7251 return endecrypt(get_site_identifier(), $data, '');
7255 * rc4decrypt
7257 * @param string $data Data to decrypt.
7258 * @return string The now decrypted data.
7260 function rc4decrypt($data) {
7261 return endecrypt(get_site_identifier(), $data, 'de');
7265 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7267 * @todo Finish documenting this function
7269 * @param string $pwd The password to use when encrypting or decrypting
7270 * @param string $data The data to be decrypted/encrypted
7271 * @param string $case Either 'de' for decrypt or '' for encrypt
7272 * @return string
7274 function endecrypt ($pwd, $data, $case) {
7276 if ($case == 'de') {
7277 $data = urldecode($data);
7280 $key[] = '';
7281 $box[] = '';
7282 $pwdlength = strlen($pwd);
7284 for ($i = 0; $i <= 255; $i++) {
7285 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7286 $box[$i] = $i;
7289 $x = 0;
7291 for ($i = 0; $i <= 255; $i++) {
7292 $x = ($x + $box[$i] + $key[$i]) % 256;
7293 $tempswap = $box[$i];
7294 $box[$i] = $box[$x];
7295 $box[$x] = $tempswap;
7298 $cipher = '';
7300 $a = 0;
7301 $j = 0;
7303 for ($i = 0; $i < strlen($data); $i++) {
7304 $a = ($a + 1) % 256;
7305 $j = ($j + $box[$a]) % 256;
7306 $temp = $box[$a];
7307 $box[$a] = $box[$j];
7308 $box[$j] = $temp;
7309 $k = $box[(($box[$a] + $box[$j]) % 256)];
7310 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7311 $cipher .= chr($cipherby);
7314 if ($case == 'de') {
7315 $cipher = urldecode(urlencode($cipher));
7316 } else {
7317 $cipher = urlencode($cipher);
7320 return $cipher;
7323 // ENVIRONMENT CHECKING.
7326 * This method validates a plug name. It is much faster than calling clean_param.
7328 * @param string $name a string that might be a plugin name.
7329 * @return bool if this string is a valid plugin name.
7331 function is_valid_plugin_name($name) {
7332 // This does not work for 'mod', bad luck, use any other type.
7333 return core_component::is_valid_plugin_name('tool', $name);
7337 * Get a list of all the plugins of a given type that define a certain API function
7338 * in a certain file. The plugin component names and function names are returned.
7340 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7341 * @param string $function the part of the name of the function after the
7342 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7343 * names like report_courselist_hook.
7344 * @param string $file the name of file within the plugin that defines the
7345 * function. Defaults to lib.php.
7346 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7347 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7349 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7350 $pluginfunctions = array();
7351 $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, $file, true);
7352 foreach ($pluginswithfile as $plugin => $notused) {
7353 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7355 if (function_exists($fullfunction)) {
7356 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7357 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
7359 } else if ($plugintype === 'mod') {
7360 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7361 $shortfunction = $plugin . '_' . $function;
7362 if (function_exists($shortfunction)) {
7363 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
7367 return $pluginfunctions;
7371 * Lists plugin-like directories within specified directory
7373 * This function was originally used for standard Moodle plugins, please use
7374 * new core_component::get_plugin_list() now.
7376 * This function is used for general directory listing and backwards compatility.
7378 * @param string $directory relative directory from root
7379 * @param string $exclude dir name to exclude from the list (defaults to none)
7380 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7381 * @return array Sorted array of directory names found under the requested parameters
7383 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7384 global $CFG;
7386 $plugins = array();
7388 if (empty($basedir)) {
7389 $basedir = $CFG->dirroot .'/'. $directory;
7391 } else {
7392 $basedir = $basedir .'/'. $directory;
7395 if ($CFG->debugdeveloper and empty($exclude)) {
7396 // Make sure devs do not use this to list normal plugins,
7397 // this is intended for general directories that are not plugins!
7399 $subtypes = core_component::get_plugin_types();
7400 if (in_array($basedir, $subtypes)) {
7401 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7403 unset($subtypes);
7406 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7407 if (!$dirhandle = opendir($basedir)) {
7408 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7409 return array();
7411 while (false !== ($dir = readdir($dirhandle))) {
7412 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7413 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7414 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7415 continue;
7417 if (filetype($basedir .'/'. $dir) != 'dir') {
7418 continue;
7420 $plugins[] = $dir;
7422 closedir($dirhandle);
7424 if ($plugins) {
7425 asort($plugins);
7427 return $plugins;
7431 * Invoke plugin's callback functions
7433 * @param string $type plugin type e.g. 'mod'
7434 * @param string $name plugin name
7435 * @param string $feature feature name
7436 * @param string $action feature's action
7437 * @param array $params parameters of callback function, should be an array
7438 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7439 * @return mixed
7441 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7443 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7444 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7448 * Invoke component's callback functions
7450 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7451 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7452 * @param array $params parameters of callback function
7453 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7454 * @return mixed
7456 function component_callback($component, $function, array $params = array(), $default = null) {
7458 $functionname = component_callback_exists($component, $function);
7460 if ($functionname) {
7461 // Function exists, so just return function result.
7462 $ret = call_user_func_array($functionname, $params);
7463 if (is_null($ret)) {
7464 return $default;
7465 } else {
7466 return $ret;
7469 return $default;
7473 * Determine if a component callback exists and return the function name to call. Note that this
7474 * function will include the required library files so that the functioname returned can be
7475 * called directly.
7477 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7478 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7479 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7480 * @throws coding_exception if invalid component specfied
7482 function component_callback_exists($component, $function) {
7483 global $CFG; // This is needed for the inclusions.
7485 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7486 if (empty($cleancomponent)) {
7487 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7489 $component = $cleancomponent;
7491 list($type, $name) = core_component::normalize_component($component);
7492 $component = $type . '_' . $name;
7494 $oldfunction = $name.'_'.$function;
7495 $function = $component.'_'.$function;
7497 $dir = core_component::get_component_directory($component);
7498 if (empty($dir)) {
7499 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7502 // Load library and look for function.
7503 if (file_exists($dir.'/lib.php')) {
7504 require_once($dir.'/lib.php');
7507 if (!function_exists($function) and function_exists($oldfunction)) {
7508 if ($type !== 'mod' and $type !== 'core') {
7509 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7511 $function = $oldfunction;
7514 if (function_exists($function)) {
7515 return $function;
7517 return false;
7521 * Checks whether a plugin supports a specified feature.
7523 * @param string $type Plugin type e.g. 'mod'
7524 * @param string $name Plugin name e.g. 'forum'
7525 * @param string $feature Feature code (FEATURE_xx constant)
7526 * @param mixed $default default value if feature support unknown
7527 * @return mixed Feature result (false if not supported, null if feature is unknown,
7528 * otherwise usually true but may have other feature-specific value such as array)
7529 * @throws coding_exception
7531 function plugin_supports($type, $name, $feature, $default = null) {
7532 global $CFG;
7534 if ($type === 'mod' and $name === 'NEWMODULE') {
7535 // Somebody forgot to rename the module template.
7536 return false;
7539 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7540 if (empty($component)) {
7541 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7544 $function = null;
7546 if ($type === 'mod') {
7547 // We need this special case because we support subplugins in modules,
7548 // otherwise it would end up in infinite loop.
7549 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7550 include_once("$CFG->dirroot/mod/$name/lib.php");
7551 $function = $component.'_supports';
7552 if (!function_exists($function)) {
7553 // Legacy non-frankenstyle function name.
7554 $function = $name.'_supports';
7558 } else {
7559 if (!$path = core_component::get_plugin_directory($type, $name)) {
7560 // Non existent plugin type.
7561 return false;
7563 if (file_exists("$path/lib.php")) {
7564 include_once("$path/lib.php");
7565 $function = $component.'_supports';
7569 if ($function and function_exists($function)) {
7570 $supports = $function($feature);
7571 if (is_null($supports)) {
7572 // Plugin does not know - use default.
7573 return $default;
7574 } else {
7575 return $supports;
7579 // Plugin does not care, so use default.
7580 return $default;
7584 * Returns true if the current version of PHP is greater that the specified one.
7586 * @todo Check PHP version being required here is it too low?
7588 * @param string $version The version of php being tested.
7589 * @return bool
7591 function check_php_version($version='5.2.4') {
7592 return (version_compare(phpversion(), $version) >= 0);
7596 * Determine if moodle installation requires update.
7598 * Checks version numbers of main code and all plugins to see
7599 * if there are any mismatches.
7601 * @return bool
7603 function moodle_needs_upgrading() {
7604 global $CFG;
7606 if (empty($CFG->version)) {
7607 return true;
7610 // There is no need to purge plugininfo caches here because
7611 // these caches are not used during upgrade and they are purged after
7612 // every upgrade.
7614 if (empty($CFG->allversionshash)) {
7615 return true;
7618 $hash = core_component::get_all_versions_hash();
7620 return ($hash !== $CFG->allversionshash);
7624 * Returns the major version of this site
7626 * Moodle version numbers consist of three numbers separated by a dot, for
7627 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7628 * called major version. This function extracts the major version from either
7629 * $CFG->release (default) or eventually from the $release variable defined in
7630 * the main version.php.
7632 * @param bool $fromdisk should the version if source code files be used
7633 * @return string|false the major version like '2.3', false if could not be determined
7635 function moodle_major_version($fromdisk = false) {
7636 global $CFG;
7638 if ($fromdisk) {
7639 $release = null;
7640 require($CFG->dirroot.'/version.php');
7641 if (empty($release)) {
7642 return false;
7645 } else {
7646 if (empty($CFG->release)) {
7647 return false;
7649 $release = $CFG->release;
7652 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7653 return $matches[0];
7654 } else {
7655 return false;
7659 // MISCELLANEOUS.
7662 * Sets the system locale
7664 * @category string
7665 * @param string $locale Can be used to force a locale
7667 function moodle_setlocale($locale='') {
7668 global $CFG;
7670 static $currentlocale = ''; // Last locale caching.
7672 $oldlocale = $currentlocale;
7674 // Fetch the correct locale based on ostype.
7675 if ($CFG->ostype == 'WINDOWS') {
7676 $stringtofetch = 'localewin';
7677 } else {
7678 $stringtofetch = 'locale';
7681 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7682 if (!empty($locale)) {
7683 $currentlocale = $locale;
7684 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7685 $currentlocale = $CFG->locale;
7686 } else {
7687 $currentlocale = get_string($stringtofetch, 'langconfig');
7690 // Do nothing if locale already set up.
7691 if ($oldlocale == $currentlocale) {
7692 return;
7695 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7696 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7697 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7699 // Get current values.
7700 $monetary= setlocale (LC_MONETARY, 0);
7701 $numeric = setlocale (LC_NUMERIC, 0);
7702 $ctype = setlocale (LC_CTYPE, 0);
7703 if ($CFG->ostype != 'WINDOWS') {
7704 $messages= setlocale (LC_MESSAGES, 0);
7706 // Set locale to all.
7707 $result = setlocale (LC_ALL, $currentlocale);
7708 // If setting of locale fails try the other utf8 or utf-8 variant,
7709 // some operating systems support both (Debian), others just one (OSX).
7710 if ($result === false) {
7711 if (stripos($currentlocale, '.UTF-8') !== false) {
7712 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7713 setlocale (LC_ALL, $newlocale);
7714 } else if (stripos($currentlocale, '.UTF8') !== false) {
7715 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7716 setlocale (LC_ALL, $newlocale);
7719 // Set old values.
7720 setlocale (LC_MONETARY, $monetary);
7721 setlocale (LC_NUMERIC, $numeric);
7722 if ($CFG->ostype != 'WINDOWS') {
7723 setlocale (LC_MESSAGES, $messages);
7725 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7726 // To workaround a well-known PHP problem with Turkish letter Ii.
7727 setlocale (LC_CTYPE, $ctype);
7732 * Count words in a string.
7734 * Words are defined as things between whitespace.
7736 * @category string
7737 * @param string $string The text to be searched for words.
7738 * @return int The count of words in the specified string
7740 function count_words($string) {
7741 $string = strip_tags($string);
7742 // Decode HTML entities.
7743 $string = html_entity_decode($string);
7744 // Replace underscores (which are classed as word characters) with spaces.
7745 $string = preg_replace('/_/u', ' ', $string);
7746 // Remove any characters that shouldn't be treated as word boundaries.
7747 $string = preg_replace('/[\'’-]/u', '', $string);
7748 // Remove dots and commas from within numbers only.
7749 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7751 return count(preg_split('/\w\b/u', $string)) - 1;
7755 * Count letters in a string.
7757 * Letters are defined as chars not in tags and different from whitespace.
7759 * @category string
7760 * @param string $string The text to be searched for letters.
7761 * @return int The count of letters in the specified text.
7763 function count_letters($string) {
7764 $string = strip_tags($string); // Tags are out now.
7765 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7767 return core_text::strlen($string);
7771 * Generate and return a random string of the specified length.
7773 * @param int $length The length of the string to be created.
7774 * @return string
7776 function random_string ($length=15) {
7777 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7778 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7779 $pool .= '0123456789';
7780 $poollen = strlen($pool);
7781 $string = '';
7782 for ($i = 0; $i < $length; $i++) {
7783 $string .= substr($pool, (mt_rand()%($poollen)), 1);
7785 return $string;
7789 * Generate a complex random string (useful for md5 salts)
7791 * This function is based on the above {@link random_string()} however it uses a
7792 * larger pool of characters and generates a string between 24 and 32 characters
7794 * @param int $length Optional if set generates a string to exactly this length
7795 * @return string
7797 function complex_random_string($length=null) {
7798 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7799 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7800 $poollen = strlen($pool);
7801 if ($length===null) {
7802 $length = floor(rand(24, 32));
7804 $string = '';
7805 for ($i = 0; $i < $length; $i++) {
7806 $string .= $pool[(mt_rand()%$poollen)];
7808 return $string;
7812 * Given some text (which may contain HTML) and an ideal length,
7813 * this function truncates the text neatly on a word boundary if possible
7815 * @category string
7816 * @param string $text text to be shortened
7817 * @param int $ideal ideal string length
7818 * @param boolean $exact if false, $text will not be cut mid-word
7819 * @param string $ending The string to append if the passed string is truncated
7820 * @return string $truncate shortened string
7822 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7823 // If the plain text is shorter than the maximum length, return the whole text.
7824 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7825 return $text;
7828 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7829 // and only tag in its 'line'.
7830 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7832 $totallength = core_text::strlen($ending);
7833 $truncate = '';
7835 // This array stores information about open and close tags and their position
7836 // in the truncated string. Each item in the array is an object with fields
7837 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7838 // (byte position in truncated text).
7839 $tagdetails = array();
7841 foreach ($lines as $linematchings) {
7842 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7843 if (!empty($linematchings[1])) {
7844 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7845 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7846 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7847 // Record closing tag.
7848 $tagdetails[] = (object) array(
7849 'open' => false,
7850 'tag' => core_text::strtolower($tagmatchings[1]),
7851 'pos' => core_text::strlen($truncate),
7854 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7855 // Record opening tag.
7856 $tagdetails[] = (object) array(
7857 'open' => true,
7858 'tag' => core_text::strtolower($tagmatchings[1]),
7859 'pos' => core_text::strlen($truncate),
7863 // Add html-tag to $truncate'd text.
7864 $truncate .= $linematchings[1];
7867 // Calculate the length of the plain text part of the line; handle entities as one character.
7868 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7869 if ($totallength + $contentlength > $ideal) {
7870 // The number of characters which are left.
7871 $left = $ideal - $totallength;
7872 $entitieslength = 0;
7873 // Search for html entities.
7874 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)) {
7875 // Calculate the real length of all entities in the legal range.
7876 foreach ($entities[0] as $entity) {
7877 if ($entity[1]+1-$entitieslength <= $left) {
7878 $left--;
7879 $entitieslength += core_text::strlen($entity[0]);
7880 } else {
7881 // No more characters left.
7882 break;
7886 $breakpos = $left + $entitieslength;
7888 // If the words shouldn't be cut in the middle...
7889 if (!$exact) {
7890 // Search the last occurence of a space.
7891 for (; $breakpos > 0; $breakpos--) {
7892 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
7893 if ($char === '.' or $char === ' ') {
7894 $breakpos += 1;
7895 break;
7896 } else if (strlen($char) > 2) {
7897 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7898 $breakpos += 1;
7899 break;
7904 if ($breakpos == 0) {
7905 // This deals with the test_shorten_text_no_spaces case.
7906 $breakpos = $left + $entitieslength;
7907 } else if ($breakpos > $left + $entitieslength) {
7908 // This deals with the previous for loop breaking on the first char.
7909 $breakpos = $left + $entitieslength;
7912 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
7913 // Maximum length is reached, so get off the loop.
7914 break;
7915 } else {
7916 $truncate .= $linematchings[2];
7917 $totallength += $contentlength;
7920 // If the maximum length is reached, get off the loop.
7921 if ($totallength >= $ideal) {
7922 break;
7926 // Add the defined ending to the text.
7927 $truncate .= $ending;
7929 // Now calculate the list of open html tags based on the truncate position.
7930 $opentags = array();
7931 foreach ($tagdetails as $taginfo) {
7932 if ($taginfo->open) {
7933 // Add tag to the beginning of $opentags list.
7934 array_unshift($opentags, $taginfo->tag);
7935 } else {
7936 // Can have multiple exact same open tags, close the last one.
7937 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
7938 if ($pos !== false) {
7939 unset($opentags[$pos]);
7944 // Close all unclosed html-tags.
7945 foreach ($opentags as $tag) {
7946 $truncate .= '</' . $tag . '>';
7949 return $truncate;
7954 * Given dates in seconds, how many weeks is the date from startdate
7955 * The first week is 1, the second 2 etc ...
7957 * @param int $startdate Timestamp for the start date
7958 * @param int $thedate Timestamp for the end date
7959 * @return string
7961 function getweek ($startdate, $thedate) {
7962 if ($thedate < $startdate) {
7963 return 0;
7966 return floor(($thedate - $startdate) / WEEKSECS) + 1;
7970 * Returns a randomly generated password of length $maxlen. inspired by
7972 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
7973 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
7975 * @param int $maxlen The maximum size of the password being generated.
7976 * @return string
7978 function generate_password($maxlen=10) {
7979 global $CFG;
7981 if (empty($CFG->passwordpolicy)) {
7982 $fillers = PASSWORD_DIGITS;
7983 $wordlist = file($CFG->wordlist);
7984 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7985 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7986 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
7987 $password = $word1 . $filler1 . $word2;
7988 } else {
7989 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
7990 $digits = $CFG->minpassworddigits;
7991 $lower = $CFG->minpasswordlower;
7992 $upper = $CFG->minpasswordupper;
7993 $nonalphanum = $CFG->minpasswordnonalphanum;
7994 $total = $lower + $upper + $digits + $nonalphanum;
7995 // Var minlength should be the greater one of the two ( $minlen and $total ).
7996 $minlen = $minlen < $total ? $total : $minlen;
7997 // Var maxlen can never be smaller than minlen.
7998 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
7999 $additional = $maxlen - $total;
8001 // Make sure we have enough characters to fulfill
8002 // complexity requirements.
8003 $passworddigits = PASSWORD_DIGITS;
8004 while ($digits > strlen($passworddigits)) {
8005 $passworddigits .= PASSWORD_DIGITS;
8007 $passwordlower = PASSWORD_LOWER;
8008 while ($lower > strlen($passwordlower)) {
8009 $passwordlower .= PASSWORD_LOWER;
8011 $passwordupper = PASSWORD_UPPER;
8012 while ($upper > strlen($passwordupper)) {
8013 $passwordupper .= PASSWORD_UPPER;
8015 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8016 while ($nonalphanum > strlen($passwordnonalphanum)) {
8017 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8020 // Now mix and shuffle it all.
8021 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8022 substr(str_shuffle ($passwordupper), 0, $upper) .
8023 substr(str_shuffle ($passworddigits), 0, $digits) .
8024 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8025 substr(str_shuffle ($passwordlower .
8026 $passwordupper .
8027 $passworddigits .
8028 $passwordnonalphanum), 0 , $additional));
8031 return substr ($password, 0, $maxlen);
8035 * Given a float, prints it nicely.
8036 * Localized floats must not be used in calculations!
8038 * The stripzeros feature is intended for making numbers look nicer in small
8039 * areas where it is not necessary to indicate the degree of accuracy by showing
8040 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8041 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8043 * @param float $float The float to print
8044 * @param int $decimalpoints The number of decimal places to print.
8045 * @param bool $localized use localized decimal separator
8046 * @param bool $stripzeros If true, removes final zeros after decimal point
8047 * @return string locale float
8049 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8050 if (is_null($float)) {
8051 return '';
8053 if ($localized) {
8054 $separator = get_string('decsep', 'langconfig');
8055 } else {
8056 $separator = '.';
8058 $result = number_format($float, $decimalpoints, $separator, '');
8059 if ($stripzeros) {
8060 // Remove zeros and final dot if not needed.
8061 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8063 return $result;
8067 * Converts locale specific floating point/comma number back to standard PHP float value
8068 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8070 * @param string $localefloat locale aware float representation
8071 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8072 * @return mixed float|bool - false or the parsed float.
8074 function unformat_float($localefloat, $strict = false) {
8075 $localefloat = trim($localefloat);
8077 if ($localefloat == '') {
8078 return null;
8081 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8082 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8084 if ($strict && !is_numeric($localefloat)) {
8085 return false;
8088 return (float)$localefloat;
8092 * Given a simple array, this shuffles it up just like shuffle()
8093 * Unlike PHP's shuffle() this function works on any machine.
8095 * @param array $array The array to be rearranged
8096 * @return array
8098 function swapshuffle($array) {
8100 $last = count($array) - 1;
8101 for ($i = 0; $i <= $last; $i++) {
8102 $from = rand(0, $last);
8103 $curr = $array[$i];
8104 $array[$i] = $array[$from];
8105 $array[$from] = $curr;
8107 return $array;
8111 * Like {@link swapshuffle()}, but works on associative arrays
8113 * @param array $array The associative array to be rearranged
8114 * @return array
8116 function swapshuffle_assoc($array) {
8118 $newarray = array();
8119 $newkeys = swapshuffle(array_keys($array));
8121 foreach ($newkeys as $newkey) {
8122 $newarray[$newkey] = $array[$newkey];
8124 return $newarray;
8128 * Given an arbitrary array, and a number of draws,
8129 * this function returns an array with that amount
8130 * of items. The indexes are retained.
8132 * @todo Finish documenting this function
8134 * @param array $array
8135 * @param int $draws
8136 * @return array
8138 function draw_rand_array($array, $draws) {
8140 $return = array();
8142 $last = count($array);
8144 if ($draws > $last) {
8145 $draws = $last;
8148 while ($draws > 0) {
8149 $last--;
8151 $keys = array_keys($array);
8152 $rand = rand(0, $last);
8154 $return[$keys[$rand]] = $array[$keys[$rand]];
8155 unset($array[$keys[$rand]]);
8157 $draws--;
8160 return $return;
8164 * Calculate the difference between two microtimes
8166 * @param string $a The first Microtime
8167 * @param string $b The second Microtime
8168 * @return string
8170 function microtime_diff($a, $b) {
8171 list($adec, $asec) = explode(' ', $a);
8172 list($bdec, $bsec) = explode(' ', $b);
8173 return $bsec - $asec + $bdec - $adec;
8177 * Given a list (eg a,b,c,d,e) this function returns
8178 * an array of 1->a, 2->b, 3->c etc
8180 * @param string $list The string to explode into array bits
8181 * @param string $separator The separator used within the list string
8182 * @return array The now assembled array
8184 function make_menu_from_list($list, $separator=',') {
8186 $array = array_reverse(explode($separator, $list), true);
8187 foreach ($array as $key => $item) {
8188 $outarray[$key+1] = trim($item);
8190 return $outarray;
8194 * Creates an array that represents all the current grades that
8195 * can be chosen using the given grading type.
8197 * Negative numbers
8198 * are scales, zero is no grade, and positive numbers are maximum
8199 * grades.
8201 * @todo Finish documenting this function or better deprecated this completely!
8203 * @param int $gradingtype
8204 * @return array
8206 function make_grades_menu($gradingtype) {
8207 global $DB;
8209 $grades = array();
8210 if ($gradingtype < 0) {
8211 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8212 return make_menu_from_list($scale->scale);
8214 } else if ($gradingtype > 0) {
8215 for ($i=$gradingtype; $i>=0; $i--) {
8216 $grades[$i] = $i .' / '. $gradingtype;
8218 return $grades;
8220 return $grades;
8224 * This function returns the number of activities using the given scale in the given course.
8226 * @param int $courseid The course ID to check.
8227 * @param int $scaleid The scale ID to check
8228 * @return int
8230 function course_scale_used($courseid, $scaleid) {
8231 global $CFG, $DB;
8233 $return = 0;
8235 if (!empty($scaleid)) {
8236 if ($cms = get_course_mods($courseid)) {
8237 foreach ($cms as $cm) {
8238 // Check cm->name/lib.php exists.
8239 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
8240 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
8241 $functionname = $cm->modname.'_scale_used';
8242 if (function_exists($functionname)) {
8243 if ($functionname($cm->instance, $scaleid)) {
8244 $return++;
8251 // Check if any course grade item makes use of the scale.
8252 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8254 // Check if any outcome in the course makes use of the scale.
8255 $return += $DB->count_records_sql("SELECT COUNT('x')
8256 FROM {grade_outcomes_courses} goc,
8257 {grade_outcomes} go
8258 WHERE go.id = goc.outcomeid
8259 AND go.scaleid = ? AND goc.courseid = ?",
8260 array($scaleid, $courseid));
8262 return $return;
8266 * This function returns the number of activities using scaleid in the entire site
8268 * @param int $scaleid
8269 * @param array $courses
8270 * @return int
8272 function site_scale_used($scaleid, &$courses) {
8273 $return = 0;
8275 if (!is_array($courses) || count($courses) == 0) {
8276 $courses = get_courses("all", false, "c.id, c.shortname");
8279 if (!empty($scaleid)) {
8280 if (is_array($courses) && count($courses) > 0) {
8281 foreach ($courses as $course) {
8282 $return += course_scale_used($course->id, $scaleid);
8286 return $return;
8290 * make_unique_id_code
8292 * @todo Finish documenting this function
8294 * @uses $_SERVER
8295 * @param string $extra Extra string to append to the end of the code
8296 * @return string
8298 function make_unique_id_code($extra = '') {
8300 $hostname = 'unknownhost';
8301 if (!empty($_SERVER['HTTP_HOST'])) {
8302 $hostname = $_SERVER['HTTP_HOST'];
8303 } else if (!empty($_ENV['HTTP_HOST'])) {
8304 $hostname = $_ENV['HTTP_HOST'];
8305 } else if (!empty($_SERVER['SERVER_NAME'])) {
8306 $hostname = $_SERVER['SERVER_NAME'];
8307 } else if (!empty($_ENV['SERVER_NAME'])) {
8308 $hostname = $_ENV['SERVER_NAME'];
8311 $date = gmdate("ymdHis");
8313 $random = random_string(6);
8315 if ($extra) {
8316 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8317 } else {
8318 return $hostname .'+'. $date .'+'. $random;
8324 * Function to check the passed address is within the passed subnet
8326 * The parameter is a comma separated string of subnet definitions.
8327 * Subnet strings can be in one of three formats:
8328 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8329 * 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)
8330 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8331 * Code for type 1 modified from user posted comments by mediator at
8332 * {@link http://au.php.net/manual/en/function.ip2long.php}
8334 * @param string $addr The address you are checking
8335 * @param string $subnetstr The string of subnet addresses
8336 * @return bool
8338 function address_in_subnet($addr, $subnetstr) {
8340 if ($addr == '0.0.0.0') {
8341 return false;
8343 $subnets = explode(',', $subnetstr);
8344 $found = false;
8345 $addr = trim($addr);
8346 $addr = cleanremoteaddr($addr, false); // Normalise.
8347 if ($addr === null) {
8348 return false;
8350 $addrparts = explode(':', $addr);
8352 $ipv6 = strpos($addr, ':');
8354 foreach ($subnets as $subnet) {
8355 $subnet = trim($subnet);
8356 if ($subnet === '') {
8357 continue;
8360 if (strpos($subnet, '/') !== false) {
8361 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8362 list($ip, $mask) = explode('/', $subnet);
8363 $mask = trim($mask);
8364 if (!is_number($mask)) {
8365 continue; // Incorect mask number, eh?
8367 $ip = cleanremoteaddr($ip, false); // Normalise.
8368 if ($ip === null) {
8369 continue;
8371 if (strpos($ip, ':') !== false) {
8372 // IPv6.
8373 if (!$ipv6) {
8374 continue;
8376 if ($mask > 128 or $mask < 0) {
8377 continue; // Nonsense.
8379 if ($mask == 0) {
8380 return true; // Any address.
8382 if ($mask == 128) {
8383 if ($ip === $addr) {
8384 return true;
8386 continue;
8388 $ipparts = explode(':', $ip);
8389 $modulo = $mask % 16;
8390 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8391 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8392 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8393 if ($modulo == 0) {
8394 return true;
8396 $pos = ($mask-$modulo)/16;
8397 $ipnet = hexdec($ipparts[$pos]);
8398 $addrnet = hexdec($addrparts[$pos]);
8399 $mask = 0xffff << (16 - $modulo);
8400 if (($addrnet & $mask) == ($ipnet & $mask)) {
8401 return true;
8405 } else {
8406 // IPv4.
8407 if ($ipv6) {
8408 continue;
8410 if ($mask > 32 or $mask < 0) {
8411 continue; // Nonsense.
8413 if ($mask == 0) {
8414 return true;
8416 if ($mask == 32) {
8417 if ($ip === $addr) {
8418 return true;
8420 continue;
8422 $mask = 0xffffffff << (32 - $mask);
8423 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8424 return true;
8428 } else if (strpos($subnet, '-') !== false) {
8429 // 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.
8430 $parts = explode('-', $subnet);
8431 if (count($parts) != 2) {
8432 continue;
8435 if (strpos($subnet, ':') !== false) {
8436 // IPv6.
8437 if (!$ipv6) {
8438 continue;
8440 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8441 if ($ipstart === null) {
8442 continue;
8444 $ipparts = explode(':', $ipstart);
8445 $start = hexdec(array_pop($ipparts));
8446 $ipparts[] = trim($parts[1]);
8447 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8448 if ($ipend === null) {
8449 continue;
8451 $ipparts[7] = '';
8452 $ipnet = implode(':', $ipparts);
8453 if (strpos($addr, $ipnet) !== 0) {
8454 continue;
8456 $ipparts = explode(':', $ipend);
8457 $end = hexdec($ipparts[7]);
8459 $addrend = hexdec($addrparts[7]);
8461 if (($addrend >= $start) and ($addrend <= $end)) {
8462 return true;
8465 } else {
8466 // IPv4.
8467 if ($ipv6) {
8468 continue;
8470 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8471 if ($ipstart === null) {
8472 continue;
8474 $ipparts = explode('.', $ipstart);
8475 $ipparts[3] = trim($parts[1]);
8476 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8477 if ($ipend === null) {
8478 continue;
8481 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8482 return true;
8486 } else {
8487 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8488 if (strpos($subnet, ':') !== false) {
8489 // IPv6.
8490 if (!$ipv6) {
8491 continue;
8493 $parts = explode(':', $subnet);
8494 $count = count($parts);
8495 if ($parts[$count-1] === '') {
8496 unset($parts[$count-1]); // Trim trailing :'s.
8497 $count--;
8498 $subnet = implode('.', $parts);
8500 $isip = cleanremoteaddr($subnet, false); // Normalise.
8501 if ($isip !== null) {
8502 if ($isip === $addr) {
8503 return true;
8505 continue;
8506 } else if ($count > 8) {
8507 continue;
8509 $zeros = array_fill(0, 8-$count, '0');
8510 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8511 if (address_in_subnet($addr, $subnet)) {
8512 return true;
8515 } else {
8516 // IPv4.
8517 if ($ipv6) {
8518 continue;
8520 $parts = explode('.', $subnet);
8521 $count = count($parts);
8522 if ($parts[$count-1] === '') {
8523 unset($parts[$count-1]); // Trim trailing .
8524 $count--;
8525 $subnet = implode('.', $parts);
8527 if ($count == 4) {
8528 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8529 if ($subnet === $addr) {
8530 return true;
8532 continue;
8533 } else if ($count > 4) {
8534 continue;
8536 $zeros = array_fill(0, 4-$count, '0');
8537 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8538 if (address_in_subnet($addr, $subnet)) {
8539 return true;
8545 return false;
8549 * For outputting debugging info
8551 * @param string $string The string to write
8552 * @param string $eol The end of line char(s) to use
8553 * @param string $sleep Period to make the application sleep
8554 * This ensures any messages have time to display before redirect
8556 function mtrace($string, $eol="\n", $sleep=0) {
8558 if (defined('STDOUT') and !PHPUNIT_TEST) {
8559 fwrite(STDOUT, $string.$eol);
8560 } else {
8561 echo $string . $eol;
8564 flush();
8566 // Delay to keep message on user's screen in case of subsequent redirect.
8567 if ($sleep) {
8568 sleep($sleep);
8573 * Replace 1 or more slashes or backslashes to 1 slash
8575 * @param string $path The path to strip
8576 * @return string the path with double slashes removed
8578 function cleardoubleslashes ($path) {
8579 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8583 * Is current ip in give list?
8585 * @param string $list
8586 * @return bool
8588 function remoteip_in_list($list) {
8589 $inlist = false;
8590 $clientip = getremoteaddr(null);
8592 if (!$clientip) {
8593 // Ensure access on cli.
8594 return true;
8597 $list = explode("\n", $list);
8598 foreach ($list as $subnet) {
8599 $subnet = trim($subnet);
8600 if (address_in_subnet($clientip, $subnet)) {
8601 $inlist = true;
8602 break;
8605 return $inlist;
8609 * Returns most reliable client address
8611 * @param string $default If an address can't be determined, then return this
8612 * @return string The remote IP address
8614 function getremoteaddr($default='0.0.0.0') {
8615 global $CFG;
8617 if (empty($CFG->getremoteaddrconf)) {
8618 // This will happen, for example, before just after the upgrade, as the
8619 // user is redirected to the admin screen.
8620 $variablestoskip = 0;
8621 } else {
8622 $variablestoskip = $CFG->getremoteaddrconf;
8624 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8625 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8626 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8627 return $address ? $address : $default;
8630 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8631 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8632 $hdr = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8633 $address = cleanremoteaddr($hdr[0]);
8634 return $address ? $address : $default;
8637 if (!empty($_SERVER['REMOTE_ADDR'])) {
8638 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8639 return $address ? $address : $default;
8640 } else {
8641 return $default;
8646 * Cleans an ip address. Internal addresses are now allowed.
8647 * (Originally local addresses were not allowed.)
8649 * @param string $addr IPv4 or IPv6 address
8650 * @param bool $compress use IPv6 address compression
8651 * @return string normalised ip address string, null if error
8653 function cleanremoteaddr($addr, $compress=false) {
8654 $addr = trim($addr);
8656 // TODO: maybe add a separate function is_addr_public() or something like this.
8658 if (strpos($addr, ':') !== false) {
8659 // Can be only IPv6.
8660 $parts = explode(':', $addr);
8661 $count = count($parts);
8663 if (strpos($parts[$count-1], '.') !== false) {
8664 // Legacy ipv4 notation.
8665 $last = array_pop($parts);
8666 $ipv4 = cleanremoteaddr($last, true);
8667 if ($ipv4 === null) {
8668 return null;
8670 $bits = explode('.', $ipv4);
8671 $parts[] = dechex($bits[0]).dechex($bits[1]);
8672 $parts[] = dechex($bits[2]).dechex($bits[3]);
8673 $count = count($parts);
8674 $addr = implode(':', $parts);
8677 if ($count < 3 or $count > 8) {
8678 return null; // Severly malformed.
8681 if ($count != 8) {
8682 if (strpos($addr, '::') === false) {
8683 return null; // Malformed.
8685 // Uncompress.
8686 $insertat = array_search('', $parts, true);
8687 $missing = array_fill(0, 1 + 8 - $count, '0');
8688 array_splice($parts, $insertat, 1, $missing);
8689 foreach ($parts as $key => $part) {
8690 if ($part === '') {
8691 $parts[$key] = '0';
8696 $adr = implode(':', $parts);
8697 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8698 return null; // Incorrect format - sorry.
8701 // Normalise 0s and case.
8702 $parts = array_map('hexdec', $parts);
8703 $parts = array_map('dechex', $parts);
8705 $result = implode(':', $parts);
8707 if (!$compress) {
8708 return $result;
8711 if ($result === '0:0:0:0:0:0:0:0') {
8712 return '::'; // All addresses.
8715 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8716 if ($compressed !== $result) {
8717 return $compressed;
8720 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8721 if ($compressed !== $result) {
8722 return $compressed;
8725 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8726 if ($compressed !== $result) {
8727 return $compressed;
8730 return $result;
8733 // First get all things that look like IPv4 addresses.
8734 $parts = array();
8735 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8736 return null;
8738 unset($parts[0]);
8740 foreach ($parts as $key => $match) {
8741 if ($match > 255) {
8742 return null;
8744 $parts[$key] = (int)$match; // Normalise 0s.
8747 return implode('.', $parts);
8751 * This function will make a complete copy of anything it's given,
8752 * regardless of whether it's an object or not.
8754 * @param mixed $thing Something you want cloned
8755 * @return mixed What ever it is you passed it
8757 function fullclone($thing) {
8758 return unserialize(serialize($thing));
8762 * If new messages are waiting for the current user, then insert
8763 * JavaScript to pop up the messaging window into the page
8765 * @return void
8767 function message_popup_window() {
8768 global $USER, $DB, $PAGE, $CFG;
8770 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
8771 return;
8774 if (!isloggedin() || isguestuser()) {
8775 return;
8778 if (!isset($USER->message_lastpopup)) {
8779 $USER->message_lastpopup = 0;
8780 } else if ($USER->message_lastpopup > (time()-120)) {
8781 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8782 return;
8785 // A quick query to check whether the user has new messages.
8786 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
8787 if ($messagecount < 1) {
8788 return;
8791 // There are unread messages so now do a more complex but slower query.
8792 $messagesql = "SELECT m.id, c.blocked
8793 FROM {message} m
8794 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8795 JOIN {message_processors} p ON mw.processorid=p.id
8796 JOIN {user} u ON m.useridfrom=u.id
8797 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8798 AND c.userid = m.useridto
8799 WHERE m.useridto = :userid
8800 AND p.name='popup'";
8802 // If the user was last notified over an hour ago we can re-notify them of old messages
8803 // so don't worry about when the new message was sent.
8804 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
8805 if (!$lastnotifiedlongago) {
8806 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8809 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
8811 $validmessages = 0;
8812 foreach ($waitingmessages as $messageinfo) {
8813 if ($messageinfo->blocked) {
8814 // Message is from a user who has since been blocked so just mark it read.
8815 // Get the full message to mark as read.
8816 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id));
8817 message_mark_message_read($messageobject, time());
8818 } else {
8819 $validmessages++;
8823 if ($validmessages > 0) {
8824 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8825 $strgomessage = get_string('gotomessages', 'message');
8826 $strstaymessage = get_string('ignore', 'admin');
8828 $notificationsound = null;
8829 $beep = get_user_preferences('message_beepnewmessage', '');
8830 if (!empty($beep)) {
8831 // Browsers will work down this list until they find something they support.
8832 $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
8833 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
8834 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8835 $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8837 $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8840 $url = $CFG->wwwroot.'/message/index.php';
8841 $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8842 html_writer::start_tag('div', array('id' => 'newmessagetext')).
8843 $strmessages.
8844 html_writer::end_tag('div').
8846 $notificationsound.
8847 html_writer::start_tag('div', array('id' => 'newmessagelinks')).
8848 html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
8849 html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
8850 html_writer::end_tag('div');
8851 html_writer::end_tag('div');
8853 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
8855 $USER->message_lastpopup = time();
8860 * Used to make sure that $min <= $value <= $max
8862 * Make sure that value is between min, and max
8864 * @param int $min The minimum value
8865 * @param int $value The value to check
8866 * @param int $max The maximum value
8867 * @return int
8869 function bounded_number($min, $value, $max) {
8870 if ($value < $min) {
8871 return $min;
8873 if ($value > $max) {
8874 return $max;
8876 return $value;
8880 * Check if there is a nested array within the passed array
8882 * @param array $array
8883 * @return bool true if there is a nested array false otherwise
8885 function array_is_nested($array) {
8886 foreach ($array as $value) {
8887 if (is_array($value)) {
8888 return true;
8891 return false;
8895 * get_performance_info() pairs up with init_performance_info()
8896 * loaded in setup.php. Returns an array with 'html' and 'txt'
8897 * values ready for use, and each of the individual stats provided
8898 * separately as well.
8900 * @return array
8902 function get_performance_info() {
8903 global $CFG, $PERF, $DB, $PAGE;
8905 $info = array();
8906 $info['html'] = ''; // Holds userfriendly HTML representation.
8907 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8909 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8911 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8912 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8914 if (function_exists('memory_get_usage')) {
8915 $info['memory_total'] = memory_get_usage();
8916 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8917 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8918 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8919 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8922 if (function_exists('memory_get_peak_usage')) {
8923 $info['memory_peak'] = memory_get_peak_usage();
8924 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8925 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8928 $inc = get_included_files();
8929 $info['includecount'] = count($inc);
8930 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8931 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8933 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8934 // We can not track more performance before installation or before PAGE init, sorry.
8935 return $info;
8938 $filtermanager = filter_manager::instance();
8939 if (method_exists($filtermanager, 'get_performance_summary')) {
8940 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8941 $info = array_merge($filterinfo, $info);
8942 foreach ($filterinfo as $key => $value) {
8943 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8944 $info['txt'] .= "$key: $value ";
8948 $stringmanager = get_string_manager();
8949 if (method_exists($stringmanager, 'get_performance_summary')) {
8950 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8951 $info = array_merge($filterinfo, $info);
8952 foreach ($filterinfo as $key => $value) {
8953 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8954 $info['txt'] .= "$key: $value ";
8958 if (!empty($PERF->logwrites)) {
8959 $info['logwrites'] = $PERF->logwrites;
8960 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8961 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8964 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
8965 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
8966 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8968 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
8969 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
8970 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
8972 if (function_exists('posix_times')) {
8973 $ptimes = posix_times();
8974 if (is_array($ptimes)) {
8975 foreach ($ptimes as $key => $val) {
8976 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
8978 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
8979 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8983 // Grab the load average for the last minute.
8984 // /proc will only work under some linux configurations
8985 // while uptime is there under MacOSX/Darwin and other unices.
8986 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
8987 list($serverload) = explode(' ', $loadavg[0]);
8988 unset($loadavg);
8989 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
8990 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
8991 $serverload = $matches[1];
8992 } else {
8993 trigger_error('Could not parse uptime output!');
8996 if (!empty($serverload)) {
8997 $info['serverload'] = $serverload;
8998 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
8999 $info['txt'] .= "serverload: {$info['serverload']} ";
9002 // Display size of session if session started.
9003 if ($si = \core\session\manager::get_performance_info()) {
9004 $info['sessionsize'] = $si['size'];
9005 $info['html'] .= $si['html'];
9006 $info['txt'] .= $si['txt'];
9009 if ($stats = cache_helper::get_stats()) {
9010 $html = '<span class="cachesused">';
9011 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
9012 $text = 'Caches used (hits/misses/sets): ';
9013 $hits = 0;
9014 $misses = 0;
9015 $sets = 0;
9016 foreach ($stats as $definition => $stores) {
9017 $html .= '<span class="cache-definition-stats">';
9018 $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
9019 $text .= "$definition {";
9020 foreach ($stores as $store => $data) {
9021 $hits += $data['hits'];
9022 $misses += $data['misses'];
9023 $sets += $data['sets'];
9024 if ($data['hits'] == 0 and $data['misses'] > 0) {
9025 $cachestoreclass = 'nohits';
9026 } else if ($data['hits'] < $data['misses']) {
9027 $cachestoreclass = 'lowhits';
9028 } else {
9029 $cachestoreclass = 'hihits';
9031 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9032 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
9034 $html .= '</span>';
9035 $text .= '} ';
9037 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
9038 $html .= '</span> ';
9039 $info['cachesused'] = "$hits / $misses / $sets";
9040 $info['html'] .= $html;
9041 $info['txt'] .= $text.'. ';
9042 } else {
9043 $info['cachesused'] = '0 / 0 / 0';
9044 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
9045 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9048 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
9049 return $info;
9053 * Legacy function.
9055 * @todo Document this function linux people
9057 function apd_get_profiling() {
9058 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
9062 * Delete directory or only its content
9064 * @param string $dir directory path
9065 * @param bool $contentonly
9066 * @return bool success, true also if dir does not exist
9068 function remove_dir($dir, $contentonly=false) {
9069 if (!file_exists($dir)) {
9070 // Nothing to do.
9071 return true;
9073 if (!$handle = opendir($dir)) {
9074 return false;
9076 $result = true;
9077 while (false!==($item = readdir($handle))) {
9078 if ($item != '.' && $item != '..') {
9079 if (is_dir($dir.'/'.$item)) {
9080 $result = remove_dir($dir.'/'.$item) && $result;
9081 } else {
9082 $result = unlink($dir.'/'.$item) && $result;
9086 closedir($handle);
9087 if ($contentonly) {
9088 clearstatcache(); // Make sure file stat cache is properly invalidated.
9089 return $result;
9091 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9092 clearstatcache(); // Make sure file stat cache is properly invalidated.
9093 return $result;
9097 * Detect if an object or a class contains a given property
9098 * will take an actual object or the name of a class
9100 * @param mix $obj Name of class or real object to test
9101 * @param string $property name of property to find
9102 * @return bool true if property exists
9104 function object_property_exists( $obj, $property ) {
9105 if (is_string( $obj )) {
9106 $properties = get_class_vars( $obj );
9107 } else {
9108 $properties = get_object_vars( $obj );
9110 return array_key_exists( $property, $properties );
9114 * Converts an object into an associative array
9116 * This function converts an object into an associative array by iterating
9117 * over its public properties. Because this function uses the foreach
9118 * construct, Iterators are respected. It works recursively on arrays of objects.
9119 * Arrays and simple values are returned as is.
9121 * If class has magic properties, it can implement IteratorAggregate
9122 * and return all available properties in getIterator()
9124 * @param mixed $var
9125 * @return array
9127 function convert_to_array($var) {
9128 $result = array();
9130 // Loop over elements/properties.
9131 foreach ($var as $key => $value) {
9132 // Recursively convert objects.
9133 if (is_object($value) || is_array($value)) {
9134 $result[$key] = convert_to_array($value);
9135 } else {
9136 // Simple values are untouched.
9137 $result[$key] = $value;
9140 return $result;
9144 * Detect a custom script replacement in the data directory that will
9145 * replace an existing moodle script
9147 * @return string|bool full path name if a custom script exists, false if no custom script exists
9149 function custom_script_path() {
9150 global $CFG, $SCRIPT;
9152 if ($SCRIPT === null) {
9153 // Probably some weird external script.
9154 return false;
9157 $scriptpath = $CFG->customscripts . $SCRIPT;
9159 // Check the custom script exists.
9160 if (file_exists($scriptpath) and is_file($scriptpath)) {
9161 return $scriptpath;
9162 } else {
9163 return false;
9168 * Returns whether or not the user object is a remote MNET user. This function
9169 * is in moodlelib because it does not rely on loading any of the MNET code.
9171 * @param object $user A valid user object
9172 * @return bool True if the user is from a remote Moodle.
9174 function is_mnet_remote_user($user) {
9175 global $CFG;
9177 if (!isset($CFG->mnet_localhost_id)) {
9178 include_once($CFG->dirroot . '/mnet/lib.php');
9179 $env = new mnet_environment();
9180 $env->init();
9181 unset($env);
9184 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9188 * This function will search for browser prefereed languages, setting Moodle
9189 * to use the best one available if $SESSION->lang is undefined
9191 function setup_lang_from_browser() {
9192 global $CFG, $SESSION, $USER;
9194 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9195 // Lang is defined in session or user profile, nothing to do.
9196 return;
9199 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9200 return;
9203 // Extract and clean langs from headers.
9204 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9205 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9206 $rawlangs = explode(',', $rawlangs); // Convert to array.
9207 $langs = array();
9209 $order = 1.0;
9210 foreach ($rawlangs as $lang) {
9211 if (strpos($lang, ';') === false) {
9212 $langs[(string)$order] = $lang;
9213 $order = $order-0.01;
9214 } else {
9215 $parts = explode(';', $lang);
9216 $pos = strpos($parts[1], '=');
9217 $langs[substr($parts[1], $pos+1)] = $parts[0];
9220 krsort($langs, SORT_NUMERIC);
9222 // Look for such langs under standard locations.
9223 foreach ($langs as $lang) {
9224 // Clean it properly for include.
9225 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9226 if (get_string_manager()->translation_exists($lang, false)) {
9227 // Lang exists, set it in session.
9228 $SESSION->lang = $lang;
9229 // We have finished. Go out.
9230 break;
9233 return;
9237 * Check if $url matches anything in proxybypass list
9239 * Any errors just result in the proxy being used (least bad)
9241 * @param string $url url to check
9242 * @return boolean true if we should bypass the proxy
9244 function is_proxybypass( $url ) {
9245 global $CFG;
9247 // Sanity check.
9248 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9249 return false;
9252 // Get the host part out of the url.
9253 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9254 return false;
9257 // Get the possible bypass hosts into an array.
9258 $matches = explode( ',', $CFG->proxybypass );
9260 // Check for a match.
9261 // (IPs need to match the left hand side and hosts the right of the url,
9262 // but we can recklessly check both as there can't be a false +ve).
9263 foreach ($matches as $match) {
9264 $match = trim($match);
9266 // Try for IP match (Left side).
9267 $lhs = substr($host, 0, strlen($match));
9268 if (strcasecmp($match, $lhs)==0) {
9269 return true;
9272 // Try for host match (Right side).
9273 $rhs = substr($host, -strlen($match));
9274 if (strcasecmp($match, $rhs)==0) {
9275 return true;
9279 // Nothing matched.
9280 return false;
9284 * Check if the passed navigation is of the new style
9286 * @param mixed $navigation
9287 * @return bool true for yes false for no
9289 function is_newnav($navigation) {
9290 if (is_array($navigation) && !empty($navigation['newnav'])) {
9291 return true;
9292 } else {
9293 return false;
9298 * Checks whether the given variable name is defined as a variable within the given object.
9300 * This will NOT work with stdClass objects, which have no class variables.
9302 * @param string $var The variable name
9303 * @param object $object The object to check
9304 * @return boolean
9306 function in_object_vars($var, $object) {
9307 $classvars = get_class_vars(get_class($object));
9308 $classvars = array_keys($classvars);
9309 return in_array($var, $classvars);
9313 * Returns an array without repeated objects.
9314 * This function is similar to array_unique, but for arrays that have objects as values
9316 * @param array $array
9317 * @param bool $keepkeyassoc
9318 * @return array
9320 function object_array_unique($array, $keepkeyassoc = true) {
9321 $duplicatekeys = array();
9322 $tmp = array();
9324 foreach ($array as $key => $val) {
9325 // Convert objects to arrays, in_array() does not support objects.
9326 if (is_object($val)) {
9327 $val = (array)$val;
9330 if (!in_array($val, $tmp)) {
9331 $tmp[] = $val;
9332 } else {
9333 $duplicatekeys[] = $key;
9337 foreach ($duplicatekeys as $key) {
9338 unset($array[$key]);
9341 return $keepkeyassoc ? $array : array_values($array);
9345 * Is a userid the primary administrator?
9347 * @param int $userid int id of user to check
9348 * @return boolean
9350 function is_primary_admin($userid) {
9351 $primaryadmin = get_admin();
9353 if ($userid == $primaryadmin->id) {
9354 return true;
9355 } else {
9356 return false;
9361 * Returns the site identifier
9363 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9365 function get_site_identifier() {
9366 global $CFG;
9367 // Check to see if it is missing. If so, initialise it.
9368 if (empty($CFG->siteidentifier)) {
9369 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9371 // Return it.
9372 return $CFG->siteidentifier;
9376 * Check whether the given password has no more than the specified
9377 * number of consecutive identical characters.
9379 * @param string $password password to be checked against the password policy
9380 * @param integer $maxchars maximum number of consecutive identical characters
9381 * @return bool
9383 function check_consecutive_identical_characters($password, $maxchars) {
9385 if ($maxchars < 1) {
9386 return true; // Zero 0 is to disable this check.
9388 if (strlen($password) <= $maxchars) {
9389 return true; // Too short to fail this test.
9392 $previouschar = '';
9393 $consecutivecount = 1;
9394 foreach (str_split($password) as $char) {
9395 if ($char != $previouschar) {
9396 $consecutivecount = 1;
9397 } else {
9398 $consecutivecount++;
9399 if ($consecutivecount > $maxchars) {
9400 return false; // Check failed already.
9404 $previouschar = $char;
9407 return true;
9411 * Helper function to do partial function binding.
9412 * so we can use it for preg_replace_callback, for example
9413 * this works with php functions, user functions, static methods and class methods
9414 * it returns you a callback that you can pass on like so:
9416 * $callback = partial('somefunction', $arg1, $arg2);
9417 * or
9418 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9419 * or even
9420 * $obj = new someclass();
9421 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9423 * and then the arguments that are passed through at calltime are appended to the argument list.
9425 * @param mixed $function a php callback
9426 * @param mixed $arg1,... $argv arguments to partially bind with
9427 * @return array Array callback
9429 function partial() {
9430 if (!class_exists('partial')) {
9432 * Used to manage function binding.
9433 * @copyright 2009 Penny Leach
9434 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9436 class partial{
9437 /** @var array */
9438 public $values = array();
9439 /** @var string The function to call as a callback. */
9440 public $func;
9442 * Constructor
9443 * @param string $func
9444 * @param array $args
9446 public function __construct($func, $args) {
9447 $this->values = $args;
9448 $this->func = $func;
9451 * Calls the callback function.
9452 * @return mixed
9454 public function method() {
9455 $args = func_get_args();
9456 return call_user_func_array($this->func, array_merge($this->values, $args));
9460 $args = func_get_args();
9461 $func = array_shift($args);
9462 $p = new partial($func, $args);
9463 return array($p, 'method');
9467 * helper function to load up and initialise the mnet environment
9468 * this must be called before you use mnet functions.
9470 * @return mnet_environment the equivalent of old $MNET global
9472 function get_mnet_environment() {
9473 global $CFG;
9474 require_once($CFG->dirroot . '/mnet/lib.php');
9475 static $instance = null;
9476 if (empty($instance)) {
9477 $instance = new mnet_environment();
9478 $instance->init();
9480 return $instance;
9484 * during xmlrpc server code execution, any code wishing to access
9485 * information about the remote peer must use this to get it.
9487 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9489 function get_mnet_remote_client() {
9490 if (!defined('MNET_SERVER')) {
9491 debugging(get_string('notinxmlrpcserver', 'mnet'));
9492 return false;
9494 global $MNET_REMOTE_CLIENT;
9495 if (isset($MNET_REMOTE_CLIENT)) {
9496 return $MNET_REMOTE_CLIENT;
9498 return false;
9502 * during the xmlrpc server code execution, this will be called
9503 * to setup the object returned by {@link get_mnet_remote_client}
9505 * @param mnet_remote_client $client the client to set up
9506 * @throws moodle_exception
9508 function set_mnet_remote_client($client) {
9509 if (!defined('MNET_SERVER')) {
9510 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9512 global $MNET_REMOTE_CLIENT;
9513 $MNET_REMOTE_CLIENT = $client;
9517 * return the jump url for a given remote user
9518 * this is used for rewriting forum post links in emails, etc
9520 * @param stdclass $user the user to get the idp url for
9522 function mnet_get_idp_jump_url($user) {
9523 global $CFG;
9525 static $mnetjumps = array();
9526 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9527 $idp = mnet_get_peer_host($user->mnethostid);
9528 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9529 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9531 return $mnetjumps[$user->mnethostid];
9535 * Gets the homepage to use for the current user
9537 * @return int One of HOMEPAGE_*
9539 function get_home_page() {
9540 global $CFG;
9542 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9543 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9544 return HOMEPAGE_MY;
9545 } else {
9546 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9549 return HOMEPAGE_SITE;
9553 * Gets the name of a course to be displayed when showing a list of courses.
9554 * By default this is just $course->fullname but user can configure it. The
9555 * result of this function should be passed through print_string.
9556 * @param stdClass|course_in_list $course Moodle course object
9557 * @return string Display name of course (either fullname or short + fullname)
9559 function get_course_display_name_for_list($course) {
9560 global $CFG;
9561 if (!empty($CFG->courselistshortnames)) {
9562 if (!($course instanceof stdClass)) {
9563 $course = (object)convert_to_array($course);
9565 return get_string('courseextendednamedisplay', '', $course);
9566 } else {
9567 return $course->fullname;
9572 * The lang_string class
9574 * This special class is used to create an object representation of a string request.
9575 * It is special because processing doesn't occur until the object is first used.
9576 * The class was created especially to aid performance in areas where strings were
9577 * required to be generated but were not necessarily used.
9578 * As an example the admin tree when generated uses over 1500 strings, of which
9579 * normally only 1/3 are ever actually printed at any time.
9580 * The performance advantage is achieved by not actually processing strings that
9581 * arn't being used, as such reducing the processing required for the page.
9583 * How to use the lang_string class?
9584 * There are two methods of using the lang_string class, first through the
9585 * forth argument of the get_string function, and secondly directly.
9586 * The following are examples of both.
9587 * 1. Through get_string calls e.g.
9588 * $string = get_string($identifier, $component, $a, true);
9589 * $string = get_string('yes', 'moodle', null, true);
9590 * 2. Direct instantiation
9591 * $string = new lang_string($identifier, $component, $a, $lang);
9592 * $string = new lang_string('yes');
9594 * How do I use a lang_string object?
9595 * The lang_string object makes use of a magic __toString method so that you
9596 * are able to use the object exactly as you would use a string in most cases.
9597 * This means you are able to collect it into a variable and then directly
9598 * echo it, or concatenate it into another string, or similar.
9599 * The other thing you can do is manually get the string by calling the
9600 * lang_strings out method e.g.
9601 * $string = new lang_string('yes');
9602 * $string->out();
9603 * Also worth noting is that the out method can take one argument, $lang which
9604 * allows the developer to change the language on the fly.
9606 * When should I use a lang_string object?
9607 * The lang_string object is designed to be used in any situation where a
9608 * string may not be needed, but needs to be generated.
9609 * The admin tree is a good example of where lang_string objects should be
9610 * used.
9611 * A more practical example would be any class that requries strings that may
9612 * not be printed (after all classes get renderer by renderers and who knows
9613 * what they will do ;))
9615 * When should I not use a lang_string object?
9616 * Don't use lang_strings when you are going to use a string immediately.
9617 * There is no need as it will be processed immediately and there will be no
9618 * advantage, and in fact perhaps a negative hit as a class has to be
9619 * instantiated for a lang_string object, however get_string won't require
9620 * that.
9622 * Limitations:
9623 * 1. You cannot use a lang_string object as an array offset. Doing so will
9624 * result in PHP throwing an error. (You can use it as an object property!)
9626 * @package core
9627 * @category string
9628 * @copyright 2011 Sam Hemelryk
9629 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9631 class lang_string {
9633 /** @var string The strings identifier */
9634 protected $identifier;
9635 /** @var string The strings component. Default '' */
9636 protected $component = '';
9637 /** @var array|stdClass Any arguments required for the string. Default null */
9638 protected $a = null;
9639 /** @var string The language to use when processing the string. Default null */
9640 protected $lang = null;
9642 /** @var string The processed string (once processed) */
9643 protected $string = null;
9646 * A special boolean. If set to true then the object has been woken up and
9647 * cannot be regenerated. If this is set then $this->string MUST be used.
9648 * @var bool
9650 protected $forcedstring = false;
9653 * Constructs a lang_string object
9655 * This function should do as little processing as possible to ensure the best
9656 * performance for strings that won't be used.
9658 * @param string $identifier The strings identifier
9659 * @param string $component The strings component
9660 * @param stdClass|array $a Any arguments the string requires
9661 * @param string $lang The language to use when processing the string.
9662 * @throws coding_exception
9664 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9665 if (empty($component)) {
9666 $component = 'moodle';
9669 $this->identifier = $identifier;
9670 $this->component = $component;
9671 $this->lang = $lang;
9673 // We MUST duplicate $a to ensure that it if it changes by reference those
9674 // changes are not carried across.
9675 // To do this we always ensure $a or its properties/values are strings
9676 // and that any properties/values that arn't convertable are forgotten.
9677 if (!empty($a)) {
9678 if (is_scalar($a)) {
9679 $this->a = $a;
9680 } else if ($a instanceof lang_string) {
9681 $this->a = $a->out();
9682 } else if (is_object($a) or is_array($a)) {
9683 $a = (array)$a;
9684 $this->a = array();
9685 foreach ($a as $key => $value) {
9686 // Make sure conversion errors don't get displayed (results in '').
9687 if (is_array($value)) {
9688 $this->a[$key] = '';
9689 } else if (is_object($value)) {
9690 if (method_exists($value, '__toString')) {
9691 $this->a[$key] = $value->__toString();
9692 } else {
9693 $this->a[$key] = '';
9695 } else {
9696 $this->a[$key] = (string)$value;
9702 if (debugging(false, DEBUG_DEVELOPER)) {
9703 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9704 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9706 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9707 throw new coding_exception('Invalid string compontent. Please check your string definition');
9709 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9710 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9716 * Processes the string.
9718 * This function actually processes the string, stores it in the string property
9719 * and then returns it.
9720 * You will notice that this function is VERY similar to the get_string method.
9721 * That is because it is pretty much doing the same thing.
9722 * However as this function is an upgrade it isn't as tolerant to backwards
9723 * compatibility.
9725 * @return string
9726 * @throws coding_exception
9728 protected function get_string() {
9729 global $CFG;
9731 // Check if we need to process the string.
9732 if ($this->string === null) {
9733 // Check the quality of the identifier.
9734 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9735 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);
9738 // Process the string.
9739 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9740 // Debugging feature lets you display string identifier and component.
9741 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9742 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9745 // Return the string.
9746 return $this->string;
9750 * Returns the string
9752 * @param string $lang The langauge to use when processing the string
9753 * @return string
9755 public function out($lang = null) {
9756 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9757 if ($this->forcedstring) {
9758 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9759 return $this->get_string();
9761 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9762 return $translatedstring->out();
9764 return $this->get_string();
9768 * Magic __toString method for printing a string
9770 * @return string
9772 public function __toString() {
9773 return $this->get_string();
9777 * Magic __set_state method used for var_export
9779 * @return string
9781 public function __set_state() {
9782 return $this->get_string();
9786 * Prepares the lang_string for sleep and stores only the forcedstring and
9787 * string properties... the string cannot be regenerated so we need to ensure
9788 * it is generated for this.
9790 * @return string
9792 public function __sleep() {
9793 $this->get_string();
9794 $this->forcedstring = true;
9795 return array('forcedstring', 'string', 'lang');