MDL-49418 core: partial revert of MDL-48804
[moodle.git] / lib / moodlelib.php
blob7463c75d87d9c4645d9395d5aa5d16829e16c0e2
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);
2857 } else {
2858 // Do not touch global $COURSE via $PAGE->set_course(),
2859 // the reasons is we need to be able to call require_login() at any time!!
2860 $course = $SITE;
2861 if ($cm) {
2862 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2866 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2867 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2868 // risk leading the user back to the AJAX request URL.
2869 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2870 $setwantsurltome = false;
2873 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2874 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
2875 if ($setwantsurltome) {
2876 $SESSION->wantsurl = qualified_me();
2878 redirect(get_login_url());
2881 // If the user is not even logged in yet then make sure they are.
2882 if (!isloggedin()) {
2883 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2884 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2885 // Misconfigured site guest, just redirect to login page.
2886 redirect(get_login_url());
2887 exit; // Never reached.
2889 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2890 complete_user_login($guest);
2891 $USER->autologinguest = true;
2892 $SESSION->lang = $lang;
2893 } else {
2894 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2895 if ($preventredirect) {
2896 throw new require_login_exception('You are not logged in');
2899 if ($setwantsurltome) {
2900 $SESSION->wantsurl = qualified_me();
2902 if (!empty($_SERVER['HTTP_REFERER'])) {
2903 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2905 redirect(get_login_url());
2906 exit; // Never reached.
2910 // Loginas as redirection if needed.
2911 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2912 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2913 if ($USER->loginascontext->instanceid != $course->id) {
2914 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2919 // Check whether the user should be changing password (but only if it is REALLY them).
2920 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2921 $userauth = get_auth_plugin($USER->auth);
2922 if ($userauth->can_change_password() and !$preventredirect) {
2923 if ($setwantsurltome) {
2924 $SESSION->wantsurl = qualified_me();
2926 if ($changeurl = $userauth->change_password_url()) {
2927 // Use plugin custom url.
2928 redirect($changeurl);
2929 } else {
2930 // Use moodle internal method.
2931 if (empty($CFG->loginhttps)) {
2932 redirect($CFG->wwwroot .'/login/change_password.php');
2933 } else {
2934 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2935 redirect($wwwroot .'/login/change_password.php');
2938 } else {
2939 print_error('nopasswordchangeforced', 'auth');
2943 // Check that the user account is properly set up.
2944 if (user_not_fully_set_up($USER)) {
2945 if ($preventredirect) {
2946 throw new require_login_exception('User not fully set-up');
2948 if ($setwantsurltome) {
2949 $SESSION->wantsurl = qualified_me();
2951 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2954 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2955 sesskey();
2957 // Do not bother admins with any formalities.
2958 if (is_siteadmin()) {
2959 // Set the global $COURSE.
2960 if ($cm) {
2961 $PAGE->set_cm($cm, $course);
2962 $PAGE->set_pagelayout('incourse');
2963 } else if (!empty($courseorid)) {
2964 $PAGE->set_course($course);
2966 // Set accesstime or the user will appear offline which messes up messaging.
2967 user_accesstime_log($course->id);
2968 return;
2971 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2972 if (!$USER->policyagreed and !is_siteadmin()) {
2973 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2974 if ($preventredirect) {
2975 throw new require_login_exception('Policy not agreed');
2977 if ($setwantsurltome) {
2978 $SESSION->wantsurl = qualified_me();
2980 redirect($CFG->wwwroot .'/user/policy.php');
2981 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2982 if ($preventredirect) {
2983 throw new require_login_exception('Policy not agreed');
2985 if ($setwantsurltome) {
2986 $SESSION->wantsurl = qualified_me();
2988 redirect($CFG->wwwroot .'/user/policy.php');
2992 // Fetch the system context, the course context, and prefetch its child contexts.
2993 $sysctx = context_system::instance();
2994 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2995 if ($cm) {
2996 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2997 } else {
2998 $cmcontext = null;
3001 // If the site is currently under maintenance, then print a message.
3002 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
3003 if ($preventredirect) {
3004 throw new require_login_exception('Maintenance in progress');
3007 print_maintenance_message();
3010 // Make sure the course itself is not hidden.
3011 if ($course->id == SITEID) {
3012 // Frontpage can not be hidden.
3013 } else {
3014 if (is_role_switched($course->id)) {
3015 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
3016 } else {
3017 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3018 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
3019 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
3020 if ($preventredirect) {
3021 throw new require_login_exception('Course is hidden');
3023 $PAGE->set_context(null);
3024 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3025 // the navigation will mess up when trying to find it.
3026 navigation_node::override_active_url(new moodle_url('/'));
3027 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3032 // Is the user enrolled?
3033 if ($course->id == SITEID) {
3034 // Everybody is enrolled on the frontpage.
3035 } else {
3036 if (\core\session\manager::is_loggedinas()) {
3037 // Make sure the REAL person can access this course first.
3038 $realuser = \core\session\manager::get_realuser();
3039 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
3040 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
3041 if ($preventredirect) {
3042 throw new require_login_exception('Invalid course login-as access');
3044 $PAGE->set_context(null);
3045 echo $OUTPUT->header();
3046 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
3050 $access = false;
3052 if (is_role_switched($course->id)) {
3053 // Ok, user had to be inside this course before the switch.
3054 $access = true;
3056 } else if (is_viewing($coursecontext, $USER)) {
3057 // Ok, no need to mess with enrol.
3058 $access = true;
3060 } else {
3061 if (isset($USER->enrol['enrolled'][$course->id])) {
3062 if ($USER->enrol['enrolled'][$course->id] > time()) {
3063 $access = true;
3064 if (isset($USER->enrol['tempguest'][$course->id])) {
3065 unset($USER->enrol['tempguest'][$course->id]);
3066 remove_temp_course_roles($coursecontext);
3068 } else {
3069 // Expired.
3070 unset($USER->enrol['enrolled'][$course->id]);
3073 if (isset($USER->enrol['tempguest'][$course->id])) {
3074 if ($USER->enrol['tempguest'][$course->id] == 0) {
3075 $access = true;
3076 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3077 $access = true;
3078 } else {
3079 // Expired.
3080 unset($USER->enrol['tempguest'][$course->id]);
3081 remove_temp_course_roles($coursecontext);
3085 if (!$access) {
3086 // Cache not ok.
3087 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3088 if ($until !== false) {
3089 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3090 if ($until == 0) {
3091 $until = ENROL_MAX_TIMESTAMP;
3093 $USER->enrol['enrolled'][$course->id] = $until;
3094 $access = true;
3096 } else {
3097 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3098 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3099 $enrols = enrol_get_plugins(true);
3100 // First ask all enabled enrol instances in course if they want to auto enrol user.
3101 foreach ($instances as $instance) {
3102 if (!isset($enrols[$instance->enrol])) {
3103 continue;
3105 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3106 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3107 if ($until !== false) {
3108 if ($until == 0) {
3109 $until = ENROL_MAX_TIMESTAMP;
3111 $USER->enrol['enrolled'][$course->id] = $until;
3112 $access = true;
3113 break;
3116 // If not enrolled yet try to gain temporary guest access.
3117 if (!$access) {
3118 foreach ($instances as $instance) {
3119 if (!isset($enrols[$instance->enrol])) {
3120 continue;
3122 // Get a duration for the guest access, a timestamp in the future or false.
3123 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3124 if ($until !== false and $until > time()) {
3125 $USER->enrol['tempguest'][$course->id] = $until;
3126 $access = true;
3127 break;
3135 if (!$access) {
3136 if ($preventredirect) {
3137 throw new require_login_exception('Not enrolled');
3139 if ($setwantsurltome) {
3140 $SESSION->wantsurl = qualified_me();
3142 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3146 // Set the global $COURSE.
3147 // TODO MDL-49434: setting current course/cm should be after the check $cm->uservisible .
3148 if ($cm) {
3149 $PAGE->set_cm($cm, $course);
3150 $PAGE->set_pagelayout('incourse');
3151 } else if (!empty($courseorid)) {
3152 $PAGE->set_course($course);
3155 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3156 if ($cm && !$cm->uservisible) {
3157 if ($preventredirect) {
3158 throw new require_login_exception('Activity is hidden');
3160 if ($course->id != SITEID) {
3161 $url = new moodle_url('/course/view.php', array('id' => $course->id));
3162 } else {
3163 $url = new moodle_url('/');
3165 redirect($url, get_string('activityiscurrentlyhidden'));
3168 // Finally access granted, update lastaccess times.
3169 user_accesstime_log($course->id);
3174 * This function just makes sure a user is logged out.
3176 * @package core_access
3177 * @category access
3179 function require_logout() {
3180 global $USER, $DB;
3182 if (!isloggedin()) {
3183 // This should not happen often, no need for hooks or events here.
3184 \core\session\manager::terminate_current();
3185 return;
3188 // Execute hooks before action.
3189 $authplugins = array();
3190 $authsequence = get_enabled_auth_plugins();
3191 foreach ($authsequence as $authname) {
3192 $authplugins[$authname] = get_auth_plugin($authname);
3193 $authplugins[$authname]->prelogout_hook();
3196 // Store info that gets removed during logout.
3197 $sid = session_id();
3198 $event = \core\event\user_loggedout::create(
3199 array(
3200 'userid' => $USER->id,
3201 'objectid' => $USER->id,
3202 'other' => array('sessionid' => $sid),
3205 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3206 $event->add_record_snapshot('sessions', $session);
3209 // Clone of $USER object to be used by auth plugins.
3210 $user = fullclone($USER);
3212 // Delete session record and drop $_SESSION content.
3213 \core\session\manager::terminate_current();
3215 // Trigger event AFTER action.
3216 $event->trigger();
3218 // Hook to execute auth plugins redirection after event trigger.
3219 foreach ($authplugins as $authplugin) {
3220 $authplugin->postlogout_hook($user);
3225 * Weaker version of require_login()
3227 * This is a weaker version of {@link require_login()} which only requires login
3228 * when called from within a course rather than the site page, unless
3229 * the forcelogin option is turned on.
3230 * @see require_login()
3232 * @package core_access
3233 * @category access
3235 * @param mixed $courseorid The course object or id in question
3236 * @param bool $autologinguest Allow autologin guests if that is wanted
3237 * @param object $cm Course activity module if known
3238 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3239 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3240 * in order to keep redirects working properly. MDL-14495
3241 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3242 * @return void
3243 * @throws coding_exception
3245 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3246 global $CFG, $PAGE, $SITE;
3247 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3248 or (!is_object($courseorid) and $courseorid == SITEID));
3249 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3250 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3251 // db queries so this is not really a performance concern, however it is obviously
3252 // better if you use get_fast_modinfo to get the cm before calling this.
3253 if (is_object($courseorid)) {
3254 $course = $courseorid;
3255 } else {
3256 $course = clone($SITE);
3258 $modinfo = get_fast_modinfo($course);
3259 $cm = $modinfo->get_cm($cm->id);
3261 if (!empty($CFG->forcelogin)) {
3262 // Login required for both SITE and courses.
3263 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3265 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3266 // Always login for hidden activities.
3267 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3269 } else if ($issite) {
3270 // Login for SITE not required.
3271 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3272 if (!empty($courseorid)) {
3273 if (is_object($courseorid)) {
3274 $course = $courseorid;
3275 } else {
3276 $course = clone $SITE;
3278 if ($cm) {
3279 if ($cm->course != $course->id) {
3280 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3282 $PAGE->set_cm($cm, $course);
3283 $PAGE->set_pagelayout('incourse');
3284 } else {
3285 $PAGE->set_course($course);
3287 } else {
3288 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3289 $PAGE->set_course($PAGE->course);
3291 user_accesstime_log(SITEID);
3292 return;
3294 } else {
3295 // Course login always required.
3296 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3301 * Require key login. Function terminates with error if key not found or incorrect.
3303 * @uses NO_MOODLE_COOKIES
3304 * @uses PARAM_ALPHANUM
3305 * @param string $script unique script identifier
3306 * @param int $instance optional instance id
3307 * @return int Instance ID
3309 function require_user_key_login($script, $instance=null) {
3310 global $DB;
3312 if (!NO_MOODLE_COOKIES) {
3313 print_error('sessioncookiesdisable');
3316 // Extra safety.
3317 \core\session\manager::write_close();
3319 $keyvalue = required_param('key', PARAM_ALPHANUM);
3321 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3322 print_error('invalidkey');
3325 if (!empty($key->validuntil) and $key->validuntil < time()) {
3326 print_error('expiredkey');
3329 if ($key->iprestriction) {
3330 $remoteaddr = getremoteaddr(null);
3331 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3332 print_error('ipmismatch');
3336 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3337 print_error('invaliduserid');
3340 // Emulate normal session.
3341 enrol_check_plugins($user);
3342 \core\session\manager::set_user($user);
3344 // Note we are not using normal login.
3345 if (!defined('USER_KEY_LOGIN')) {
3346 define('USER_KEY_LOGIN', true);
3349 // Return instance id - it might be empty.
3350 return $key->instance;
3354 * Creates a new private user access key.
3356 * @param string $script unique target identifier
3357 * @param int $userid
3358 * @param int $instance optional instance id
3359 * @param string $iprestriction optional ip restricted access
3360 * @param timestamp $validuntil key valid only until given data
3361 * @return string access key value
3363 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3364 global $DB;
3366 $key = new stdClass();
3367 $key->script = $script;
3368 $key->userid = $userid;
3369 $key->instance = $instance;
3370 $key->iprestriction = $iprestriction;
3371 $key->validuntil = $validuntil;
3372 $key->timecreated = time();
3374 // Something long and unique.
3375 $key->value = md5($userid.'_'.time().random_string(40));
3376 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3377 // Must be unique.
3378 $key->value = md5($userid.'_'.time().random_string(40));
3380 $DB->insert_record('user_private_key', $key);
3381 return $key->value;
3385 * Delete the user's new private user access keys for a particular script.
3387 * @param string $script unique target identifier
3388 * @param int $userid
3389 * @return void
3391 function delete_user_key($script, $userid) {
3392 global $DB;
3393 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3397 * Gets a private user access key (and creates one if one doesn't exist).
3399 * @param string $script unique target identifier
3400 * @param int $userid
3401 * @param int $instance optional instance id
3402 * @param string $iprestriction optional ip restricted access
3403 * @param timestamp $validuntil key valid only until given data
3404 * @return string access key value
3406 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3407 global $DB;
3409 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3410 'instance' => $instance, 'iprestriction' => $iprestriction,
3411 'validuntil' => $validuntil))) {
3412 return $key->value;
3413 } else {
3414 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3420 * Modify the user table by setting the currently logged in user's last login to now.
3422 * @return bool Always returns true
3424 function update_user_login_times() {
3425 global $USER, $DB;
3427 if (isguestuser()) {
3428 // Do not update guest access times/ips for performance.
3429 return true;
3432 $now = time();
3434 $user = new stdClass();
3435 $user->id = $USER->id;
3437 // Make sure all users that logged in have some firstaccess.
3438 if ($USER->firstaccess == 0) {
3439 $USER->firstaccess = $user->firstaccess = $now;
3442 // Store the previous current as lastlogin.
3443 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3445 $USER->currentlogin = $user->currentlogin = $now;
3447 // Function user_accesstime_log() may not update immediately, better do it here.
3448 $USER->lastaccess = $user->lastaccess = $now;
3449 $USER->lastip = $user->lastip = getremoteaddr();
3451 // Note: do not call user_update_user() here because this is part of the login process,
3452 // the login event means that these fields were updated.
3453 $DB->update_record('user', $user);
3454 return true;
3458 * Determines if a user has completed setting up their account.
3460 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3461 * @return bool
3463 function user_not_fully_set_up($user) {
3464 if (isguestuser($user)) {
3465 return false;
3467 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3471 * Check whether the user has exceeded the bounce threshold
3473 * @param stdClass $user A {@link $USER} object
3474 * @return bool true => User has exceeded bounce threshold
3476 function over_bounce_threshold($user) {
3477 global $CFG, $DB;
3479 if (empty($CFG->handlebounces)) {
3480 return false;
3483 if (empty($user->id)) {
3484 // No real (DB) user, nothing to do here.
3485 return false;
3488 // Set sensible defaults.
3489 if (empty($CFG->minbounces)) {
3490 $CFG->minbounces = 10;
3492 if (empty($CFG->bounceratio)) {
3493 $CFG->bounceratio = .20;
3495 $bouncecount = 0;
3496 $sendcount = 0;
3497 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3498 $bouncecount = $bounce->value;
3500 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3501 $sendcount = $send->value;
3503 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3507 * Used to increment or reset email sent count
3509 * @param stdClass $user object containing an id
3510 * @param bool $reset will reset the count to 0
3511 * @return void
3513 function set_send_count($user, $reset=false) {
3514 global $DB;
3516 if (empty($user->id)) {
3517 // No real (DB) user, nothing to do here.
3518 return;
3521 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3522 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3523 $DB->update_record('user_preferences', $pref);
3524 } else if (!empty($reset)) {
3525 // If it's not there and we're resetting, don't bother. Make a new one.
3526 $pref = new stdClass();
3527 $pref->name = 'email_send_count';
3528 $pref->value = 1;
3529 $pref->userid = $user->id;
3530 $DB->insert_record('user_preferences', $pref, false);
3535 * Increment or reset user's email bounce count
3537 * @param stdClass $user object containing an id
3538 * @param bool $reset will reset the count to 0
3540 function set_bounce_count($user, $reset=false) {
3541 global $DB;
3543 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3544 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3545 $DB->update_record('user_preferences', $pref);
3546 } else if (!empty($reset)) {
3547 // If it's not there and we're resetting, don't bother. Make a new one.
3548 $pref = new stdClass();
3549 $pref->name = 'email_bounce_count';
3550 $pref->value = 1;
3551 $pref->userid = $user->id;
3552 $DB->insert_record('user_preferences', $pref, false);
3557 * Determines if the logged in user is currently moving an activity
3559 * @param int $courseid The id of the course being tested
3560 * @return bool
3562 function ismoving($courseid) {
3563 global $USER;
3565 if (!empty($USER->activitycopy)) {
3566 return ($USER->activitycopycourse == $courseid);
3568 return false;
3572 * Returns a persons full name
3574 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3575 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3576 * specify one.
3578 * @param stdClass $user A {@link $USER} object to get full name of.
3579 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3580 * @return string
3582 function fullname($user, $override=false) {
3583 global $CFG, $SESSION;
3585 if (!isset($user->firstname) and !isset($user->lastname)) {
3586 return '';
3589 // Get all of the name fields.
3590 $allnames = get_all_user_name_fields();
3591 if ($CFG->debugdeveloper) {
3592 foreach ($allnames as $allname) {
3593 if (!array_key_exists($allname, $user)) {
3594 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3595 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3596 // Message has been sent, no point in sending the message multiple times.
3597 break;
3602 if (!$override) {
3603 if (!empty($CFG->forcefirstname)) {
3604 $user->firstname = $CFG->forcefirstname;
3606 if (!empty($CFG->forcelastname)) {
3607 $user->lastname = $CFG->forcelastname;
3611 if (!empty($SESSION->fullnamedisplay)) {
3612 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3615 $template = null;
3616 // If the fullnamedisplay setting is available, set the template to that.
3617 if (isset($CFG->fullnamedisplay)) {
3618 $template = $CFG->fullnamedisplay;
3620 // If the template is empty, or set to language, return the language string.
3621 if ((empty($template) || $template == 'language') && !$override) {
3622 return get_string('fullnamedisplay', null, $user);
3625 // Check to see if we are displaying according to the alternative full name format.
3626 if ($override) {
3627 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3628 // Default to show just the user names according to the fullnamedisplay string.
3629 return get_string('fullnamedisplay', null, $user);
3630 } else {
3631 // If the override is true, then change the template to use the complete name.
3632 $template = $CFG->alternativefullnameformat;
3636 $requirednames = array();
3637 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3638 foreach ($allnames as $allname) {
3639 if (strpos($template, $allname) !== false) {
3640 $requirednames[] = $allname;
3644 $displayname = $template;
3645 // Switch in the actual data into the template.
3646 foreach ($requirednames as $altname) {
3647 if (isset($user->$altname)) {
3648 // Using empty() on the below if statement causes breakages.
3649 if ((string)$user->$altname == '') {
3650 $displayname = str_replace($altname, 'EMPTY', $displayname);
3651 } else {
3652 $displayname = str_replace($altname, $user->$altname, $displayname);
3654 } else {
3655 $displayname = str_replace($altname, 'EMPTY', $displayname);
3658 // Tidy up any misc. characters (Not perfect, but gets most characters).
3659 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3660 // katakana and parenthesis.
3661 $patterns = array();
3662 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3663 // filled in by a user.
3664 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3665 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3666 // This regular expression is to remove any double spaces in the display name.
3667 $patterns[] = '/\s{2,}/u';
3668 foreach ($patterns as $pattern) {
3669 $displayname = preg_replace($pattern, ' ', $displayname);
3672 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3673 $displayname = trim($displayname);
3674 if (empty($displayname)) {
3675 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3676 // people in general feel is a good setting to fall back on.
3677 $displayname = $user->firstname;
3679 return $displayname;
3683 * A centralised location for the all name fields. Returns an array / sql string snippet.
3685 * @param bool $returnsql True for an sql select field snippet.
3686 * @param string $tableprefix table query prefix to use in front of each field.
3687 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3688 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3689 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3690 * @return array|string All name fields.
3692 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3693 // This array is provided in this order because when called by fullname() (above) if firstname is before
3694 // firstnamephonetic str_replace() will change the wrong placeholder.
3695 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3696 'lastnamephonetic' => 'lastnamephonetic',
3697 'middlename' => 'middlename',
3698 'alternatename' => 'alternatename',
3699 'firstname' => 'firstname',
3700 'lastname' => 'lastname');
3702 // Let's add a prefix to the array of user name fields if provided.
3703 if ($prefix) {
3704 foreach ($alternatenames as $key => $altname) {
3705 $alternatenames[$key] = $prefix . $altname;
3709 // If we want the end result to have firstname and lastname at the front / top of the result.
3710 if ($order) {
3711 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3712 for ($i = 0; $i < 2; $i++) {
3713 // Get the last element.
3714 $lastelement = end($alternatenames);
3715 // Remove it from the array.
3716 unset($alternatenames[$lastelement]);
3717 // Put the element back on the top of the array.
3718 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3722 // Create an sql field snippet if requested.
3723 if ($returnsql) {
3724 if ($tableprefix) {
3725 if ($fieldprefix) {
3726 foreach ($alternatenames as $key => $altname) {
3727 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3729 } else {
3730 foreach ($alternatenames as $key => $altname) {
3731 $alternatenames[$key] = $tableprefix . '.' . $altname;
3735 $alternatenames = implode(',', $alternatenames);
3737 return $alternatenames;
3741 * Reduces lines of duplicated code for getting user name fields.
3743 * See also {@link user_picture::unalias()}
3745 * @param object $addtoobject Object to add user name fields to.
3746 * @param object $secondobject Object that contains user name field information.
3747 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3748 * @param array $additionalfields Additional fields to be matched with data in the second object.
3749 * The key can be set to the user table field name.
3750 * @return object User name fields.
3752 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3753 $fields = get_all_user_name_fields(false, null, $prefix);
3754 if ($additionalfields) {
3755 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3756 // the key is a number and then sets the key to the array value.
3757 foreach ($additionalfields as $key => $value) {
3758 if (is_numeric($key)) {
3759 $additionalfields[$value] = $prefix . $value;
3760 unset($additionalfields[$key]);
3761 } else {
3762 $additionalfields[$key] = $prefix . $value;
3765 $fields = array_merge($fields, $additionalfields);
3767 foreach ($fields as $key => $field) {
3768 // Important that we have all of the user name fields present in the object that we are sending back.
3769 $addtoobject->$key = '';
3770 if (isset($secondobject->$field)) {
3771 $addtoobject->$key = $secondobject->$field;
3774 return $addtoobject;
3778 * Returns an array of values in order of occurance in a provided string.
3779 * The key in the result is the character postion in the string.
3781 * @param array $values Values to be found in the string format
3782 * @param string $stringformat The string which may contain values being searched for.
3783 * @return array An array of values in order according to placement in the string format.
3785 function order_in_string($values, $stringformat) {
3786 $valuearray = array();
3787 foreach ($values as $value) {
3788 $pattern = "/$value\b/";
3789 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3790 if (preg_match($pattern, $stringformat)) {
3791 $replacement = "thing";
3792 // Replace the value with something more unique to ensure we get the right position when using strpos().
3793 $newformat = preg_replace($pattern, $replacement, $stringformat);
3794 $position = strpos($newformat, $replacement);
3795 $valuearray[$position] = $value;
3798 ksort($valuearray);
3799 return $valuearray;
3803 * Checks if current user is shown any extra fields when listing users.
3805 * @param object $context Context
3806 * @param array $already Array of fields that we're going to show anyway
3807 * so don't bother listing them
3808 * @return array Array of field names from user table, not including anything
3809 * listed in $already
3811 function get_extra_user_fields($context, $already = array()) {
3812 global $CFG;
3814 // Only users with permission get the extra fields.
3815 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3816 return array();
3819 // Split showuseridentity on comma.
3820 if (empty($CFG->showuseridentity)) {
3821 // Explode gives wrong result with empty string.
3822 $extra = array();
3823 } else {
3824 $extra = explode(',', $CFG->showuseridentity);
3826 $renumber = false;
3827 foreach ($extra as $key => $field) {
3828 if (in_array($field, $already)) {
3829 unset($extra[$key]);
3830 $renumber = true;
3833 if ($renumber) {
3834 // For consistency, if entries are removed from array, renumber it
3835 // so they are numbered as you would expect.
3836 $extra = array_merge($extra);
3838 return $extra;
3842 * If the current user is to be shown extra user fields when listing or
3843 * selecting users, returns a string suitable for including in an SQL select
3844 * clause to retrieve those fields.
3846 * @param context $context Context
3847 * @param string $alias Alias of user table, e.g. 'u' (default none)
3848 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3849 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3850 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3852 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3853 $fields = get_extra_user_fields($context, $already);
3854 $result = '';
3855 // Add punctuation for alias.
3856 if ($alias !== '') {
3857 $alias .= '.';
3859 foreach ($fields as $field) {
3860 $result .= ', ' . $alias . $field;
3861 if ($prefix) {
3862 $result .= ' AS ' . $prefix . $field;
3865 return $result;
3869 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3870 * @param string $field Field name, e.g. 'phone1'
3871 * @return string Text description taken from language file, e.g. 'Phone number'
3873 function get_user_field_name($field) {
3874 // Some fields have language strings which are not the same as field name.
3875 switch ($field) {
3876 case 'phone1' : {
3877 return get_string('phone');
3879 case 'url' : {
3880 return get_string('webpage');
3882 case 'icq' : {
3883 return get_string('icqnumber');
3885 case 'skype' : {
3886 return get_string('skypeid');
3888 case 'aim' : {
3889 return get_string('aimid');
3891 case 'yahoo' : {
3892 return get_string('yahooid');
3894 case 'msn' : {
3895 return get_string('msnid');
3898 // Otherwise just use the same lang string.
3899 return get_string($field);
3903 * Returns whether a given authentication plugin exists.
3905 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3906 * @return boolean Whether the plugin is available.
3908 function exists_auth_plugin($auth) {
3909 global $CFG;
3911 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3912 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3914 return false;
3918 * Checks if a given plugin is in the list of enabled authentication plugins.
3920 * @param string $auth Authentication plugin.
3921 * @return boolean Whether the plugin is enabled.
3923 function is_enabled_auth($auth) {
3924 if (empty($auth)) {
3925 return false;
3928 $enabled = get_enabled_auth_plugins();
3930 return in_array($auth, $enabled);
3934 * Returns an authentication plugin instance.
3936 * @param string $auth name of authentication plugin
3937 * @return auth_plugin_base An instance of the required authentication plugin.
3939 function get_auth_plugin($auth) {
3940 global $CFG;
3942 // Check the plugin exists first.
3943 if (! exists_auth_plugin($auth)) {
3944 print_error('authpluginnotfound', 'debug', '', $auth);
3947 // Return auth plugin instance.
3948 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3949 $class = "auth_plugin_$auth";
3950 return new $class;
3954 * Returns array of active auth plugins.
3956 * @param bool $fix fix $CFG->auth if needed
3957 * @return array
3959 function get_enabled_auth_plugins($fix=false) {
3960 global $CFG;
3962 $default = array('manual', 'nologin');
3964 if (empty($CFG->auth)) {
3965 $auths = array();
3966 } else {
3967 $auths = explode(',', $CFG->auth);
3970 if ($fix) {
3971 $auths = array_unique($auths);
3972 foreach ($auths as $k => $authname) {
3973 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3974 unset($auths[$k]);
3977 $newconfig = implode(',', $auths);
3978 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3979 set_config('auth', $newconfig);
3983 return (array_merge($default, $auths));
3987 * Returns true if an internal authentication method is being used.
3988 * if method not specified then, global default is assumed
3990 * @param string $auth Form of authentication required
3991 * @return bool
3993 function is_internal_auth($auth) {
3994 // Throws error if bad $auth.
3995 $authplugin = get_auth_plugin($auth);
3996 return $authplugin->is_internal();
4000 * Returns true if the user is a 'restored' one.
4002 * Used in the login process to inform the user and allow him/her to reset the password
4004 * @param string $username username to be checked
4005 * @return bool
4007 function is_restored_user($username) {
4008 global $CFG, $DB;
4010 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
4014 * Returns an array of user fields
4016 * @return array User field/column names
4018 function get_user_fieldnames() {
4019 global $DB;
4021 $fieldarray = $DB->get_columns('user');
4022 unset($fieldarray['id']);
4023 $fieldarray = array_keys($fieldarray);
4025 return $fieldarray;
4029 * Creates a bare-bones user record
4031 * @todo Outline auth types and provide code example
4033 * @param string $username New user's username to add to record
4034 * @param string $password New user's password to add to record
4035 * @param string $auth Form of authentication required
4036 * @return stdClass A complete user object
4038 function create_user_record($username, $password, $auth = 'manual') {
4039 global $CFG, $DB;
4040 require_once($CFG->dirroot.'/user/profile/lib.php');
4041 require_once($CFG->dirroot.'/user/lib.php');
4043 // Just in case check text case.
4044 $username = trim(core_text::strtolower($username));
4046 $authplugin = get_auth_plugin($auth);
4047 $customfields = $authplugin->get_custom_user_profile_fields();
4048 $newuser = new stdClass();
4049 if ($newinfo = $authplugin->get_userinfo($username)) {
4050 $newinfo = truncate_userinfo($newinfo);
4051 foreach ($newinfo as $key => $value) {
4052 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
4053 $newuser->$key = $value;
4058 if (!empty($newuser->email)) {
4059 if (email_is_not_allowed($newuser->email)) {
4060 unset($newuser->email);
4064 if (!isset($newuser->city)) {
4065 $newuser->city = '';
4068 $newuser->auth = $auth;
4069 $newuser->username = $username;
4071 // Fix for MDL-8480
4072 // user CFG lang for user if $newuser->lang is empty
4073 // or $user->lang is not an installed language.
4074 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
4075 $newuser->lang = $CFG->lang;
4077 $newuser->confirmed = 1;
4078 $newuser->lastip = getremoteaddr();
4079 $newuser->timecreated = time();
4080 $newuser->timemodified = $newuser->timecreated;
4081 $newuser->mnethostid = $CFG->mnet_localhost_id;
4083 $newuser->id = user_create_user($newuser, false, false);
4085 // Save user profile data.
4086 profile_save_data($newuser);
4088 $user = get_complete_user_data('id', $newuser->id);
4089 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
4090 set_user_preference('auth_forcepasswordchange', 1, $user);
4092 // Set the password.
4093 update_internal_user_password($user, $password);
4095 // Trigger event.
4096 \core\event\user_created::create_from_userid($newuser->id)->trigger();
4098 return $user;
4102 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4104 * @param string $username user's username to update the record
4105 * @return stdClass A complete user object
4107 function update_user_record($username) {
4108 global $DB, $CFG;
4109 // Just in case check text case.
4110 $username = trim(core_text::strtolower($username));
4112 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
4113 return update_user_record_by_id($oldinfo->id);
4117 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4119 * @param int $id user id
4120 * @return stdClass A complete user object
4122 function update_user_record_by_id($id) {
4123 global $DB, $CFG;
4124 require_once($CFG->dirroot."/user/profile/lib.php");
4125 require_once($CFG->dirroot.'/user/lib.php');
4127 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
4128 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
4130 $newuser = array();
4131 $userauth = get_auth_plugin($oldinfo->auth);
4133 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
4134 $newinfo = truncate_userinfo($newinfo);
4135 $customfields = $userauth->get_custom_user_profile_fields();
4137 foreach ($newinfo as $key => $value) {
4138 $key = strtolower($key);
4139 $iscustom = in_array($key, $customfields);
4140 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4141 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4142 // Unknown or must not be changed.
4143 continue;
4145 $confval = $userauth->config->{'field_updatelocal_' . $key};
4146 $lockval = $userauth->config->{'field_lock_' . $key};
4147 if (empty($confval) || empty($lockval)) {
4148 continue;
4150 if ($confval === 'onlogin') {
4151 // MDL-4207 Don't overwrite modified user profile values with
4152 // empty LDAP values when 'unlocked if empty' is set. The purpose
4153 // of the setting 'unlocked if empty' is to allow the user to fill
4154 // in a value for the selected field _if LDAP is giving
4155 // nothing_ for this field. Thus it makes sense to let this value
4156 // stand in until LDAP is giving a value for this field.
4157 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4158 if ($iscustom || (in_array($key, $userauth->userfields) &&
4159 ((string)$oldinfo->$key !== (string)$value))) {
4160 $newuser[$key] = (string)$value;
4165 if ($newuser) {
4166 $newuser['id'] = $oldinfo->id;
4167 $newuser['timemodified'] = time();
4168 user_update_user((object) $newuser, false, false);
4170 // Save user profile data.
4171 profile_save_data((object) $newuser);
4173 // Trigger event.
4174 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4178 return get_complete_user_data('id', $oldinfo->id);
4182 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4184 * @param array $info Array of user properties to truncate if needed
4185 * @return array The now truncated information that was passed in
4187 function truncate_userinfo(array $info) {
4188 // Define the limits.
4189 $limit = array(
4190 'username' => 100,
4191 'idnumber' => 255,
4192 'firstname' => 100,
4193 'lastname' => 100,
4194 'email' => 100,
4195 'icq' => 15,
4196 'phone1' => 20,
4197 'phone2' => 20,
4198 'institution' => 255,
4199 'department' => 255,
4200 'address' => 255,
4201 'city' => 120,
4202 'country' => 2,
4203 'url' => 255,
4206 // Apply where needed.
4207 foreach (array_keys($info) as $key) {
4208 if (!empty($limit[$key])) {
4209 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4213 return $info;
4217 * Marks user deleted in internal user database and notifies the auth plugin.
4218 * Also unenrols user from all roles and does other cleanup.
4220 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4222 * @param stdClass $user full user object before delete
4223 * @return boolean success
4224 * @throws coding_exception if invalid $user parameter detected
4226 function delete_user(stdClass $user) {
4227 global $CFG, $DB;
4228 require_once($CFG->libdir.'/grouplib.php');
4229 require_once($CFG->libdir.'/gradelib.php');
4230 require_once($CFG->dirroot.'/message/lib.php');
4231 require_once($CFG->dirroot.'/tag/lib.php');
4232 require_once($CFG->dirroot.'/user/lib.php');
4234 // Make sure nobody sends bogus record type as parameter.
4235 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4236 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4239 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4240 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4241 debugging('Attempt to delete unknown user account.');
4242 return false;
4245 // There must be always exactly one guest record, originally the guest account was identified by username only,
4246 // now we use $CFG->siteguest for performance reasons.
4247 if ($user->username === 'guest' or isguestuser($user)) {
4248 debugging('Guest user account can not be deleted.');
4249 return false;
4252 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4253 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4254 if ($user->auth === 'manual' and is_siteadmin($user)) {
4255 debugging('Local administrator accounts can not be deleted.');
4256 return false;
4259 // Keep user record before updating it, as we have to pass this to user_deleted event.
4260 $olduser = clone $user;
4262 // Keep a copy of user context, we need it for event.
4263 $usercontext = context_user::instance($user->id);
4265 // Delete all grades - backup is kept in grade_grades_history table.
4266 grade_user_delete($user->id);
4268 // Move unread messages from this user to read.
4269 message_move_userfrom_unread2read($user->id);
4271 // TODO: remove from cohorts using standard API here.
4273 // Remove user tags.
4274 tag_set('user', $user->id, array(), 'core', $usercontext->id);
4276 // Unconditionally unenrol from all courses.
4277 enrol_user_delete($user);
4279 // Unenrol from all roles in all contexts.
4280 // This might be slow but it is really needed - modules might do some extra cleanup!
4281 role_unassign_all(array('userid' => $user->id));
4283 // Now do a brute force cleanup.
4285 // Remove from all cohorts.
4286 $DB->delete_records('cohort_members', array('userid' => $user->id));
4288 // Remove from all groups.
4289 $DB->delete_records('groups_members', array('userid' => $user->id));
4291 // Brute force unenrol from all courses.
4292 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4294 // Purge user preferences.
4295 $DB->delete_records('user_preferences', array('userid' => $user->id));
4297 // Purge user extra profile info.
4298 $DB->delete_records('user_info_data', array('userid' => $user->id));
4300 // Last course access not necessary either.
4301 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4302 // Remove all user tokens.
4303 $DB->delete_records('external_tokens', array('userid' => $user->id));
4305 // Unauthorise the user for all services.
4306 $DB->delete_records('external_services_users', array('userid' => $user->id));
4308 // Remove users private keys.
4309 $DB->delete_records('user_private_key', array('userid' => $user->id));
4311 // Remove users customised pages.
4312 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4314 // Force logout - may fail if file based sessions used, sorry.
4315 \core\session\manager::kill_user_sessions($user->id);
4317 // Workaround for bulk deletes of users with the same email address.
4318 $delname = clean_param($user->email . "." . time(), PARAM_USERNAME);
4319 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4320 $delname++;
4323 // Mark internal user record as "deleted".
4324 $updateuser = new stdClass();
4325 $updateuser->id = $user->id;
4326 $updateuser->deleted = 1;
4327 $updateuser->username = $delname; // Remember it just in case.
4328 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4329 $updateuser->idnumber = ''; // Clear this field to free it up.
4330 $updateuser->picture = 0;
4331 $updateuser->timemodified = time();
4333 // Don't trigger update event, as user is being deleted.
4334 user_update_user($updateuser, false, false);
4336 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4337 context_helper::delete_instance(CONTEXT_USER, $user->id);
4339 // Any plugin that needs to cleanup should register this event.
4340 // Trigger event.
4341 $event = \core\event\user_deleted::create(
4342 array(
4343 'objectid' => $user->id,
4344 'relateduserid' => $user->id,
4345 'context' => $usercontext,
4346 'other' => array(
4347 'username' => $user->username,
4348 'email' => $user->email,
4349 'idnumber' => $user->idnumber,
4350 'picture' => $user->picture,
4351 'mnethostid' => $user->mnethostid
4355 $event->add_record_snapshot('user', $olduser);
4356 $event->trigger();
4358 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4359 // should know about this updated property persisted to the user's table.
4360 $user->timemodified = $updateuser->timemodified;
4362 // Notify auth plugin - do not block the delete even when plugin fails.
4363 $authplugin = get_auth_plugin($user->auth);
4364 $authplugin->user_delete($user);
4366 return true;
4370 * Retrieve the guest user object.
4372 * @return stdClass A {@link $USER} object
4374 function guest_user() {
4375 global $CFG, $DB;
4377 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4378 $newuser->confirmed = 1;
4379 $newuser->lang = $CFG->lang;
4380 $newuser->lastip = getremoteaddr();
4383 return $newuser;
4387 * Authenticates a user against the chosen authentication mechanism
4389 * Given a username and password, this function looks them
4390 * up using the currently selected authentication mechanism,
4391 * and if the authentication is successful, it returns a
4392 * valid $user object from the 'user' table.
4394 * Uses auth_ functions from the currently active auth module
4396 * After authenticate_user_login() returns success, you will need to
4397 * log that the user has logged in, and call complete_user_login() to set
4398 * the session up.
4400 * Note: this function works only with non-mnet accounts!
4402 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4403 * @param string $password User's password
4404 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4405 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4406 * @return stdClass|false A {@link $USER} object or false if error
4408 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4409 global $CFG, $DB;
4410 require_once("$CFG->libdir/authlib.php");
4412 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4413 // we have found the user
4415 } else if (!empty($CFG->authloginviaemail)) {
4416 if ($email = clean_param($username, PARAM_EMAIL)) {
4417 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4418 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4419 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4420 if (count($users) === 1) {
4421 // Use email for login only if unique.
4422 $user = reset($users);
4423 $user = get_complete_user_data('id', $user->id);
4424 $username = $user->username;
4426 unset($users);
4430 $authsenabled = get_enabled_auth_plugins();
4432 if ($user) {
4433 // Use manual if auth not set.
4434 $auth = empty($user->auth) ? 'manual' : $user->auth;
4435 if (!empty($user->suspended)) {
4436 $failurereason = AUTH_LOGIN_SUSPENDED;
4438 // Trigger login failed event.
4439 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4440 'other' => array('username' => $username, 'reason' => $failurereason)));
4441 $event->trigger();
4442 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4443 return false;
4445 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4446 // Legacy way to suspend user.
4447 $failurereason = AUTH_LOGIN_SUSPENDED;
4449 // Trigger login failed event.
4450 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4451 'other' => array('username' => $username, 'reason' => $failurereason)));
4452 $event->trigger();
4453 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4454 return false;
4456 $auths = array($auth);
4458 } else {
4459 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4460 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4461 $failurereason = AUTH_LOGIN_NOUSER;
4463 // Trigger login failed event.
4464 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4465 'reason' => $failurereason)));
4466 $event->trigger();
4467 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4468 return false;
4471 // User does not exist.
4472 $auths = $authsenabled;
4473 $user = new stdClass();
4474 $user->id = 0;
4477 if ($ignorelockout) {
4478 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4479 // or this function is called from a SSO script.
4480 } else if ($user->id) {
4481 // Verify login lockout after other ways that may prevent user login.
4482 if (login_is_lockedout($user)) {
4483 $failurereason = AUTH_LOGIN_LOCKOUT;
4485 // Trigger login failed event.
4486 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4487 'other' => array('username' => $username, 'reason' => $failurereason)));
4488 $event->trigger();
4490 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4491 return false;
4493 } else {
4494 // We can not lockout non-existing accounts.
4497 foreach ($auths as $auth) {
4498 $authplugin = get_auth_plugin($auth);
4500 // On auth fail fall through to the next plugin.
4501 if (!$authplugin->user_login($username, $password)) {
4502 continue;
4505 // Successful authentication.
4506 if ($user->id) {
4507 // User already exists in database.
4508 if (empty($user->auth)) {
4509 // For some reason auth isn't set yet.
4510 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4511 $user->auth = $auth;
4514 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4515 // the current hash algorithm while we have access to the user's password.
4516 update_internal_user_password($user, $password);
4518 if ($authplugin->is_synchronised_with_external()) {
4519 // Update user record from external DB.
4520 $user = update_user_record_by_id($user->id);
4522 } else {
4523 // The user is authenticated but user creation may be disabled.
4524 if (!empty($CFG->authpreventaccountcreation)) {
4525 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4527 // Trigger login failed event.
4528 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4529 'reason' => $failurereason)));
4530 $event->trigger();
4532 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4533 $_SERVER['HTTP_USER_AGENT']);
4534 return false;
4535 } else {
4536 $user = create_user_record($username, $password, $auth);
4540 $authplugin->sync_roles($user);
4542 foreach ($authsenabled as $hau) {
4543 $hauth = get_auth_plugin($hau);
4544 $hauth->user_authenticated_hook($user, $username, $password);
4547 if (empty($user->id)) {
4548 $failurereason = AUTH_LOGIN_NOUSER;
4549 // Trigger login failed event.
4550 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4551 'reason' => $failurereason)));
4552 $event->trigger();
4553 return false;
4556 if (!empty($user->suspended)) {
4557 // Just in case some auth plugin suspended account.
4558 $failurereason = AUTH_LOGIN_SUSPENDED;
4559 // Trigger login failed event.
4560 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4561 'other' => array('username' => $username, 'reason' => $failurereason)));
4562 $event->trigger();
4563 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4564 return false;
4567 login_attempt_valid($user);
4568 $failurereason = AUTH_LOGIN_OK;
4569 return $user;
4572 // Failed if all the plugins have failed.
4573 if (debugging('', DEBUG_ALL)) {
4574 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4577 if ($user->id) {
4578 login_attempt_failed($user);
4579 $failurereason = AUTH_LOGIN_FAILED;
4580 // Trigger login failed event.
4581 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4582 'other' => array('username' => $username, 'reason' => $failurereason)));
4583 $event->trigger();
4584 } else {
4585 $failurereason = AUTH_LOGIN_NOUSER;
4586 // Trigger login failed event.
4587 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4588 'reason' => $failurereason)));
4589 $event->trigger();
4592 return false;
4596 * Call to complete the user login process after authenticate_user_login()
4597 * has succeeded. It will setup the $USER variable and other required bits
4598 * and pieces.
4600 * NOTE:
4601 * - It will NOT log anything -- up to the caller to decide what to log.
4602 * - this function does not set any cookies any more!
4604 * @param stdClass $user
4605 * @return stdClass A {@link $USER} object - BC only, do not use
4607 function complete_user_login($user) {
4608 global $CFG, $USER;
4610 \core\session\manager::login_user($user);
4612 // Reload preferences from DB.
4613 unset($USER->preference);
4614 check_user_preferences_loaded($USER);
4616 // Update login times.
4617 update_user_login_times();
4619 // Extra session prefs init.
4620 set_login_session_preferences();
4622 // Trigger login event.
4623 $event = \core\event\user_loggedin::create(
4624 array(
4625 'userid' => $USER->id,
4626 'objectid' => $USER->id,
4627 'other' => array('username' => $USER->username),
4630 $event->trigger();
4632 if (isguestuser()) {
4633 // No need to continue when user is THE guest.
4634 return $USER;
4637 if (CLI_SCRIPT) {
4638 // We can redirect to password change URL only in browser.
4639 return $USER;
4642 // Select password change url.
4643 $userauth = get_auth_plugin($USER->auth);
4645 // Check whether the user should be changing password.
4646 if (get_user_preferences('auth_forcepasswordchange', false)) {
4647 if ($userauth->can_change_password()) {
4648 if ($changeurl = $userauth->change_password_url()) {
4649 redirect($changeurl);
4650 } else {
4651 redirect($CFG->httpswwwroot.'/login/change_password.php');
4653 } else {
4654 print_error('nopasswordchangeforced', 'auth');
4657 return $USER;
4661 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4663 * @param string $password String to check.
4664 * @return boolean True if the $password matches the format of an md5 sum.
4666 function password_is_legacy_hash($password) {
4667 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4671 * Compare password against hash stored in user object to determine if it is valid.
4673 * If necessary it also updates the stored hash to the current format.
4675 * @param stdClass $user (Password property may be updated).
4676 * @param string $password Plain text password.
4677 * @return bool True if password is valid.
4679 function validate_internal_user_password($user, $password) {
4680 global $CFG;
4681 require_once($CFG->libdir.'/password_compat/lib/password.php');
4683 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4684 // Internal password is not used at all, it can not validate.
4685 return false;
4688 // If hash isn't a legacy (md5) hash, validate using the library function.
4689 if (!password_is_legacy_hash($user->password)) {
4690 return password_verify($password, $user->password);
4693 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4694 // is valid we can then update it to the new algorithm.
4696 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4697 $validated = false;
4699 if ($user->password === md5($password.$sitesalt)
4700 or $user->password === md5($password)
4701 or $user->password === md5(addslashes($password).$sitesalt)
4702 or $user->password === md5(addslashes($password))) {
4703 // Note: we are intentionally using the addslashes() here because we
4704 // need to accept old password hashes of passwords with magic quotes.
4705 $validated = true;
4707 } else {
4708 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4709 $alt = 'passwordsaltalt'.$i;
4710 if (!empty($CFG->$alt)) {
4711 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4712 $validated = true;
4713 break;
4719 if ($validated) {
4720 // If the password matches the existing md5 hash, update to the
4721 // current hash algorithm while we have access to the user's password.
4722 update_internal_user_password($user, $password);
4725 return $validated;
4729 * Calculate hash for a plain text password.
4731 * @param string $password Plain text password to be hashed.
4732 * @param bool $fasthash If true, use a low cost factor when generating the hash
4733 * This is much faster to generate but makes the hash
4734 * less secure. It is used when lots of hashes need to
4735 * be generated quickly.
4736 * @return string The hashed password.
4738 * @throws moodle_exception If a problem occurs while generating the hash.
4740 function hash_internal_user_password($password, $fasthash = false) {
4741 global $CFG;
4742 require_once($CFG->libdir.'/password_compat/lib/password.php');
4744 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4745 $options = ($fasthash) ? array('cost' => 4) : array();
4747 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4749 if ($generatedhash === false || $generatedhash === null) {
4750 throw new moodle_exception('Failed to generate password hash.');
4753 return $generatedhash;
4757 * Update password hash in user object (if necessary).
4759 * The password is updated if:
4760 * 1. The password has changed (the hash of $user->password is different
4761 * to the hash of $password).
4762 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4763 * md5 algorithm).
4765 * Updating the password will modify the $user object and the database
4766 * record to use the current hashing algorithm.
4768 * @param stdClass $user User object (password property may be updated).
4769 * @param string $password Plain text password.
4770 * @param bool $fasthash If true, use a low cost factor when generating the hash
4771 * This is much faster to generate but makes the hash
4772 * less secure. It is used when lots of hashes need to
4773 * be generated quickly.
4774 * @return bool Always returns true.
4776 function update_internal_user_password($user, $password, $fasthash = false) {
4777 global $CFG, $DB;
4778 require_once($CFG->libdir.'/password_compat/lib/password.php');
4780 // Figure out what the hashed password should be.
4781 if (!isset($user->auth)) {
4782 debugging('User record in update_internal_user_password() must include field auth',
4783 DEBUG_DEVELOPER);
4784 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4786 $authplugin = get_auth_plugin($user->auth);
4787 if ($authplugin->prevent_local_passwords()) {
4788 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4789 } else {
4790 $hashedpassword = hash_internal_user_password($password, $fasthash);
4793 $algorithmchanged = false;
4795 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4796 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4797 $passwordchanged = ($user->password !== $hashedpassword);
4799 } else if (isset($user->password)) {
4800 // If verification fails then it means the password has changed.
4801 $passwordchanged = !password_verify($password, $user->password);
4802 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4803 } else {
4804 // While creating new user, password in unset in $user object, to avoid
4805 // saving it with user_create()
4806 $passwordchanged = true;
4809 if ($passwordchanged || $algorithmchanged) {
4810 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4811 $user->password = $hashedpassword;
4813 // Trigger event.
4814 $user = $DB->get_record('user', array('id' => $user->id));
4815 \core\event\user_password_updated::create_from_user($user)->trigger();
4818 return true;
4822 * Get a complete user record, which includes all the info in the user record.
4824 * Intended for setting as $USER session variable
4826 * @param string $field The user field to be checked for a given value.
4827 * @param string $value The value to match for $field.
4828 * @param int $mnethostid
4829 * @return mixed False, or A {@link $USER} object.
4831 function get_complete_user_data($field, $value, $mnethostid = null) {
4832 global $CFG, $DB;
4834 if (!$field || !$value) {
4835 return false;
4838 // Build the WHERE clause for an SQL query.
4839 $params = array('fieldval' => $value);
4840 $constraints = "$field = :fieldval AND deleted <> 1";
4842 // If we are loading user data based on anything other than id,
4843 // we must also restrict our search based on mnet host.
4844 if ($field != 'id') {
4845 if (empty($mnethostid)) {
4846 // If empty, we restrict to local users.
4847 $mnethostid = $CFG->mnet_localhost_id;
4850 if (!empty($mnethostid)) {
4851 $params['mnethostid'] = $mnethostid;
4852 $constraints .= " AND mnethostid = :mnethostid";
4855 // Get all the basic user data.
4856 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4857 return false;
4860 // Get various settings and preferences.
4862 // Preload preference cache.
4863 check_user_preferences_loaded($user);
4865 // Load course enrolment related stuff.
4866 $user->lastcourseaccess = array(); // During last session.
4867 $user->currentcourseaccess = array(); // During current session.
4868 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4869 foreach ($lastaccesses as $lastaccess) {
4870 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4874 $sql = "SELECT g.id, g.courseid
4875 FROM {groups} g, {groups_members} gm
4876 WHERE gm.groupid=g.id AND gm.userid=?";
4878 // This is a special hack to speedup calendar display.
4879 $user->groupmember = array();
4880 if (!isguestuser($user)) {
4881 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4882 foreach ($groups as $group) {
4883 if (!array_key_exists($group->courseid, $user->groupmember)) {
4884 $user->groupmember[$group->courseid] = array();
4886 $user->groupmember[$group->courseid][$group->id] = $group->id;
4891 // Add the custom profile fields to the user record.
4892 $user->profile = array();
4893 if (!isguestuser($user)) {
4894 require_once($CFG->dirroot.'/user/profile/lib.php');
4895 profile_load_custom_fields($user);
4898 // Rewrite some variables if necessary.
4899 if (!empty($user->description)) {
4900 // No need to cart all of it around.
4901 $user->description = true;
4903 if (isguestuser($user)) {
4904 // Guest language always same as site.
4905 $user->lang = $CFG->lang;
4906 // Name always in current language.
4907 $user->firstname = get_string('guestuser');
4908 $user->lastname = ' ';
4911 return $user;
4915 * Validate a password against the configured password policy
4917 * @param string $password the password to be checked against the password policy
4918 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4919 * @return bool true if the password is valid according to the policy. false otherwise.
4921 function check_password_policy($password, &$errmsg) {
4922 global $CFG;
4924 if (empty($CFG->passwordpolicy)) {
4925 return true;
4928 $errmsg = '';
4929 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4930 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4933 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4934 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4937 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4938 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4941 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4942 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4945 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4946 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4948 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4949 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4952 if ($errmsg == '') {
4953 return true;
4954 } else {
4955 return false;
4961 * When logging in, this function is run to set certain preferences for the current SESSION.
4963 function set_login_session_preferences() {
4964 global $SESSION;
4966 $SESSION->justloggedin = true;
4968 unset($SESSION->lang);
4969 unset($SESSION->forcelang);
4970 unset($SESSION->load_navigation_admin);
4975 * Delete a course, including all related data from the database, and any associated files.
4977 * @param mixed $courseorid The id of the course or course object to delete.
4978 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4979 * @return bool true if all the removals succeeded. false if there were any failures. If this
4980 * method returns false, some of the removals will probably have succeeded, and others
4981 * failed, but you have no way of knowing which.
4983 function delete_course($courseorid, $showfeedback = true) {
4984 global $DB;
4986 if (is_object($courseorid)) {
4987 $courseid = $courseorid->id;
4988 $course = $courseorid;
4989 } else {
4990 $courseid = $courseorid;
4991 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4992 return false;
4995 $context = context_course::instance($courseid);
4997 // Frontpage course can not be deleted!!
4998 if ($courseid == SITEID) {
4999 return false;
5002 // Make the course completely empty.
5003 remove_course_contents($courseid, $showfeedback);
5005 // Delete the course and related context instance.
5006 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5008 $DB->delete_records("course", array("id" => $courseid));
5009 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5011 // Reset all course related caches here.
5012 if (class_exists('format_base', false)) {
5013 format_base::reset_course_cache($courseid);
5016 // Trigger a course deleted event.
5017 $event = \core\event\course_deleted::create(array(
5018 'objectid' => $course->id,
5019 'context' => $context,
5020 'other' => array(
5021 'shortname' => $course->shortname,
5022 'fullname' => $course->fullname,
5023 'idnumber' => $course->idnumber
5026 $event->add_record_snapshot('course', $course);
5027 $event->trigger();
5029 return true;
5033 * Clear a course out completely, deleting all content but don't delete the course itself.
5035 * This function does not verify any permissions.
5037 * Please note this function also deletes all user enrolments,
5038 * enrolment instances and role assignments by default.
5040 * $options:
5041 * - 'keep_roles_and_enrolments' - false by default
5042 * - 'keep_groups_and_groupings' - false by default
5044 * @param int $courseid The id of the course that is being deleted
5045 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5046 * @param array $options extra options
5047 * @return bool true if all the removals succeeded. false if there were any failures. If this
5048 * method returns false, some of the removals will probably have succeeded, and others
5049 * failed, but you have no way of knowing which.
5051 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5052 global $CFG, $DB, $OUTPUT;
5054 require_once($CFG->libdir.'/badgeslib.php');
5055 require_once($CFG->libdir.'/completionlib.php');
5056 require_once($CFG->libdir.'/questionlib.php');
5057 require_once($CFG->libdir.'/gradelib.php');
5058 require_once($CFG->dirroot.'/group/lib.php');
5059 require_once($CFG->dirroot.'/tag/coursetagslib.php');
5060 require_once($CFG->dirroot.'/comment/lib.php');
5061 require_once($CFG->dirroot.'/rating/lib.php');
5062 require_once($CFG->dirroot.'/notes/lib.php');
5064 // Handle course badges.
5065 badges_handle_course_deletion($courseid);
5067 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5068 $strdeleted = get_string('deleted').' - ';
5070 // Some crazy wishlist of stuff we should skip during purging of course content.
5071 $options = (array)$options;
5073 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5074 $coursecontext = context_course::instance($courseid);
5075 $fs = get_file_storage();
5077 // Delete course completion information, this has to be done before grades and enrols.
5078 $cc = new completion_info($course);
5079 $cc->clear_criteria();
5080 if ($showfeedback) {
5081 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5084 // Remove all data from gradebook - this needs to be done before course modules
5085 // because while deleting this information, the system may need to reference
5086 // the course modules that own the grades.
5087 remove_course_grades($courseid, $showfeedback);
5088 remove_grade_letters($coursecontext, $showfeedback);
5090 // Delete course blocks in any all child contexts,
5091 // they may depend on modules so delete them first.
5092 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5093 foreach ($childcontexts as $childcontext) {
5094 blocks_delete_all_for_context($childcontext->id);
5096 unset($childcontexts);
5097 blocks_delete_all_for_context($coursecontext->id);
5098 if ($showfeedback) {
5099 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5102 // Delete every instance of every module,
5103 // this has to be done before deleting of course level stuff.
5104 $locations = core_component::get_plugin_list('mod');
5105 foreach ($locations as $modname => $moddir) {
5106 if ($modname === 'NEWMODULE') {
5107 continue;
5109 if ($module = $DB->get_record('modules', array('name' => $modname))) {
5110 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5111 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5112 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
5114 if ($instances = $DB->get_records($modname, array('course' => $course->id))) {
5115 foreach ($instances as $instance) {
5116 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
5117 // Delete activity context questions and question categories.
5118 question_delete_activity($cm, $showfeedback);
5120 if (function_exists($moddelete)) {
5121 // This purges all module data in related tables, extra user prefs, settings, etc.
5122 $moddelete($instance->id);
5123 } else {
5124 // NOTE: we should not allow installation of modules with missing delete support!
5125 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5126 $DB->delete_records($modname, array('id' => $instance->id));
5129 if ($cm) {
5130 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5131 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5132 $DB->delete_records('course_modules', array('id' => $cm->id));
5136 if (function_exists($moddeletecourse)) {
5137 // Execute ptional course cleanup callback.
5138 $moddeletecourse($course, $showfeedback);
5140 if ($instances and $showfeedback) {
5141 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5143 } else {
5144 // Ooops, this module is not properly installed, force-delete it in the next block.
5148 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5150 // Remove all data from availability and completion tables that is associated
5151 // with course-modules belonging to this course. Note this is done even if the
5152 // features are not enabled now, in case they were enabled previously.
5153 $DB->delete_records_select('course_modules_completion',
5154 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5155 array($courseid));
5157 // Remove course-module data.
5158 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5159 foreach ($cms as $cm) {
5160 if ($module = $DB->get_record('modules', array('id' => $cm->module))) {
5161 try {
5162 $DB->delete_records($module->name, array('id' => $cm->instance));
5163 } catch (Exception $e) {
5164 // Ignore weird or missing table problems.
5167 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5168 $DB->delete_records('course_modules', array('id' => $cm->id));
5171 if ($showfeedback) {
5172 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5175 // Cleanup the rest of plugins.
5176 $cleanuplugintypes = array('report', 'coursereport', 'format');
5177 foreach ($cleanuplugintypes as $type) {
5178 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
5179 foreach ($plugins as $plugin => $pluginfunction) {
5180 $pluginfunction($course->id, $showfeedback);
5182 if ($showfeedback) {
5183 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5187 // Delete questions and question categories.
5188 question_delete_course($course, $showfeedback);
5189 if ($showfeedback) {
5190 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5193 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5194 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5195 foreach ($childcontexts as $childcontext) {
5196 $childcontext->delete();
5198 unset($childcontexts);
5200 // Remove all roles and enrolments by default.
5201 if (empty($options['keep_roles_and_enrolments'])) {
5202 // This hack is used in restore when deleting contents of existing course.
5203 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5204 enrol_course_delete($course);
5205 if ($showfeedback) {
5206 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5210 // Delete any groups, removing members and grouping/course links first.
5211 if (empty($options['keep_groups_and_groupings'])) {
5212 groups_delete_groupings($course->id, $showfeedback);
5213 groups_delete_groups($course->id, $showfeedback);
5216 // Filters be gone!
5217 filter_delete_all_for_context($coursecontext->id);
5219 // Notes, you shall not pass!
5220 note_delete_all($course->id);
5222 // Die comments!
5223 comment::delete_comments($coursecontext->id);
5225 // Ratings are history too.
5226 $delopt = new stdclass();
5227 $delopt->contextid = $coursecontext->id;
5228 $rm = new rating_manager();
5229 $rm->delete_ratings($delopt);
5231 // Delete course tags.
5232 coursetag_delete_course_tags($course->id, $showfeedback);
5234 // Delete calendar events.
5235 $DB->delete_records('event', array('courseid' => $course->id));
5236 $fs->delete_area_files($coursecontext->id, 'calendar');
5238 // Delete all related records in other core tables that may have a courseid
5239 // This array stores the tables that need to be cleared, as
5240 // table_name => column_name that contains the course id.
5241 $tablestoclear = array(
5242 'backup_courses' => 'courseid', // Scheduled backup stuff.
5243 'user_lastaccess' => 'courseid', // User access info.
5245 foreach ($tablestoclear as $table => $col) {
5246 $DB->delete_records($table, array($col => $course->id));
5249 // Delete all course backup files.
5250 $fs->delete_area_files($coursecontext->id, 'backup');
5252 // Cleanup course record - remove links to deleted stuff.
5253 $oldcourse = new stdClass();
5254 $oldcourse->id = $course->id;
5255 $oldcourse->summary = '';
5256 $oldcourse->cacherev = 0;
5257 $oldcourse->legacyfiles = 0;
5258 $oldcourse->enablecompletion = 0;
5259 if (!empty($options['keep_groups_and_groupings'])) {
5260 $oldcourse->defaultgroupingid = 0;
5262 $DB->update_record('course', $oldcourse);
5264 // Delete course sections.
5265 $DB->delete_records('course_sections', array('course' => $course->id));
5267 // Delete legacy, section and any other course files.
5268 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5270 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5271 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5272 // Easy, do not delete the context itself...
5273 $coursecontext->delete_content();
5274 } else {
5275 // Hack alert!!!!
5276 // We can not drop all context stuff because it would bork enrolments and roles,
5277 // there might be also files used by enrol plugins...
5280 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5281 // also some non-standard unsupported plugins may try to store something there.
5282 fulldelete($CFG->dataroot.'/'.$course->id);
5284 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5285 $cachemodinfo = cache::make('core', 'coursemodinfo');
5286 $cachemodinfo->delete($courseid);
5288 // Trigger a course content deleted event.
5289 $event = \core\event\course_content_deleted::create(array(
5290 'objectid' => $course->id,
5291 'context' => $coursecontext,
5292 'other' => array('shortname' => $course->shortname,
5293 'fullname' => $course->fullname,
5294 'options' => $options) // Passing this for legacy reasons.
5296 $event->add_record_snapshot('course', $course);
5297 $event->trigger();
5299 return true;
5303 * Change dates in module - used from course reset.
5305 * @param string $modname forum, assignment, etc
5306 * @param array $fields array of date fields from mod table
5307 * @param int $timeshift time difference
5308 * @param int $courseid
5309 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5310 * @return bool success
5312 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5313 global $CFG, $DB;
5314 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5316 $return = true;
5317 $params = array($timeshift, $courseid);
5318 foreach ($fields as $field) {
5319 $updatesql = "UPDATE {".$modname."}
5320 SET $field = $field + ?
5321 WHERE course=? AND $field<>0";
5322 if ($modid) {
5323 $updatesql .= ' AND id=?';
5324 $params[] = $modid;
5326 $return = $DB->execute($updatesql, $params) && $return;
5329 $refreshfunction = $modname.'_refresh_events';
5330 if (function_exists($refreshfunction)) {
5331 $refreshfunction($courseid);
5334 return $return;
5338 * This function will empty a course of user data.
5339 * It will retain the activities and the structure of the course.
5341 * @param object $data an object containing all the settings including courseid (without magic quotes)
5342 * @return array status array of array component, item, error
5344 function reset_course_userdata($data) {
5345 global $CFG, $DB;
5346 require_once($CFG->libdir.'/gradelib.php');
5347 require_once($CFG->libdir.'/completionlib.php');
5348 require_once($CFG->dirroot.'/group/lib.php');
5350 $data->courseid = $data->id;
5351 $context = context_course::instance($data->courseid);
5353 $eventparams = array(
5354 'context' => $context,
5355 'courseid' => $data->id,
5356 'other' => array(
5357 'reset_options' => (array) $data
5360 $event = \core\event\course_reset_started::create($eventparams);
5361 $event->trigger();
5363 // Calculate the time shift of dates.
5364 if (!empty($data->reset_start_date)) {
5365 // Time part of course startdate should be zero.
5366 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5367 } else {
5368 $data->timeshift = 0;
5371 // Result array: component, item, error.
5372 $status = array();
5374 // Start the resetting.
5375 $componentstr = get_string('general');
5377 // Move the course start time.
5378 if (!empty($data->reset_start_date) and $data->timeshift) {
5379 // Change course start data.
5380 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5381 // Update all course and group events - do not move activity events.
5382 $updatesql = "UPDATE {event}
5383 SET timestart = timestart + ?
5384 WHERE courseid=? AND instance=0";
5385 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5387 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5390 if (!empty($data->reset_events)) {
5391 $DB->delete_records('event', array('courseid' => $data->courseid));
5392 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5395 if (!empty($data->reset_notes)) {
5396 require_once($CFG->dirroot.'/notes/lib.php');
5397 note_delete_all($data->courseid);
5398 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5401 if (!empty($data->delete_blog_associations)) {
5402 require_once($CFG->dirroot.'/blog/lib.php');
5403 blog_remove_associations_for_course($data->courseid);
5404 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5407 if (!empty($data->reset_completion)) {
5408 // Delete course and activity completion information.
5409 $course = $DB->get_record('course', array('id' => $data->courseid));
5410 $cc = new completion_info($course);
5411 $cc->delete_all_completion_data();
5412 $status[] = array('component' => $componentstr,
5413 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5416 $componentstr = get_string('roles');
5418 if (!empty($data->reset_roles_overrides)) {
5419 $children = $context->get_child_contexts();
5420 foreach ($children as $child) {
5421 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5423 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5424 // Force refresh for logged in users.
5425 $context->mark_dirty();
5426 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5429 if (!empty($data->reset_roles_local)) {
5430 $children = $context->get_child_contexts();
5431 foreach ($children as $child) {
5432 role_unassign_all(array('contextid' => $child->id));
5434 // Force refresh for logged in users.
5435 $context->mark_dirty();
5436 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5439 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5440 $data->unenrolled = array();
5441 if (!empty($data->unenrol_users)) {
5442 $plugins = enrol_get_plugins(true);
5443 $instances = enrol_get_instances($data->courseid, true);
5444 foreach ($instances as $key => $instance) {
5445 if (!isset($plugins[$instance->enrol])) {
5446 unset($instances[$key]);
5447 continue;
5451 foreach ($data->unenrol_users as $withroleid) {
5452 if ($withroleid) {
5453 $sql = "SELECT ue.*
5454 FROM {user_enrolments} ue
5455 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5456 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5457 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5458 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5460 } else {
5461 // Without any role assigned at course context.
5462 $sql = "SELECT ue.*
5463 FROM {user_enrolments} ue
5464 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5465 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5466 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5467 WHERE ra.id IS null";
5468 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5471 $rs = $DB->get_recordset_sql($sql, $params);
5472 foreach ($rs as $ue) {
5473 if (!isset($instances[$ue->enrolid])) {
5474 continue;
5476 $instance = $instances[$ue->enrolid];
5477 $plugin = $plugins[$instance->enrol];
5478 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5479 continue;
5482 $plugin->unenrol_user($instance, $ue->userid);
5483 $data->unenrolled[$ue->userid] = $ue->userid;
5485 $rs->close();
5488 if (!empty($data->unenrolled)) {
5489 $status[] = array(
5490 'component' => $componentstr,
5491 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5492 'error' => false
5496 $componentstr = get_string('groups');
5498 // Remove all group members.
5499 if (!empty($data->reset_groups_members)) {
5500 groups_delete_group_members($data->courseid);
5501 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5504 // Remove all groups.
5505 if (!empty($data->reset_groups_remove)) {
5506 groups_delete_groups($data->courseid, false);
5507 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5510 // Remove all grouping members.
5511 if (!empty($data->reset_groupings_members)) {
5512 groups_delete_groupings_groups($data->courseid, false);
5513 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5516 // Remove all groupings.
5517 if (!empty($data->reset_groupings_remove)) {
5518 groups_delete_groupings($data->courseid, false);
5519 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5522 // Look in every instance of every module for data to delete.
5523 $unsupportedmods = array();
5524 if ($allmods = $DB->get_records('modules') ) {
5525 foreach ($allmods as $mod) {
5526 $modname = $mod->name;
5527 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5528 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5529 if (file_exists($modfile)) {
5530 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5531 continue; // Skip mods with no instances.
5533 include_once($modfile);
5534 if (function_exists($moddeleteuserdata)) {
5535 $modstatus = $moddeleteuserdata($data);
5536 if (is_array($modstatus)) {
5537 $status = array_merge($status, $modstatus);
5538 } else {
5539 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5541 } else {
5542 $unsupportedmods[] = $mod;
5544 } else {
5545 debugging('Missing lib.php in '.$modname.' module!');
5550 // Mention unsupported mods.
5551 if (!empty($unsupportedmods)) {
5552 foreach ($unsupportedmods as $mod) {
5553 $status[] = array(
5554 'component' => get_string('modulenameplural', $mod->name),
5555 'item' => '',
5556 'error' => get_string('resetnotimplemented')
5561 $componentstr = get_string('gradebook', 'grades');
5562 // Reset gradebook,.
5563 if (!empty($data->reset_gradebook_items)) {
5564 remove_course_grades($data->courseid, false);
5565 grade_grab_course_grades($data->courseid);
5566 grade_regrade_final_grades($data->courseid);
5567 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5569 } else if (!empty($data->reset_gradebook_grades)) {
5570 grade_course_reset($data->courseid);
5571 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5573 // Reset comments.
5574 if (!empty($data->reset_comments)) {
5575 require_once($CFG->dirroot.'/comment/lib.php');
5576 comment::reset_course_page_comments($context);
5579 $event = \core\event\course_reset_ended::create($eventparams);
5580 $event->trigger();
5582 return $status;
5586 * Generate an email processing address.
5588 * @param int $modid
5589 * @param string $modargs
5590 * @return string Returns email processing address
5592 function generate_email_processing_address($modid, $modargs) {
5593 global $CFG;
5595 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5596 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5602 * @todo Finish documenting this function
5604 * @param string $modargs
5605 * @param string $body Currently unused
5607 function moodle_process_email($modargs, $body) {
5608 global $DB;
5610 // The first char should be an unencoded letter. We'll take this as an action.
5611 switch ($modargs{0}) {
5612 case 'B': { // Bounce.
5613 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5614 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5615 // Check the half md5 of their email.
5616 $md5check = substr(md5($user->email), 0, 16);
5617 if ($md5check == substr($modargs, -16)) {
5618 set_bounce_count($user);
5620 // Else maybe they've already changed it?
5623 break;
5624 // Maybe more later?
5628 // CORRESPONDENCE.
5631 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5633 * @param string $action 'get', 'buffer', 'close' or 'flush'
5634 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5636 function get_mailer($action='get') {
5637 global $CFG;
5639 /** @var moodle_phpmailer $mailer */
5640 static $mailer = null;
5641 static $counter = 0;
5643 if (!isset($CFG->smtpmaxbulk)) {
5644 $CFG->smtpmaxbulk = 1;
5647 if ($action == 'get') {
5648 $prevkeepalive = false;
5650 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5651 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5652 $counter++;
5653 // Reset the mailer.
5654 $mailer->Priority = 3;
5655 $mailer->CharSet = 'UTF-8'; // Our default.
5656 $mailer->ContentType = "text/plain";
5657 $mailer->Encoding = "8bit";
5658 $mailer->From = "root@localhost";
5659 $mailer->FromName = "Root User";
5660 $mailer->Sender = "";
5661 $mailer->Subject = "";
5662 $mailer->Body = "";
5663 $mailer->AltBody = "";
5664 $mailer->ConfirmReadingTo = "";
5666 $mailer->clearAllRecipients();
5667 $mailer->clearReplyTos();
5668 $mailer->clearAttachments();
5669 $mailer->clearCustomHeaders();
5670 return $mailer;
5673 $prevkeepalive = $mailer->SMTPKeepAlive;
5674 get_mailer('flush');
5677 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5678 $mailer = new moodle_phpmailer();
5680 $counter = 1;
5682 if ($CFG->smtphosts == 'qmail') {
5683 // Use Qmail system.
5684 $mailer->isQmail();
5686 } else if (empty($CFG->smtphosts)) {
5687 // Use PHP mail() = sendmail.
5688 $mailer->isMail();
5690 } else {
5691 // Use SMTP directly.
5692 $mailer->isSMTP();
5693 if (!empty($CFG->debugsmtp)) {
5694 $mailer->SMTPDebug = true;
5696 // Specify main and backup servers.
5697 $mailer->Host = $CFG->smtphosts;
5698 // Specify secure connection protocol.
5699 $mailer->SMTPSecure = $CFG->smtpsecure;
5700 // Use previous keepalive.
5701 $mailer->SMTPKeepAlive = $prevkeepalive;
5703 if ($CFG->smtpuser) {
5704 // Use SMTP authentication.
5705 $mailer->SMTPAuth = true;
5706 $mailer->Username = $CFG->smtpuser;
5707 $mailer->Password = $CFG->smtppass;
5711 return $mailer;
5714 $nothing = null;
5716 // Keep smtp session open after sending.
5717 if ($action == 'buffer') {
5718 if (!empty($CFG->smtpmaxbulk)) {
5719 get_mailer('flush');
5720 $m = get_mailer();
5721 if ($m->Mailer == 'smtp') {
5722 $m->SMTPKeepAlive = true;
5725 return $nothing;
5728 // Close smtp session, but continue buffering.
5729 if ($action == 'flush') {
5730 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5731 if (!empty($mailer->SMTPDebug)) {
5732 echo '<pre>'."\n";
5734 $mailer->SmtpClose();
5735 if (!empty($mailer->SMTPDebug)) {
5736 echo '</pre>';
5739 return $nothing;
5742 // Close smtp session, do not buffer anymore.
5743 if ($action == 'close') {
5744 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5745 get_mailer('flush');
5746 $mailer->SMTPKeepAlive = false;
5748 $mailer = null; // Better force new instance.
5749 return $nothing;
5754 * Send an email to a specified user
5756 * @param stdClass $user A {@link $USER} object
5757 * @param stdClass $from A {@link $USER} object
5758 * @param string $subject plain text subject line of the email
5759 * @param string $messagetext plain text version of the message
5760 * @param string $messagehtml complete html version of the message (optional)
5761 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5762 * @param string $attachname the name of the file (extension indicates MIME)
5763 * @param bool $usetrueaddress determines whether $from email address should
5764 * be sent out. Will be overruled by user profile setting for maildisplay
5765 * @param string $replyto Email address to reply to
5766 * @param string $replytoname Name of reply to recipient
5767 * @param int $wordwrapwidth custom word wrap width, default 79
5768 * @return bool Returns true if mail was sent OK and false if there was an error.
5770 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5771 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5773 global $CFG;
5775 if (empty($user) or empty($user->id)) {
5776 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5777 return false;
5780 if (empty($user->email)) {
5781 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5782 return false;
5785 if (!empty($user->deleted)) {
5786 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5787 return false;
5790 if (defined('BEHAT_SITE_RUNNING')) {
5791 // Fake email sending in behat.
5792 return true;
5795 if (!empty($CFG->noemailever)) {
5796 // Hidden setting for development sites, set in config.php if needed.
5797 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5798 return true;
5801 if (!empty($CFG->divertallemailsto)) {
5802 $subject = "[DIVERTED {$user->email}] $subject";
5803 $user = clone($user);
5804 $user->email = $CFG->divertallemailsto;
5807 // Skip mail to suspended users.
5808 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5809 return true;
5812 if (!validate_email($user->email)) {
5813 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5814 $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
5815 error_log($invalidemail);
5816 if (CLI_SCRIPT) {
5817 mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
5819 return false;
5822 if (over_bounce_threshold($user)) {
5823 $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
5824 error_log($bouncemsg);
5825 if (CLI_SCRIPT) {
5826 mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
5828 return false;
5831 // If the user is a remote mnet user, parse the email text for URL to the
5832 // wwwroot and modify the url to direct the user's browser to login at their
5833 // home site (identity provider - idp) before hitting the link itself.
5834 if (is_mnet_remote_user($user)) {
5835 require_once($CFG->dirroot.'/mnet/lib.php');
5837 $jumpurl = mnet_get_idp_jump_url($user);
5838 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5840 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5841 $callback,
5842 $messagetext);
5843 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5844 $callback,
5845 $messagehtml);
5847 $mail = get_mailer();
5849 if (!empty($mail->SMTPDebug)) {
5850 echo '<pre>' . "\n";
5853 $temprecipients = array();
5854 $tempreplyto = array();
5856 $supportuser = core_user::get_support_user();
5858 // Make up an email address for handling bounces.
5859 if (!empty($CFG->handlebounces)) {
5860 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5861 $mail->Sender = generate_email_processing_address(0, $modargs);
5862 } else {
5863 $mail->Sender = $supportuser->email;
5866 if (!empty($CFG->emailonlyfromnoreplyaddress)) {
5867 $usetrueaddress = false;
5868 if (empty($replyto) && $from->maildisplay) {
5869 $replyto = $from->email;
5870 $replytoname = fullname($from);
5874 if (is_string($from)) { // So we can pass whatever we want if there is need.
5875 $mail->From = $CFG->noreplyaddress;
5876 $mail->FromName = $from;
5877 } else if ($usetrueaddress and $from->maildisplay) {
5878 $mail->From = $from->email;
5879 $mail->FromName = fullname($from);
5880 } else {
5881 $mail->From = $CFG->noreplyaddress;
5882 $mail->FromName = fullname($from);
5883 if (empty($replyto)) {
5884 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5888 if (!empty($replyto)) {
5889 $tempreplyto[] = array($replyto, $replytoname);
5892 $mail->Subject = substr($subject, 0, 900);
5894 $temprecipients[] = array($user->email, fullname($user));
5896 // Set word wrap.
5897 $mail->WordWrap = $wordwrapwidth;
5899 if (!empty($from->customheaders)) {
5900 // Add custom headers.
5901 if (is_array($from->customheaders)) {
5902 foreach ($from->customheaders as $customheader) {
5903 $mail->addCustomHeader($customheader);
5905 } else {
5906 $mail->addCustomHeader($from->customheaders);
5910 if (!empty($from->priority)) {
5911 $mail->Priority = $from->priority;
5914 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5915 // Don't ever send HTML to users who don't want it.
5916 $mail->isHTML(true);
5917 $mail->Encoding = 'quoted-printable';
5918 $mail->Body = $messagehtml;
5919 $mail->AltBody = "\n$messagetext\n";
5920 } else {
5921 $mail->IsHTML(false);
5922 $mail->Body = "\n$messagetext\n";
5925 if ($attachment && $attachname) {
5926 if (preg_match( "~\\.\\.~" , $attachment )) {
5927 // Security check for ".." in dir path.
5928 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5929 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5930 } else {
5931 require_once($CFG->libdir.'/filelib.php');
5932 $mimetype = mimeinfo('type', $attachname);
5934 $attachmentpath = $attachment;
5936 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5937 $attachpath = str_replace('\\', '/', $attachmentpath);
5938 // Make sure both variables are normalised before comparing.
5939 $temppath = str_replace('\\', '/', $CFG->tempdir);
5941 // If the attachment is a full path to a file in the tempdir, use it as is,
5942 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5943 if (strpos($attachpath, $temppath) !== 0) {
5944 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5947 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5951 // Check if the email should be sent in an other charset then the default UTF-8.
5952 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5954 // Use the defined site mail charset or eventually the one preferred by the recipient.
5955 $charset = $CFG->sitemailcharset;
5956 if (!empty($CFG->allowusermailcharset)) {
5957 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5958 $charset = $useremailcharset;
5962 // Convert all the necessary strings if the charset is supported.
5963 $charsets = get_list_of_charsets();
5964 unset($charsets['UTF-8']);
5965 if (in_array($charset, $charsets)) {
5966 $mail->CharSet = $charset;
5967 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5968 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5969 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5970 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5972 foreach ($temprecipients as $key => $values) {
5973 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5975 foreach ($tempreplyto as $key => $values) {
5976 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5981 foreach ($temprecipients as $values) {
5982 $mail->addAddress($values[0], $values[1]);
5984 foreach ($tempreplyto as $values) {
5985 $mail->addReplyTo($values[0], $values[1]);
5988 if ($mail->send()) {
5989 set_send_count($user);
5990 if (!empty($mail->SMTPDebug)) {
5991 echo '</pre>';
5993 return true;
5994 } else {
5995 // Trigger event for failing to send email.
5996 $event = \core\event\email_failed::create(array(
5997 'context' => context_system::instance(),
5998 'userid' => $from->id,
5999 'relateduserid' => $user->id,
6000 'other' => array(
6001 'subject' => $subject,
6002 'message' => $messagetext,
6003 'errorinfo' => $mail->ErrorInfo
6006 $event->trigger();
6007 if (CLI_SCRIPT) {
6008 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6010 if (!empty($mail->SMTPDebug)) {
6011 echo '</pre>';
6013 return false;
6018 * Generate a signoff for emails based on support settings
6020 * @return string
6022 function generate_email_signoff() {
6023 global $CFG;
6025 $signoff = "\n";
6026 if (!empty($CFG->supportname)) {
6027 $signoff .= $CFG->supportname."\n";
6029 if (!empty($CFG->supportemail)) {
6030 $signoff .= $CFG->supportemail."\n";
6032 if (!empty($CFG->supportpage)) {
6033 $signoff .= $CFG->supportpage."\n";
6035 return $signoff;
6039 * Sets specified user's password and send the new password to the user via email.
6041 * @param stdClass $user A {@link $USER} object
6042 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6043 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6045 function setnew_password_and_mail($user, $fasthash = false) {
6046 global $CFG, $DB;
6048 // We try to send the mail in language the user understands,
6049 // unfortunately the filter_string() does not support alternative langs yet
6050 // so multilang will not work properly for site->fullname.
6051 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6053 $site = get_site();
6055 $supportuser = core_user::get_support_user();
6057 $newpassword = generate_password();
6059 update_internal_user_password($user, $newpassword, $fasthash);
6061 $a = new stdClass();
6062 $a->firstname = fullname($user, true);
6063 $a->sitename = format_string($site->fullname);
6064 $a->username = $user->username;
6065 $a->newpassword = $newpassword;
6066 $a->link = $CFG->wwwroot .'/login/';
6067 $a->signoff = generate_email_signoff();
6069 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6071 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6073 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6074 return email_to_user($user, $supportuser, $subject, $message);
6079 * Resets specified user's password and send the new password to the user via email.
6081 * @param stdClass $user A {@link $USER} object
6082 * @return bool Returns true if mail was sent OK and false if there was an error.
6084 function reset_password_and_mail($user) {
6085 global $CFG;
6087 $site = get_site();
6088 $supportuser = core_user::get_support_user();
6090 $userauth = get_auth_plugin($user->auth);
6091 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6092 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6093 return false;
6096 $newpassword = generate_password();
6098 if (!$userauth->user_update_password($user, $newpassword)) {
6099 print_error("cannotsetpassword");
6102 $a = new stdClass();
6103 $a->firstname = $user->firstname;
6104 $a->lastname = $user->lastname;
6105 $a->sitename = format_string($site->fullname);
6106 $a->username = $user->username;
6107 $a->newpassword = $newpassword;
6108 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
6109 $a->signoff = generate_email_signoff();
6111 $message = get_string('newpasswordtext', '', $a);
6113 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6115 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6117 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6118 return email_to_user($user, $supportuser, $subject, $message);
6122 * Send email to specified user with confirmation text and activation link.
6124 * @param stdClass $user A {@link $USER} object
6125 * @return bool Returns true if mail was sent OK and false if there was an error.
6127 function send_confirmation_email($user) {
6128 global $CFG;
6130 $site = get_site();
6131 $supportuser = core_user::get_support_user();
6133 $data = new stdClass();
6134 $data->firstname = fullname($user);
6135 $data->sitename = format_string($site->fullname);
6136 $data->admin = generate_email_signoff();
6138 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6140 $username = urlencode($user->username);
6141 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
6142 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
6143 $message = get_string('emailconfirmation', '', $data);
6144 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6146 $user->mailformat = 1; // Always send HTML version as well.
6148 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6149 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6153 * Sends a password change confirmation email.
6155 * @param stdClass $user A {@link $USER} object
6156 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6157 * @return bool Returns true if mail was sent OK and false if there was an error.
6159 function send_password_change_confirmation_email($user, $resetrecord) {
6160 global $CFG;
6162 $site = get_site();
6163 $supportuser = core_user::get_support_user();
6164 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6166 $data = new stdClass();
6167 $data->firstname = $user->firstname;
6168 $data->lastname = $user->lastname;
6169 $data->username = $user->username;
6170 $data->sitename = format_string($site->fullname);
6171 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6172 $data->admin = generate_email_signoff();
6173 $data->resetminutes = $pwresetmins;
6175 $message = get_string('emailresetconfirmation', '', $data);
6176 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6178 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6179 return email_to_user($user, $supportuser, $subject, $message);
6184 * Sends an email containinginformation on how to change your password.
6186 * @param stdClass $user A {@link $USER} object
6187 * @return bool Returns true if mail was sent OK and false if there was an error.
6189 function send_password_change_info($user) {
6190 global $CFG;
6192 $site = get_site();
6193 $supportuser = core_user::get_support_user();
6194 $systemcontext = context_system::instance();
6196 $data = new stdClass();
6197 $data->firstname = $user->firstname;
6198 $data->lastname = $user->lastname;
6199 $data->sitename = format_string($site->fullname);
6200 $data->admin = generate_email_signoff();
6202 $userauth = get_auth_plugin($user->auth);
6204 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6205 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6206 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6207 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6208 return email_to_user($user, $supportuser, $subject, $message);
6211 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6212 // We have some external url for password changing.
6213 $data->link .= $userauth->change_password_url();
6215 } else {
6216 // No way to change password, sorry.
6217 $data->link = '';
6220 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6221 $message = get_string('emailpasswordchangeinfo', '', $data);
6222 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6223 } else {
6224 $message = get_string('emailpasswordchangeinfofail', '', $data);
6225 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6228 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6229 return email_to_user($user, $supportuser, $subject, $message);
6234 * Check that an email is allowed. It returns an error message if there was a problem.
6236 * @param string $email Content of email
6237 * @return string|false
6239 function email_is_not_allowed($email) {
6240 global $CFG;
6242 if (!empty($CFG->allowemailaddresses)) {
6243 $allowed = explode(' ', $CFG->allowemailaddresses);
6244 foreach ($allowed as $allowedpattern) {
6245 $allowedpattern = trim($allowedpattern);
6246 if (!$allowedpattern) {
6247 continue;
6249 if (strpos($allowedpattern, '.') === 0) {
6250 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6251 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6252 return false;
6255 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6256 return false;
6259 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6261 } else if (!empty($CFG->denyemailaddresses)) {
6262 $denied = explode(' ', $CFG->denyemailaddresses);
6263 foreach ($denied as $deniedpattern) {
6264 $deniedpattern = trim($deniedpattern);
6265 if (!$deniedpattern) {
6266 continue;
6268 if (strpos($deniedpattern, '.') === 0) {
6269 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6270 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6271 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6274 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6275 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6280 return false;
6283 // FILE HANDLING.
6286 * Returns local file storage instance
6288 * @return file_storage
6290 function get_file_storage() {
6291 global $CFG;
6293 static $fs = null;
6295 if ($fs) {
6296 return $fs;
6299 require_once("$CFG->libdir/filelib.php");
6301 if (isset($CFG->filedir)) {
6302 $filedir = $CFG->filedir;
6303 } else {
6304 $filedir = $CFG->dataroot.'/filedir';
6307 if (isset($CFG->trashdir)) {
6308 $trashdirdir = $CFG->trashdir;
6309 } else {
6310 $trashdirdir = $CFG->dataroot.'/trashdir';
6313 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6315 return $fs;
6319 * Returns local file storage instance
6321 * @return file_browser
6323 function get_file_browser() {
6324 global $CFG;
6326 static $fb = null;
6328 if ($fb) {
6329 return $fb;
6332 require_once("$CFG->libdir/filelib.php");
6334 $fb = new file_browser();
6336 return $fb;
6340 * Returns file packer
6342 * @param string $mimetype default application/zip
6343 * @return file_packer
6345 function get_file_packer($mimetype='application/zip') {
6346 global $CFG;
6348 static $fp = array();
6350 if (isset($fp[$mimetype])) {
6351 return $fp[$mimetype];
6354 switch ($mimetype) {
6355 case 'application/zip':
6356 case 'application/vnd.moodle.profiling':
6357 $classname = 'zip_packer';
6358 break;
6360 case 'application/x-gzip' :
6361 $classname = 'tgz_packer';
6362 break;
6364 case 'application/vnd.moodle.backup':
6365 $classname = 'mbz_packer';
6366 break;
6368 default:
6369 return false;
6372 require_once("$CFG->libdir/filestorage/$classname.php");
6373 $fp[$mimetype] = new $classname();
6375 return $fp[$mimetype];
6379 * Returns current name of file on disk if it exists.
6381 * @param string $newfile File to be verified
6382 * @return string Current name of file on disk if true
6384 function valid_uploaded_file($newfile) {
6385 if (empty($newfile)) {
6386 return '';
6388 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6389 return $newfile['tmp_name'];
6390 } else {
6391 return '';
6396 * Returns the maximum size for uploading files.
6398 * There are seven possible upload limits:
6399 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6400 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6401 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6402 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6403 * 5. by the Moodle admin in $CFG->maxbytes
6404 * 6. by the teacher in the current course $course->maxbytes
6405 * 7. by the teacher for the current module, eg $assignment->maxbytes
6407 * These last two are passed to this function as arguments (in bytes).
6408 * Anything defined as 0 is ignored.
6409 * The smallest of all the non-zero numbers is returned.
6411 * @todo Finish documenting this function
6413 * @param int $sitebytes Set maximum size
6414 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6415 * @param int $modulebytes Current module ->maxbytes (in bytes)
6416 * @return int The maximum size for uploading files.
6418 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6420 if (! $filesize = ini_get('upload_max_filesize')) {
6421 $filesize = '5M';
6423 $minimumsize = get_real_size($filesize);
6425 if ($postsize = ini_get('post_max_size')) {
6426 $postsize = get_real_size($postsize);
6427 if ($postsize < $minimumsize) {
6428 $minimumsize = $postsize;
6432 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6433 $minimumsize = $sitebytes;
6436 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6437 $minimumsize = $coursebytes;
6440 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6441 $minimumsize = $modulebytes;
6444 return $minimumsize;
6448 * Returns the maximum size for uploading files for the current user
6450 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6452 * @param context $context The context in which to check user capabilities
6453 * @param int $sitebytes Set maximum size
6454 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6455 * @param int $modulebytes Current module ->maxbytes (in bytes)
6456 * @param stdClass $user The user
6457 * @return int The maximum size for uploading files.
6459 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6460 global $USER;
6462 if (empty($user)) {
6463 $user = $USER;
6466 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6467 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6470 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6474 * Returns an array of possible sizes in local language
6476 * Related to {@link get_max_upload_file_size()} - this function returns an
6477 * array of possible sizes in an array, translated to the
6478 * local language.
6480 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6482 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6483 * with the value set to 0. This option will be the first in the list.
6485 * @uses SORT_NUMERIC
6486 * @param int $sitebytes Set maximum size
6487 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6488 * @param int $modulebytes Current module ->maxbytes (in bytes)
6489 * @param int|array $custombytes custom upload size/s which will be added to list,
6490 * Only value/s smaller then maxsize will be added to list.
6491 * @return array
6493 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6494 global $CFG;
6496 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6497 return array();
6500 if ($sitebytes == 0) {
6501 // Will get the minimum of upload_max_filesize or post_max_size.
6502 $sitebytes = get_max_upload_file_size();
6505 $filesize = array();
6506 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6507 5242880, 10485760, 20971520, 52428800, 104857600);
6509 // If custombytes is given and is valid then add it to the list.
6510 if (is_number($custombytes) and $custombytes > 0) {
6511 $custombytes = (int)$custombytes;
6512 if (!in_array($custombytes, $sizelist)) {
6513 $sizelist[] = $custombytes;
6515 } else if (is_array($custombytes)) {
6516 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6519 // Allow maxbytes to be selected if it falls outside the above boundaries.
6520 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6521 // Note: get_real_size() is used in order to prevent problems with invalid values.
6522 $sizelist[] = get_real_size($CFG->maxbytes);
6525 foreach ($sizelist as $sizebytes) {
6526 if ($sizebytes < $maxsize && $sizebytes > 0) {
6527 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6531 $limitlevel = '';
6532 $displaysize = '';
6533 if ($modulebytes &&
6534 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6535 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6536 $limitlevel = get_string('activity', 'core');
6537 $displaysize = display_size($modulebytes);
6538 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6540 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6541 $limitlevel = get_string('course', 'core');
6542 $displaysize = display_size($coursebytes);
6543 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6545 } else if ($sitebytes) {
6546 $limitlevel = get_string('site', 'core');
6547 $displaysize = display_size($sitebytes);
6548 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6551 krsort($filesize, SORT_NUMERIC);
6552 if ($limitlevel) {
6553 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6554 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6557 return $filesize;
6561 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6563 * If excludefiles is defined, then that file/directory is ignored
6564 * If getdirs is true, then (sub)directories are included in the output
6565 * If getfiles is true, then files are included in the output
6566 * (at least one of these must be true!)
6568 * @todo Finish documenting this function. Add examples of $excludefile usage.
6570 * @param string $rootdir A given root directory to start from
6571 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6572 * @param bool $descend If true then subdirectories are recursed as well
6573 * @param bool $getdirs If true then (sub)directories are included in the output
6574 * @param bool $getfiles If true then files are included in the output
6575 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6577 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6579 $dirs = array();
6581 if (!$getdirs and !$getfiles) { // Nothing to show.
6582 return $dirs;
6585 if (!is_dir($rootdir)) { // Must be a directory.
6586 return $dirs;
6589 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6590 return $dirs;
6593 if (!is_array($excludefiles)) {
6594 $excludefiles = array($excludefiles);
6597 while (false !== ($file = readdir($dir))) {
6598 $firstchar = substr($file, 0, 1);
6599 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6600 continue;
6602 $fullfile = $rootdir .'/'. $file;
6603 if (filetype($fullfile) == 'dir') {
6604 if ($getdirs) {
6605 $dirs[] = $file;
6607 if ($descend) {
6608 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6609 foreach ($subdirs as $subdir) {
6610 $dirs[] = $file .'/'. $subdir;
6613 } else if ($getfiles) {
6614 $dirs[] = $file;
6617 closedir($dir);
6619 asort($dirs);
6621 return $dirs;
6626 * Adds up all the files in a directory and works out the size.
6628 * @param string $rootdir The directory to start from
6629 * @param string $excludefile A file to exclude when summing directory size
6630 * @return int The summed size of all files and subfiles within the root directory
6632 function get_directory_size($rootdir, $excludefile='') {
6633 global $CFG;
6635 // Do it this way if we can, it's much faster.
6636 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6637 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6638 $output = null;
6639 $return = null;
6640 exec($command, $output, $return);
6641 if (is_array($output)) {
6642 // We told it to return k.
6643 return get_real_size(intval($output[0]).'k');
6647 if (!is_dir($rootdir)) {
6648 // Must be a directory.
6649 return 0;
6652 if (!$dir = @opendir($rootdir)) {
6653 // Can't open it for some reason.
6654 return 0;
6657 $size = 0;
6659 while (false !== ($file = readdir($dir))) {
6660 $firstchar = substr($file, 0, 1);
6661 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6662 continue;
6664 $fullfile = $rootdir .'/'. $file;
6665 if (filetype($fullfile) == 'dir') {
6666 $size += get_directory_size($fullfile, $excludefile);
6667 } else {
6668 $size += filesize($fullfile);
6671 closedir($dir);
6673 return $size;
6677 * Converts bytes into display form
6679 * @static string $gb Localized string for size in gigabytes
6680 * @static string $mb Localized string for size in megabytes
6681 * @static string $kb Localized string for size in kilobytes
6682 * @static string $b Localized string for size in bytes
6683 * @param int $size The size to convert to human readable form
6684 * @return string
6686 function display_size($size) {
6688 static $gb, $mb, $kb, $b;
6690 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6691 return get_string('unlimited');
6694 if (empty($gb)) {
6695 $gb = get_string('sizegb');
6696 $mb = get_string('sizemb');
6697 $kb = get_string('sizekb');
6698 $b = get_string('sizeb');
6701 if ($size >= 1073741824) {
6702 $size = round($size / 1073741824 * 10) / 10 . $gb;
6703 } else if ($size >= 1048576) {
6704 $size = round($size / 1048576 * 10) / 10 . $mb;
6705 } else if ($size >= 1024) {
6706 $size = round($size / 1024 * 10) / 10 . $kb;
6707 } else {
6708 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6710 return $size;
6714 * Cleans a given filename by removing suspicious or troublesome characters
6716 * @see clean_param()
6717 * @param string $string file name
6718 * @return string cleaned file name
6720 function clean_filename($string) {
6721 return clean_param($string, PARAM_FILE);
6725 // STRING TRANSLATION.
6728 * Returns the code for the current language
6730 * @category string
6731 * @return string
6733 function current_language() {
6734 global $CFG, $USER, $SESSION, $COURSE;
6736 if (!empty($SESSION->forcelang)) {
6737 // Allows overriding course-forced language (useful for admins to check
6738 // issues in courses whose language they don't understand).
6739 // Also used by some code to temporarily get language-related information in a
6740 // specific language (see force_current_language()).
6741 $return = $SESSION->forcelang;
6743 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6744 // Course language can override all other settings for this page.
6745 $return = $COURSE->lang;
6747 } else if (!empty($SESSION->lang)) {
6748 // Session language can override other settings.
6749 $return = $SESSION->lang;
6751 } else if (!empty($USER->lang)) {
6752 $return = $USER->lang;
6754 } else if (isset($CFG->lang)) {
6755 $return = $CFG->lang;
6757 } else {
6758 $return = 'en';
6761 // Just in case this slipped in from somewhere by accident.
6762 $return = str_replace('_utf8', '', $return);
6764 return $return;
6768 * Returns parent language of current active language if defined
6770 * @category string
6771 * @param string $lang null means current language
6772 * @return string
6774 function get_parent_language($lang=null) {
6776 // Let's hack around the current language.
6777 if (!empty($lang)) {
6778 $oldforcelang = force_current_language($lang);
6781 $parentlang = get_string('parentlanguage', 'langconfig');
6782 if ($parentlang === 'en') {
6783 $parentlang = '';
6786 // Let's hack around the current language.
6787 if (!empty($lang)) {
6788 force_current_language($oldforcelang);
6791 return $parentlang;
6795 * Force the current language to get strings and dates localised in the given language.
6797 * After calling this function, all strings will be provided in the given language
6798 * until this function is called again, or equivalent code is run.
6800 * @param string $language
6801 * @return string previous $SESSION->forcelang value
6803 function force_current_language($language) {
6804 global $SESSION;
6805 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6806 if ($language !== $sessionforcelang) {
6807 // Seting forcelang to null or an empty string disables it's effect.
6808 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6809 $SESSION->forcelang = $language;
6810 moodle_setlocale();
6813 return $sessionforcelang;
6817 * Returns current string_manager instance.
6819 * The param $forcereload is needed for CLI installer only where the string_manager instance
6820 * must be replaced during the install.php script life time.
6822 * @category string
6823 * @param bool $forcereload shall the singleton be released and new instance created instead?
6824 * @return core_string_manager
6826 function get_string_manager($forcereload=false) {
6827 global $CFG;
6829 static $singleton = null;
6831 if ($forcereload) {
6832 $singleton = null;
6834 if ($singleton === null) {
6835 if (empty($CFG->early_install_lang)) {
6837 if (empty($CFG->langlist)) {
6838 $translist = array();
6839 } else {
6840 $translist = explode(',', $CFG->langlist);
6843 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6845 } else {
6846 $singleton = new core_string_manager_install();
6850 return $singleton;
6854 * Returns a localized string.
6856 * Returns the translated string specified by $identifier as
6857 * for $module. Uses the same format files as STphp.
6858 * $a is an object, string or number that can be used
6859 * within translation strings
6861 * eg 'hello {$a->firstname} {$a->lastname}'
6862 * or 'hello {$a}'
6864 * If you would like to directly echo the localized string use
6865 * the function {@link print_string()}
6867 * Example usage of this function involves finding the string you would
6868 * like a local equivalent of and using its identifier and module information
6869 * to retrieve it.<br/>
6870 * If you open moodle/lang/en/moodle.php and look near line 278
6871 * you will find a string to prompt a user for their word for 'course'
6872 * <code>
6873 * $string['course'] = 'Course';
6874 * </code>
6875 * So if you want to display the string 'Course'
6876 * in any language that supports it on your site
6877 * you just need to use the identifier 'course'
6878 * <code>
6879 * $mystring = '<strong>'. get_string('course') .'</strong>';
6880 * or
6881 * </code>
6882 * If the string you want is in another file you'd take a slightly
6883 * different approach. Looking in moodle/lang/en/calendar.php you find
6884 * around line 75:
6885 * <code>
6886 * $string['typecourse'] = 'Course event';
6887 * </code>
6888 * If you want to display the string "Course event" in any language
6889 * supported you would use the identifier 'typecourse' and the module 'calendar'
6890 * (because it is in the file calendar.php):
6891 * <code>
6892 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6893 * </code>
6895 * As a last resort, should the identifier fail to map to a string
6896 * the returned string will be [[ $identifier ]]
6898 * In Moodle 2.3 there is a new argument to this function $lazyload.
6899 * Setting $lazyload to true causes get_string to return a lang_string object
6900 * rather than the string itself. The fetching of the string is then put off until
6901 * the string object is first used. The object can be used by calling it's out
6902 * method or by casting the object to a string, either directly e.g.
6903 * (string)$stringobject
6904 * or indirectly by using the string within another string or echoing it out e.g.
6905 * echo $stringobject
6906 * return "<p>{$stringobject}</p>";
6907 * It is worth noting that using $lazyload and attempting to use the string as an
6908 * array key will cause a fatal error as objects cannot be used as array keys.
6909 * But you should never do that anyway!
6910 * For more information {@link lang_string}
6912 * @category string
6913 * @param string $identifier The key identifier for the localized string
6914 * @param string $component The module where the key identifier is stored,
6915 * usually expressed as the filename in the language pack without the
6916 * .php on the end but can also be written as mod/forum or grade/export/xls.
6917 * If none is specified then moodle.php is used.
6918 * @param string|object|array $a An object, string or number that can be used
6919 * within translation strings
6920 * @param bool $lazyload If set to true a string object is returned instead of
6921 * the string itself. The string then isn't calculated until it is first used.
6922 * @return string The localized string.
6923 * @throws coding_exception
6925 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6926 global $CFG;
6928 // If the lazy load argument has been supplied return a lang_string object
6929 // instead.
6930 // We need to make sure it is true (and a bool) as you will see below there
6931 // used to be a forth argument at one point.
6932 if ($lazyload === true) {
6933 return new lang_string($identifier, $component, $a);
6936 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6937 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6940 // There is now a forth argument again, this time it is a boolean however so
6941 // we can still check for the old extralocations parameter.
6942 if (!is_bool($lazyload) && !empty($lazyload)) {
6943 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6946 if (strpos($component, '/') !== false) {
6947 debugging('The module name you passed to get_string is the deprecated format ' .
6948 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6949 $componentpath = explode('/', $component);
6951 switch ($componentpath[0]) {
6952 case 'mod':
6953 $component = $componentpath[1];
6954 break;
6955 case 'blocks':
6956 case 'block':
6957 $component = 'block_'.$componentpath[1];
6958 break;
6959 case 'enrol':
6960 $component = 'enrol_'.$componentpath[1];
6961 break;
6962 case 'format':
6963 $component = 'format_'.$componentpath[1];
6964 break;
6965 case 'grade':
6966 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6967 break;
6971 $result = get_string_manager()->get_string($identifier, $component, $a);
6973 // Debugging feature lets you display string identifier and component.
6974 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6975 $result .= ' {' . $identifier . '/' . $component . '}';
6977 return $result;
6981 * Converts an array of strings to their localized value.
6983 * @param array $array An array of strings
6984 * @param string $component The language module that these strings can be found in.
6985 * @return stdClass translated strings.
6987 function get_strings($array, $component = '') {
6988 $string = new stdClass;
6989 foreach ($array as $item) {
6990 $string->$item = get_string($item, $component);
6992 return $string;
6996 * Prints out a translated string.
6998 * Prints out a translated string using the return value from the {@link get_string()} function.
7000 * Example usage of this function when the string is in the moodle.php file:<br/>
7001 * <code>
7002 * echo '<strong>';
7003 * print_string('course');
7004 * echo '</strong>';
7005 * </code>
7007 * Example usage of this function when the string is not in the moodle.php file:<br/>
7008 * <code>
7009 * echo '<h1>';
7010 * print_string('typecourse', 'calendar');
7011 * echo '</h1>';
7012 * </code>
7014 * @category string
7015 * @param string $identifier The key identifier for the localized string
7016 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7017 * @param string|object|array $a An object, string or number that can be used within translation strings
7019 function print_string($identifier, $component = '', $a = null) {
7020 echo get_string($identifier, $component, $a);
7024 * Returns a list of charset codes
7026 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7027 * (checking that such charset is supported by the texlib library!)
7029 * @return array And associative array with contents in the form of charset => charset
7031 function get_list_of_charsets() {
7033 $charsets = array(
7034 'EUC-JP' => 'EUC-JP',
7035 'ISO-2022-JP'=> 'ISO-2022-JP',
7036 'ISO-8859-1' => 'ISO-8859-1',
7037 'SHIFT-JIS' => 'SHIFT-JIS',
7038 'GB2312' => 'GB2312',
7039 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7040 'UTF-8' => 'UTF-8');
7042 asort($charsets);
7044 return $charsets;
7048 * Returns a list of valid and compatible themes
7050 * @return array
7052 function get_list_of_themes() {
7053 global $CFG;
7055 $themes = array();
7057 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7058 $themelist = explode(',', $CFG->themelist);
7059 } else {
7060 $themelist = array_keys(core_component::get_plugin_list("theme"));
7063 foreach ($themelist as $key => $themename) {
7064 $theme = theme_config::load($themename);
7065 $themes[$themename] = $theme;
7068 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7070 return $themes;
7074 * Returns a list of timezones in the current language
7076 * @return array
7078 function get_list_of_timezones() {
7079 global $DB;
7081 static $timezones;
7083 if (!empty($timezones)) { // This function has been called recently.
7084 return $timezones;
7087 $timezones = array();
7089 if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
7090 foreach ($rawtimezones as $timezone) {
7091 if (!empty($timezone->name)) {
7092 if (get_string_manager()->string_exists(strtolower($timezone->name), 'timezones')) {
7093 $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
7094 } else {
7095 $timezones[$timezone->name] = $timezone->name;
7097 if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found.
7098 $timezones[$timezone->name] = $timezone->name;
7104 asort($timezones);
7106 for ($i = -13; $i <= 13; $i += .5) {
7107 $tzstring = 'UTC';
7108 if ($i < 0) {
7109 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
7110 } else if ($i > 0) {
7111 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
7112 } else {
7113 $timezones[sprintf("%.1f", $i)] = $tzstring;
7117 return $timezones;
7121 * Factory function for emoticon_manager
7123 * @return emoticon_manager singleton
7125 function get_emoticon_manager() {
7126 static $singleton = null;
7128 if (is_null($singleton)) {
7129 $singleton = new emoticon_manager();
7132 return $singleton;
7136 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7138 * Whenever this manager mentiones 'emoticon object', the following data
7139 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7140 * altidentifier and altcomponent
7142 * @see admin_setting_emoticons
7144 * @copyright 2010 David Mudrak
7145 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7147 class emoticon_manager {
7150 * Returns the currently enabled emoticons
7152 * @return array of emoticon objects
7154 public function get_emoticons() {
7155 global $CFG;
7157 if (empty($CFG->emoticons)) {
7158 return array();
7161 $emoticons = $this->decode_stored_config($CFG->emoticons);
7163 if (!is_array($emoticons)) {
7164 // Something is wrong with the format of stored setting.
7165 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7166 return array();
7169 return $emoticons;
7173 * Converts emoticon object into renderable pix_emoticon object
7175 * @param stdClass $emoticon emoticon object
7176 * @param array $attributes explicit HTML attributes to set
7177 * @return pix_emoticon
7179 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7180 $stringmanager = get_string_manager();
7181 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7182 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7183 } else {
7184 $alt = s($emoticon->text);
7186 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7190 * Encodes the array of emoticon objects into a string storable in config table
7192 * @see self::decode_stored_config()
7193 * @param array $emoticons array of emtocion objects
7194 * @return string
7196 public function encode_stored_config(array $emoticons) {
7197 return json_encode($emoticons);
7201 * Decodes the string into an array of emoticon objects
7203 * @see self::encode_stored_config()
7204 * @param string $encoded
7205 * @return string|null
7207 public function decode_stored_config($encoded) {
7208 $decoded = json_decode($encoded);
7209 if (!is_array($decoded)) {
7210 return null;
7212 return $decoded;
7216 * Returns default set of emoticons supported by Moodle
7218 * @return array of sdtClasses
7220 public function default_emoticons() {
7221 return array(
7222 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7223 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7224 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7225 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7226 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7227 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7228 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7229 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7230 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7231 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7232 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7233 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7234 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7235 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7236 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7237 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7238 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7239 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7240 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7241 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7242 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7243 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7244 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7245 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7246 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7247 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7248 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7249 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7250 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7251 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7256 * Helper method preparing the stdClass with the emoticon properties
7258 * @param string|array $text or array of strings
7259 * @param string $imagename to be used by {@link pix_emoticon}
7260 * @param string $altidentifier alternative string identifier, null for no alt
7261 * @param string $altcomponent where the alternative string is defined
7262 * @param string $imagecomponent to be used by {@link pix_emoticon}
7263 * @return stdClass
7265 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7266 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7267 return (object)array(
7268 'text' => $text,
7269 'imagename' => $imagename,
7270 'imagecomponent' => $imagecomponent,
7271 'altidentifier' => $altidentifier,
7272 'altcomponent' => $altcomponent,
7277 // ENCRYPTION.
7280 * rc4encrypt
7282 * @param string $data Data to encrypt.
7283 * @return string The now encrypted data.
7285 function rc4encrypt($data) {
7286 return endecrypt(get_site_identifier(), $data, '');
7290 * rc4decrypt
7292 * @param string $data Data to decrypt.
7293 * @return string The now decrypted data.
7295 function rc4decrypt($data) {
7296 return endecrypt(get_site_identifier(), $data, 'de');
7300 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7302 * @todo Finish documenting this function
7304 * @param string $pwd The password to use when encrypting or decrypting
7305 * @param string $data The data to be decrypted/encrypted
7306 * @param string $case Either 'de' for decrypt or '' for encrypt
7307 * @return string
7309 function endecrypt ($pwd, $data, $case) {
7311 if ($case == 'de') {
7312 $data = urldecode($data);
7315 $key[] = '';
7316 $box[] = '';
7317 $pwdlength = strlen($pwd);
7319 for ($i = 0; $i <= 255; $i++) {
7320 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7321 $box[$i] = $i;
7324 $x = 0;
7326 for ($i = 0; $i <= 255; $i++) {
7327 $x = ($x + $box[$i] + $key[$i]) % 256;
7328 $tempswap = $box[$i];
7329 $box[$i] = $box[$x];
7330 $box[$x] = $tempswap;
7333 $cipher = '';
7335 $a = 0;
7336 $j = 0;
7338 for ($i = 0; $i < strlen($data); $i++) {
7339 $a = ($a + 1) % 256;
7340 $j = ($j + $box[$a]) % 256;
7341 $temp = $box[$a];
7342 $box[$a] = $box[$j];
7343 $box[$j] = $temp;
7344 $k = $box[(($box[$a] + $box[$j]) % 256)];
7345 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7346 $cipher .= chr($cipherby);
7349 if ($case == 'de') {
7350 $cipher = urldecode(urlencode($cipher));
7351 } else {
7352 $cipher = urlencode($cipher);
7355 return $cipher;
7358 // ENVIRONMENT CHECKING.
7361 * This method validates a plug name. It is much faster than calling clean_param.
7363 * @param string $name a string that might be a plugin name.
7364 * @return bool if this string is a valid plugin name.
7366 function is_valid_plugin_name($name) {
7367 // This does not work for 'mod', bad luck, use any other type.
7368 return core_component::is_valid_plugin_name('tool', $name);
7372 * Get a list of all the plugins of a given type that define a certain API function
7373 * in a certain file. The plugin component names and function names are returned.
7375 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7376 * @param string $function the part of the name of the function after the
7377 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7378 * names like report_courselist_hook.
7379 * @param string $file the name of file within the plugin that defines the
7380 * function. Defaults to lib.php.
7381 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7382 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7384 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7385 $pluginfunctions = array();
7386 $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, $file, true);
7387 foreach ($pluginswithfile as $plugin => $notused) {
7388 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7390 if (function_exists($fullfunction)) {
7391 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7392 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
7394 } else if ($plugintype === 'mod') {
7395 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7396 $shortfunction = $plugin . '_' . $function;
7397 if (function_exists($shortfunction)) {
7398 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
7402 return $pluginfunctions;
7406 * Lists plugin-like directories within specified directory
7408 * This function was originally used for standard Moodle plugins, please use
7409 * new core_component::get_plugin_list() now.
7411 * This function is used for general directory listing and backwards compatility.
7413 * @param string $directory relative directory from root
7414 * @param string $exclude dir name to exclude from the list (defaults to none)
7415 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7416 * @return array Sorted array of directory names found under the requested parameters
7418 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7419 global $CFG;
7421 $plugins = array();
7423 if (empty($basedir)) {
7424 $basedir = $CFG->dirroot .'/'. $directory;
7426 } else {
7427 $basedir = $basedir .'/'. $directory;
7430 if ($CFG->debugdeveloper and empty($exclude)) {
7431 // Make sure devs do not use this to list normal plugins,
7432 // this is intended for general directories that are not plugins!
7434 $subtypes = core_component::get_plugin_types();
7435 if (in_array($basedir, $subtypes)) {
7436 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7438 unset($subtypes);
7441 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7442 if (!$dirhandle = opendir($basedir)) {
7443 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7444 return array();
7446 while (false !== ($dir = readdir($dirhandle))) {
7447 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7448 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7449 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7450 continue;
7452 if (filetype($basedir .'/'. $dir) != 'dir') {
7453 continue;
7455 $plugins[] = $dir;
7457 closedir($dirhandle);
7459 if ($plugins) {
7460 asort($plugins);
7462 return $plugins;
7466 * Invoke plugin's callback functions
7468 * @param string $type plugin type e.g. 'mod'
7469 * @param string $name plugin name
7470 * @param string $feature feature name
7471 * @param string $action feature's action
7472 * @param array $params parameters of callback function, should be an array
7473 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7474 * @return mixed
7476 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7478 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7479 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7483 * Invoke component's callback functions
7485 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7486 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7487 * @param array $params parameters of callback function
7488 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7489 * @return mixed
7491 function component_callback($component, $function, array $params = array(), $default = null) {
7493 $functionname = component_callback_exists($component, $function);
7495 if ($functionname) {
7496 // Function exists, so just return function result.
7497 $ret = call_user_func_array($functionname, $params);
7498 if (is_null($ret)) {
7499 return $default;
7500 } else {
7501 return $ret;
7504 return $default;
7508 * Determine if a component callback exists and return the function name to call. Note that this
7509 * function will include the required library files so that the functioname returned can be
7510 * called directly.
7512 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7513 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7514 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7515 * @throws coding_exception if invalid component specfied
7517 function component_callback_exists($component, $function) {
7518 global $CFG; // This is needed for the inclusions.
7520 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7521 if (empty($cleancomponent)) {
7522 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7524 $component = $cleancomponent;
7526 list($type, $name) = core_component::normalize_component($component);
7527 $component = $type . '_' . $name;
7529 $oldfunction = $name.'_'.$function;
7530 $function = $component.'_'.$function;
7532 $dir = core_component::get_component_directory($component);
7533 if (empty($dir)) {
7534 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7537 // Load library and look for function.
7538 if (file_exists($dir.'/lib.php')) {
7539 require_once($dir.'/lib.php');
7542 if (!function_exists($function) and function_exists($oldfunction)) {
7543 if ($type !== 'mod' and $type !== 'core') {
7544 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7546 $function = $oldfunction;
7549 if (function_exists($function)) {
7550 return $function;
7552 return false;
7556 * Checks whether a plugin supports a specified feature.
7558 * @param string $type Plugin type e.g. 'mod'
7559 * @param string $name Plugin name e.g. 'forum'
7560 * @param string $feature Feature code (FEATURE_xx constant)
7561 * @param mixed $default default value if feature support unknown
7562 * @return mixed Feature result (false if not supported, null if feature is unknown,
7563 * otherwise usually true but may have other feature-specific value such as array)
7564 * @throws coding_exception
7566 function plugin_supports($type, $name, $feature, $default = null) {
7567 global $CFG;
7569 if ($type === 'mod' and $name === 'NEWMODULE') {
7570 // Somebody forgot to rename the module template.
7571 return false;
7574 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7575 if (empty($component)) {
7576 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7579 $function = null;
7581 if ($type === 'mod') {
7582 // We need this special case because we support subplugins in modules,
7583 // otherwise it would end up in infinite loop.
7584 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7585 include_once("$CFG->dirroot/mod/$name/lib.php");
7586 $function = $component.'_supports';
7587 if (!function_exists($function)) {
7588 // Legacy non-frankenstyle function name.
7589 $function = $name.'_supports';
7593 } else {
7594 if (!$path = core_component::get_plugin_directory($type, $name)) {
7595 // Non existent plugin type.
7596 return false;
7598 if (file_exists("$path/lib.php")) {
7599 include_once("$path/lib.php");
7600 $function = $component.'_supports';
7604 if ($function and function_exists($function)) {
7605 $supports = $function($feature);
7606 if (is_null($supports)) {
7607 // Plugin does not know - use default.
7608 return $default;
7609 } else {
7610 return $supports;
7614 // Plugin does not care, so use default.
7615 return $default;
7619 * Returns true if the current version of PHP is greater that the specified one.
7621 * @todo Check PHP version being required here is it too low?
7623 * @param string $version The version of php being tested.
7624 * @return bool
7626 function check_php_version($version='5.2.4') {
7627 return (version_compare(phpversion(), $version) >= 0);
7631 * Determine if moodle installation requires update.
7633 * Checks version numbers of main code and all plugins to see
7634 * if there are any mismatches.
7636 * @return bool
7638 function moodle_needs_upgrading() {
7639 global $CFG;
7641 if (empty($CFG->version)) {
7642 return true;
7645 // There is no need to purge plugininfo caches here because
7646 // these caches are not used during upgrade and they are purged after
7647 // every upgrade.
7649 if (empty($CFG->allversionshash)) {
7650 return true;
7653 $hash = core_component::get_all_versions_hash();
7655 return ($hash !== $CFG->allversionshash);
7659 * Returns the major version of this site
7661 * Moodle version numbers consist of three numbers separated by a dot, for
7662 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7663 * called major version. This function extracts the major version from either
7664 * $CFG->release (default) or eventually from the $release variable defined in
7665 * the main version.php.
7667 * @param bool $fromdisk should the version if source code files be used
7668 * @return string|false the major version like '2.3', false if could not be determined
7670 function moodle_major_version($fromdisk = false) {
7671 global $CFG;
7673 if ($fromdisk) {
7674 $release = null;
7675 require($CFG->dirroot.'/version.php');
7676 if (empty($release)) {
7677 return false;
7680 } else {
7681 if (empty($CFG->release)) {
7682 return false;
7684 $release = $CFG->release;
7687 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7688 return $matches[0];
7689 } else {
7690 return false;
7694 // MISCELLANEOUS.
7697 * Sets the system locale
7699 * @category string
7700 * @param string $locale Can be used to force a locale
7702 function moodle_setlocale($locale='') {
7703 global $CFG;
7705 static $currentlocale = ''; // Last locale caching.
7707 $oldlocale = $currentlocale;
7709 // Fetch the correct locale based on ostype.
7710 if ($CFG->ostype == 'WINDOWS') {
7711 $stringtofetch = 'localewin';
7712 } else {
7713 $stringtofetch = 'locale';
7716 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7717 if (!empty($locale)) {
7718 $currentlocale = $locale;
7719 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7720 $currentlocale = $CFG->locale;
7721 } else {
7722 $currentlocale = get_string($stringtofetch, 'langconfig');
7725 // Do nothing if locale already set up.
7726 if ($oldlocale == $currentlocale) {
7727 return;
7730 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7731 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7732 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7734 // Get current values.
7735 $monetary= setlocale (LC_MONETARY, 0);
7736 $numeric = setlocale (LC_NUMERIC, 0);
7737 $ctype = setlocale (LC_CTYPE, 0);
7738 if ($CFG->ostype != 'WINDOWS') {
7739 $messages= setlocale (LC_MESSAGES, 0);
7741 // Set locale to all.
7742 $result = setlocale (LC_ALL, $currentlocale);
7743 // If setting of locale fails try the other utf8 or utf-8 variant,
7744 // some operating systems support both (Debian), others just one (OSX).
7745 if ($result === false) {
7746 if (stripos($currentlocale, '.UTF-8') !== false) {
7747 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7748 setlocale (LC_ALL, $newlocale);
7749 } else if (stripos($currentlocale, '.UTF8') !== false) {
7750 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7751 setlocale (LC_ALL, $newlocale);
7754 // Set old values.
7755 setlocale (LC_MONETARY, $monetary);
7756 setlocale (LC_NUMERIC, $numeric);
7757 if ($CFG->ostype != 'WINDOWS') {
7758 setlocale (LC_MESSAGES, $messages);
7760 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7761 // To workaround a well-known PHP problem with Turkish letter Ii.
7762 setlocale (LC_CTYPE, $ctype);
7767 * Count words in a string.
7769 * Words are defined as things between whitespace.
7771 * @category string
7772 * @param string $string The text to be searched for words.
7773 * @return int The count of words in the specified string
7775 function count_words($string) {
7776 $string = strip_tags($string);
7777 // Decode HTML entities.
7778 $string = html_entity_decode($string);
7779 // Replace underscores (which are classed as word characters) with spaces.
7780 $string = preg_replace('/_/u', ' ', $string);
7781 // Remove any characters that shouldn't be treated as word boundaries.
7782 $string = preg_replace('/[\'’-]/u', '', $string);
7783 // Remove dots and commas from within numbers only.
7784 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7786 return count(preg_split('/\w\b/u', $string)) - 1;
7790 * Count letters in a string.
7792 * Letters are defined as chars not in tags and different from whitespace.
7794 * @category string
7795 * @param string $string The text to be searched for letters.
7796 * @return int The count of letters in the specified text.
7798 function count_letters($string) {
7799 $string = strip_tags($string); // Tags are out now.
7800 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7802 return core_text::strlen($string);
7806 * Generate and return a random string of the specified length.
7808 * @param int $length The length of the string to be created.
7809 * @return string
7811 function random_string ($length=15) {
7812 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7813 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7814 $pool .= '0123456789';
7815 $poollen = strlen($pool);
7816 $string = '';
7817 for ($i = 0; $i < $length; $i++) {
7818 $string .= substr($pool, (mt_rand()%($poollen)), 1);
7820 return $string;
7824 * Generate a complex random string (useful for md5 salts)
7826 * This function is based on the above {@link random_string()} however it uses a
7827 * larger pool of characters and generates a string between 24 and 32 characters
7829 * @param int $length Optional if set generates a string to exactly this length
7830 * @return string
7832 function complex_random_string($length=null) {
7833 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7834 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7835 $poollen = strlen($pool);
7836 if ($length===null) {
7837 $length = floor(rand(24, 32));
7839 $string = '';
7840 for ($i = 0; $i < $length; $i++) {
7841 $string .= $pool[(mt_rand()%$poollen)];
7843 return $string;
7847 * Given some text (which may contain HTML) and an ideal length,
7848 * this function truncates the text neatly on a word boundary if possible
7850 * @category string
7851 * @param string $text text to be shortened
7852 * @param int $ideal ideal string length
7853 * @param boolean $exact if false, $text will not be cut mid-word
7854 * @param string $ending The string to append if the passed string is truncated
7855 * @return string $truncate shortened string
7857 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7858 // If the plain text is shorter than the maximum length, return the whole text.
7859 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7860 return $text;
7863 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7864 // and only tag in its 'line'.
7865 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7867 $totallength = core_text::strlen($ending);
7868 $truncate = '';
7870 // This array stores information about open and close tags and their position
7871 // in the truncated string. Each item in the array is an object with fields
7872 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7873 // (byte position in truncated text).
7874 $tagdetails = array();
7876 foreach ($lines as $linematchings) {
7877 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7878 if (!empty($linematchings[1])) {
7879 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7880 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7881 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7882 // Record closing tag.
7883 $tagdetails[] = (object) array(
7884 'open' => false,
7885 'tag' => core_text::strtolower($tagmatchings[1]),
7886 'pos' => core_text::strlen($truncate),
7889 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7890 // Record opening tag.
7891 $tagdetails[] = (object) array(
7892 'open' => true,
7893 'tag' => core_text::strtolower($tagmatchings[1]),
7894 'pos' => core_text::strlen($truncate),
7898 // Add html-tag to $truncate'd text.
7899 $truncate .= $linematchings[1];
7902 // Calculate the length of the plain text part of the line; handle entities as one character.
7903 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7904 if ($totallength + $contentlength > $ideal) {
7905 // The number of characters which are left.
7906 $left = $ideal - $totallength;
7907 $entitieslength = 0;
7908 // Search for html entities.
7909 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)) {
7910 // Calculate the real length of all entities in the legal range.
7911 foreach ($entities[0] as $entity) {
7912 if ($entity[1]+1-$entitieslength <= $left) {
7913 $left--;
7914 $entitieslength += core_text::strlen($entity[0]);
7915 } else {
7916 // No more characters left.
7917 break;
7921 $breakpos = $left + $entitieslength;
7923 // If the words shouldn't be cut in the middle...
7924 if (!$exact) {
7925 // Search the last occurence of a space.
7926 for (; $breakpos > 0; $breakpos--) {
7927 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
7928 if ($char === '.' or $char === ' ') {
7929 $breakpos += 1;
7930 break;
7931 } else if (strlen($char) > 2) {
7932 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7933 $breakpos += 1;
7934 break;
7939 if ($breakpos == 0) {
7940 // This deals with the test_shorten_text_no_spaces case.
7941 $breakpos = $left + $entitieslength;
7942 } else if ($breakpos > $left + $entitieslength) {
7943 // This deals with the previous for loop breaking on the first char.
7944 $breakpos = $left + $entitieslength;
7947 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
7948 // Maximum length is reached, so get off the loop.
7949 break;
7950 } else {
7951 $truncate .= $linematchings[2];
7952 $totallength += $contentlength;
7955 // If the maximum length is reached, get off the loop.
7956 if ($totallength >= $ideal) {
7957 break;
7961 // Add the defined ending to the text.
7962 $truncate .= $ending;
7964 // Now calculate the list of open html tags based on the truncate position.
7965 $opentags = array();
7966 foreach ($tagdetails as $taginfo) {
7967 if ($taginfo->open) {
7968 // Add tag to the beginning of $opentags list.
7969 array_unshift($opentags, $taginfo->tag);
7970 } else {
7971 // Can have multiple exact same open tags, close the last one.
7972 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
7973 if ($pos !== false) {
7974 unset($opentags[$pos]);
7979 // Close all unclosed html-tags.
7980 foreach ($opentags as $tag) {
7981 $truncate .= '</' . $tag . '>';
7984 return $truncate;
7989 * Given dates in seconds, how many weeks is the date from startdate
7990 * The first week is 1, the second 2 etc ...
7992 * @param int $startdate Timestamp for the start date
7993 * @param int $thedate Timestamp for the end date
7994 * @return string
7996 function getweek ($startdate, $thedate) {
7997 if ($thedate < $startdate) {
7998 return 0;
8001 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8005 * Returns a randomly generated password of length $maxlen. inspired by
8007 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8008 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8010 * @param int $maxlen The maximum size of the password being generated.
8011 * @return string
8013 function generate_password($maxlen=10) {
8014 global $CFG;
8016 if (empty($CFG->passwordpolicy)) {
8017 $fillers = PASSWORD_DIGITS;
8018 $wordlist = file($CFG->wordlist);
8019 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8020 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8021 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8022 $password = $word1 . $filler1 . $word2;
8023 } else {
8024 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8025 $digits = $CFG->minpassworddigits;
8026 $lower = $CFG->minpasswordlower;
8027 $upper = $CFG->minpasswordupper;
8028 $nonalphanum = $CFG->minpasswordnonalphanum;
8029 $total = $lower + $upper + $digits + $nonalphanum;
8030 // Var minlength should be the greater one of the two ( $minlen and $total ).
8031 $minlen = $minlen < $total ? $total : $minlen;
8032 // Var maxlen can never be smaller than minlen.
8033 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8034 $additional = $maxlen - $total;
8036 // Make sure we have enough characters to fulfill
8037 // complexity requirements.
8038 $passworddigits = PASSWORD_DIGITS;
8039 while ($digits > strlen($passworddigits)) {
8040 $passworddigits .= PASSWORD_DIGITS;
8042 $passwordlower = PASSWORD_LOWER;
8043 while ($lower > strlen($passwordlower)) {
8044 $passwordlower .= PASSWORD_LOWER;
8046 $passwordupper = PASSWORD_UPPER;
8047 while ($upper > strlen($passwordupper)) {
8048 $passwordupper .= PASSWORD_UPPER;
8050 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8051 while ($nonalphanum > strlen($passwordnonalphanum)) {
8052 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8055 // Now mix and shuffle it all.
8056 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8057 substr(str_shuffle ($passwordupper), 0, $upper) .
8058 substr(str_shuffle ($passworddigits), 0, $digits) .
8059 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8060 substr(str_shuffle ($passwordlower .
8061 $passwordupper .
8062 $passworddigits .
8063 $passwordnonalphanum), 0 , $additional));
8066 return substr ($password, 0, $maxlen);
8070 * Given a float, prints it nicely.
8071 * Localized floats must not be used in calculations!
8073 * The stripzeros feature is intended for making numbers look nicer in small
8074 * areas where it is not necessary to indicate the degree of accuracy by showing
8075 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8076 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8078 * @param float $float The float to print
8079 * @param int $decimalpoints The number of decimal places to print.
8080 * @param bool $localized use localized decimal separator
8081 * @param bool $stripzeros If true, removes final zeros after decimal point
8082 * @return string locale float
8084 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8085 if (is_null($float)) {
8086 return '';
8088 if ($localized) {
8089 $separator = get_string('decsep', 'langconfig');
8090 } else {
8091 $separator = '.';
8093 $result = number_format($float, $decimalpoints, $separator, '');
8094 if ($stripzeros) {
8095 // Remove zeros and final dot if not needed.
8096 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8098 return $result;
8102 * Converts locale specific floating point/comma number back to standard PHP float value
8103 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8105 * @param string $localefloat locale aware float representation
8106 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8107 * @return mixed float|bool - false or the parsed float.
8109 function unformat_float($localefloat, $strict = false) {
8110 $localefloat = trim($localefloat);
8112 if ($localefloat == '') {
8113 return null;
8116 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8117 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8119 if ($strict && !is_numeric($localefloat)) {
8120 return false;
8123 return (float)$localefloat;
8127 * Given a simple array, this shuffles it up just like shuffle()
8128 * Unlike PHP's shuffle() this function works on any machine.
8130 * @param array $array The array to be rearranged
8131 * @return array
8133 function swapshuffle($array) {
8135 $last = count($array) - 1;
8136 for ($i = 0; $i <= $last; $i++) {
8137 $from = rand(0, $last);
8138 $curr = $array[$i];
8139 $array[$i] = $array[$from];
8140 $array[$from] = $curr;
8142 return $array;
8146 * Like {@link swapshuffle()}, but works on associative arrays
8148 * @param array $array The associative array to be rearranged
8149 * @return array
8151 function swapshuffle_assoc($array) {
8153 $newarray = array();
8154 $newkeys = swapshuffle(array_keys($array));
8156 foreach ($newkeys as $newkey) {
8157 $newarray[$newkey] = $array[$newkey];
8159 return $newarray;
8163 * Given an arbitrary array, and a number of draws,
8164 * this function returns an array with that amount
8165 * of items. The indexes are retained.
8167 * @todo Finish documenting this function
8169 * @param array $array
8170 * @param int $draws
8171 * @return array
8173 function draw_rand_array($array, $draws) {
8175 $return = array();
8177 $last = count($array);
8179 if ($draws > $last) {
8180 $draws = $last;
8183 while ($draws > 0) {
8184 $last--;
8186 $keys = array_keys($array);
8187 $rand = rand(0, $last);
8189 $return[$keys[$rand]] = $array[$keys[$rand]];
8190 unset($array[$keys[$rand]]);
8192 $draws--;
8195 return $return;
8199 * Calculate the difference between two microtimes
8201 * @param string $a The first Microtime
8202 * @param string $b The second Microtime
8203 * @return string
8205 function microtime_diff($a, $b) {
8206 list($adec, $asec) = explode(' ', $a);
8207 list($bdec, $bsec) = explode(' ', $b);
8208 return $bsec - $asec + $bdec - $adec;
8212 * Given a list (eg a,b,c,d,e) this function returns
8213 * an array of 1->a, 2->b, 3->c etc
8215 * @param string $list The string to explode into array bits
8216 * @param string $separator The separator used within the list string
8217 * @return array The now assembled array
8219 function make_menu_from_list($list, $separator=',') {
8221 $array = array_reverse(explode($separator, $list), true);
8222 foreach ($array as $key => $item) {
8223 $outarray[$key+1] = trim($item);
8225 return $outarray;
8229 * Creates an array that represents all the current grades that
8230 * can be chosen using the given grading type.
8232 * Negative numbers
8233 * are scales, zero is no grade, and positive numbers are maximum
8234 * grades.
8236 * @todo Finish documenting this function or better deprecated this completely!
8238 * @param int $gradingtype
8239 * @return array
8241 function make_grades_menu($gradingtype) {
8242 global $DB;
8244 $grades = array();
8245 if ($gradingtype < 0) {
8246 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8247 return make_menu_from_list($scale->scale);
8249 } else if ($gradingtype > 0) {
8250 for ($i=$gradingtype; $i>=0; $i--) {
8251 $grades[$i] = $i .' / '. $gradingtype;
8253 return $grades;
8255 return $grades;
8259 * This function returns the number of activities using the given scale in the given course.
8261 * @param int $courseid The course ID to check.
8262 * @param int $scaleid The scale ID to check
8263 * @return int
8265 function course_scale_used($courseid, $scaleid) {
8266 global $CFG, $DB;
8268 $return = 0;
8270 if (!empty($scaleid)) {
8271 if ($cms = get_course_mods($courseid)) {
8272 foreach ($cms as $cm) {
8273 // Check cm->name/lib.php exists.
8274 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
8275 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
8276 $functionname = $cm->modname.'_scale_used';
8277 if (function_exists($functionname)) {
8278 if ($functionname($cm->instance, $scaleid)) {
8279 $return++;
8286 // Check if any course grade item makes use of the scale.
8287 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8289 // Check if any outcome in the course makes use of the scale.
8290 $return += $DB->count_records_sql("SELECT COUNT('x')
8291 FROM {grade_outcomes_courses} goc,
8292 {grade_outcomes} go
8293 WHERE go.id = goc.outcomeid
8294 AND go.scaleid = ? AND goc.courseid = ?",
8295 array($scaleid, $courseid));
8297 return $return;
8301 * This function returns the number of activities using scaleid in the entire site
8303 * @param int $scaleid
8304 * @param array $courses
8305 * @return int
8307 function site_scale_used($scaleid, &$courses) {
8308 $return = 0;
8310 if (!is_array($courses) || count($courses) == 0) {
8311 $courses = get_courses("all", false, "c.id, c.shortname");
8314 if (!empty($scaleid)) {
8315 if (is_array($courses) && count($courses) > 0) {
8316 foreach ($courses as $course) {
8317 $return += course_scale_used($course->id, $scaleid);
8321 return $return;
8325 * make_unique_id_code
8327 * @todo Finish documenting this function
8329 * @uses $_SERVER
8330 * @param string $extra Extra string to append to the end of the code
8331 * @return string
8333 function make_unique_id_code($extra = '') {
8335 $hostname = 'unknownhost';
8336 if (!empty($_SERVER['HTTP_HOST'])) {
8337 $hostname = $_SERVER['HTTP_HOST'];
8338 } else if (!empty($_ENV['HTTP_HOST'])) {
8339 $hostname = $_ENV['HTTP_HOST'];
8340 } else if (!empty($_SERVER['SERVER_NAME'])) {
8341 $hostname = $_SERVER['SERVER_NAME'];
8342 } else if (!empty($_ENV['SERVER_NAME'])) {
8343 $hostname = $_ENV['SERVER_NAME'];
8346 $date = gmdate("ymdHis");
8348 $random = random_string(6);
8350 if ($extra) {
8351 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8352 } else {
8353 return $hostname .'+'. $date .'+'. $random;
8359 * Function to check the passed address is within the passed subnet
8361 * The parameter is a comma separated string of subnet definitions.
8362 * Subnet strings can be in one of three formats:
8363 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8364 * 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)
8365 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8366 * Code for type 1 modified from user posted comments by mediator at
8367 * {@link http://au.php.net/manual/en/function.ip2long.php}
8369 * @param string $addr The address you are checking
8370 * @param string $subnetstr The string of subnet addresses
8371 * @return bool
8373 function address_in_subnet($addr, $subnetstr) {
8375 if ($addr == '0.0.0.0') {
8376 return false;
8378 $subnets = explode(',', $subnetstr);
8379 $found = false;
8380 $addr = trim($addr);
8381 $addr = cleanremoteaddr($addr, false); // Normalise.
8382 if ($addr === null) {
8383 return false;
8385 $addrparts = explode(':', $addr);
8387 $ipv6 = strpos($addr, ':');
8389 foreach ($subnets as $subnet) {
8390 $subnet = trim($subnet);
8391 if ($subnet === '') {
8392 continue;
8395 if (strpos($subnet, '/') !== false) {
8396 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8397 list($ip, $mask) = explode('/', $subnet);
8398 $mask = trim($mask);
8399 if (!is_number($mask)) {
8400 continue; // Incorect mask number, eh?
8402 $ip = cleanremoteaddr($ip, false); // Normalise.
8403 if ($ip === null) {
8404 continue;
8406 if (strpos($ip, ':') !== false) {
8407 // IPv6.
8408 if (!$ipv6) {
8409 continue;
8411 if ($mask > 128 or $mask < 0) {
8412 continue; // Nonsense.
8414 if ($mask == 0) {
8415 return true; // Any address.
8417 if ($mask == 128) {
8418 if ($ip === $addr) {
8419 return true;
8421 continue;
8423 $ipparts = explode(':', $ip);
8424 $modulo = $mask % 16;
8425 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8426 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8427 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8428 if ($modulo == 0) {
8429 return true;
8431 $pos = ($mask-$modulo)/16;
8432 $ipnet = hexdec($ipparts[$pos]);
8433 $addrnet = hexdec($addrparts[$pos]);
8434 $mask = 0xffff << (16 - $modulo);
8435 if (($addrnet & $mask) == ($ipnet & $mask)) {
8436 return true;
8440 } else {
8441 // IPv4.
8442 if ($ipv6) {
8443 continue;
8445 if ($mask > 32 or $mask < 0) {
8446 continue; // Nonsense.
8448 if ($mask == 0) {
8449 return true;
8451 if ($mask == 32) {
8452 if ($ip === $addr) {
8453 return true;
8455 continue;
8457 $mask = 0xffffffff << (32 - $mask);
8458 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8459 return true;
8463 } else if (strpos($subnet, '-') !== false) {
8464 // 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.
8465 $parts = explode('-', $subnet);
8466 if (count($parts) != 2) {
8467 continue;
8470 if (strpos($subnet, ':') !== false) {
8471 // IPv6.
8472 if (!$ipv6) {
8473 continue;
8475 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8476 if ($ipstart === null) {
8477 continue;
8479 $ipparts = explode(':', $ipstart);
8480 $start = hexdec(array_pop($ipparts));
8481 $ipparts[] = trim($parts[1]);
8482 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8483 if ($ipend === null) {
8484 continue;
8486 $ipparts[7] = '';
8487 $ipnet = implode(':', $ipparts);
8488 if (strpos($addr, $ipnet) !== 0) {
8489 continue;
8491 $ipparts = explode(':', $ipend);
8492 $end = hexdec($ipparts[7]);
8494 $addrend = hexdec($addrparts[7]);
8496 if (($addrend >= $start) and ($addrend <= $end)) {
8497 return true;
8500 } else {
8501 // IPv4.
8502 if ($ipv6) {
8503 continue;
8505 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8506 if ($ipstart === null) {
8507 continue;
8509 $ipparts = explode('.', $ipstart);
8510 $ipparts[3] = trim($parts[1]);
8511 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8512 if ($ipend === null) {
8513 continue;
8516 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8517 return true;
8521 } else {
8522 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8523 if (strpos($subnet, ':') !== false) {
8524 // IPv6.
8525 if (!$ipv6) {
8526 continue;
8528 $parts = explode(':', $subnet);
8529 $count = count($parts);
8530 if ($parts[$count-1] === '') {
8531 unset($parts[$count-1]); // Trim trailing :'s.
8532 $count--;
8533 $subnet = implode('.', $parts);
8535 $isip = cleanremoteaddr($subnet, false); // Normalise.
8536 if ($isip !== null) {
8537 if ($isip === $addr) {
8538 return true;
8540 continue;
8541 } else if ($count > 8) {
8542 continue;
8544 $zeros = array_fill(0, 8-$count, '0');
8545 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8546 if (address_in_subnet($addr, $subnet)) {
8547 return true;
8550 } else {
8551 // IPv4.
8552 if ($ipv6) {
8553 continue;
8555 $parts = explode('.', $subnet);
8556 $count = count($parts);
8557 if ($parts[$count-1] === '') {
8558 unset($parts[$count-1]); // Trim trailing .
8559 $count--;
8560 $subnet = implode('.', $parts);
8562 if ($count == 4) {
8563 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8564 if ($subnet === $addr) {
8565 return true;
8567 continue;
8568 } else if ($count > 4) {
8569 continue;
8571 $zeros = array_fill(0, 4-$count, '0');
8572 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8573 if (address_in_subnet($addr, $subnet)) {
8574 return true;
8580 return false;
8584 * For outputting debugging info
8586 * @param string $string The string to write
8587 * @param string $eol The end of line char(s) to use
8588 * @param string $sleep Period to make the application sleep
8589 * This ensures any messages have time to display before redirect
8591 function mtrace($string, $eol="\n", $sleep=0) {
8593 if (defined('STDOUT') and !PHPUNIT_TEST) {
8594 fwrite(STDOUT, $string.$eol);
8595 } else {
8596 echo $string . $eol;
8599 flush();
8601 // Delay to keep message on user's screen in case of subsequent redirect.
8602 if ($sleep) {
8603 sleep($sleep);
8608 * Replace 1 or more slashes or backslashes to 1 slash
8610 * @param string $path The path to strip
8611 * @return string the path with double slashes removed
8613 function cleardoubleslashes ($path) {
8614 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8618 * Is current ip in give list?
8620 * @param string $list
8621 * @return bool
8623 function remoteip_in_list($list) {
8624 $inlist = false;
8625 $clientip = getremoteaddr(null);
8627 if (!$clientip) {
8628 // Ensure access on cli.
8629 return true;
8632 $list = explode("\n", $list);
8633 foreach ($list as $subnet) {
8634 $subnet = trim($subnet);
8635 if (address_in_subnet($clientip, $subnet)) {
8636 $inlist = true;
8637 break;
8640 return $inlist;
8644 * Returns most reliable client address
8646 * @param string $default If an address can't be determined, then return this
8647 * @return string The remote IP address
8649 function getremoteaddr($default='0.0.0.0') {
8650 global $CFG;
8652 if (empty($CFG->getremoteaddrconf)) {
8653 // This will happen, for example, before just after the upgrade, as the
8654 // user is redirected to the admin screen.
8655 $variablestoskip = 0;
8656 } else {
8657 $variablestoskip = $CFG->getremoteaddrconf;
8659 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8660 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8661 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8662 return $address ? $address : $default;
8665 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8666 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8667 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8668 $address = $forwardedaddresses[0];
8670 if (substr_count($address, ":") > 1) {
8671 // Remove port and brackets from IPv6.
8672 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8673 $address = $matches[1];
8675 } else {
8676 // Remove port from IPv4.
8677 if (substr_count($address, ":") == 1) {
8678 $parts = explode(":", $address);
8679 $address = $parts[0];
8683 $address = cleanremoteaddr($address);
8684 return $address ? $address : $default;
8687 if (!empty($_SERVER['REMOTE_ADDR'])) {
8688 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8689 return $address ? $address : $default;
8690 } else {
8691 return $default;
8696 * Cleans an ip address. Internal addresses are now allowed.
8697 * (Originally local addresses were not allowed.)
8699 * @param string $addr IPv4 or IPv6 address
8700 * @param bool $compress use IPv6 address compression
8701 * @return string normalised ip address string, null if error
8703 function cleanremoteaddr($addr, $compress=false) {
8704 $addr = trim($addr);
8706 // TODO: maybe add a separate function is_addr_public() or something like this.
8708 if (strpos($addr, ':') !== false) {
8709 // Can be only IPv6.
8710 $parts = explode(':', $addr);
8711 $count = count($parts);
8713 if (strpos($parts[$count-1], '.') !== false) {
8714 // Legacy ipv4 notation.
8715 $last = array_pop($parts);
8716 $ipv4 = cleanremoteaddr($last, true);
8717 if ($ipv4 === null) {
8718 return null;
8720 $bits = explode('.', $ipv4);
8721 $parts[] = dechex($bits[0]).dechex($bits[1]);
8722 $parts[] = dechex($bits[2]).dechex($bits[3]);
8723 $count = count($parts);
8724 $addr = implode(':', $parts);
8727 if ($count < 3 or $count > 8) {
8728 return null; // Severly malformed.
8731 if ($count != 8) {
8732 if (strpos($addr, '::') === false) {
8733 return null; // Malformed.
8735 // Uncompress.
8736 $insertat = array_search('', $parts, true);
8737 $missing = array_fill(0, 1 + 8 - $count, '0');
8738 array_splice($parts, $insertat, 1, $missing);
8739 foreach ($parts as $key => $part) {
8740 if ($part === '') {
8741 $parts[$key] = '0';
8746 $adr = implode(':', $parts);
8747 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8748 return null; // Incorrect format - sorry.
8751 // Normalise 0s and case.
8752 $parts = array_map('hexdec', $parts);
8753 $parts = array_map('dechex', $parts);
8755 $result = implode(':', $parts);
8757 if (!$compress) {
8758 return $result;
8761 if ($result === '0:0:0:0:0:0:0:0') {
8762 return '::'; // All addresses.
8765 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8766 if ($compressed !== $result) {
8767 return $compressed;
8770 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8771 if ($compressed !== $result) {
8772 return $compressed;
8775 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8776 if ($compressed !== $result) {
8777 return $compressed;
8780 return $result;
8783 // First get all things that look like IPv4 addresses.
8784 $parts = array();
8785 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8786 return null;
8788 unset($parts[0]);
8790 foreach ($parts as $key => $match) {
8791 if ($match > 255) {
8792 return null;
8794 $parts[$key] = (int)$match; // Normalise 0s.
8797 return implode('.', $parts);
8801 * This function will make a complete copy of anything it's given,
8802 * regardless of whether it's an object or not.
8804 * @param mixed $thing Something you want cloned
8805 * @return mixed What ever it is you passed it
8807 function fullclone($thing) {
8808 return unserialize(serialize($thing));
8812 * If new messages are waiting for the current user, then insert
8813 * JavaScript to pop up the messaging window into the page
8815 * @return void
8817 function message_popup_window() {
8818 global $USER, $DB, $PAGE, $CFG;
8820 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
8821 return;
8824 if (!isloggedin() || isguestuser()) {
8825 return;
8828 if (!isset($USER->message_lastpopup)) {
8829 $USER->message_lastpopup = 0;
8830 } else if ($USER->message_lastpopup > (time()-120)) {
8831 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8832 return;
8835 // A quick query to check whether the user has new messages.
8836 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
8837 if ($messagecount < 1) {
8838 return;
8841 // There are unread messages so now do a more complex but slower query.
8842 $messagesql = "SELECT m.id, c.blocked
8843 FROM {message} m
8844 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8845 JOIN {message_processors} p ON mw.processorid=p.id
8846 JOIN {user} u ON m.useridfrom=u.id
8847 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8848 AND c.userid = m.useridto
8849 WHERE m.useridto = :userid
8850 AND p.name='popup'";
8852 // If the user was last notified over an hour ago we can re-notify them of old messages
8853 // so don't worry about when the new message was sent.
8854 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
8855 if (!$lastnotifiedlongago) {
8856 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8859 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
8861 $validmessages = 0;
8862 foreach ($waitingmessages as $messageinfo) {
8863 if ($messageinfo->blocked) {
8864 // Message is from a user who has since been blocked so just mark it read.
8865 // Get the full message to mark as read.
8866 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id));
8867 message_mark_message_read($messageobject, time());
8868 } else {
8869 $validmessages++;
8873 if ($validmessages > 0) {
8874 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8875 $strgomessage = get_string('gotomessages', 'message');
8876 $strstaymessage = get_string('ignore', 'admin');
8878 $notificationsound = null;
8879 $beep = get_user_preferences('message_beepnewmessage', '');
8880 if (!empty($beep)) {
8881 // Browsers will work down this list until they find something they support.
8882 $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
8883 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
8884 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8885 $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8887 $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8890 $url = $CFG->wwwroot.'/message/index.php';
8891 $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8892 html_writer::start_tag('div', array('id' => 'newmessagetext')).
8893 $strmessages.
8894 html_writer::end_tag('div').
8896 $notificationsound.
8897 html_writer::start_tag('div', array('id' => 'newmessagelinks')).
8898 html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
8899 html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
8900 html_writer::end_tag('div');
8901 html_writer::end_tag('div');
8903 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
8905 $USER->message_lastpopup = time();
8910 * Used to make sure that $min <= $value <= $max
8912 * Make sure that value is between min, and max
8914 * @param int $min The minimum value
8915 * @param int $value The value to check
8916 * @param int $max The maximum value
8917 * @return int
8919 function bounded_number($min, $value, $max) {
8920 if ($value < $min) {
8921 return $min;
8923 if ($value > $max) {
8924 return $max;
8926 return $value;
8930 * Check if there is a nested array within the passed array
8932 * @param array $array
8933 * @return bool true if there is a nested array false otherwise
8935 function array_is_nested($array) {
8936 foreach ($array as $value) {
8937 if (is_array($value)) {
8938 return true;
8941 return false;
8945 * get_performance_info() pairs up with init_performance_info()
8946 * loaded in setup.php. Returns an array with 'html' and 'txt'
8947 * values ready for use, and each of the individual stats provided
8948 * separately as well.
8950 * @return array
8952 function get_performance_info() {
8953 global $CFG, $PERF, $DB, $PAGE;
8955 $info = array();
8956 $info['html'] = ''; // Holds userfriendly HTML representation.
8957 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8959 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8961 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8962 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8964 if (function_exists('memory_get_usage')) {
8965 $info['memory_total'] = memory_get_usage();
8966 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8967 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8968 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8969 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8972 if (function_exists('memory_get_peak_usage')) {
8973 $info['memory_peak'] = memory_get_peak_usage();
8974 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8975 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8978 $inc = get_included_files();
8979 $info['includecount'] = count($inc);
8980 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8981 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8983 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8984 // We can not track more performance before installation or before PAGE init, sorry.
8985 return $info;
8988 $filtermanager = filter_manager::instance();
8989 if (method_exists($filtermanager, 'get_performance_summary')) {
8990 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8991 $info = array_merge($filterinfo, $info);
8992 foreach ($filterinfo as $key => $value) {
8993 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8994 $info['txt'] .= "$key: $value ";
8998 $stringmanager = get_string_manager();
8999 if (method_exists($stringmanager, 'get_performance_summary')) {
9000 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9001 $info = array_merge($filterinfo, $info);
9002 foreach ($filterinfo as $key => $value) {
9003 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
9004 $info['txt'] .= "$key: $value ";
9008 if (!empty($PERF->logwrites)) {
9009 $info['logwrites'] = $PERF->logwrites;
9010 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
9011 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9014 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9015 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
9016 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9018 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9019 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
9020 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9022 if (function_exists('posix_times')) {
9023 $ptimes = posix_times();
9024 if (is_array($ptimes)) {
9025 foreach ($ptimes as $key => $val) {
9026 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9028 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
9029 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9033 // Grab the load average for the last minute.
9034 // /proc will only work under some linux configurations
9035 // while uptime is there under MacOSX/Darwin and other unices.
9036 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9037 list($serverload) = explode(' ', $loadavg[0]);
9038 unset($loadavg);
9039 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9040 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9041 $serverload = $matches[1];
9042 } else {
9043 trigger_error('Could not parse uptime output!');
9046 if (!empty($serverload)) {
9047 $info['serverload'] = $serverload;
9048 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
9049 $info['txt'] .= "serverload: {$info['serverload']} ";
9052 // Display size of session if session started.
9053 if ($si = \core\session\manager::get_performance_info()) {
9054 $info['sessionsize'] = $si['size'];
9055 $info['html'] .= $si['html'];
9056 $info['txt'] .= $si['txt'];
9059 if ($stats = cache_helper::get_stats()) {
9060 $html = '<span class="cachesused">';
9061 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
9062 $text = 'Caches used (hits/misses/sets): ';
9063 $hits = 0;
9064 $misses = 0;
9065 $sets = 0;
9066 foreach ($stats as $definition => $stores) {
9067 $html .= '<span class="cache-definition-stats">';
9068 $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
9069 $text .= "$definition {";
9070 foreach ($stores as $store => $data) {
9071 $hits += $data['hits'];
9072 $misses += $data['misses'];
9073 $sets += $data['sets'];
9074 if ($data['hits'] == 0 and $data['misses'] > 0) {
9075 $cachestoreclass = 'nohits';
9076 } else if ($data['hits'] < $data['misses']) {
9077 $cachestoreclass = 'lowhits';
9078 } else {
9079 $cachestoreclass = 'hihits';
9081 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9082 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
9084 $html .= '</span>';
9085 $text .= '} ';
9087 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
9088 $html .= '</span> ';
9089 $info['cachesused'] = "$hits / $misses / $sets";
9090 $info['html'] .= $html;
9091 $info['txt'] .= $text.'. ';
9092 } else {
9093 $info['cachesused'] = '0 / 0 / 0';
9094 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
9095 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9098 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
9099 return $info;
9103 * Legacy function.
9105 * @todo Document this function linux people
9107 function apd_get_profiling() {
9108 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
9112 * Delete directory or only its content
9114 * @param string $dir directory path
9115 * @param bool $contentonly
9116 * @return bool success, true also if dir does not exist
9118 function remove_dir($dir, $contentonly=false) {
9119 if (!file_exists($dir)) {
9120 // Nothing to do.
9121 return true;
9123 if (!$handle = opendir($dir)) {
9124 return false;
9126 $result = true;
9127 while (false!==($item = readdir($handle))) {
9128 if ($item != '.' && $item != '..') {
9129 if (is_dir($dir.'/'.$item)) {
9130 $result = remove_dir($dir.'/'.$item) && $result;
9131 } else {
9132 $result = unlink($dir.'/'.$item) && $result;
9136 closedir($handle);
9137 if ($contentonly) {
9138 clearstatcache(); // Make sure file stat cache is properly invalidated.
9139 return $result;
9141 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9142 clearstatcache(); // Make sure file stat cache is properly invalidated.
9143 return $result;
9147 * Detect if an object or a class contains a given property
9148 * will take an actual object or the name of a class
9150 * @param mix $obj Name of class or real object to test
9151 * @param string $property name of property to find
9152 * @return bool true if property exists
9154 function object_property_exists( $obj, $property ) {
9155 if (is_string( $obj )) {
9156 $properties = get_class_vars( $obj );
9157 } else {
9158 $properties = get_object_vars( $obj );
9160 return array_key_exists( $property, $properties );
9164 * Converts an object into an associative array
9166 * This function converts an object into an associative array by iterating
9167 * over its public properties. Because this function uses the foreach
9168 * construct, Iterators are respected. It works recursively on arrays of objects.
9169 * Arrays and simple values are returned as is.
9171 * If class has magic properties, it can implement IteratorAggregate
9172 * and return all available properties in getIterator()
9174 * @param mixed $var
9175 * @return array
9177 function convert_to_array($var) {
9178 $result = array();
9180 // Loop over elements/properties.
9181 foreach ($var as $key => $value) {
9182 // Recursively convert objects.
9183 if (is_object($value) || is_array($value)) {
9184 $result[$key] = convert_to_array($value);
9185 } else {
9186 // Simple values are untouched.
9187 $result[$key] = $value;
9190 return $result;
9194 * Detect a custom script replacement in the data directory that will
9195 * replace an existing moodle script
9197 * @return string|bool full path name if a custom script exists, false if no custom script exists
9199 function custom_script_path() {
9200 global $CFG, $SCRIPT;
9202 if ($SCRIPT === null) {
9203 // Probably some weird external script.
9204 return false;
9207 $scriptpath = $CFG->customscripts . $SCRIPT;
9209 // Check the custom script exists.
9210 if (file_exists($scriptpath) and is_file($scriptpath)) {
9211 return $scriptpath;
9212 } else {
9213 return false;
9218 * Returns whether or not the user object is a remote MNET user. This function
9219 * is in moodlelib because it does not rely on loading any of the MNET code.
9221 * @param object $user A valid user object
9222 * @return bool True if the user is from a remote Moodle.
9224 function is_mnet_remote_user($user) {
9225 global $CFG;
9227 if (!isset($CFG->mnet_localhost_id)) {
9228 include_once($CFG->dirroot . '/mnet/lib.php');
9229 $env = new mnet_environment();
9230 $env->init();
9231 unset($env);
9234 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9238 * This function will search for browser prefereed languages, setting Moodle
9239 * to use the best one available if $SESSION->lang is undefined
9241 function setup_lang_from_browser() {
9242 global $CFG, $SESSION, $USER;
9244 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9245 // Lang is defined in session or user profile, nothing to do.
9246 return;
9249 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9250 return;
9253 // Extract and clean langs from headers.
9254 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9255 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9256 $rawlangs = explode(',', $rawlangs); // Convert to array.
9257 $langs = array();
9259 $order = 1.0;
9260 foreach ($rawlangs as $lang) {
9261 if (strpos($lang, ';') === false) {
9262 $langs[(string)$order] = $lang;
9263 $order = $order-0.01;
9264 } else {
9265 $parts = explode(';', $lang);
9266 $pos = strpos($parts[1], '=');
9267 $langs[substr($parts[1], $pos+1)] = $parts[0];
9270 krsort($langs, SORT_NUMERIC);
9272 // Look for such langs under standard locations.
9273 foreach ($langs as $lang) {
9274 // Clean it properly for include.
9275 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9276 if (get_string_manager()->translation_exists($lang, false)) {
9277 // Lang exists, set it in session.
9278 $SESSION->lang = $lang;
9279 // We have finished. Go out.
9280 break;
9283 return;
9287 * Check if $url matches anything in proxybypass list
9289 * Any errors just result in the proxy being used (least bad)
9291 * @param string $url url to check
9292 * @return boolean true if we should bypass the proxy
9294 function is_proxybypass( $url ) {
9295 global $CFG;
9297 // Sanity check.
9298 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9299 return false;
9302 // Get the host part out of the url.
9303 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9304 return false;
9307 // Get the possible bypass hosts into an array.
9308 $matches = explode( ',', $CFG->proxybypass );
9310 // Check for a match.
9311 // (IPs need to match the left hand side and hosts the right of the url,
9312 // but we can recklessly check both as there can't be a false +ve).
9313 foreach ($matches as $match) {
9314 $match = trim($match);
9316 // Try for IP match (Left side).
9317 $lhs = substr($host, 0, strlen($match));
9318 if (strcasecmp($match, $lhs)==0) {
9319 return true;
9322 // Try for host match (Right side).
9323 $rhs = substr($host, -strlen($match));
9324 if (strcasecmp($match, $rhs)==0) {
9325 return true;
9329 // Nothing matched.
9330 return false;
9334 * Check if the passed navigation is of the new style
9336 * @param mixed $navigation
9337 * @return bool true for yes false for no
9339 function is_newnav($navigation) {
9340 if (is_array($navigation) && !empty($navigation['newnav'])) {
9341 return true;
9342 } else {
9343 return false;
9348 * Checks whether the given variable name is defined as a variable within the given object.
9350 * This will NOT work with stdClass objects, which have no class variables.
9352 * @param string $var The variable name
9353 * @param object $object The object to check
9354 * @return boolean
9356 function in_object_vars($var, $object) {
9357 $classvars = get_class_vars(get_class($object));
9358 $classvars = array_keys($classvars);
9359 return in_array($var, $classvars);
9363 * Returns an array without repeated objects.
9364 * This function is similar to array_unique, but for arrays that have objects as values
9366 * @param array $array
9367 * @param bool $keepkeyassoc
9368 * @return array
9370 function object_array_unique($array, $keepkeyassoc = true) {
9371 $duplicatekeys = array();
9372 $tmp = array();
9374 foreach ($array as $key => $val) {
9375 // Convert objects to arrays, in_array() does not support objects.
9376 if (is_object($val)) {
9377 $val = (array)$val;
9380 if (!in_array($val, $tmp)) {
9381 $tmp[] = $val;
9382 } else {
9383 $duplicatekeys[] = $key;
9387 foreach ($duplicatekeys as $key) {
9388 unset($array[$key]);
9391 return $keepkeyassoc ? $array : array_values($array);
9395 * Is a userid the primary administrator?
9397 * @param int $userid int id of user to check
9398 * @return boolean
9400 function is_primary_admin($userid) {
9401 $primaryadmin = get_admin();
9403 if ($userid == $primaryadmin->id) {
9404 return true;
9405 } else {
9406 return false;
9411 * Returns the site identifier
9413 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9415 function get_site_identifier() {
9416 global $CFG;
9417 // Check to see if it is missing. If so, initialise it.
9418 if (empty($CFG->siteidentifier)) {
9419 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9421 // Return it.
9422 return $CFG->siteidentifier;
9426 * Check whether the given password has no more than the specified
9427 * number of consecutive identical characters.
9429 * @param string $password password to be checked against the password policy
9430 * @param integer $maxchars maximum number of consecutive identical characters
9431 * @return bool
9433 function check_consecutive_identical_characters($password, $maxchars) {
9435 if ($maxchars < 1) {
9436 return true; // Zero 0 is to disable this check.
9438 if (strlen($password) <= $maxchars) {
9439 return true; // Too short to fail this test.
9442 $previouschar = '';
9443 $consecutivecount = 1;
9444 foreach (str_split($password) as $char) {
9445 if ($char != $previouschar) {
9446 $consecutivecount = 1;
9447 } else {
9448 $consecutivecount++;
9449 if ($consecutivecount > $maxchars) {
9450 return false; // Check failed already.
9454 $previouschar = $char;
9457 return true;
9461 * Helper function to do partial function binding.
9462 * so we can use it for preg_replace_callback, for example
9463 * this works with php functions, user functions, static methods and class methods
9464 * it returns you a callback that you can pass on like so:
9466 * $callback = partial('somefunction', $arg1, $arg2);
9467 * or
9468 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9469 * or even
9470 * $obj = new someclass();
9471 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9473 * and then the arguments that are passed through at calltime are appended to the argument list.
9475 * @param mixed $function a php callback
9476 * @param mixed $arg1,... $argv arguments to partially bind with
9477 * @return array Array callback
9479 function partial() {
9480 if (!class_exists('partial')) {
9482 * Used to manage function binding.
9483 * @copyright 2009 Penny Leach
9484 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9486 class partial{
9487 /** @var array */
9488 public $values = array();
9489 /** @var string The function to call as a callback. */
9490 public $func;
9492 * Constructor
9493 * @param string $func
9494 * @param array $args
9496 public function __construct($func, $args) {
9497 $this->values = $args;
9498 $this->func = $func;
9501 * Calls the callback function.
9502 * @return mixed
9504 public function method() {
9505 $args = func_get_args();
9506 return call_user_func_array($this->func, array_merge($this->values, $args));
9510 $args = func_get_args();
9511 $func = array_shift($args);
9512 $p = new partial($func, $args);
9513 return array($p, 'method');
9517 * helper function to load up and initialise the mnet environment
9518 * this must be called before you use mnet functions.
9520 * @return mnet_environment the equivalent of old $MNET global
9522 function get_mnet_environment() {
9523 global $CFG;
9524 require_once($CFG->dirroot . '/mnet/lib.php');
9525 static $instance = null;
9526 if (empty($instance)) {
9527 $instance = new mnet_environment();
9528 $instance->init();
9530 return $instance;
9534 * during xmlrpc server code execution, any code wishing to access
9535 * information about the remote peer must use this to get it.
9537 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9539 function get_mnet_remote_client() {
9540 if (!defined('MNET_SERVER')) {
9541 debugging(get_string('notinxmlrpcserver', 'mnet'));
9542 return false;
9544 global $MNET_REMOTE_CLIENT;
9545 if (isset($MNET_REMOTE_CLIENT)) {
9546 return $MNET_REMOTE_CLIENT;
9548 return false;
9552 * during the xmlrpc server code execution, this will be called
9553 * to setup the object returned by {@link get_mnet_remote_client}
9555 * @param mnet_remote_client $client the client to set up
9556 * @throws moodle_exception
9558 function set_mnet_remote_client($client) {
9559 if (!defined('MNET_SERVER')) {
9560 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9562 global $MNET_REMOTE_CLIENT;
9563 $MNET_REMOTE_CLIENT = $client;
9567 * return the jump url for a given remote user
9568 * this is used for rewriting forum post links in emails, etc
9570 * @param stdclass $user the user to get the idp url for
9572 function mnet_get_idp_jump_url($user) {
9573 global $CFG;
9575 static $mnetjumps = array();
9576 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9577 $idp = mnet_get_peer_host($user->mnethostid);
9578 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9579 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9581 return $mnetjumps[$user->mnethostid];
9585 * Gets the homepage to use for the current user
9587 * @return int One of HOMEPAGE_*
9589 function get_home_page() {
9590 global $CFG;
9592 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9593 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9594 return HOMEPAGE_MY;
9595 } else {
9596 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9599 return HOMEPAGE_SITE;
9603 * Gets the name of a course to be displayed when showing a list of courses.
9604 * By default this is just $course->fullname but user can configure it. The
9605 * result of this function should be passed through print_string.
9606 * @param stdClass|course_in_list $course Moodle course object
9607 * @return string Display name of course (either fullname or short + fullname)
9609 function get_course_display_name_for_list($course) {
9610 global $CFG;
9611 if (!empty($CFG->courselistshortnames)) {
9612 if (!($course instanceof stdClass)) {
9613 $course = (object)convert_to_array($course);
9615 return get_string('courseextendednamedisplay', '', $course);
9616 } else {
9617 return $course->fullname;
9622 * The lang_string class
9624 * This special class is used to create an object representation of a string request.
9625 * It is special because processing doesn't occur until the object is first used.
9626 * The class was created especially to aid performance in areas where strings were
9627 * required to be generated but were not necessarily used.
9628 * As an example the admin tree when generated uses over 1500 strings, of which
9629 * normally only 1/3 are ever actually printed at any time.
9630 * The performance advantage is achieved by not actually processing strings that
9631 * arn't being used, as such reducing the processing required for the page.
9633 * How to use the lang_string class?
9634 * There are two methods of using the lang_string class, first through the
9635 * forth argument of the get_string function, and secondly directly.
9636 * The following are examples of both.
9637 * 1. Through get_string calls e.g.
9638 * $string = get_string($identifier, $component, $a, true);
9639 * $string = get_string('yes', 'moodle', null, true);
9640 * 2. Direct instantiation
9641 * $string = new lang_string($identifier, $component, $a, $lang);
9642 * $string = new lang_string('yes');
9644 * How do I use a lang_string object?
9645 * The lang_string object makes use of a magic __toString method so that you
9646 * are able to use the object exactly as you would use a string in most cases.
9647 * This means you are able to collect it into a variable and then directly
9648 * echo it, or concatenate it into another string, or similar.
9649 * The other thing you can do is manually get the string by calling the
9650 * lang_strings out method e.g.
9651 * $string = new lang_string('yes');
9652 * $string->out();
9653 * Also worth noting is that the out method can take one argument, $lang which
9654 * allows the developer to change the language on the fly.
9656 * When should I use a lang_string object?
9657 * The lang_string object is designed to be used in any situation where a
9658 * string may not be needed, but needs to be generated.
9659 * The admin tree is a good example of where lang_string objects should be
9660 * used.
9661 * A more practical example would be any class that requries strings that may
9662 * not be printed (after all classes get renderer by renderers and who knows
9663 * what they will do ;))
9665 * When should I not use a lang_string object?
9666 * Don't use lang_strings when you are going to use a string immediately.
9667 * There is no need as it will be processed immediately and there will be no
9668 * advantage, and in fact perhaps a negative hit as a class has to be
9669 * instantiated for a lang_string object, however get_string won't require
9670 * that.
9672 * Limitations:
9673 * 1. You cannot use a lang_string object as an array offset. Doing so will
9674 * result in PHP throwing an error. (You can use it as an object property!)
9676 * @package core
9677 * @category string
9678 * @copyright 2011 Sam Hemelryk
9679 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9681 class lang_string {
9683 /** @var string The strings identifier */
9684 protected $identifier;
9685 /** @var string The strings component. Default '' */
9686 protected $component = '';
9687 /** @var array|stdClass Any arguments required for the string. Default null */
9688 protected $a = null;
9689 /** @var string The language to use when processing the string. Default null */
9690 protected $lang = null;
9692 /** @var string The processed string (once processed) */
9693 protected $string = null;
9696 * A special boolean. If set to true then the object has been woken up and
9697 * cannot be regenerated. If this is set then $this->string MUST be used.
9698 * @var bool
9700 protected $forcedstring = false;
9703 * Constructs a lang_string object
9705 * This function should do as little processing as possible to ensure the best
9706 * performance for strings that won't be used.
9708 * @param string $identifier The strings identifier
9709 * @param string $component The strings component
9710 * @param stdClass|array $a Any arguments the string requires
9711 * @param string $lang The language to use when processing the string.
9712 * @throws coding_exception
9714 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9715 if (empty($component)) {
9716 $component = 'moodle';
9719 $this->identifier = $identifier;
9720 $this->component = $component;
9721 $this->lang = $lang;
9723 // We MUST duplicate $a to ensure that it if it changes by reference those
9724 // changes are not carried across.
9725 // To do this we always ensure $a or its properties/values are strings
9726 // and that any properties/values that arn't convertable are forgotten.
9727 if (!empty($a)) {
9728 if (is_scalar($a)) {
9729 $this->a = $a;
9730 } else if ($a instanceof lang_string) {
9731 $this->a = $a->out();
9732 } else if (is_object($a) or is_array($a)) {
9733 $a = (array)$a;
9734 $this->a = array();
9735 foreach ($a as $key => $value) {
9736 // Make sure conversion errors don't get displayed (results in '').
9737 if (is_array($value)) {
9738 $this->a[$key] = '';
9739 } else if (is_object($value)) {
9740 if (method_exists($value, '__toString')) {
9741 $this->a[$key] = $value->__toString();
9742 } else {
9743 $this->a[$key] = '';
9745 } else {
9746 $this->a[$key] = (string)$value;
9752 if (debugging(false, DEBUG_DEVELOPER)) {
9753 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9754 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9756 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9757 throw new coding_exception('Invalid string compontent. Please check your string definition');
9759 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9760 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9766 * Processes the string.
9768 * This function actually processes the string, stores it in the string property
9769 * and then returns it.
9770 * You will notice that this function is VERY similar to the get_string method.
9771 * That is because it is pretty much doing the same thing.
9772 * However as this function is an upgrade it isn't as tolerant to backwards
9773 * compatibility.
9775 * @return string
9776 * @throws coding_exception
9778 protected function get_string() {
9779 global $CFG;
9781 // Check if we need to process the string.
9782 if ($this->string === null) {
9783 // Check the quality of the identifier.
9784 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9785 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);
9788 // Process the string.
9789 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9790 // Debugging feature lets you display string identifier and component.
9791 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9792 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9795 // Return the string.
9796 return $this->string;
9800 * Returns the string
9802 * @param string $lang The langauge to use when processing the string
9803 * @return string
9805 public function out($lang = null) {
9806 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9807 if ($this->forcedstring) {
9808 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9809 return $this->get_string();
9811 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9812 return $translatedstring->out();
9814 return $this->get_string();
9818 * Magic __toString method for printing a string
9820 * @return string
9822 public function __toString() {
9823 return $this->get_string();
9827 * Magic __set_state method used for var_export
9829 * @return string
9831 public function __set_state() {
9832 return $this->get_string();
9836 * Prepares the lang_string for sleep and stores only the forcedstring and
9837 * string properties... the string cannot be regenerated so we need to ensure
9838 * it is generated for this.
9840 * @return string
9842 public function __sleep() {
9843 $this->get_string();
9844 $this->forcedstring = true;
9845 return array('forcedstring', 'string', 'lang');