Merge branch 'install_master' of https://git.in.moodle.com/amosbot/moodle-install
[moodle.git] / lib / moodlelib.php
blob574225b27039a415beb15d7048075247abbd6b7a
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 (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
418 * True if module supports groupmembersonly (which no longer exists)
419 * @deprecated Since Moodle 2.8
421 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
423 /** Type of module */
424 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
425 /** True if module supports intro editor */
426 define('FEATURE_MOD_INTRO', 'mod_intro');
427 /** True if module has default completion */
428 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
430 define('FEATURE_COMMENT', 'comment');
432 define('FEATURE_RATE', 'rate');
433 /** True if module supports backup/restore of moodle2 format */
434 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
436 /** True if module can show description on course main page */
437 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
439 /** True if module uses the question bank */
440 define('FEATURE_USES_QUESTIONS', 'usesquestions');
442 /** Unspecified module archetype */
443 define('MOD_ARCHETYPE_OTHER', 0);
444 /** Resource-like type module */
445 define('MOD_ARCHETYPE_RESOURCE', 1);
446 /** Assignment module archetype */
447 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
448 /** System (not user-addable) module archetype */
449 define('MOD_ARCHETYPE_SYSTEM', 3);
451 /** Return this from modname_get_types callback to use default display in activity chooser */
452 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
455 * Security token used for allowing access
456 * from external application such as web services.
457 * Scripts do not use any session, performance is relatively
458 * low because we need to load access info in each request.
459 * Scripts are executed in parallel.
461 define('EXTERNAL_TOKEN_PERMANENT', 0);
464 * Security token used for allowing access
465 * of embedded applications, the code is executed in the
466 * active user session. Token is invalidated after user logs out.
467 * Scripts are executed serially - normal session locking is used.
469 define('EXTERNAL_TOKEN_EMBEDDED', 1);
472 * The home page should be the site home
474 define('HOMEPAGE_SITE', 0);
476 * The home page should be the users my page
478 define('HOMEPAGE_MY', 1);
480 * The home page can be chosen by the user
482 define('HOMEPAGE_USER', 2);
485 * Hub directory url (should be moodle.org)
487 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
491 * Moodle.org url (should be moodle.org)
493 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
496 * Moodle mobile app service name
498 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
501 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
503 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
506 * Course display settings: display all sections on one page.
508 define('COURSE_DISPLAY_SINGLEPAGE', 0);
510 * Course display settings: split pages into a page per section.
512 define('COURSE_DISPLAY_MULTIPAGE', 1);
515 * Authentication constant: String used in password field when password is not stored.
517 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
519 // PARAMETER HANDLING.
522 * Returns a particular value for the named variable, taken from
523 * POST or GET. If the parameter doesn't exist then an error is
524 * thrown because we require this variable.
526 * This function should be used to initialise all required values
527 * in a script that are based on parameters. Usually it will be
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.')');
627 // POST has precedence.
628 if (isset($_POST[$parname])) {
629 $param = $_POST[$parname];
630 } else if (isset($_GET[$parname])) {
631 $param = $_GET[$parname];
632 } else {
633 return $default;
636 if (is_array($param)) {
637 debugging('Invalid array parameter detected in required_param(): '.$parname);
638 // TODO: switch to $default in Moodle 2.3.
639 return optional_param_array($parname, $default, $type);
642 return clean_param($param, $type);
646 * Returns a particular array value for the named variable, taken from
647 * POST or GET, otherwise returning a given default.
649 * This function should be used to initialise all optional values
650 * in a script that are based on parameters. Usually it will be
651 * used like this:
652 * $ids = optional_param('id', array(), PARAM_INT);
654 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
656 * @param string $parname the name of the page parameter we want
657 * @param mixed $default the default value to return if nothing is found
658 * @param string $type expected type of parameter
659 * @return array
660 * @throws coding_exception
662 function optional_param_array($parname, $default, $type) {
663 if (func_num_args() != 3 or empty($parname) or empty($type)) {
664 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
667 // POST has precedence.
668 if (isset($_POST[$parname])) {
669 $param = $_POST[$parname];
670 } else if (isset($_GET[$parname])) {
671 $param = $_GET[$parname];
672 } else {
673 return $default;
675 if (!is_array($param)) {
676 debugging('optional_param_array() expects array parameters only: '.$parname);
677 return $default;
680 $result = array();
681 foreach ($param as $key => $value) {
682 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
683 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
684 continue;
686 $result[$key] = clean_param($value, $type);
689 return $result;
693 * Strict validation of parameter values, the values are only converted
694 * to requested PHP type. Internally it is using clean_param, the values
695 * before and after cleaning must be equal - otherwise
696 * an invalid_parameter_exception is thrown.
697 * Objects and classes are not accepted.
699 * @param mixed $param
700 * @param string $type PARAM_ constant
701 * @param bool $allownull are nulls valid value?
702 * @param string $debuginfo optional debug information
703 * @return mixed the $param value converted to PHP type
704 * @throws invalid_parameter_exception if $param is not of given type
706 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
707 if (is_null($param)) {
708 if ($allownull == NULL_ALLOWED) {
709 return null;
710 } else {
711 throw new invalid_parameter_exception($debuginfo);
714 if (is_array($param) or is_object($param)) {
715 throw new invalid_parameter_exception($debuginfo);
718 $cleaned = clean_param($param, $type);
720 if ($type == PARAM_FLOAT) {
721 // Do not detect precision loss here.
722 if (is_float($param) or is_int($param)) {
723 // These always fit.
724 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
725 throw new invalid_parameter_exception($debuginfo);
727 } else if ((string)$param !== (string)$cleaned) {
728 // Conversion to string is usually lossless.
729 throw new invalid_parameter_exception($debuginfo);
732 return $cleaned;
736 * Makes sure array contains only the allowed types, this function does not validate array key names!
738 * <code>
739 * $options = clean_param($options, PARAM_INT);
740 * </code>
742 * @param array $param the variable array we are cleaning
743 * @param string $type expected format of param after cleaning.
744 * @param bool $recursive clean recursive arrays
745 * @return array
746 * @throws coding_exception
748 function clean_param_array(array $param = null, $type, $recursive = false) {
749 // Convert null to empty array.
750 $param = (array)$param;
751 foreach ($param as $key => $value) {
752 if (is_array($value)) {
753 if ($recursive) {
754 $param[$key] = clean_param_array($value, $type, true);
755 } else {
756 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
758 } else {
759 $param[$key] = clean_param($value, $type);
762 return $param;
766 * Used by {@link optional_param()} and {@link required_param()} to
767 * clean the variables and/or cast to specific types, based on
768 * an options field.
769 * <code>
770 * $course->format = clean_param($course->format, PARAM_ALPHA);
771 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
772 * </code>
774 * @param mixed $param the variable we are cleaning
775 * @param string $type expected format of param after cleaning.
776 * @return mixed
777 * @throws coding_exception
779 function clean_param($param, $type) {
780 global $CFG;
782 if (is_array($param)) {
783 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
784 } else if (is_object($param)) {
785 if (method_exists($param, '__toString')) {
786 $param = $param->__toString();
787 } else {
788 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
792 switch ($type) {
793 case PARAM_RAW:
794 // No cleaning at all.
795 $param = fix_utf8($param);
796 return $param;
798 case PARAM_RAW_TRIMMED:
799 // No cleaning, but strip leading and trailing whitespace.
800 $param = fix_utf8($param);
801 return trim($param);
803 case PARAM_CLEAN:
804 // General HTML cleaning, try to use more specific type if possible this is deprecated!
805 // Please use more specific type instead.
806 if (is_numeric($param)) {
807 return $param;
809 $param = fix_utf8($param);
810 // Sweep for scripts, etc.
811 return clean_text($param);
813 case PARAM_CLEANHTML:
814 // Clean html fragment.
815 $param = fix_utf8($param);
816 // Sweep for scripts, etc.
817 $param = clean_text($param, FORMAT_HTML);
818 return trim($param);
820 case PARAM_INT:
821 // Convert to integer.
822 return (int)$param;
824 case PARAM_FLOAT:
825 // Convert to float.
826 return (float)$param;
828 case PARAM_ALPHA:
829 // Remove everything not `a-z`.
830 return preg_replace('/[^a-zA-Z]/i', '', $param);
832 case PARAM_ALPHAEXT:
833 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
834 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
836 case PARAM_ALPHANUM:
837 // Remove everything not `a-zA-Z0-9`.
838 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
840 case PARAM_ALPHANUMEXT:
841 // Remove everything not `a-zA-Z0-9_-`.
842 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
844 case PARAM_SEQUENCE:
845 // Remove everything not `0-9,`.
846 return preg_replace('/[^0-9,]/i', '', $param);
848 case PARAM_BOOL:
849 // Convert to 1 or 0.
850 $tempstr = strtolower($param);
851 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
852 $param = 1;
853 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
854 $param = 0;
855 } else {
856 $param = empty($param) ? 0 : 1;
858 return $param;
860 case PARAM_NOTAGS:
861 // Strip all tags.
862 $param = fix_utf8($param);
863 return strip_tags($param);
865 case PARAM_TEXT:
866 // Leave only tags needed for multilang.
867 $param = fix_utf8($param);
868 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
869 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
870 do {
871 if (strpos($param, '</lang>') !== false) {
872 // Old and future mutilang syntax.
873 $param = strip_tags($param, '<lang>');
874 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
875 break;
877 $open = false;
878 foreach ($matches[0] as $match) {
879 if ($match === '</lang>') {
880 if ($open) {
881 $open = false;
882 continue;
883 } else {
884 break 2;
887 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
888 break 2;
889 } else {
890 $open = true;
893 if ($open) {
894 break;
896 return $param;
898 } else if (strpos($param, '</span>') !== false) {
899 // Current problematic multilang syntax.
900 $param = strip_tags($param, '<span>');
901 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
902 break;
904 $open = false;
905 foreach ($matches[0] as $match) {
906 if ($match === '</span>') {
907 if ($open) {
908 $open = false;
909 continue;
910 } else {
911 break 2;
914 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
915 break 2;
916 } else {
917 $open = true;
920 if ($open) {
921 break;
923 return $param;
925 } while (false);
926 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
927 return strip_tags($param);
929 case PARAM_COMPONENT:
930 // We do not want any guessing here, either the name is correct or not
931 // please note only normalised component names are accepted.
932 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
933 return '';
935 if (strpos($param, '__') !== false) {
936 return '';
938 if (strpos($param, 'mod_') === 0) {
939 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
940 if (substr_count($param, '_') != 1) {
941 return '';
944 return $param;
946 case PARAM_PLUGIN:
947 case PARAM_AREA:
948 // We do not want any guessing here, either the name is correct or not.
949 if (!is_valid_plugin_name($param)) {
950 return '';
952 return $param;
954 case PARAM_SAFEDIR:
955 // Remove everything not a-zA-Z0-9_- .
956 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
958 case PARAM_SAFEPATH:
959 // Remove everything not a-zA-Z0-9/_- .
960 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
962 case PARAM_FILE:
963 // Strip all suspicious characters from filename.
964 $param = fix_utf8($param);
965 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
966 if ($param === '.' || $param === '..') {
967 $param = '';
969 return $param;
971 case PARAM_PATH:
972 // Strip all suspicious characters from file path.
973 $param = fix_utf8($param);
974 $param = str_replace('\\', '/', $param);
976 // Explode the path and clean each element using the PARAM_FILE rules.
977 $breadcrumb = explode('/', $param);
978 foreach ($breadcrumb as $key => $crumb) {
979 if ($crumb === '.' && $key === 0) {
980 // Special condition to allow for relative current path such as ./currentdirfile.txt.
981 } else {
982 $crumb = clean_param($crumb, PARAM_FILE);
984 $breadcrumb[$key] = $crumb;
986 $param = implode('/', $breadcrumb);
988 // Remove multiple current path (./././) and multiple slashes (///).
989 $param = preg_replace('~//+~', '/', $param);
990 $param = preg_replace('~/(\./)+~', '/', $param);
991 return $param;
993 case PARAM_HOST:
994 // Allow FQDN or IPv4 dotted quad.
995 $param = preg_replace('/[^\.\d\w-]/', '', $param );
996 // Match ipv4 dotted quad.
997 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
998 // Confirm values are ok.
999 if ( $match[0] > 255
1000 || $match[1] > 255
1001 || $match[3] > 255
1002 || $match[4] > 255 ) {
1003 // Hmmm, what kind of dotted quad is this?
1004 $param = '';
1006 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1007 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1008 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1010 // All is ok - $param is respected.
1011 } else {
1012 // All is not ok...
1013 $param='';
1015 return $param;
1017 case PARAM_URL: // Allow safe ftp, http, mailto urls.
1018 $param = fix_utf8($param);
1019 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1020 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1021 // All is ok, param is respected.
1022 } else {
1023 // Not really ok.
1024 $param ='';
1026 return $param;
1028 case PARAM_LOCALURL:
1029 // Allow http absolute, root relative and relative URLs within wwwroot.
1030 $param = clean_param($param, PARAM_URL);
1031 if (!empty($param)) {
1033 // Simulate the HTTPS version of the site.
1034 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1036 if ($param === $CFG->wwwroot) {
1037 // Exact match;
1038 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1039 // Exact match;
1040 } else if (preg_match(':^/:', $param)) {
1041 // Root-relative, ok!
1042 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1043 // Absolute, and matches our wwwroot.
1044 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
1045 // Absolute, and matches our httpswwwroot.
1046 } else {
1047 // Relative - let's make sure there are no tricks.
1048 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1049 // Looks ok.
1050 } else {
1051 $param = '';
1055 return $param;
1057 case PARAM_PEM:
1058 $param = trim($param);
1059 // PEM formatted strings may contain letters/numbers and the symbols:
1060 // forward slash: /
1061 // plus sign: +
1062 // equal sign: =
1063 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1064 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1065 list($wholething, $body) = $matches;
1066 unset($wholething, $matches);
1067 $b64 = clean_param($body, PARAM_BASE64);
1068 if (!empty($b64)) {
1069 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1070 } else {
1071 return '';
1074 return '';
1076 case PARAM_BASE64:
1077 if (!empty($param)) {
1078 // PEM formatted strings may contain letters/numbers and the symbols
1079 // forward slash: /
1080 // plus sign: +
1081 // equal sign: =.
1082 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1083 return '';
1085 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1086 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1087 // than (or equal to) 64 characters long.
1088 for ($i=0, $j=count($lines); $i < $j; $i++) {
1089 if ($i + 1 == $j) {
1090 if (64 < strlen($lines[$i])) {
1091 return '';
1093 continue;
1096 if (64 != strlen($lines[$i])) {
1097 return '';
1100 return implode("\n", $lines);
1101 } else {
1102 return '';
1105 case PARAM_TAG:
1106 $param = fix_utf8($param);
1107 // Please note it is not safe to use the tag name directly anywhere,
1108 // it must be processed with s(), urlencode() before embedding anywhere.
1109 // Remove some nasties.
1110 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1111 // Convert many whitespace chars into one.
1112 $param = preg_replace('/\s+/u', ' ', $param);
1113 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1114 return $param;
1116 case PARAM_TAGLIST:
1117 $param = fix_utf8($param);
1118 $tags = explode(',', $param);
1119 $result = array();
1120 foreach ($tags as $tag) {
1121 $res = clean_param($tag, PARAM_TAG);
1122 if ($res !== '') {
1123 $result[] = $res;
1126 if ($result) {
1127 return implode(',', $result);
1128 } else {
1129 return '';
1132 case PARAM_CAPABILITY:
1133 if (get_capability_info($param)) {
1134 return $param;
1135 } else {
1136 return '';
1139 case PARAM_PERMISSION:
1140 $param = (int)$param;
1141 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1142 return $param;
1143 } else {
1144 return CAP_INHERIT;
1147 case PARAM_AUTH:
1148 $param = clean_param($param, PARAM_PLUGIN);
1149 if (empty($param)) {
1150 return '';
1151 } else if (exists_auth_plugin($param)) {
1152 return $param;
1153 } else {
1154 return '';
1157 case PARAM_LANG:
1158 $param = clean_param($param, PARAM_SAFEDIR);
1159 if (get_string_manager()->translation_exists($param)) {
1160 return $param;
1161 } else {
1162 // Specified language is not installed or param malformed.
1163 return '';
1166 case PARAM_THEME:
1167 $param = clean_param($param, PARAM_PLUGIN);
1168 if (empty($param)) {
1169 return '';
1170 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1171 return $param;
1172 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1173 return $param;
1174 } else {
1175 // Specified theme is not installed.
1176 return '';
1179 case PARAM_USERNAME:
1180 $param = fix_utf8($param);
1181 $param = trim($param);
1182 // Convert uppercase to lowercase MDL-16919.
1183 $param = core_text::strtolower($param);
1184 if (empty($CFG->extendedusernamechars)) {
1185 $param = str_replace(" " , "", $param);
1186 // Regular expression, eliminate all chars EXCEPT:
1187 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1188 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1190 return $param;
1192 case PARAM_EMAIL:
1193 $param = fix_utf8($param);
1194 if (validate_email($param)) {
1195 return $param;
1196 } else {
1197 return '';
1200 case PARAM_STRINGID:
1201 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1202 return $param;
1203 } else {
1204 return '';
1207 case PARAM_TIMEZONE:
1208 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1209 $param = fix_utf8($param);
1210 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1211 if (preg_match($timezonepattern, $param)) {
1212 return $param;
1213 } else {
1214 return '';
1217 default:
1218 // Doh! throw error, switched parameters in optional_param or another serious problem.
1219 print_error("unknownparamtype", '', '', $type);
1224 * Makes sure the data is using valid utf8, invalid characters are discarded.
1226 * Note: this function is not intended for full objects with methods and private properties.
1228 * @param mixed $value
1229 * @return mixed with proper utf-8 encoding
1231 function fix_utf8($value) {
1232 if (is_null($value) or $value === '') {
1233 return $value;
1235 } else if (is_string($value)) {
1236 if ((string)(int)$value === $value) {
1237 // Shortcut.
1238 return $value;
1240 // No null bytes expected in our data, so let's remove it.
1241 $value = str_replace("\0", '', $value);
1243 // Note: this duplicates min_fix_utf8() intentionally.
1244 static $buggyiconv = null;
1245 if ($buggyiconv === null) {
1246 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1249 if ($buggyiconv) {
1250 if (function_exists('mb_convert_encoding')) {
1251 $subst = mb_substitute_character();
1252 mb_substitute_character('');
1253 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1254 mb_substitute_character($subst);
1256 } else {
1257 // Warn admins on admin/index.php page.
1258 $result = $value;
1261 } else {
1262 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1265 return $result;
1267 } else if (is_array($value)) {
1268 foreach ($value as $k => $v) {
1269 $value[$k] = fix_utf8($v);
1271 return $value;
1273 } else if (is_object($value)) {
1274 // Do not modify original.
1275 $value = clone($value);
1276 foreach ($value as $k => $v) {
1277 $value->$k = fix_utf8($v);
1279 return $value;
1281 } else {
1282 // This is some other type, no utf-8 here.
1283 return $value;
1288 * Return true if given value is integer or string with integer value
1290 * @param mixed $value String or Int
1291 * @return bool true if number, false if not
1293 function is_number($value) {
1294 if (is_int($value)) {
1295 return true;
1296 } else if (is_string($value)) {
1297 return ((string)(int)$value) === $value;
1298 } else {
1299 return false;
1304 * Returns host part from url.
1306 * @param string $url full url
1307 * @return string host, null if not found
1309 function get_host_from_url($url) {
1310 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1311 if ($matches) {
1312 return $matches[1];
1314 return null;
1318 * Tests whether anything was returned by text editor
1320 * This function is useful for testing whether something you got back from
1321 * the HTML editor actually contains anything. Sometimes the HTML editor
1322 * appear to be empty, but actually you get back a <br> tag or something.
1324 * @param string $string a string containing HTML.
1325 * @return boolean does the string contain any actual content - that is text,
1326 * images, objects, etc.
1328 function html_is_blank($string) {
1329 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1333 * Set a key in global configuration
1335 * Set a key/value pair in both this session's {@link $CFG} global variable
1336 * and in the 'config' database table for future sessions.
1338 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1339 * In that case it doesn't affect $CFG.
1341 * A NULL value will delete the entry.
1343 * NOTE: this function is called from lib/db/upgrade.php
1345 * @param string $name the key to set
1346 * @param string $value the value to set (without magic quotes)
1347 * @param string $plugin (optional) the plugin scope, default null
1348 * @return bool true or exception
1350 function set_config($name, $value, $plugin=null) {
1351 global $CFG, $DB;
1353 if (empty($plugin)) {
1354 if (!array_key_exists($name, $CFG->config_php_settings)) {
1355 // So it's defined for this invocation at least.
1356 if (is_null($value)) {
1357 unset($CFG->$name);
1358 } else {
1359 // Settings from db are always strings.
1360 $CFG->$name = (string)$value;
1364 if ($DB->get_field('config', 'name', array('name' => $name))) {
1365 if ($value === null) {
1366 $DB->delete_records('config', array('name' => $name));
1367 } else {
1368 $DB->set_field('config', 'value', $value, array('name' => $name));
1370 } else {
1371 if ($value !== null) {
1372 $config = new stdClass();
1373 $config->name = $name;
1374 $config->value = $value;
1375 $DB->insert_record('config', $config, false);
1378 if ($name === 'siteidentifier') {
1379 cache_helper::update_site_identifier($value);
1381 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1382 } else {
1383 // Plugin scope.
1384 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1385 if ($value===null) {
1386 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1387 } else {
1388 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1390 } else {
1391 if ($value !== null) {
1392 $config = new stdClass();
1393 $config->plugin = $plugin;
1394 $config->name = $name;
1395 $config->value = $value;
1396 $DB->insert_record('config_plugins', $config, false);
1399 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1402 return true;
1406 * Get configuration values from the global config table
1407 * or the config_plugins table.
1409 * If called with one parameter, it will load all the config
1410 * variables for one plugin, and return them as an object.
1412 * If called with 2 parameters it will return a string single
1413 * value or false if the value is not found.
1415 * NOTE: this function is called from lib/db/upgrade.php
1417 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1418 * that we need only fetch it once per request.
1419 * @param string $plugin full component name
1420 * @param string $name default null
1421 * @return mixed hash-like object or single value, return false no config found
1422 * @throws dml_exception
1424 function get_config($plugin, $name = null) {
1425 global $CFG, $DB;
1427 static $siteidentifier = null;
1429 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1430 $forced =& $CFG->config_php_settings;
1431 $iscore = true;
1432 $plugin = 'core';
1433 } else {
1434 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1435 $forced =& $CFG->forced_plugin_settings[$plugin];
1436 } else {
1437 $forced = array();
1439 $iscore = false;
1442 if ($siteidentifier === null) {
1443 try {
1444 // This may fail during installation.
1445 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1446 // install the database.
1447 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1448 } catch (dml_exception $ex) {
1449 // Set siteidentifier to false. We don't want to trip this continually.
1450 $siteidentifier = false;
1451 throw $ex;
1455 if (!empty($name)) {
1456 if (array_key_exists($name, $forced)) {
1457 return (string)$forced[$name];
1458 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1459 return $siteidentifier;
1463 $cache = cache::make('core', 'config');
1464 $result = $cache->get($plugin);
1465 if ($result === false) {
1466 // The user is after a recordset.
1467 if (!$iscore) {
1468 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1469 } else {
1470 // This part is not really used any more, but anyway...
1471 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1473 $cache->set($plugin, $result);
1476 if (!empty($name)) {
1477 if (array_key_exists($name, $result)) {
1478 return $result[$name];
1480 return false;
1483 if ($plugin === 'core') {
1484 $result['siteidentifier'] = $siteidentifier;
1487 foreach ($forced as $key => $value) {
1488 if (is_null($value) or is_array($value) or is_object($value)) {
1489 // We do not want any extra mess here, just real settings that could be saved in db.
1490 unset($result[$key]);
1491 } else {
1492 // Convert to string as if it went through the DB.
1493 $result[$key] = (string)$value;
1497 return (object)$result;
1501 * Removes a key from global configuration.
1503 * NOTE: this function is called from lib/db/upgrade.php
1505 * @param string $name the key to set
1506 * @param string $plugin (optional) the plugin scope
1507 * @return boolean whether the operation succeeded.
1509 function unset_config($name, $plugin=null) {
1510 global $CFG, $DB;
1512 if (empty($plugin)) {
1513 unset($CFG->$name);
1514 $DB->delete_records('config', array('name' => $name));
1515 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1516 } else {
1517 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1518 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1521 return true;
1525 * Remove all the config variables for a given plugin.
1527 * NOTE: this function is called from lib/db/upgrade.php
1529 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1530 * @return boolean whether the operation succeeded.
1532 function unset_all_config_for_plugin($plugin) {
1533 global $DB;
1534 // Delete from the obvious config_plugins first.
1535 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1536 // Next delete any suspect settings from config.
1537 $like = $DB->sql_like('name', '?', true, true, false, '|');
1538 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1539 $DB->delete_records_select('config', $like, $params);
1540 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1541 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1543 return true;
1547 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1549 * All users are verified if they still have the necessary capability.
1551 * @param string $value the value of the config setting.
1552 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1553 * @param bool $includeadmins include administrators.
1554 * @return array of user objects.
1556 function get_users_from_config($value, $capability, $includeadmins = true) {
1557 if (empty($value) or $value === '$@NONE@$') {
1558 return array();
1561 // We have to make sure that users still have the necessary capability,
1562 // it should be faster to fetch them all first and then test if they are present
1563 // instead of validating them one-by-one.
1564 $users = get_users_by_capability(context_system::instance(), $capability);
1565 if ($includeadmins) {
1566 $admins = get_admins();
1567 foreach ($admins as $admin) {
1568 $users[$admin->id] = $admin;
1572 if ($value === '$@ALL@$') {
1573 return $users;
1576 $result = array(); // Result in correct order.
1577 $allowed = explode(',', $value);
1578 foreach ($allowed as $uid) {
1579 if (isset($users[$uid])) {
1580 $user = $users[$uid];
1581 $result[$user->id] = $user;
1585 return $result;
1590 * Invalidates browser caches and cached data in temp.
1592 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1593 * {@link phpunit_util::reset_dataroot()}
1595 * @return void
1597 function purge_all_caches() {
1598 global $CFG, $DB;
1600 reset_text_filters_cache();
1601 js_reset_all_caches();
1602 theme_reset_all_caches();
1603 get_string_manager()->reset_caches();
1604 core_text::reset_caches();
1605 if (class_exists('core_plugin_manager')) {
1606 core_plugin_manager::reset_caches();
1609 // Bump up cacherev field for all courses.
1610 try {
1611 increment_revision_number('course', 'cacherev', '');
1612 } catch (moodle_exception $e) {
1613 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1616 $DB->reset_caches();
1617 cache_helper::purge_all();
1619 // Purge all other caches: rss, simplepie, etc.
1620 remove_dir($CFG->cachedir.'', true);
1622 // Make sure cache dir is writable, throws exception if not.
1623 make_cache_directory('');
1625 // This is the only place where we purge local caches, we are only adding files there.
1626 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1627 remove_dir($CFG->localcachedir, true);
1628 set_config('localcachedirpurged', time());
1629 make_localcache_directory('', true);
1630 \core\task\manager::clear_static_caches();
1634 * Get volatile flags
1636 * @param string $type
1637 * @param int $changedsince default null
1638 * @return array records array
1640 function get_cache_flags($type, $changedsince = null) {
1641 global $DB;
1643 $params = array('type' => $type, 'expiry' => time());
1644 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1645 if ($changedsince !== null) {
1646 $params['changedsince'] = $changedsince;
1647 $sqlwhere .= " AND timemodified > :changedsince";
1649 $cf = array();
1650 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1651 foreach ($flags as $flag) {
1652 $cf[$flag->name] = $flag->value;
1655 return $cf;
1659 * Get volatile flags
1661 * @param string $type
1662 * @param string $name
1663 * @param int $changedsince default null
1664 * @return string|false The cache flag value or false
1666 function get_cache_flag($type, $name, $changedsince=null) {
1667 global $DB;
1669 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1671 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1672 if ($changedsince !== null) {
1673 $params['changedsince'] = $changedsince;
1674 $sqlwhere .= " AND timemodified > :changedsince";
1677 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1681 * Set a volatile flag
1683 * @param string $type the "type" namespace for the key
1684 * @param string $name the key to set
1685 * @param string $value the value to set (without magic quotes) - null will remove the flag
1686 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1687 * @return bool Always returns true
1689 function set_cache_flag($type, $name, $value, $expiry = null) {
1690 global $DB;
1692 $timemodified = time();
1693 if ($expiry === null || $expiry < $timemodified) {
1694 $expiry = $timemodified + 24 * 60 * 60;
1695 } else {
1696 $expiry = (int)$expiry;
1699 if ($value === null) {
1700 unset_cache_flag($type, $name);
1701 return true;
1704 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1705 // This is a potential problem in DEBUG_DEVELOPER.
1706 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1707 return true; // No need to update.
1709 $f->value = $value;
1710 $f->expiry = $expiry;
1711 $f->timemodified = $timemodified;
1712 $DB->update_record('cache_flags', $f);
1713 } else {
1714 $f = new stdClass();
1715 $f->flagtype = $type;
1716 $f->name = $name;
1717 $f->value = $value;
1718 $f->expiry = $expiry;
1719 $f->timemodified = $timemodified;
1720 $DB->insert_record('cache_flags', $f);
1722 return true;
1726 * Removes a single volatile flag
1728 * @param string $type the "type" namespace for the key
1729 * @param string $name the key to set
1730 * @return bool
1732 function unset_cache_flag($type, $name) {
1733 global $DB;
1734 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1735 return true;
1739 * Garbage-collect volatile flags
1741 * @return bool Always returns true
1743 function gc_cache_flags() {
1744 global $DB;
1745 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1746 return true;
1749 // USER PREFERENCE API.
1752 * Refresh user preference cache. This is used most often for $USER
1753 * object that is stored in session, but it also helps with performance in cron script.
1755 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1757 * @package core
1758 * @category preference
1759 * @access public
1760 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1761 * @param int $cachelifetime Cache life time on the current page (in seconds)
1762 * @throws coding_exception
1763 * @return null
1765 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1766 global $DB;
1767 // Static cache, we need to check on each page load, not only every 2 minutes.
1768 static $loadedusers = array();
1770 if (!isset($user->id)) {
1771 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1774 if (empty($user->id) or isguestuser($user->id)) {
1775 // No permanent storage for not-logged-in users and guest.
1776 if (!isset($user->preference)) {
1777 $user->preference = array();
1779 return;
1782 $timenow = time();
1784 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1785 // Already loaded at least once on this page. Are we up to date?
1786 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1787 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1788 return;
1790 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1791 // No change since the lastcheck on this page.
1792 $user->preference['_lastloaded'] = $timenow;
1793 return;
1797 // OK, so we have to reload all preferences.
1798 $loadedusers[$user->id] = true;
1799 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1800 $user->preference['_lastloaded'] = $timenow;
1804 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1806 * NOTE: internal function, do not call from other code.
1808 * @package core
1809 * @access private
1810 * @param integer $userid the user whose prefs were changed.
1812 function mark_user_preferences_changed($userid) {
1813 global $CFG;
1815 if (empty($userid) or isguestuser($userid)) {
1816 // No cache flags for guest and not-logged-in users.
1817 return;
1820 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1824 * Sets a preference for the specified user.
1826 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1828 * @package core
1829 * @category preference
1830 * @access public
1831 * @param string $name The key to set as preference for the specified user
1832 * @param string $value The value to set for the $name key in the specified user's
1833 * record, null means delete current value.
1834 * @param stdClass|int|null $user A moodle user object or id, null means current user
1835 * @throws coding_exception
1836 * @return bool Always true or exception
1838 function set_user_preference($name, $value, $user = null) {
1839 global $USER, $DB;
1841 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1842 throw new coding_exception('Invalid preference name in set_user_preference() call');
1845 if (is_null($value)) {
1846 // Null means delete current.
1847 return unset_user_preference($name, $user);
1848 } else if (is_object($value)) {
1849 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1850 } else if (is_array($value)) {
1851 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1853 // Value column maximum length is 1333 characters.
1854 $value = (string)$value;
1855 if (core_text::strlen($value) > 1333) {
1856 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1859 if (is_null($user)) {
1860 $user = $USER;
1861 } else if (isset($user->id)) {
1862 // It is a valid object.
1863 } else if (is_numeric($user)) {
1864 $user = (object)array('id' => (int)$user);
1865 } else {
1866 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1869 check_user_preferences_loaded($user);
1871 if (empty($user->id) or isguestuser($user->id)) {
1872 // No permanent storage for not-logged-in users and guest.
1873 $user->preference[$name] = $value;
1874 return true;
1877 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1878 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1879 // Preference already set to this value.
1880 return true;
1882 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1884 } else {
1885 $preference = new stdClass();
1886 $preference->userid = $user->id;
1887 $preference->name = $name;
1888 $preference->value = $value;
1889 $DB->insert_record('user_preferences', $preference);
1892 // Update value in cache.
1893 $user->preference[$name] = $value;
1895 // Set reload flag for other sessions.
1896 mark_user_preferences_changed($user->id);
1898 return true;
1902 * Sets a whole array of preferences for the current user
1904 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1906 * @package core
1907 * @category preference
1908 * @access public
1909 * @param array $prefarray An array of key/value pairs to be set
1910 * @param stdClass|int|null $user A moodle user object or id, null means current user
1911 * @return bool Always true or exception
1913 function set_user_preferences(array $prefarray, $user = null) {
1914 foreach ($prefarray as $name => $value) {
1915 set_user_preference($name, $value, $user);
1917 return true;
1921 * Unsets a preference completely by deleting it from the database
1923 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1925 * @package core
1926 * @category preference
1927 * @access public
1928 * @param string $name The key to unset as preference for the specified user
1929 * @param stdClass|int|null $user A moodle user object or id, null means current user
1930 * @throws coding_exception
1931 * @return bool Always true or exception
1933 function unset_user_preference($name, $user = null) {
1934 global $USER, $DB;
1936 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1937 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1940 if (is_null($user)) {
1941 $user = $USER;
1942 } else if (isset($user->id)) {
1943 // It is a valid object.
1944 } else if (is_numeric($user)) {
1945 $user = (object)array('id' => (int)$user);
1946 } else {
1947 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1950 check_user_preferences_loaded($user);
1952 if (empty($user->id) or isguestuser($user->id)) {
1953 // No permanent storage for not-logged-in user and guest.
1954 unset($user->preference[$name]);
1955 return true;
1958 // Delete from DB.
1959 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1961 // Delete the preference from cache.
1962 unset($user->preference[$name]);
1964 // Set reload flag for other sessions.
1965 mark_user_preferences_changed($user->id);
1967 return true;
1971 * Used to fetch user preference(s)
1973 * If no arguments are supplied this function will return
1974 * all of the current user preferences as an array.
1976 * If a name is specified then this function
1977 * attempts to return that particular preference value. If
1978 * none is found, then the optional value $default is returned,
1979 * otherwise null.
1981 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1983 * @package core
1984 * @category preference
1985 * @access public
1986 * @param string $name Name of the key to use in finding a preference value
1987 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1988 * @param stdClass|int|null $user A moodle user object or id, null means current user
1989 * @throws coding_exception
1990 * @return string|mixed|null A string containing the value of a single preference. An
1991 * array with all of the preferences or null
1993 function get_user_preferences($name = null, $default = null, $user = null) {
1994 global $USER;
1996 if (is_null($name)) {
1997 // All prefs.
1998 } else if (is_numeric($name) or $name === '_lastloaded') {
1999 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2002 if (is_null($user)) {
2003 $user = $USER;
2004 } else if (isset($user->id)) {
2005 // Is a valid object.
2006 } else if (is_numeric($user)) {
2007 $user = (object)array('id' => (int)$user);
2008 } else {
2009 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2012 check_user_preferences_loaded($user);
2014 if (empty($name)) {
2015 // All values.
2016 return $user->preference;
2017 } else if (isset($user->preference[$name])) {
2018 // The single string value.
2019 return $user->preference[$name];
2020 } else {
2021 // Default value (null if not specified).
2022 return $default;
2026 // FUNCTIONS FOR HANDLING TIME.
2029 * Given date parts in user time produce a GMT timestamp.
2031 * @package core
2032 * @category time
2033 * @param int $year The year part to create timestamp of
2034 * @param int $month The month part to create timestamp of
2035 * @param int $day The day part to create timestamp of
2036 * @param int $hour The hour part to create timestamp of
2037 * @param int $minute The minute part to create timestamp of
2038 * @param int $second The second part to create timestamp of
2039 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2040 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2041 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2042 * applied only if timezone is 99 or string.
2043 * @return int GMT timestamp
2045 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2046 $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2047 $date->setDate((int)$year, (int)$month, (int)$day);
2048 $date->setTime((int)$hour, (int)$minute, (int)$second);
2050 $time = $date->getTimestamp();
2052 // Moodle BC DST stuff.
2053 if (!$applydst) {
2054 $time += dst_offset_on($time, $timezone);
2057 return $time;
2062 * Format a date/time (seconds) as weeks, days, hours etc as needed
2064 * Given an amount of time in seconds, returns string
2065 * formatted nicely as weeks, days, hours etc as needed
2067 * @package core
2068 * @category time
2069 * @uses MINSECS
2070 * @uses HOURSECS
2071 * @uses DAYSECS
2072 * @uses YEARSECS
2073 * @param int $totalsecs Time in seconds
2074 * @param stdClass $str Should be a time object
2075 * @return string A nicely formatted date/time string
2077 function format_time($totalsecs, $str = null) {
2079 $totalsecs = abs($totalsecs);
2081 if (!$str) {
2082 // Create the str structure the slow way.
2083 $str = new stdClass();
2084 $str->day = get_string('day');
2085 $str->days = get_string('days');
2086 $str->hour = get_string('hour');
2087 $str->hours = get_string('hours');
2088 $str->min = get_string('min');
2089 $str->mins = get_string('mins');
2090 $str->sec = get_string('sec');
2091 $str->secs = get_string('secs');
2092 $str->year = get_string('year');
2093 $str->years = get_string('years');
2096 $years = floor($totalsecs/YEARSECS);
2097 $remainder = $totalsecs - ($years*YEARSECS);
2098 $days = floor($remainder/DAYSECS);
2099 $remainder = $totalsecs - ($days*DAYSECS);
2100 $hours = floor($remainder/HOURSECS);
2101 $remainder = $remainder - ($hours*HOURSECS);
2102 $mins = floor($remainder/MINSECS);
2103 $secs = $remainder - ($mins*MINSECS);
2105 $ss = ($secs == 1) ? $str->sec : $str->secs;
2106 $sm = ($mins == 1) ? $str->min : $str->mins;
2107 $sh = ($hours == 1) ? $str->hour : $str->hours;
2108 $sd = ($days == 1) ? $str->day : $str->days;
2109 $sy = ($years == 1) ? $str->year : $str->years;
2111 $oyears = '';
2112 $odays = '';
2113 $ohours = '';
2114 $omins = '';
2115 $osecs = '';
2117 if ($years) {
2118 $oyears = $years .' '. $sy;
2120 if ($days) {
2121 $odays = $days .' '. $sd;
2123 if ($hours) {
2124 $ohours = $hours .' '. $sh;
2126 if ($mins) {
2127 $omins = $mins .' '. $sm;
2129 if ($secs) {
2130 $osecs = $secs .' '. $ss;
2133 if ($years) {
2134 return trim($oyears .' '. $odays);
2136 if ($days) {
2137 return trim($odays .' '. $ohours);
2139 if ($hours) {
2140 return trim($ohours .' '. $omins);
2142 if ($mins) {
2143 return trim($omins .' '. $osecs);
2145 if ($secs) {
2146 return $osecs;
2148 return get_string('now');
2152 * Returns a formatted string that represents a date in user time.
2154 * @package core
2155 * @category time
2156 * @param int $date the timestamp in UTC, as obtained from the database.
2157 * @param string $format strftime format. You should probably get this using
2158 * get_string('strftime...', 'langconfig');
2159 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2160 * not 99 then daylight saving will not be added.
2161 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2162 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2163 * If false then the leading zero is maintained.
2164 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2165 * @return string the formatted date/time.
2167 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2168 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2169 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2173 * Returns a formatted date ensuring it is UTF-8.
2175 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2176 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2178 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2179 * @param string $format strftime format.
2180 * @param int|float|string $tz the user timezone
2181 * @return string the formatted date/time.
2182 * @since Moodle 2.3.3
2184 function date_format_string($date, $format, $tz = 99) {
2185 global $CFG;
2187 $localewincharset = null;
2188 // Get the calendar type user is using.
2189 if ($CFG->ostype == 'WINDOWS') {
2190 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2191 $localewincharset = $calendartype->locale_win_charset();
2194 if ($localewincharset) {
2195 $format = core_text::convert($format, 'utf-8', $localewincharset);
2198 date_default_timezone_set(core_date::get_user_timezone($tz));
2199 $datestring = strftime($format, $date);
2200 core_date::set_default_server_timezone();
2202 if ($localewincharset) {
2203 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2206 return $datestring;
2210 * Given a $time timestamp in GMT (seconds since epoch),
2211 * returns an array that represents the date in user time
2213 * @package core
2214 * @category time
2215 * @param int $time Timestamp in GMT
2216 * @param float|int|string $timezone user timezone
2217 * @return array An array that represents the date in user time
2219 function usergetdate($time, $timezone=99) {
2220 date_default_timezone_set(core_date::get_user_timezone($timezone));
2221 $result = getdate($time);
2222 core_date::set_default_server_timezone();
2224 return $result;
2228 * Given a GMT timestamp (seconds since epoch), offsets it by
2229 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2231 * NOTE: this function does not include DST properly,
2232 * you should use the PHP date stuff instead!
2234 * @package core
2235 * @category time
2236 * @param int $date Timestamp in GMT
2237 * @param float|int|string $timezone user timezone
2238 * @return int
2240 function usertime($date, $timezone=99) {
2241 $userdate = new DateTime('@' . $date);
2242 $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2243 $dst = dst_offset_on($date, $timezone);
2245 return $date - $userdate->getOffset() + $dst;
2249 * Given a time, return the GMT timestamp of the most recent midnight
2250 * for the current user.
2252 * @package core
2253 * @category time
2254 * @param int $date Timestamp in GMT
2255 * @param float|int|string $timezone user timezone
2256 * @return int Returns a GMT timestamp
2258 function usergetmidnight($date, $timezone=99) {
2260 $userdate = usergetdate($date, $timezone);
2262 // Time of midnight of this user's day, in GMT.
2263 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2268 * Returns a string that prints the user's timezone
2270 * @package core
2271 * @category time
2272 * @param float|int|string $timezone user timezone
2273 * @return string
2275 function usertimezone($timezone=99) {
2276 $tz = core_date::get_user_timezone($timezone);
2277 return core_date::get_localised_timezone($tz);
2281 * Returns a float or a string which denotes the user's timezone
2282 * 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)
2283 * means that for this timezone there are also DST rules to be taken into account
2284 * Checks various settings and picks the most dominant of those which have a value
2286 * @package core
2287 * @category time
2288 * @param float|int|string $tz timezone to calculate GMT time offset before
2289 * calculating user timezone, 99 is default user timezone
2290 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2291 * @return float|string
2293 function get_user_timezone($tz = 99) {
2294 global $USER, $CFG;
2296 $timezones = array(
2297 $tz,
2298 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2299 isset($USER->timezone) ? $USER->timezone : 99,
2300 isset($CFG->timezone) ? $CFG->timezone : 99,
2303 $tz = 99;
2305 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2306 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2307 $tz = $next['value'];
2309 return is_numeric($tz) ? (float) $tz : $tz;
2313 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2314 * - Note: Daylight saving only works for string timezones and not for float.
2316 * @package core
2317 * @category time
2318 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2319 * @param int|float|string $strtimezone user timezone
2320 * @return int
2322 function dst_offset_on($time, $strtimezone = null) {
2323 $tz = core_date::get_user_timezone($strtimezone);
2324 $date = new DateTime('@' . $time);
2325 $date->setTimezone(new DateTimeZone($tz));
2326 if ($date->format('I') == '1') {
2327 if ($tz === 'Australia/Lord_Howe') {
2328 return 1800;
2330 return 3600;
2332 return 0;
2336 * Calculates when the day appears in specific month
2338 * @package core
2339 * @category time
2340 * @param int $startday starting day of the month
2341 * @param int $weekday The day when week starts (normally taken from user preferences)
2342 * @param int $month The month whose day is sought
2343 * @param int $year The year of the month whose day is sought
2344 * @return int
2346 function find_day_in_month($startday, $weekday, $month, $year) {
2347 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2349 $daysinmonth = days_in_month($month, $year);
2350 $daysinweek = count($calendartype->get_weekdays());
2352 if ($weekday == -1) {
2353 // Don't care about weekday, so return:
2354 // abs($startday) if $startday != -1
2355 // $daysinmonth otherwise.
2356 return ($startday == -1) ? $daysinmonth : abs($startday);
2359 // From now on we 're looking for a specific weekday.
2360 // Give "end of month" its actual value, since we know it.
2361 if ($startday == -1) {
2362 $startday = -1 * $daysinmonth;
2365 // Starting from day $startday, the sign is the direction.
2366 if ($startday < 1) {
2367 $startday = abs($startday);
2368 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2370 // This is the last such weekday of the month.
2371 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2372 if ($lastinmonth > $daysinmonth) {
2373 $lastinmonth -= $daysinweek;
2376 // Find the first such weekday <= $startday.
2377 while ($lastinmonth > $startday) {
2378 $lastinmonth -= $daysinweek;
2381 return $lastinmonth;
2382 } else {
2383 $indexweekday = dayofweek($startday, $month, $year);
2385 $diff = $weekday - $indexweekday;
2386 if ($diff < 0) {
2387 $diff += $daysinweek;
2390 // This is the first such weekday of the month equal to or after $startday.
2391 $firstfromindex = $startday + $diff;
2393 return $firstfromindex;
2398 * Calculate the number of days in a given month
2400 * @package core
2401 * @category time
2402 * @param int $month The month whose day count is sought
2403 * @param int $year The year of the month whose day count is sought
2404 * @return int
2406 function days_in_month($month, $year) {
2407 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2408 return $calendartype->get_num_days_in_month($year, $month);
2412 * Calculate the position in the week of a specific calendar day
2414 * @package core
2415 * @category time
2416 * @param int $day The day of the date whose position in the week is sought
2417 * @param int $month The month of the date whose position in the week is sought
2418 * @param int $year The year of the date whose position in the week is sought
2419 * @return int
2421 function dayofweek($day, $month, $year) {
2422 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2423 return $calendartype->get_weekday($year, $month, $day);
2426 // USER AUTHENTICATION AND LOGIN.
2429 * Returns full login url.
2431 * @return string login url
2433 function get_login_url() {
2434 global $CFG;
2436 $url = "$CFG->wwwroot/login/index.php";
2438 if (!empty($CFG->loginhttps)) {
2439 $url = str_replace('http:', 'https:', $url);
2442 return $url;
2446 * This function checks that the current user is logged in and has the
2447 * required privileges
2449 * This function checks that the current user is logged in, and optionally
2450 * whether they are allowed to be in a particular course and view a particular
2451 * course module.
2452 * If they are not logged in, then it redirects them to the site login unless
2453 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2454 * case they are automatically logged in as guests.
2455 * If $courseid is given and the user is not enrolled in that course then the
2456 * user is redirected to the course enrolment page.
2457 * If $cm is given and the course module is hidden and the user is not a teacher
2458 * in the course then the user is redirected to the course home page.
2460 * When $cm parameter specified, this function sets page layout to 'module'.
2461 * You need to change it manually later if some other layout needed.
2463 * @package core_access
2464 * @category access
2466 * @param mixed $courseorid id of the course or course object
2467 * @param bool $autologinguest default true
2468 * @param object $cm course module object
2469 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2470 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2471 * in order to keep redirects working properly. MDL-14495
2472 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2473 * @return mixed Void, exit, and die depending on path
2474 * @throws coding_exception
2475 * @throws require_login_exception
2477 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2478 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2480 // Must not redirect when byteserving already started.
2481 if (!empty($_SERVER['HTTP_RANGE'])) {
2482 $preventredirect = true;
2485 // Setup global $COURSE, themes, language and locale.
2486 if (!empty($courseorid)) {
2487 if (is_object($courseorid)) {
2488 $course = $courseorid;
2489 } else if ($courseorid == SITEID) {
2490 $course = clone($SITE);
2491 } else {
2492 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2494 if ($cm) {
2495 if ($cm->course != $course->id) {
2496 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2498 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2499 if (!($cm instanceof cm_info)) {
2500 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2501 // db queries so this is not really a performance concern, however it is obviously
2502 // better if you use get_fast_modinfo to get the cm before calling this.
2503 $modinfo = get_fast_modinfo($course);
2504 $cm = $modinfo->get_cm($cm->id);
2507 } else {
2508 // Do not touch global $COURSE via $PAGE->set_course(),
2509 // the reasons is we need to be able to call require_login() at any time!!
2510 $course = $SITE;
2511 if ($cm) {
2512 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2516 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2517 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2518 // risk leading the user back to the AJAX request URL.
2519 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2520 $setwantsurltome = false;
2523 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2524 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
2525 if ($setwantsurltome) {
2526 $SESSION->wantsurl = qualified_me();
2528 redirect(get_login_url());
2531 // If the user is not even logged in yet then make sure they are.
2532 if (!isloggedin()) {
2533 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2534 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2535 // Misconfigured site guest, just redirect to login page.
2536 redirect(get_login_url());
2537 exit; // Never reached.
2539 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2540 complete_user_login($guest);
2541 $USER->autologinguest = true;
2542 $SESSION->lang = $lang;
2543 } else {
2544 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2545 if ($preventredirect) {
2546 throw new require_login_exception('You are not logged in');
2549 if ($setwantsurltome) {
2550 $SESSION->wantsurl = qualified_me();
2552 if (!empty($_SERVER['HTTP_REFERER'])) {
2553 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2556 // Give auth plugins an opportunity to authenticate or redirect to an external login page
2557 $authsequence = get_enabled_auth_plugins(true); // auths, in sequence
2558 foreach($authsequence as $authname) {
2559 $authplugin = get_auth_plugin($authname);
2560 $authplugin->pre_loginpage_hook();
2561 if (isloggedin()) {
2562 break;
2566 // If we're still not logged in then go to the login page
2567 if (!isloggedin()) {
2568 redirect(get_login_url());
2569 exit; // Never reached.
2574 // Loginas as redirection if needed.
2575 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2576 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2577 if ($USER->loginascontext->instanceid != $course->id) {
2578 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2583 // Check whether the user should be changing password (but only if it is REALLY them).
2584 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2585 $userauth = get_auth_plugin($USER->auth);
2586 if ($userauth->can_change_password() and !$preventredirect) {
2587 if ($setwantsurltome) {
2588 $SESSION->wantsurl = qualified_me();
2590 if ($changeurl = $userauth->change_password_url()) {
2591 // Use plugin custom url.
2592 redirect($changeurl);
2593 } else {
2594 // Use moodle internal method.
2595 if (empty($CFG->loginhttps)) {
2596 redirect($CFG->wwwroot .'/login/change_password.php');
2597 } else {
2598 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2599 redirect($wwwroot .'/login/change_password.php');
2602 } else {
2603 print_error('nopasswordchangeforced', 'auth');
2607 // Check that the user account is properly set up.
2608 if (user_not_fully_set_up($USER)) {
2609 if ($preventredirect) {
2610 throw new require_login_exception('User not fully set-up');
2612 if ($setwantsurltome) {
2613 $SESSION->wantsurl = qualified_me();
2615 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2618 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2619 sesskey();
2621 // Do not bother admins with any formalities.
2622 if (is_siteadmin()) {
2623 // Set the global $COURSE.
2624 if ($cm) {
2625 $PAGE->set_cm($cm, $course);
2626 $PAGE->set_pagelayout('incourse');
2627 } else if (!empty($courseorid)) {
2628 $PAGE->set_course($course);
2630 // Set accesstime or the user will appear offline which messes up messaging.
2631 user_accesstime_log($course->id);
2632 return;
2635 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2636 if (!$USER->policyagreed and !is_siteadmin()) {
2637 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2638 if ($preventredirect) {
2639 throw new require_login_exception('Policy not agreed');
2641 if ($setwantsurltome) {
2642 $SESSION->wantsurl = qualified_me();
2644 redirect($CFG->wwwroot .'/user/policy.php');
2645 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2646 if ($preventredirect) {
2647 throw new require_login_exception('Policy not agreed');
2649 if ($setwantsurltome) {
2650 $SESSION->wantsurl = qualified_me();
2652 redirect($CFG->wwwroot .'/user/policy.php');
2656 // Fetch the system context, the course context, and prefetch its child contexts.
2657 $sysctx = context_system::instance();
2658 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2659 if ($cm) {
2660 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2661 } else {
2662 $cmcontext = null;
2665 // If the site is currently under maintenance, then print a message.
2666 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2667 if ($preventredirect) {
2668 throw new require_login_exception('Maintenance in progress');
2671 print_maintenance_message();
2674 // Make sure the course itself is not hidden.
2675 if ($course->id == SITEID) {
2676 // Frontpage can not be hidden.
2677 } else {
2678 if (is_role_switched($course->id)) {
2679 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2680 } else {
2681 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2682 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2683 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2684 if ($preventredirect) {
2685 throw new require_login_exception('Course is hidden');
2687 $PAGE->set_context(null);
2688 // We need to override the navigation URL as the course won't have been added to the navigation and thus
2689 // the navigation will mess up when trying to find it.
2690 navigation_node::override_active_url(new moodle_url('/'));
2691 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2696 // Is the user enrolled?
2697 if ($course->id == SITEID) {
2698 // Everybody is enrolled on the frontpage.
2699 } else {
2700 if (\core\session\manager::is_loggedinas()) {
2701 // Make sure the REAL person can access this course first.
2702 $realuser = \core\session\manager::get_realuser();
2703 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2704 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2705 if ($preventredirect) {
2706 throw new require_login_exception('Invalid course login-as access');
2708 $PAGE->set_context(null);
2709 echo $OUTPUT->header();
2710 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2714 $access = false;
2716 if (is_role_switched($course->id)) {
2717 // Ok, user had to be inside this course before the switch.
2718 $access = true;
2720 } else if (is_viewing($coursecontext, $USER)) {
2721 // Ok, no need to mess with enrol.
2722 $access = true;
2724 } else {
2725 if (isset($USER->enrol['enrolled'][$course->id])) {
2726 if ($USER->enrol['enrolled'][$course->id] > time()) {
2727 $access = true;
2728 if (isset($USER->enrol['tempguest'][$course->id])) {
2729 unset($USER->enrol['tempguest'][$course->id]);
2730 remove_temp_course_roles($coursecontext);
2732 } else {
2733 // Expired.
2734 unset($USER->enrol['enrolled'][$course->id]);
2737 if (isset($USER->enrol['tempguest'][$course->id])) {
2738 if ($USER->enrol['tempguest'][$course->id] == 0) {
2739 $access = true;
2740 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2741 $access = true;
2742 } else {
2743 // Expired.
2744 unset($USER->enrol['tempguest'][$course->id]);
2745 remove_temp_course_roles($coursecontext);
2749 if (!$access) {
2750 // Cache not ok.
2751 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2752 if ($until !== false) {
2753 // Active participants may always access, a timestamp in the future, 0 (always) or false.
2754 if ($until == 0) {
2755 $until = ENROL_MAX_TIMESTAMP;
2757 $USER->enrol['enrolled'][$course->id] = $until;
2758 $access = true;
2760 } else {
2761 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2762 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2763 $enrols = enrol_get_plugins(true);
2764 // First ask all enabled enrol instances in course if they want to auto enrol user.
2765 foreach ($instances as $instance) {
2766 if (!isset($enrols[$instance->enrol])) {
2767 continue;
2769 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2770 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2771 if ($until !== false) {
2772 if ($until == 0) {
2773 $until = ENROL_MAX_TIMESTAMP;
2775 $USER->enrol['enrolled'][$course->id] = $until;
2776 $access = true;
2777 break;
2780 // If not enrolled yet try to gain temporary guest access.
2781 if (!$access) {
2782 foreach ($instances as $instance) {
2783 if (!isset($enrols[$instance->enrol])) {
2784 continue;
2786 // Get a duration for the guest access, a timestamp in the future or false.
2787 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2788 if ($until !== false and $until > time()) {
2789 $USER->enrol['tempguest'][$course->id] = $until;
2790 $access = true;
2791 break;
2799 if (!$access) {
2800 if ($preventredirect) {
2801 throw new require_login_exception('Not enrolled');
2803 if ($setwantsurltome) {
2804 $SESSION->wantsurl = qualified_me();
2806 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2810 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2811 if ($cm && !$cm->uservisible) {
2812 if ($preventredirect) {
2813 throw new require_login_exception('Activity is hidden');
2815 if ($course->id != SITEID) {
2816 $url = new moodle_url('/course/view.php', array('id' => $course->id));
2817 } else {
2818 $url = new moodle_url('/');
2820 redirect($url, get_string('activityiscurrentlyhidden'));
2823 // Set the global $COURSE.
2824 if ($cm) {
2825 $PAGE->set_cm($cm, $course);
2826 $PAGE->set_pagelayout('incourse');
2827 } else if (!empty($courseorid)) {
2828 $PAGE->set_course($course);
2831 // Finally access granted, update lastaccess times.
2832 user_accesstime_log($course->id);
2837 * This function just makes sure a user is logged out.
2839 * @package core_access
2840 * @category access
2842 function require_logout() {
2843 global $USER, $DB;
2845 if (!isloggedin()) {
2846 // This should not happen often, no need for hooks or events here.
2847 \core\session\manager::terminate_current();
2848 return;
2851 // Execute hooks before action.
2852 $authplugins = array();
2853 $authsequence = get_enabled_auth_plugins();
2854 foreach ($authsequence as $authname) {
2855 $authplugins[$authname] = get_auth_plugin($authname);
2856 $authplugins[$authname]->prelogout_hook();
2859 // Store info that gets removed during logout.
2860 $sid = session_id();
2861 $event = \core\event\user_loggedout::create(
2862 array(
2863 'userid' => $USER->id,
2864 'objectid' => $USER->id,
2865 'other' => array('sessionid' => $sid),
2868 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2869 $event->add_record_snapshot('sessions', $session);
2872 // Clone of $USER object to be used by auth plugins.
2873 $user = fullclone($USER);
2875 // Delete session record and drop $_SESSION content.
2876 \core\session\manager::terminate_current();
2878 // Trigger event AFTER action.
2879 $event->trigger();
2881 // Hook to execute auth plugins redirection after event trigger.
2882 foreach ($authplugins as $authplugin) {
2883 $authplugin->postlogout_hook($user);
2888 * Weaker version of require_login()
2890 * This is a weaker version of {@link require_login()} which only requires login
2891 * when called from within a course rather than the site page, unless
2892 * the forcelogin option is turned on.
2893 * @see require_login()
2895 * @package core_access
2896 * @category access
2898 * @param mixed $courseorid The course object or id in question
2899 * @param bool $autologinguest Allow autologin guests if that is wanted
2900 * @param object $cm Course activity module if known
2901 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2902 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2903 * in order to keep redirects working properly. MDL-14495
2904 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2905 * @return void
2906 * @throws coding_exception
2908 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2909 global $CFG, $PAGE, $SITE;
2910 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2911 or (!is_object($courseorid) and $courseorid == SITEID));
2912 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2913 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2914 // db queries so this is not really a performance concern, however it is obviously
2915 // better if you use get_fast_modinfo to get the cm before calling this.
2916 if (is_object($courseorid)) {
2917 $course = $courseorid;
2918 } else {
2919 $course = clone($SITE);
2921 $modinfo = get_fast_modinfo($course);
2922 $cm = $modinfo->get_cm($cm->id);
2924 if (!empty($CFG->forcelogin)) {
2925 // Login required for both SITE and courses.
2926 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2928 } else if ($issite && !empty($cm) and !$cm->uservisible) {
2929 // Always login for hidden activities.
2930 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2932 } else if ($issite) {
2933 // Login for SITE not required.
2934 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
2935 if (!empty($courseorid)) {
2936 if (is_object($courseorid)) {
2937 $course = $courseorid;
2938 } else {
2939 $course = clone $SITE;
2941 if ($cm) {
2942 if ($cm->course != $course->id) {
2943 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2945 $PAGE->set_cm($cm, $course);
2946 $PAGE->set_pagelayout('incourse');
2947 } else {
2948 $PAGE->set_course($course);
2950 } else {
2951 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
2952 $PAGE->set_course($PAGE->course);
2954 user_accesstime_log(SITEID);
2955 return;
2957 } else {
2958 // Course login always required.
2959 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2964 * Require key login. Function terminates with error if key not found or incorrect.
2966 * @uses NO_MOODLE_COOKIES
2967 * @uses PARAM_ALPHANUM
2968 * @param string $script unique script identifier
2969 * @param int $instance optional instance id
2970 * @return int Instance ID
2972 function require_user_key_login($script, $instance=null) {
2973 global $DB;
2975 if (!NO_MOODLE_COOKIES) {
2976 print_error('sessioncookiesdisable');
2979 // Extra safety.
2980 \core\session\manager::write_close();
2982 $keyvalue = required_param('key', PARAM_ALPHANUM);
2984 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
2985 print_error('invalidkey');
2988 if (!empty($key->validuntil) and $key->validuntil < time()) {
2989 print_error('expiredkey');
2992 if ($key->iprestriction) {
2993 $remoteaddr = getremoteaddr(null);
2994 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2995 print_error('ipmismatch');
2999 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3000 print_error('invaliduserid');
3003 // Emulate normal session.
3004 enrol_check_plugins($user);
3005 \core\session\manager::set_user($user);
3007 // Note we are not using normal login.
3008 if (!defined('USER_KEY_LOGIN')) {
3009 define('USER_KEY_LOGIN', true);
3012 // Return instance id - it might be empty.
3013 return $key->instance;
3017 * Creates a new private user access key.
3019 * @param string $script unique target identifier
3020 * @param int $userid
3021 * @param int $instance optional instance id
3022 * @param string $iprestriction optional ip restricted access
3023 * @param timestamp $validuntil key valid only until given data
3024 * @return string access key value
3026 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3027 global $DB;
3029 $key = new stdClass();
3030 $key->script = $script;
3031 $key->userid = $userid;
3032 $key->instance = $instance;
3033 $key->iprestriction = $iprestriction;
3034 $key->validuntil = $validuntil;
3035 $key->timecreated = time();
3037 // Something long and unique.
3038 $key->value = md5($userid.'_'.time().random_string(40));
3039 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3040 // Must be unique.
3041 $key->value = md5($userid.'_'.time().random_string(40));
3043 $DB->insert_record('user_private_key', $key);
3044 return $key->value;
3048 * Delete the user's new private user access keys for a particular script.
3050 * @param string $script unique target identifier
3051 * @param int $userid
3052 * @return void
3054 function delete_user_key($script, $userid) {
3055 global $DB;
3056 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3060 * Gets a private user access key (and creates one if one doesn't exist).
3062 * @param string $script unique target identifier
3063 * @param int $userid
3064 * @param int $instance optional instance id
3065 * @param string $iprestriction optional ip restricted access
3066 * @param timestamp $validuntil key valid only until given data
3067 * @return string access key value
3069 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3070 global $DB;
3072 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3073 'instance' => $instance, 'iprestriction' => $iprestriction,
3074 'validuntil' => $validuntil))) {
3075 return $key->value;
3076 } else {
3077 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3083 * Modify the user table by setting the currently logged in user's last login to now.
3085 * @return bool Always returns true
3087 function update_user_login_times() {
3088 global $USER, $DB;
3090 if (isguestuser()) {
3091 // Do not update guest access times/ips for performance.
3092 return true;
3095 $now = time();
3097 $user = new stdClass();
3098 $user->id = $USER->id;
3100 // Make sure all users that logged in have some firstaccess.
3101 if ($USER->firstaccess == 0) {
3102 $USER->firstaccess = $user->firstaccess = $now;
3105 // Store the previous current as lastlogin.
3106 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3108 $USER->currentlogin = $user->currentlogin = $now;
3110 // Function user_accesstime_log() may not update immediately, better do it here.
3111 $USER->lastaccess = $user->lastaccess = $now;
3112 $USER->lastip = $user->lastip = getremoteaddr();
3114 // Note: do not call user_update_user() here because this is part of the login process,
3115 // the login event means that these fields were updated.
3116 $DB->update_record('user', $user);
3117 return true;
3121 * Determines if a user has completed setting up their account.
3123 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3124 * @return bool
3126 function user_not_fully_set_up($user) {
3127 if (isguestuser($user)) {
3128 return false;
3130 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3134 * Check whether the user has exceeded the bounce threshold
3136 * @param stdClass $user A {@link $USER} object
3137 * @return bool true => User has exceeded bounce threshold
3139 function over_bounce_threshold($user) {
3140 global $CFG, $DB;
3142 if (empty($CFG->handlebounces)) {
3143 return false;
3146 if (empty($user->id)) {
3147 // No real (DB) user, nothing to do here.
3148 return false;
3151 // Set sensible defaults.
3152 if (empty($CFG->minbounces)) {
3153 $CFG->minbounces = 10;
3155 if (empty($CFG->bounceratio)) {
3156 $CFG->bounceratio = .20;
3158 $bouncecount = 0;
3159 $sendcount = 0;
3160 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3161 $bouncecount = $bounce->value;
3163 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3164 $sendcount = $send->value;
3166 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3170 * Used to increment or reset email sent count
3172 * @param stdClass $user object containing an id
3173 * @param bool $reset will reset the count to 0
3174 * @return void
3176 function set_send_count($user, $reset=false) {
3177 global $DB;
3179 if (empty($user->id)) {
3180 // No real (DB) user, nothing to do here.
3181 return;
3184 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3185 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3186 $DB->update_record('user_preferences', $pref);
3187 } else if (!empty($reset)) {
3188 // If it's not there and we're resetting, don't bother. Make a new one.
3189 $pref = new stdClass();
3190 $pref->name = 'email_send_count';
3191 $pref->value = 1;
3192 $pref->userid = $user->id;
3193 $DB->insert_record('user_preferences', $pref, false);
3198 * Increment or reset user's email bounce count
3200 * @param stdClass $user object containing an id
3201 * @param bool $reset will reset the count to 0
3203 function set_bounce_count($user, $reset=false) {
3204 global $DB;
3206 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3207 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3208 $DB->update_record('user_preferences', $pref);
3209 } else if (!empty($reset)) {
3210 // If it's not there and we're resetting, don't bother. Make a new one.
3211 $pref = new stdClass();
3212 $pref->name = 'email_bounce_count';
3213 $pref->value = 1;
3214 $pref->userid = $user->id;
3215 $DB->insert_record('user_preferences', $pref, false);
3220 * Determines if the logged in user is currently moving an activity
3222 * @param int $courseid The id of the course being tested
3223 * @return bool
3225 function ismoving($courseid) {
3226 global $USER;
3228 if (!empty($USER->activitycopy)) {
3229 return ($USER->activitycopycourse == $courseid);
3231 return false;
3235 * Returns a persons full name
3237 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3238 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3239 * specify one.
3241 * @param stdClass $user A {@link $USER} object to get full name of.
3242 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3243 * @return string
3245 function fullname($user, $override=false) {
3246 global $CFG, $SESSION;
3248 if (!isset($user->firstname) and !isset($user->lastname)) {
3249 return '';
3252 // Get all of the name fields.
3253 $allnames = get_all_user_name_fields();
3254 if ($CFG->debugdeveloper) {
3255 foreach ($allnames as $allname) {
3256 if (!array_key_exists($allname, $user)) {
3257 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3258 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3259 // Message has been sent, no point in sending the message multiple times.
3260 break;
3265 if (!$override) {
3266 if (!empty($CFG->forcefirstname)) {
3267 $user->firstname = $CFG->forcefirstname;
3269 if (!empty($CFG->forcelastname)) {
3270 $user->lastname = $CFG->forcelastname;
3274 if (!empty($SESSION->fullnamedisplay)) {
3275 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3278 $template = null;
3279 // If the fullnamedisplay setting is available, set the template to that.
3280 if (isset($CFG->fullnamedisplay)) {
3281 $template = $CFG->fullnamedisplay;
3283 // If the template is empty, or set to language, return the language string.
3284 if ((empty($template) || $template == 'language') && !$override) {
3285 return get_string('fullnamedisplay', null, $user);
3288 // Check to see if we are displaying according to the alternative full name format.
3289 if ($override) {
3290 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3291 // Default to show just the user names according to the fullnamedisplay string.
3292 return get_string('fullnamedisplay', null, $user);
3293 } else {
3294 // If the override is true, then change the template to use the complete name.
3295 $template = $CFG->alternativefullnameformat;
3299 $requirednames = array();
3300 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3301 foreach ($allnames as $allname) {
3302 if (strpos($template, $allname) !== false) {
3303 $requirednames[] = $allname;
3307 $displayname = $template;
3308 // Switch in the actual data into the template.
3309 foreach ($requirednames as $altname) {
3310 if (isset($user->$altname)) {
3311 // Using empty() on the below if statement causes breakages.
3312 if ((string)$user->$altname == '') {
3313 $displayname = str_replace($altname, 'EMPTY', $displayname);
3314 } else {
3315 $displayname = str_replace($altname, $user->$altname, $displayname);
3317 } else {
3318 $displayname = str_replace($altname, 'EMPTY', $displayname);
3321 // Tidy up any misc. characters (Not perfect, but gets most characters).
3322 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3323 // katakana and parenthesis.
3324 $patterns = array();
3325 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3326 // filled in by a user.
3327 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3328 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3329 // This regular expression is to remove any double spaces in the display name.
3330 $patterns[] = '/\s{2,}/u';
3331 foreach ($patterns as $pattern) {
3332 $displayname = preg_replace($pattern, ' ', $displayname);
3335 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3336 $displayname = trim($displayname);
3337 if (empty($displayname)) {
3338 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3339 // people in general feel is a good setting to fall back on.
3340 $displayname = $user->firstname;
3342 return $displayname;
3346 * A centralised location for the all name fields. Returns an array / sql string snippet.
3348 * @param bool $returnsql True for an sql select field snippet.
3349 * @param string $tableprefix table query prefix to use in front of each field.
3350 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3351 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3352 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3353 * @return array|string All name fields.
3355 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3356 // This array is provided in this order because when called by fullname() (above) if firstname is before
3357 // firstnamephonetic str_replace() will change the wrong placeholder.
3358 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3359 'lastnamephonetic' => 'lastnamephonetic',
3360 'middlename' => 'middlename',
3361 'alternatename' => 'alternatename',
3362 'firstname' => 'firstname',
3363 'lastname' => 'lastname');
3365 // Let's add a prefix to the array of user name fields if provided.
3366 if ($prefix) {
3367 foreach ($alternatenames as $key => $altname) {
3368 $alternatenames[$key] = $prefix . $altname;
3372 // If we want the end result to have firstname and lastname at the front / top of the result.
3373 if ($order) {
3374 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3375 for ($i = 0; $i < 2; $i++) {
3376 // Get the last element.
3377 $lastelement = end($alternatenames);
3378 // Remove it from the array.
3379 unset($alternatenames[$lastelement]);
3380 // Put the element back on the top of the array.
3381 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3385 // Create an sql field snippet if requested.
3386 if ($returnsql) {
3387 if ($tableprefix) {
3388 if ($fieldprefix) {
3389 foreach ($alternatenames as $key => $altname) {
3390 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3392 } else {
3393 foreach ($alternatenames as $key => $altname) {
3394 $alternatenames[$key] = $tableprefix . '.' . $altname;
3398 $alternatenames = implode(',', $alternatenames);
3400 return $alternatenames;
3404 * Reduces lines of duplicated code for getting user name fields.
3406 * See also {@link user_picture::unalias()}
3408 * @param object $addtoobject Object to add user name fields to.
3409 * @param object $secondobject Object that contains user name field information.
3410 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3411 * @param array $additionalfields Additional fields to be matched with data in the second object.
3412 * The key can be set to the user table field name.
3413 * @return object User name fields.
3415 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3416 $fields = get_all_user_name_fields(false, null, $prefix);
3417 if ($additionalfields) {
3418 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3419 // the key is a number and then sets the key to the array value.
3420 foreach ($additionalfields as $key => $value) {
3421 if (is_numeric($key)) {
3422 $additionalfields[$value] = $prefix . $value;
3423 unset($additionalfields[$key]);
3424 } else {
3425 $additionalfields[$key] = $prefix . $value;
3428 $fields = array_merge($fields, $additionalfields);
3430 foreach ($fields as $key => $field) {
3431 // Important that we have all of the user name fields present in the object that we are sending back.
3432 $addtoobject->$key = '';
3433 if (isset($secondobject->$field)) {
3434 $addtoobject->$key = $secondobject->$field;
3437 return $addtoobject;
3441 * Returns an array of values in order of occurance in a provided string.
3442 * The key in the result is the character postion in the string.
3444 * @param array $values Values to be found in the string format
3445 * @param string $stringformat The string which may contain values being searched for.
3446 * @return array An array of values in order according to placement in the string format.
3448 function order_in_string($values, $stringformat) {
3449 $valuearray = array();
3450 foreach ($values as $value) {
3451 $pattern = "/$value\b/";
3452 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3453 if (preg_match($pattern, $stringformat)) {
3454 $replacement = "thing";
3455 // Replace the value with something more unique to ensure we get the right position when using strpos().
3456 $newformat = preg_replace($pattern, $replacement, $stringformat);
3457 $position = strpos($newformat, $replacement);
3458 $valuearray[$position] = $value;
3461 ksort($valuearray);
3462 return $valuearray;
3466 * Checks if current user is shown any extra fields when listing users.
3468 * @param object $context Context
3469 * @param array $already Array of fields that we're going to show anyway
3470 * so don't bother listing them
3471 * @return array Array of field names from user table, not including anything
3472 * listed in $already
3474 function get_extra_user_fields($context, $already = array()) {
3475 global $CFG;
3477 // Only users with permission get the extra fields.
3478 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3479 return array();
3482 // Split showuseridentity on comma.
3483 if (empty($CFG->showuseridentity)) {
3484 // Explode gives wrong result with empty string.
3485 $extra = array();
3486 } else {
3487 $extra = explode(',', $CFG->showuseridentity);
3489 $renumber = false;
3490 foreach ($extra as $key => $field) {
3491 if (in_array($field, $already)) {
3492 unset($extra[$key]);
3493 $renumber = true;
3496 if ($renumber) {
3497 // For consistency, if entries are removed from array, renumber it
3498 // so they are numbered as you would expect.
3499 $extra = array_merge($extra);
3501 return $extra;
3505 * If the current user is to be shown extra user fields when listing or
3506 * selecting users, returns a string suitable for including in an SQL select
3507 * clause to retrieve those fields.
3509 * @param context $context Context
3510 * @param string $alias Alias of user table, e.g. 'u' (default none)
3511 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3512 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3513 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3515 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3516 $fields = get_extra_user_fields($context, $already);
3517 $result = '';
3518 // Add punctuation for alias.
3519 if ($alias !== '') {
3520 $alias .= '.';
3522 foreach ($fields as $field) {
3523 $result .= ', ' . $alias . $field;
3524 if ($prefix) {
3525 $result .= ' AS ' . $prefix . $field;
3528 return $result;
3532 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3533 * @param string $field Field name, e.g. 'phone1'
3534 * @return string Text description taken from language file, e.g. 'Phone number'
3536 function get_user_field_name($field) {
3537 // Some fields have language strings which are not the same as field name.
3538 switch ($field) {
3539 case 'phone1' : {
3540 return get_string('phone');
3542 case 'url' : {
3543 return get_string('webpage');
3545 case 'icq' : {
3546 return get_string('icqnumber');
3548 case 'skype' : {
3549 return get_string('skypeid');
3551 case 'aim' : {
3552 return get_string('aimid');
3554 case 'yahoo' : {
3555 return get_string('yahooid');
3557 case 'msn' : {
3558 return get_string('msnid');
3561 // Otherwise just use the same lang string.
3562 return get_string($field);
3566 * Returns whether a given authentication plugin exists.
3568 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3569 * @return boolean Whether the plugin is available.
3571 function exists_auth_plugin($auth) {
3572 global $CFG;
3574 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3575 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3577 return false;
3581 * Checks if a given plugin is in the list of enabled authentication plugins.
3583 * @param string $auth Authentication plugin.
3584 * @return boolean Whether the plugin is enabled.
3586 function is_enabled_auth($auth) {
3587 if (empty($auth)) {
3588 return false;
3591 $enabled = get_enabled_auth_plugins();
3593 return in_array($auth, $enabled);
3597 * Returns an authentication plugin instance.
3599 * @param string $auth name of authentication plugin
3600 * @return auth_plugin_base An instance of the required authentication plugin.
3602 function get_auth_plugin($auth) {
3603 global $CFG;
3605 // Check the plugin exists first.
3606 if (! exists_auth_plugin($auth)) {
3607 print_error('authpluginnotfound', 'debug', '', $auth);
3610 // Return auth plugin instance.
3611 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3612 $class = "auth_plugin_$auth";
3613 return new $class;
3617 * Returns array of active auth plugins.
3619 * @param bool $fix fix $CFG->auth if needed
3620 * @return array
3622 function get_enabled_auth_plugins($fix=false) {
3623 global $CFG;
3625 $default = array('manual', 'nologin');
3627 if (empty($CFG->auth)) {
3628 $auths = array();
3629 } else {
3630 $auths = explode(',', $CFG->auth);
3633 if ($fix) {
3634 $auths = array_unique($auths);
3635 foreach ($auths as $k => $authname) {
3636 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3637 unset($auths[$k]);
3640 $newconfig = implode(',', $auths);
3641 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3642 set_config('auth', $newconfig);
3646 return (array_merge($default, $auths));
3650 * Returns true if an internal authentication method is being used.
3651 * if method not specified then, global default is assumed
3653 * @param string $auth Form of authentication required
3654 * @return bool
3656 function is_internal_auth($auth) {
3657 // Throws error if bad $auth.
3658 $authplugin = get_auth_plugin($auth);
3659 return $authplugin->is_internal();
3663 * Returns true if the user is a 'restored' one.
3665 * Used in the login process to inform the user and allow him/her to reset the password
3667 * @param string $username username to be checked
3668 * @return bool
3670 function is_restored_user($username) {
3671 global $CFG, $DB;
3673 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3677 * Returns an array of user fields
3679 * @return array User field/column names
3681 function get_user_fieldnames() {
3682 global $DB;
3684 $fieldarray = $DB->get_columns('user');
3685 unset($fieldarray['id']);
3686 $fieldarray = array_keys($fieldarray);
3688 return $fieldarray;
3692 * Creates a bare-bones user record
3694 * @todo Outline auth types and provide code example
3696 * @param string $username New user's username to add to record
3697 * @param string $password New user's password to add to record
3698 * @param string $auth Form of authentication required
3699 * @return stdClass A complete user object
3701 function create_user_record($username, $password, $auth = 'manual') {
3702 global $CFG, $DB;
3703 require_once($CFG->dirroot.'/user/profile/lib.php');
3704 require_once($CFG->dirroot.'/user/lib.php');
3706 // Just in case check text case.
3707 $username = trim(core_text::strtolower($username));
3709 $authplugin = get_auth_plugin($auth);
3710 $customfields = $authplugin->get_custom_user_profile_fields();
3711 $newuser = new stdClass();
3712 if ($newinfo = $authplugin->get_userinfo($username)) {
3713 $newinfo = truncate_userinfo($newinfo);
3714 foreach ($newinfo as $key => $value) {
3715 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3716 $newuser->$key = $value;
3721 if (!empty($newuser->email)) {
3722 if (email_is_not_allowed($newuser->email)) {
3723 unset($newuser->email);
3727 if (!isset($newuser->city)) {
3728 $newuser->city = '';
3731 $newuser->auth = $auth;
3732 $newuser->username = $username;
3734 // Fix for MDL-8480
3735 // user CFG lang for user if $newuser->lang is empty
3736 // or $user->lang is not an installed language.
3737 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3738 $newuser->lang = $CFG->lang;
3740 $newuser->confirmed = 1;
3741 $newuser->lastip = getremoteaddr();
3742 $newuser->timecreated = time();
3743 $newuser->timemodified = $newuser->timecreated;
3744 $newuser->mnethostid = $CFG->mnet_localhost_id;
3746 $newuser->id = user_create_user($newuser, false, false);
3748 // Save user profile data.
3749 profile_save_data($newuser);
3751 $user = get_complete_user_data('id', $newuser->id);
3752 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3753 set_user_preference('auth_forcepasswordchange', 1, $user);
3755 // Set the password.
3756 update_internal_user_password($user, $password);
3758 // Trigger event.
3759 \core\event\user_created::create_from_userid($newuser->id)->trigger();
3761 return $user;
3765 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3767 * @param string $username user's username to update the record
3768 * @return stdClass A complete user object
3770 function update_user_record($username) {
3771 global $DB, $CFG;
3772 // Just in case check text case.
3773 $username = trim(core_text::strtolower($username));
3775 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3776 return update_user_record_by_id($oldinfo->id);
3780 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3782 * @param int $id user id
3783 * @return stdClass A complete user object
3785 function update_user_record_by_id($id) {
3786 global $DB, $CFG;
3787 require_once($CFG->dirroot."/user/profile/lib.php");
3788 require_once($CFG->dirroot.'/user/lib.php');
3790 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3791 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3793 $newuser = array();
3794 $userauth = get_auth_plugin($oldinfo->auth);
3796 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3797 $newinfo = truncate_userinfo($newinfo);
3798 $customfields = $userauth->get_custom_user_profile_fields();
3800 foreach ($newinfo as $key => $value) {
3801 $key = strtolower($key);
3802 $iscustom = in_array($key, $customfields);
3803 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3804 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3805 // Unknown or must not be changed.
3806 continue;
3808 $confval = $userauth->config->{'field_updatelocal_' . $key};
3809 $lockval = $userauth->config->{'field_lock_' . $key};
3810 if (empty($confval) || empty($lockval)) {
3811 continue;
3813 if ($confval === 'onlogin') {
3814 // MDL-4207 Don't overwrite modified user profile values with
3815 // empty LDAP values when 'unlocked if empty' is set. The purpose
3816 // of the setting 'unlocked if empty' is to allow the user to fill
3817 // in a value for the selected field _if LDAP is giving
3818 // nothing_ for this field. Thus it makes sense to let this value
3819 // stand in until LDAP is giving a value for this field.
3820 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3821 if ($iscustom || (in_array($key, $userauth->userfields) &&
3822 ((string)$oldinfo->$key !== (string)$value))) {
3823 $newuser[$key] = (string)$value;
3828 if ($newuser) {
3829 $newuser['id'] = $oldinfo->id;
3830 $newuser['timemodified'] = time();
3831 user_update_user((object) $newuser, false, false);
3833 // Save user profile data.
3834 profile_save_data((object) $newuser);
3836 // Trigger event.
3837 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
3841 return get_complete_user_data('id', $oldinfo->id);
3845 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
3847 * @param array $info Array of user properties to truncate if needed
3848 * @return array The now truncated information that was passed in
3850 function truncate_userinfo(array $info) {
3851 // Define the limits.
3852 $limit = array(
3853 'username' => 100,
3854 'idnumber' => 255,
3855 'firstname' => 100,
3856 'lastname' => 100,
3857 'email' => 100,
3858 'icq' => 15,
3859 'phone1' => 20,
3860 'phone2' => 20,
3861 'institution' => 255,
3862 'department' => 255,
3863 'address' => 255,
3864 'city' => 120,
3865 'country' => 2,
3866 'url' => 255,
3869 // Apply where needed.
3870 foreach (array_keys($info) as $key) {
3871 if (!empty($limit[$key])) {
3872 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
3876 return $info;
3880 * Marks user deleted in internal user database and notifies the auth plugin.
3881 * Also unenrols user from all roles and does other cleanup.
3883 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3885 * @param stdClass $user full user object before delete
3886 * @return boolean success
3887 * @throws coding_exception if invalid $user parameter detected
3889 function delete_user(stdClass $user) {
3890 global $CFG, $DB;
3891 require_once($CFG->libdir.'/grouplib.php');
3892 require_once($CFG->libdir.'/gradelib.php');
3893 require_once($CFG->dirroot.'/message/lib.php');
3894 require_once($CFG->dirroot.'/tag/lib.php');
3895 require_once($CFG->dirroot.'/user/lib.php');
3897 // Make sure nobody sends bogus record type as parameter.
3898 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
3899 throw new coding_exception('Invalid $user parameter in delete_user() detected');
3902 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
3903 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
3904 debugging('Attempt to delete unknown user account.');
3905 return false;
3908 // There must be always exactly one guest record, originally the guest account was identified by username only,
3909 // now we use $CFG->siteguest for performance reasons.
3910 if ($user->username === 'guest' or isguestuser($user)) {
3911 debugging('Guest user account can not be deleted.');
3912 return false;
3915 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
3916 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
3917 if ($user->auth === 'manual' and is_siteadmin($user)) {
3918 debugging('Local administrator accounts can not be deleted.');
3919 return false;
3922 // Keep user record before updating it, as we have to pass this to user_deleted event.
3923 $olduser = clone $user;
3925 // Keep a copy of user context, we need it for event.
3926 $usercontext = context_user::instance($user->id);
3928 // Delete all grades - backup is kept in grade_grades_history table.
3929 grade_user_delete($user->id);
3931 // Move unread messages from this user to read.
3932 message_move_userfrom_unread2read($user->id);
3934 // TODO: remove from cohorts using standard API here.
3936 // Remove user tags.
3937 tag_set('user', $user->id, array(), 'core', $usercontext->id);
3939 // Unconditionally unenrol from all courses.
3940 enrol_user_delete($user);
3942 // Unenrol from all roles in all contexts.
3943 // This might be slow but it is really needed - modules might do some extra cleanup!
3944 role_unassign_all(array('userid' => $user->id));
3946 // Now do a brute force cleanup.
3948 // Remove from all cohorts.
3949 $DB->delete_records('cohort_members', array('userid' => $user->id));
3951 // Remove from all groups.
3952 $DB->delete_records('groups_members', array('userid' => $user->id));
3954 // Brute force unenrol from all courses.
3955 $DB->delete_records('user_enrolments', array('userid' => $user->id));
3957 // Purge user preferences.
3958 $DB->delete_records('user_preferences', array('userid' => $user->id));
3960 // Purge user extra profile info.
3961 $DB->delete_records('user_info_data', array('userid' => $user->id));
3963 // Purge log of previous password hashes.
3964 $DB->delete_records('user_password_history', array('userid' => $user->id));
3966 // Last course access not necessary either.
3967 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
3968 // Remove all user tokens.
3969 $DB->delete_records('external_tokens', array('userid' => $user->id));
3971 // Unauthorise the user for all services.
3972 $DB->delete_records('external_services_users', array('userid' => $user->id));
3974 // Remove users private keys.
3975 $DB->delete_records('user_private_key', array('userid' => $user->id));
3977 // Remove users customised pages.
3978 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
3980 // Force logout - may fail if file based sessions used, sorry.
3981 \core\session\manager::kill_user_sessions($user->id);
3983 // Workaround for bulk deletes of users with the same email address.
3984 $delname = clean_param($user->email . "." . time(), PARAM_USERNAME);
3985 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
3986 $delname++;
3989 // Mark internal user record as "deleted".
3990 $updateuser = new stdClass();
3991 $updateuser->id = $user->id;
3992 $updateuser->deleted = 1;
3993 $updateuser->username = $delname; // Remember it just in case.
3994 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
3995 $updateuser->idnumber = ''; // Clear this field to free it up.
3996 $updateuser->picture = 0;
3997 $updateuser->timemodified = time();
3999 // Don't trigger update event, as user is being deleted.
4000 user_update_user($updateuser, false, false);
4002 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4003 context_helper::delete_instance(CONTEXT_USER, $user->id);
4005 // Any plugin that needs to cleanup should register this event.
4006 // Trigger event.
4007 $event = \core\event\user_deleted::create(
4008 array(
4009 'objectid' => $user->id,
4010 'relateduserid' => $user->id,
4011 'context' => $usercontext,
4012 'other' => array(
4013 'username' => $user->username,
4014 'email' => $user->email,
4015 'idnumber' => $user->idnumber,
4016 'picture' => $user->picture,
4017 'mnethostid' => $user->mnethostid
4021 $event->add_record_snapshot('user', $olduser);
4022 $event->trigger();
4024 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4025 // should know about this updated property persisted to the user's table.
4026 $user->timemodified = $updateuser->timemodified;
4028 // Notify auth plugin - do not block the delete even when plugin fails.
4029 $authplugin = get_auth_plugin($user->auth);
4030 $authplugin->user_delete($user);
4032 return true;
4036 * Retrieve the guest user object.
4038 * @return stdClass A {@link $USER} object
4040 function guest_user() {
4041 global $CFG, $DB;
4043 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4044 $newuser->confirmed = 1;
4045 $newuser->lang = $CFG->lang;
4046 $newuser->lastip = getremoteaddr();
4049 return $newuser;
4053 * Authenticates a user against the chosen authentication mechanism
4055 * Given a username and password, this function looks them
4056 * up using the currently selected authentication mechanism,
4057 * and if the authentication is successful, it returns a
4058 * valid $user object from the 'user' table.
4060 * Uses auth_ functions from the currently active auth module
4062 * After authenticate_user_login() returns success, you will need to
4063 * log that the user has logged in, and call complete_user_login() to set
4064 * the session up.
4066 * Note: this function works only with non-mnet accounts!
4068 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4069 * @param string $password User's password
4070 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4071 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4072 * @return stdClass|false A {@link $USER} object or false if error
4074 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4075 global $CFG, $DB;
4076 require_once("$CFG->libdir/authlib.php");
4078 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4079 // we have found the user
4081 } else if (!empty($CFG->authloginviaemail)) {
4082 if ($email = clean_param($username, PARAM_EMAIL)) {
4083 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4084 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4085 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4086 if (count($users) === 1) {
4087 // Use email for login only if unique.
4088 $user = reset($users);
4089 $user = get_complete_user_data('id', $user->id);
4090 $username = $user->username;
4092 unset($users);
4096 $authsenabled = get_enabled_auth_plugins();
4098 if ($user) {
4099 // Use manual if auth not set.
4100 $auth = empty($user->auth) ? 'manual' : $user->auth;
4101 if (!empty($user->suspended)) {
4102 $failurereason = AUTH_LOGIN_SUSPENDED;
4104 // Trigger login failed event.
4105 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4106 'other' => array('username' => $username, 'reason' => $failurereason)));
4107 $event->trigger();
4108 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4109 return false;
4111 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4112 // Legacy way to suspend user.
4113 $failurereason = AUTH_LOGIN_SUSPENDED;
4115 // Trigger login failed event.
4116 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4117 'other' => array('username' => $username, 'reason' => $failurereason)));
4118 $event->trigger();
4119 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4120 return false;
4122 $auths = array($auth);
4124 } else {
4125 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4126 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4127 $failurereason = AUTH_LOGIN_NOUSER;
4129 // Trigger login failed event.
4130 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4131 'reason' => $failurereason)));
4132 $event->trigger();
4133 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4134 return false;
4137 // User does not exist.
4138 $auths = $authsenabled;
4139 $user = new stdClass();
4140 $user->id = 0;
4143 if ($ignorelockout) {
4144 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4145 // or this function is called from a SSO script.
4146 } else if ($user->id) {
4147 // Verify login lockout after other ways that may prevent user login.
4148 if (login_is_lockedout($user)) {
4149 $failurereason = AUTH_LOGIN_LOCKOUT;
4151 // Trigger login failed event.
4152 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4153 'other' => array('username' => $username, 'reason' => $failurereason)));
4154 $event->trigger();
4156 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4157 return false;
4159 } else {
4160 // We can not lockout non-existing accounts.
4163 foreach ($auths as $auth) {
4164 $authplugin = get_auth_plugin($auth);
4166 // On auth fail fall through to the next plugin.
4167 if (!$authplugin->user_login($username, $password)) {
4168 continue;
4171 // Successful authentication.
4172 if ($user->id) {
4173 // User already exists in database.
4174 if (empty($user->auth)) {
4175 // For some reason auth isn't set yet.
4176 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4177 $user->auth = $auth;
4180 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4181 // the current hash algorithm while we have access to the user's password.
4182 update_internal_user_password($user, $password);
4184 if ($authplugin->is_synchronised_with_external()) {
4185 // Update user record from external DB.
4186 $user = update_user_record_by_id($user->id);
4188 } else {
4189 // The user is authenticated but user creation may be disabled.
4190 if (!empty($CFG->authpreventaccountcreation)) {
4191 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4193 // Trigger login failed event.
4194 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4195 'reason' => $failurereason)));
4196 $event->trigger();
4198 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4199 $_SERVER['HTTP_USER_AGENT']);
4200 return false;
4201 } else {
4202 $user = create_user_record($username, $password, $auth);
4206 $authplugin->sync_roles($user);
4208 foreach ($authsenabled as $hau) {
4209 $hauth = get_auth_plugin($hau);
4210 $hauth->user_authenticated_hook($user, $username, $password);
4213 if (empty($user->id)) {
4214 $failurereason = AUTH_LOGIN_NOUSER;
4215 // Trigger login failed event.
4216 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4217 'reason' => $failurereason)));
4218 $event->trigger();
4219 return false;
4222 if (!empty($user->suspended)) {
4223 // Just in case some auth plugin suspended account.
4224 $failurereason = AUTH_LOGIN_SUSPENDED;
4225 // Trigger login failed event.
4226 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4227 'other' => array('username' => $username, 'reason' => $failurereason)));
4228 $event->trigger();
4229 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4230 return false;
4233 login_attempt_valid($user);
4234 $failurereason = AUTH_LOGIN_OK;
4235 return $user;
4238 // Failed if all the plugins have failed.
4239 if (debugging('', DEBUG_ALL)) {
4240 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4243 if ($user->id) {
4244 login_attempt_failed($user);
4245 $failurereason = AUTH_LOGIN_FAILED;
4246 // Trigger login failed event.
4247 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4248 'other' => array('username' => $username, 'reason' => $failurereason)));
4249 $event->trigger();
4250 } else {
4251 $failurereason = AUTH_LOGIN_NOUSER;
4252 // Trigger login failed event.
4253 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4254 'reason' => $failurereason)));
4255 $event->trigger();
4258 return false;
4262 * Call to complete the user login process after authenticate_user_login()
4263 * has succeeded. It will setup the $USER variable and other required bits
4264 * and pieces.
4266 * NOTE:
4267 * - It will NOT log anything -- up to the caller to decide what to log.
4268 * - this function does not set any cookies any more!
4270 * @param stdClass $user
4271 * @return stdClass A {@link $USER} object - BC only, do not use
4273 function complete_user_login($user) {
4274 global $CFG, $USER;
4276 \core\session\manager::login_user($user);
4278 // Reload preferences from DB.
4279 unset($USER->preference);
4280 check_user_preferences_loaded($USER);
4282 // Update login times.
4283 update_user_login_times();
4285 // Extra session prefs init.
4286 set_login_session_preferences();
4288 // Trigger login event.
4289 $event = \core\event\user_loggedin::create(
4290 array(
4291 'userid' => $USER->id,
4292 'objectid' => $USER->id,
4293 'other' => array('username' => $USER->username),
4296 $event->trigger();
4298 if (isguestuser()) {
4299 // No need to continue when user is THE guest.
4300 return $USER;
4303 if (CLI_SCRIPT) {
4304 // We can redirect to password change URL only in browser.
4305 return $USER;
4308 // Select password change url.
4309 $userauth = get_auth_plugin($USER->auth);
4311 // Check whether the user should be changing password.
4312 if (get_user_preferences('auth_forcepasswordchange', false)) {
4313 if ($userauth->can_change_password()) {
4314 if ($changeurl = $userauth->change_password_url()) {
4315 redirect($changeurl);
4316 } else {
4317 redirect($CFG->httpswwwroot.'/login/change_password.php');
4319 } else {
4320 print_error('nopasswordchangeforced', 'auth');
4323 return $USER;
4327 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4329 * @param string $password String to check.
4330 * @return boolean True if the $password matches the format of an md5 sum.
4332 function password_is_legacy_hash($password) {
4333 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4337 * Compare password against hash stored in user object to determine if it is valid.
4339 * If necessary it also updates the stored hash to the current format.
4341 * @param stdClass $user (Password property may be updated).
4342 * @param string $password Plain text password.
4343 * @return bool True if password is valid.
4345 function validate_internal_user_password($user, $password) {
4346 global $CFG;
4347 require_once($CFG->libdir.'/password_compat/lib/password.php');
4349 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4350 // Internal password is not used at all, it can not validate.
4351 return false;
4354 // If hash isn't a legacy (md5) hash, validate using the library function.
4355 if (!password_is_legacy_hash($user->password)) {
4356 return password_verify($password, $user->password);
4359 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4360 // is valid we can then update it to the new algorithm.
4362 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4363 $validated = false;
4365 if ($user->password === md5($password.$sitesalt)
4366 or $user->password === md5($password)
4367 or $user->password === md5(addslashes($password).$sitesalt)
4368 or $user->password === md5(addslashes($password))) {
4369 // Note: we are intentionally using the addslashes() here because we
4370 // need to accept old password hashes of passwords with magic quotes.
4371 $validated = true;
4373 } else {
4374 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4375 $alt = 'passwordsaltalt'.$i;
4376 if (!empty($CFG->$alt)) {
4377 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4378 $validated = true;
4379 break;
4385 if ($validated) {
4386 // If the password matches the existing md5 hash, update to the
4387 // current hash algorithm while we have access to the user's password.
4388 update_internal_user_password($user, $password);
4391 return $validated;
4395 * Calculate hash for a plain text password.
4397 * @param string $password Plain text password to be hashed.
4398 * @param bool $fasthash If true, use a low cost factor when generating the hash
4399 * This is much faster to generate but makes the hash
4400 * less secure. It is used when lots of hashes need to
4401 * be generated quickly.
4402 * @return string The hashed password.
4404 * @throws moodle_exception If a problem occurs while generating the hash.
4406 function hash_internal_user_password($password, $fasthash = false) {
4407 global $CFG;
4408 require_once($CFG->libdir.'/password_compat/lib/password.php');
4410 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4411 $options = ($fasthash) ? array('cost' => 4) : array();
4413 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4415 if ($generatedhash === false || $generatedhash === null) {
4416 throw new moodle_exception('Failed to generate password hash.');
4419 return $generatedhash;
4423 * Update password hash in user object (if necessary).
4425 * The password is updated if:
4426 * 1. The password has changed (the hash of $user->password is different
4427 * to the hash of $password).
4428 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4429 * md5 algorithm).
4431 * Updating the password will modify the $user object and the database
4432 * record to use the current hashing algorithm.
4434 * @param stdClass $user User object (password property may be updated).
4435 * @param string $password Plain text password.
4436 * @param bool $fasthash If true, use a low cost factor when generating the hash
4437 * This is much faster to generate but makes the hash
4438 * less secure. It is used when lots of hashes need to
4439 * be generated quickly.
4440 * @return bool Always returns true.
4442 function update_internal_user_password($user, $password, $fasthash = false) {
4443 global $CFG, $DB;
4444 require_once($CFG->libdir.'/password_compat/lib/password.php');
4446 // Figure out what the hashed password should be.
4447 if (!isset($user->auth)) {
4448 debugging('User record in update_internal_user_password() must include field auth',
4449 DEBUG_DEVELOPER);
4450 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4452 $authplugin = get_auth_plugin($user->auth);
4453 if ($authplugin->prevent_local_passwords()) {
4454 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4455 } else {
4456 $hashedpassword = hash_internal_user_password($password, $fasthash);
4459 $algorithmchanged = false;
4461 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4462 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4463 $passwordchanged = ($user->password !== $hashedpassword);
4465 } else if (isset($user->password)) {
4466 // If verification fails then it means the password has changed.
4467 $passwordchanged = !password_verify($password, $user->password);
4468 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4469 } else {
4470 // While creating new user, password in unset in $user object, to avoid
4471 // saving it with user_create()
4472 $passwordchanged = true;
4475 if ($passwordchanged || $algorithmchanged) {
4476 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4477 $user->password = $hashedpassword;
4479 // Trigger event.
4480 $user = $DB->get_record('user', array('id' => $user->id));
4481 \core\event\user_password_updated::create_from_user($user)->trigger();
4484 return true;
4488 * Get a complete user record, which includes all the info in the user record.
4490 * Intended for setting as $USER session variable
4492 * @param string $field The user field to be checked for a given value.
4493 * @param string $value The value to match for $field.
4494 * @param int $mnethostid
4495 * @return mixed False, or A {@link $USER} object.
4497 function get_complete_user_data($field, $value, $mnethostid = null) {
4498 global $CFG, $DB;
4500 if (!$field || !$value) {
4501 return false;
4504 // Build the WHERE clause for an SQL query.
4505 $params = array('fieldval' => $value);
4506 $constraints = "$field = :fieldval AND deleted <> 1";
4508 // If we are loading user data based on anything other than id,
4509 // we must also restrict our search based on mnet host.
4510 if ($field != 'id') {
4511 if (empty($mnethostid)) {
4512 // If empty, we restrict to local users.
4513 $mnethostid = $CFG->mnet_localhost_id;
4516 if (!empty($mnethostid)) {
4517 $params['mnethostid'] = $mnethostid;
4518 $constraints .= " AND mnethostid = :mnethostid";
4521 // Get all the basic user data.
4522 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4523 return false;
4526 // Get various settings and preferences.
4528 // Preload preference cache.
4529 check_user_preferences_loaded($user);
4531 // Load course enrolment related stuff.
4532 $user->lastcourseaccess = array(); // During last session.
4533 $user->currentcourseaccess = array(); // During current session.
4534 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4535 foreach ($lastaccesses as $lastaccess) {
4536 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4540 $sql = "SELECT g.id, g.courseid
4541 FROM {groups} g, {groups_members} gm
4542 WHERE gm.groupid=g.id AND gm.userid=?";
4544 // This is a special hack to speedup calendar display.
4545 $user->groupmember = array();
4546 if (!isguestuser($user)) {
4547 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4548 foreach ($groups as $group) {
4549 if (!array_key_exists($group->courseid, $user->groupmember)) {
4550 $user->groupmember[$group->courseid] = array();
4552 $user->groupmember[$group->courseid][$group->id] = $group->id;
4557 // Add the custom profile fields to the user record.
4558 $user->profile = array();
4559 if (!isguestuser($user)) {
4560 require_once($CFG->dirroot.'/user/profile/lib.php');
4561 profile_load_custom_fields($user);
4564 // Rewrite some variables if necessary.
4565 if (!empty($user->description)) {
4566 // No need to cart all of it around.
4567 $user->description = true;
4569 if (isguestuser($user)) {
4570 // Guest language always same as site.
4571 $user->lang = $CFG->lang;
4572 // Name always in current language.
4573 $user->firstname = get_string('guestuser');
4574 $user->lastname = ' ';
4577 return $user;
4581 * Validate a password against the configured password policy
4583 * @param string $password the password to be checked against the password policy
4584 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4585 * @return bool true if the password is valid according to the policy. false otherwise.
4587 function check_password_policy($password, &$errmsg) {
4588 global $CFG;
4590 if (empty($CFG->passwordpolicy)) {
4591 return true;
4594 $errmsg = '';
4595 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4596 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4599 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4600 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4603 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4604 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4607 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4608 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4611 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4612 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4614 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4615 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4618 if ($errmsg == '') {
4619 return true;
4620 } else {
4621 return false;
4627 * When logging in, this function is run to set certain preferences for the current SESSION.
4629 function set_login_session_preferences() {
4630 global $SESSION;
4632 $SESSION->justloggedin = true;
4634 unset($SESSION->lang);
4635 unset($SESSION->forcelang);
4636 unset($SESSION->load_navigation_admin);
4641 * Delete a course, including all related data from the database, and any associated files.
4643 * @param mixed $courseorid The id of the course or course object to delete.
4644 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4645 * @return bool true if all the removals succeeded. false if there were any failures. If this
4646 * method returns false, some of the removals will probably have succeeded, and others
4647 * failed, but you have no way of knowing which.
4649 function delete_course($courseorid, $showfeedback = true) {
4650 global $DB;
4652 if (is_object($courseorid)) {
4653 $courseid = $courseorid->id;
4654 $course = $courseorid;
4655 } else {
4656 $courseid = $courseorid;
4657 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4658 return false;
4661 $context = context_course::instance($courseid);
4663 // Frontpage course can not be deleted!!
4664 if ($courseid == SITEID) {
4665 return false;
4668 // Make the course completely empty.
4669 remove_course_contents($courseid, $showfeedback);
4671 // Delete the course and related context instance.
4672 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4674 $DB->delete_records("course", array("id" => $courseid));
4675 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4677 // Reset all course related caches here.
4678 if (class_exists('format_base', false)) {
4679 format_base::reset_course_cache($courseid);
4682 // Trigger a course deleted event.
4683 $event = \core\event\course_deleted::create(array(
4684 'objectid' => $course->id,
4685 'context' => $context,
4686 'other' => array(
4687 'shortname' => $course->shortname,
4688 'fullname' => $course->fullname,
4689 'idnumber' => $course->idnumber
4692 $event->add_record_snapshot('course', $course);
4693 $event->trigger();
4695 return true;
4699 * Clear a course out completely, deleting all content but don't delete the course itself.
4701 * This function does not verify any permissions.
4703 * Please note this function also deletes all user enrolments,
4704 * enrolment instances and role assignments by default.
4706 * $options:
4707 * - 'keep_roles_and_enrolments' - false by default
4708 * - 'keep_groups_and_groupings' - false by default
4710 * @param int $courseid The id of the course that is being deleted
4711 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4712 * @param array $options extra options
4713 * @return bool true if all the removals succeeded. false if there were any failures. If this
4714 * method returns false, some of the removals will probably have succeeded, and others
4715 * failed, but you have no way of knowing which.
4717 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4718 global $CFG, $DB, $OUTPUT;
4720 require_once($CFG->libdir.'/badgeslib.php');
4721 require_once($CFG->libdir.'/completionlib.php');
4722 require_once($CFG->libdir.'/questionlib.php');
4723 require_once($CFG->libdir.'/gradelib.php');
4724 require_once($CFG->dirroot.'/group/lib.php');
4725 require_once($CFG->dirroot.'/tag/coursetagslib.php');
4726 require_once($CFG->dirroot.'/comment/lib.php');
4727 require_once($CFG->dirroot.'/rating/lib.php');
4728 require_once($CFG->dirroot.'/notes/lib.php');
4730 // Handle course badges.
4731 badges_handle_course_deletion($courseid);
4733 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4734 $strdeleted = get_string('deleted').' - ';
4736 // Some crazy wishlist of stuff we should skip during purging of course content.
4737 $options = (array)$options;
4739 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4740 $coursecontext = context_course::instance($courseid);
4741 $fs = get_file_storage();
4743 // Delete course completion information, this has to be done before grades and enrols.
4744 $cc = new completion_info($course);
4745 $cc->clear_criteria();
4746 if ($showfeedback) {
4747 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4750 // Remove all data from gradebook - this needs to be done before course modules
4751 // because while deleting this information, the system may need to reference
4752 // the course modules that own the grades.
4753 remove_course_grades($courseid, $showfeedback);
4754 remove_grade_letters($coursecontext, $showfeedback);
4756 // Delete course blocks in any all child contexts,
4757 // they may depend on modules so delete them first.
4758 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4759 foreach ($childcontexts as $childcontext) {
4760 blocks_delete_all_for_context($childcontext->id);
4762 unset($childcontexts);
4763 blocks_delete_all_for_context($coursecontext->id);
4764 if ($showfeedback) {
4765 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4768 // Delete every instance of every module,
4769 // this has to be done before deleting of course level stuff.
4770 $locations = core_component::get_plugin_list('mod');
4771 foreach ($locations as $modname => $moddir) {
4772 if ($modname === 'NEWMODULE') {
4773 continue;
4775 if ($module = $DB->get_record('modules', array('name' => $modname))) {
4776 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
4777 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
4778 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
4780 if ($instances = $DB->get_records($modname, array('course' => $course->id))) {
4781 foreach ($instances as $instance) {
4782 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
4783 // Delete activity context questions and question categories.
4784 question_delete_activity($cm, $showfeedback);
4786 if (function_exists($moddelete)) {
4787 // This purges all module data in related tables, extra user prefs, settings, etc.
4788 $moddelete($instance->id);
4789 } else {
4790 // NOTE: we should not allow installation of modules with missing delete support!
4791 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4792 $DB->delete_records($modname, array('id' => $instance->id));
4795 if ($cm) {
4796 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
4797 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4798 $DB->delete_records('course_modules', array('id' => $cm->id));
4802 if (function_exists($moddeletecourse)) {
4803 // Execute ptional course cleanup callback.
4804 $moddeletecourse($course, $showfeedback);
4806 if ($instances and $showfeedback) {
4807 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4809 } else {
4810 // Ooops, this module is not properly installed, force-delete it in the next block.
4814 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
4816 // Remove all data from availability and completion tables that is associated
4817 // with course-modules belonging to this course. Note this is done even if the
4818 // features are not enabled now, in case they were enabled previously.
4819 $DB->delete_records_select('course_modules_completion',
4820 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4821 array($courseid));
4823 // Remove course-module data.
4824 $cms = $DB->get_records('course_modules', array('course' => $course->id));
4825 foreach ($cms as $cm) {
4826 if ($module = $DB->get_record('modules', array('id' => $cm->module))) {
4827 try {
4828 $DB->delete_records($module->name, array('id' => $cm->instance));
4829 } catch (Exception $e) {
4830 // Ignore weird or missing table problems.
4833 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4834 $DB->delete_records('course_modules', array('id' => $cm->id));
4837 if ($showfeedback) {
4838 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
4841 // Cleanup the rest of plugins.
4842 $cleanuplugintypes = array('report', 'coursereport', 'format');
4843 foreach ($cleanuplugintypes as $type) {
4844 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
4845 foreach ($plugins as $plugin => $pluginfunction) {
4846 $pluginfunction($course->id, $showfeedback);
4848 if ($showfeedback) {
4849 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
4853 // Delete questions and question categories.
4854 question_delete_course($course, $showfeedback);
4855 if ($showfeedback) {
4856 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
4859 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
4860 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4861 foreach ($childcontexts as $childcontext) {
4862 $childcontext->delete();
4864 unset($childcontexts);
4866 // Remove all roles and enrolments by default.
4867 if (empty($options['keep_roles_and_enrolments'])) {
4868 // This hack is used in restore when deleting contents of existing course.
4869 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
4870 enrol_course_delete($course);
4871 if ($showfeedback) {
4872 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
4876 // Delete any groups, removing members and grouping/course links first.
4877 if (empty($options['keep_groups_and_groupings'])) {
4878 groups_delete_groupings($course->id, $showfeedback);
4879 groups_delete_groups($course->id, $showfeedback);
4882 // Filters be gone!
4883 filter_delete_all_for_context($coursecontext->id);
4885 // Notes, you shall not pass!
4886 note_delete_all($course->id);
4888 // Die comments!
4889 comment::delete_comments($coursecontext->id);
4891 // Ratings are history too.
4892 $delopt = new stdclass();
4893 $delopt->contextid = $coursecontext->id;
4894 $rm = new rating_manager();
4895 $rm->delete_ratings($delopt);
4897 // Delete course tags.
4898 coursetag_delete_course_tags($course->id, $showfeedback);
4900 // Delete calendar events.
4901 $DB->delete_records('event', array('courseid' => $course->id));
4902 $fs->delete_area_files($coursecontext->id, 'calendar');
4904 // Delete all related records in other core tables that may have a courseid
4905 // This array stores the tables that need to be cleared, as
4906 // table_name => column_name that contains the course id.
4907 $tablestoclear = array(
4908 'backup_courses' => 'courseid', // Scheduled backup stuff.
4909 'user_lastaccess' => 'courseid', // User access info.
4911 foreach ($tablestoclear as $table => $col) {
4912 $DB->delete_records($table, array($col => $course->id));
4915 // Delete all course backup files.
4916 $fs->delete_area_files($coursecontext->id, 'backup');
4918 // Cleanup course record - remove links to deleted stuff.
4919 $oldcourse = new stdClass();
4920 $oldcourse->id = $course->id;
4921 $oldcourse->summary = '';
4922 $oldcourse->cacherev = 0;
4923 $oldcourse->legacyfiles = 0;
4924 $oldcourse->enablecompletion = 0;
4925 if (!empty($options['keep_groups_and_groupings'])) {
4926 $oldcourse->defaultgroupingid = 0;
4928 $DB->update_record('course', $oldcourse);
4930 // Delete course sections.
4931 $DB->delete_records('course_sections', array('course' => $course->id));
4933 // Delete legacy, section and any other course files.
4934 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
4936 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
4937 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
4938 // Easy, do not delete the context itself...
4939 $coursecontext->delete_content();
4940 } else {
4941 // Hack alert!!!!
4942 // We can not drop all context stuff because it would bork enrolments and roles,
4943 // there might be also files used by enrol plugins...
4946 // Delete legacy files - just in case some files are still left there after conversion to new file api,
4947 // also some non-standard unsupported plugins may try to store something there.
4948 fulldelete($CFG->dataroot.'/'.$course->id);
4950 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
4951 $cachemodinfo = cache::make('core', 'coursemodinfo');
4952 $cachemodinfo->delete($courseid);
4954 // Trigger a course content deleted event.
4955 $event = \core\event\course_content_deleted::create(array(
4956 'objectid' => $course->id,
4957 'context' => $coursecontext,
4958 'other' => array('shortname' => $course->shortname,
4959 'fullname' => $course->fullname,
4960 'options' => $options) // Passing this for legacy reasons.
4962 $event->add_record_snapshot('course', $course);
4963 $event->trigger();
4965 return true;
4969 * Change dates in module - used from course reset.
4971 * @param string $modname forum, assignment, etc
4972 * @param array $fields array of date fields from mod table
4973 * @param int $timeshift time difference
4974 * @param int $courseid
4975 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
4976 * @return bool success
4978 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
4979 global $CFG, $DB;
4980 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
4982 $return = true;
4983 $params = array($timeshift, $courseid);
4984 foreach ($fields as $field) {
4985 $updatesql = "UPDATE {".$modname."}
4986 SET $field = $field + ?
4987 WHERE course=? AND $field<>0";
4988 if ($modid) {
4989 $updatesql .= ' AND id=?';
4990 $params[] = $modid;
4992 $return = $DB->execute($updatesql, $params) && $return;
4995 $refreshfunction = $modname.'_refresh_events';
4996 if (function_exists($refreshfunction)) {
4997 $refreshfunction($courseid);
5000 return $return;
5004 * This function will empty a course of user data.
5005 * It will retain the activities and the structure of the course.
5007 * @param object $data an object containing all the settings including courseid (without magic quotes)
5008 * @return array status array of array component, item, error
5010 function reset_course_userdata($data) {
5011 global $CFG, $DB;
5012 require_once($CFG->libdir.'/gradelib.php');
5013 require_once($CFG->libdir.'/completionlib.php');
5014 require_once($CFG->dirroot.'/group/lib.php');
5016 $data->courseid = $data->id;
5017 $context = context_course::instance($data->courseid);
5019 $eventparams = array(
5020 'context' => $context,
5021 'courseid' => $data->id,
5022 'other' => array(
5023 'reset_options' => (array) $data
5026 $event = \core\event\course_reset_started::create($eventparams);
5027 $event->trigger();
5029 // Calculate the time shift of dates.
5030 if (!empty($data->reset_start_date)) {
5031 // Time part of course startdate should be zero.
5032 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5033 } else {
5034 $data->timeshift = 0;
5037 // Result array: component, item, error.
5038 $status = array();
5040 // Start the resetting.
5041 $componentstr = get_string('general');
5043 // Move the course start time.
5044 if (!empty($data->reset_start_date) and $data->timeshift) {
5045 // Change course start data.
5046 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5047 // Update all course and group events - do not move activity events.
5048 $updatesql = "UPDATE {event}
5049 SET timestart = timestart + ?
5050 WHERE courseid=? AND instance=0";
5051 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5053 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5056 if (!empty($data->reset_events)) {
5057 $DB->delete_records('event', array('courseid' => $data->courseid));
5058 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5061 if (!empty($data->reset_notes)) {
5062 require_once($CFG->dirroot.'/notes/lib.php');
5063 note_delete_all($data->courseid);
5064 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5067 if (!empty($data->delete_blog_associations)) {
5068 require_once($CFG->dirroot.'/blog/lib.php');
5069 blog_remove_associations_for_course($data->courseid);
5070 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5073 if (!empty($data->reset_completion)) {
5074 // Delete course and activity completion information.
5075 $course = $DB->get_record('course', array('id' => $data->courseid));
5076 $cc = new completion_info($course);
5077 $cc->delete_all_completion_data();
5078 $status[] = array('component' => $componentstr,
5079 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5082 $componentstr = get_string('roles');
5084 if (!empty($data->reset_roles_overrides)) {
5085 $children = $context->get_child_contexts();
5086 foreach ($children as $child) {
5087 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5089 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5090 // Force refresh for logged in users.
5091 $context->mark_dirty();
5092 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5095 if (!empty($data->reset_roles_local)) {
5096 $children = $context->get_child_contexts();
5097 foreach ($children as $child) {
5098 role_unassign_all(array('contextid' => $child->id));
5100 // Force refresh for logged in users.
5101 $context->mark_dirty();
5102 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5105 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5106 $data->unenrolled = array();
5107 if (!empty($data->unenrol_users)) {
5108 $plugins = enrol_get_plugins(true);
5109 $instances = enrol_get_instances($data->courseid, true);
5110 foreach ($instances as $key => $instance) {
5111 if (!isset($plugins[$instance->enrol])) {
5112 unset($instances[$key]);
5113 continue;
5117 foreach ($data->unenrol_users as $withroleid) {
5118 if ($withroleid) {
5119 $sql = "SELECT ue.*
5120 FROM {user_enrolments} ue
5121 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5122 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5123 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5124 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5126 } else {
5127 // Without any role assigned at course context.
5128 $sql = "SELECT ue.*
5129 FROM {user_enrolments} ue
5130 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5131 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5132 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5133 WHERE ra.id IS null";
5134 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5137 $rs = $DB->get_recordset_sql($sql, $params);
5138 foreach ($rs as $ue) {
5139 if (!isset($instances[$ue->enrolid])) {
5140 continue;
5142 $instance = $instances[$ue->enrolid];
5143 $plugin = $plugins[$instance->enrol];
5144 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5145 continue;
5148 $plugin->unenrol_user($instance, $ue->userid);
5149 $data->unenrolled[$ue->userid] = $ue->userid;
5151 $rs->close();
5154 if (!empty($data->unenrolled)) {
5155 $status[] = array(
5156 'component' => $componentstr,
5157 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5158 'error' => false
5162 $componentstr = get_string('groups');
5164 // Remove all group members.
5165 if (!empty($data->reset_groups_members)) {
5166 groups_delete_group_members($data->courseid);
5167 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5170 // Remove all groups.
5171 if (!empty($data->reset_groups_remove)) {
5172 groups_delete_groups($data->courseid, false);
5173 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5176 // Remove all grouping members.
5177 if (!empty($data->reset_groupings_members)) {
5178 groups_delete_groupings_groups($data->courseid, false);
5179 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5182 // Remove all groupings.
5183 if (!empty($data->reset_groupings_remove)) {
5184 groups_delete_groupings($data->courseid, false);
5185 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5188 // Look in every instance of every module for data to delete.
5189 $unsupportedmods = array();
5190 if ($allmods = $DB->get_records('modules') ) {
5191 foreach ($allmods as $mod) {
5192 $modname = $mod->name;
5193 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5194 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5195 if (file_exists($modfile)) {
5196 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5197 continue; // Skip mods with no instances.
5199 include_once($modfile);
5200 if (function_exists($moddeleteuserdata)) {
5201 $modstatus = $moddeleteuserdata($data);
5202 if (is_array($modstatus)) {
5203 $status = array_merge($status, $modstatus);
5204 } else {
5205 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5207 } else {
5208 $unsupportedmods[] = $mod;
5210 } else {
5211 debugging('Missing lib.php in '.$modname.' module!');
5216 // Mention unsupported mods.
5217 if (!empty($unsupportedmods)) {
5218 foreach ($unsupportedmods as $mod) {
5219 $status[] = array(
5220 'component' => get_string('modulenameplural', $mod->name),
5221 'item' => '',
5222 'error' => get_string('resetnotimplemented')
5227 $componentstr = get_string('gradebook', 'grades');
5228 // Reset gradebook,.
5229 if (!empty($data->reset_gradebook_items)) {
5230 remove_course_grades($data->courseid, false);
5231 grade_grab_course_grades($data->courseid);
5232 grade_regrade_final_grades($data->courseid);
5233 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5235 } else if (!empty($data->reset_gradebook_grades)) {
5236 grade_course_reset($data->courseid);
5237 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5239 // Reset comments.
5240 if (!empty($data->reset_comments)) {
5241 require_once($CFG->dirroot.'/comment/lib.php');
5242 comment::reset_course_page_comments($context);
5245 $event = \core\event\course_reset_ended::create($eventparams);
5246 $event->trigger();
5248 return $status;
5252 * Generate an email processing address.
5254 * @param int $modid
5255 * @param string $modargs
5256 * @return string Returns email processing address
5258 function generate_email_processing_address($modid, $modargs) {
5259 global $CFG;
5261 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5262 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5268 * @todo Finish documenting this function
5270 * @param string $modargs
5271 * @param string $body Currently unused
5273 function moodle_process_email($modargs, $body) {
5274 global $DB;
5276 // The first char should be an unencoded letter. We'll take this as an action.
5277 switch ($modargs{0}) {
5278 case 'B': { // Bounce.
5279 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5280 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5281 // Check the half md5 of their email.
5282 $md5check = substr(md5($user->email), 0, 16);
5283 if ($md5check == substr($modargs, -16)) {
5284 set_bounce_count($user);
5286 // Else maybe they've already changed it?
5289 break;
5290 // Maybe more later?
5294 // CORRESPONDENCE.
5297 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5299 * @param string $action 'get', 'buffer', 'close' or 'flush'
5300 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5302 function get_mailer($action='get') {
5303 global $CFG;
5305 /** @var moodle_phpmailer $mailer */
5306 static $mailer = null;
5307 static $counter = 0;
5309 if (!isset($CFG->smtpmaxbulk)) {
5310 $CFG->smtpmaxbulk = 1;
5313 if ($action == 'get') {
5314 $prevkeepalive = false;
5316 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5317 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5318 $counter++;
5319 // Reset the mailer.
5320 $mailer->Priority = 3;
5321 $mailer->CharSet = 'UTF-8'; // Our default.
5322 $mailer->ContentType = "text/plain";
5323 $mailer->Encoding = "8bit";
5324 $mailer->From = "root@localhost";
5325 $mailer->FromName = "Root User";
5326 $mailer->Sender = "";
5327 $mailer->Subject = "";
5328 $mailer->Body = "";
5329 $mailer->AltBody = "";
5330 $mailer->ConfirmReadingTo = "";
5332 $mailer->clearAllRecipients();
5333 $mailer->clearReplyTos();
5334 $mailer->clearAttachments();
5335 $mailer->clearCustomHeaders();
5336 return $mailer;
5339 $prevkeepalive = $mailer->SMTPKeepAlive;
5340 get_mailer('flush');
5343 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5344 $mailer = new moodle_phpmailer();
5346 $counter = 1;
5348 if ($CFG->smtphosts == 'qmail') {
5349 // Use Qmail system.
5350 $mailer->isQmail();
5352 } else if (empty($CFG->smtphosts)) {
5353 // Use PHP mail() = sendmail.
5354 $mailer->isMail();
5356 } else {
5357 // Use SMTP directly.
5358 $mailer->isSMTP();
5359 if (!empty($CFG->debugsmtp)) {
5360 $mailer->SMTPDebug = true;
5362 // Specify main and backup servers.
5363 $mailer->Host = $CFG->smtphosts;
5364 // Specify secure connection protocol.
5365 $mailer->SMTPSecure = $CFG->smtpsecure;
5366 // Use previous keepalive.
5367 $mailer->SMTPKeepAlive = $prevkeepalive;
5369 if ($CFG->smtpuser) {
5370 // Use SMTP authentication.
5371 $mailer->SMTPAuth = true;
5372 $mailer->Username = $CFG->smtpuser;
5373 $mailer->Password = $CFG->smtppass;
5377 return $mailer;
5380 $nothing = null;
5382 // Keep smtp session open after sending.
5383 if ($action == 'buffer') {
5384 if (!empty($CFG->smtpmaxbulk)) {
5385 get_mailer('flush');
5386 $m = get_mailer();
5387 if ($m->Mailer == 'smtp') {
5388 $m->SMTPKeepAlive = true;
5391 return $nothing;
5394 // Close smtp session, but continue buffering.
5395 if ($action == 'flush') {
5396 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5397 if (!empty($mailer->SMTPDebug)) {
5398 echo '<pre>'."\n";
5400 $mailer->SmtpClose();
5401 if (!empty($mailer->SMTPDebug)) {
5402 echo '</pre>';
5405 return $nothing;
5408 // Close smtp session, do not buffer anymore.
5409 if ($action == 'close') {
5410 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5411 get_mailer('flush');
5412 $mailer->SMTPKeepAlive = false;
5414 $mailer = null; // Better force new instance.
5415 return $nothing;
5420 * Send an email to a specified user
5422 * @param stdClass $user A {@link $USER} object
5423 * @param stdClass $from A {@link $USER} object
5424 * @param string $subject plain text subject line of the email
5425 * @param string $messagetext plain text version of the message
5426 * @param string $messagehtml complete html version of the message (optional)
5427 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5428 * @param string $attachname the name of the file (extension indicates MIME)
5429 * @param bool $usetrueaddress determines whether $from email address should
5430 * be sent out. Will be overruled by user profile setting for maildisplay
5431 * @param string $replyto Email address to reply to
5432 * @param string $replytoname Name of reply to recipient
5433 * @param int $wordwrapwidth custom word wrap width, default 79
5434 * @return bool Returns true if mail was sent OK and false if there was an error.
5436 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5437 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5439 global $CFG;
5441 if (empty($user) or empty($user->id)) {
5442 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5443 return false;
5446 if (empty($user->email)) {
5447 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5448 return false;
5451 if (!empty($user->deleted)) {
5452 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5453 return false;
5456 if (defined('BEHAT_SITE_RUNNING')) {
5457 // Fake email sending in behat.
5458 return true;
5461 if (!empty($CFG->noemailever)) {
5462 // Hidden setting for development sites, set in config.php if needed.
5463 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5464 return true;
5467 if (!empty($CFG->divertallemailsto)) {
5468 $subject = "[DIVERTED {$user->email}] $subject";
5469 $user = clone($user);
5470 $user->email = $CFG->divertallemailsto;
5473 // Skip mail to suspended users.
5474 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5475 return true;
5478 if (!validate_email($user->email)) {
5479 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5480 debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5481 return false;
5484 if (over_bounce_threshold($user)) {
5485 debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5486 return false;
5489 // TLD .invalid is specifically reserved for invalid domain names.
5490 // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5491 if (substr($user->email, -8) == '.invalid') {
5492 debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5493 return true; // This is not an error.
5496 // If the user is a remote mnet user, parse the email text for URL to the
5497 // wwwroot and modify the url to direct the user's browser to login at their
5498 // home site (identity provider - idp) before hitting the link itself.
5499 if (is_mnet_remote_user($user)) {
5500 require_once($CFG->dirroot.'/mnet/lib.php');
5502 $jumpurl = mnet_get_idp_jump_url($user);
5503 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5505 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5506 $callback,
5507 $messagetext);
5508 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5509 $callback,
5510 $messagehtml);
5512 $mail = get_mailer();
5514 if (!empty($mail->SMTPDebug)) {
5515 echo '<pre>' . "\n";
5518 $temprecipients = array();
5519 $tempreplyto = array();
5521 $supportuser = core_user::get_support_user();
5523 // Make up an email address for handling bounces.
5524 if (!empty($CFG->handlebounces)) {
5525 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5526 $mail->Sender = generate_email_processing_address(0, $modargs);
5527 } else {
5528 $mail->Sender = $supportuser->email;
5531 if (!empty($CFG->emailonlyfromnoreplyaddress)) {
5532 $usetrueaddress = false;
5533 if (empty($replyto) && $from->maildisplay) {
5534 $replyto = $from->email;
5535 $replytoname = fullname($from);
5539 if (is_string($from)) { // So we can pass whatever we want if there is need.
5540 $mail->From = $CFG->noreplyaddress;
5541 $mail->FromName = $from;
5542 } else if ($usetrueaddress and $from->maildisplay) {
5543 $mail->From = $from->email;
5544 $mail->FromName = fullname($from);
5545 } else {
5546 $mail->From = $CFG->noreplyaddress;
5547 $mail->FromName = fullname($from);
5548 if (empty($replyto)) {
5549 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5553 if (!empty($replyto)) {
5554 $tempreplyto[] = array($replyto, $replytoname);
5557 $mail->Subject = substr($subject, 0, 900);
5559 $temprecipients[] = array($user->email, fullname($user));
5561 // Set word wrap.
5562 $mail->WordWrap = $wordwrapwidth;
5564 if (!empty($from->customheaders)) {
5565 // Add custom headers.
5566 if (is_array($from->customheaders)) {
5567 foreach ($from->customheaders as $customheader) {
5568 $mail->addCustomHeader($customheader);
5570 } else {
5571 $mail->addCustomHeader($from->customheaders);
5575 if (!empty($from->priority)) {
5576 $mail->Priority = $from->priority;
5579 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5580 // Don't ever send HTML to users who don't want it.
5581 $mail->isHTML(true);
5582 $mail->Encoding = 'quoted-printable';
5583 $mail->Body = $messagehtml;
5584 $mail->AltBody = "\n$messagetext\n";
5585 } else {
5586 $mail->IsHTML(false);
5587 $mail->Body = "\n$messagetext\n";
5590 if ($attachment && $attachname) {
5591 if (preg_match( "~\\.\\.~" , $attachment )) {
5592 // Security check for ".." in dir path.
5593 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5594 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5595 } else {
5596 require_once($CFG->libdir.'/filelib.php');
5597 $mimetype = mimeinfo('type', $attachname);
5599 $attachmentpath = $attachment;
5601 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5602 $attachpath = str_replace('\\', '/', $attachmentpath);
5603 // Make sure both variables are normalised before comparing.
5604 $temppath = str_replace('\\', '/', $CFG->tempdir);
5606 // If the attachment is a full path to a file in the tempdir, use it as is,
5607 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5608 if (strpos($attachpath, realpath($temppath)) !== 0) {
5609 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5612 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5616 // Check if the email should be sent in an other charset then the default UTF-8.
5617 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5619 // Use the defined site mail charset or eventually the one preferred by the recipient.
5620 $charset = $CFG->sitemailcharset;
5621 if (!empty($CFG->allowusermailcharset)) {
5622 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5623 $charset = $useremailcharset;
5627 // Convert all the necessary strings if the charset is supported.
5628 $charsets = get_list_of_charsets();
5629 unset($charsets['UTF-8']);
5630 if (in_array($charset, $charsets)) {
5631 $mail->CharSet = $charset;
5632 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5633 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5634 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5635 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5637 foreach ($temprecipients as $key => $values) {
5638 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5640 foreach ($tempreplyto as $key => $values) {
5641 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5646 foreach ($temprecipients as $values) {
5647 $mail->addAddress($values[0], $values[1]);
5649 foreach ($tempreplyto as $values) {
5650 $mail->addReplyTo($values[0], $values[1]);
5653 if ($mail->send()) {
5654 set_send_count($user);
5655 if (!empty($mail->SMTPDebug)) {
5656 echo '</pre>';
5658 return true;
5659 } else {
5660 // Trigger event for failing to send email.
5661 $event = \core\event\email_failed::create(array(
5662 'context' => context_system::instance(),
5663 'userid' => $from->id,
5664 'relateduserid' => $user->id,
5665 'other' => array(
5666 'subject' => $subject,
5667 'message' => $messagetext,
5668 'errorinfo' => $mail->ErrorInfo
5671 $event->trigger();
5672 if (CLI_SCRIPT) {
5673 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5675 if (!empty($mail->SMTPDebug)) {
5676 echo '</pre>';
5678 return false;
5683 * Generate a signoff for emails based on support settings
5685 * @return string
5687 function generate_email_signoff() {
5688 global $CFG;
5690 $signoff = "\n";
5691 if (!empty($CFG->supportname)) {
5692 $signoff .= $CFG->supportname."\n";
5694 if (!empty($CFG->supportemail)) {
5695 $signoff .= $CFG->supportemail."\n";
5697 if (!empty($CFG->supportpage)) {
5698 $signoff .= $CFG->supportpage."\n";
5700 return $signoff;
5704 * Sets specified user's password and send the new password to the user via email.
5706 * @param stdClass $user A {@link $USER} object
5707 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
5708 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
5710 function setnew_password_and_mail($user, $fasthash = false) {
5711 global $CFG, $DB;
5713 // We try to send the mail in language the user understands,
5714 // unfortunately the filter_string() does not support alternative langs yet
5715 // so multilang will not work properly for site->fullname.
5716 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
5718 $site = get_site();
5720 $supportuser = core_user::get_support_user();
5722 $newpassword = generate_password();
5724 update_internal_user_password($user, $newpassword, $fasthash);
5726 $a = new stdClass();
5727 $a->firstname = fullname($user, true);
5728 $a->sitename = format_string($site->fullname);
5729 $a->username = $user->username;
5730 $a->newpassword = $newpassword;
5731 $a->link = $CFG->wwwroot .'/login/';
5732 $a->signoff = generate_email_signoff();
5734 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
5736 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
5738 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5739 return email_to_user($user, $supportuser, $subject, $message);
5744 * Resets specified user's password and send the new password to the user via email.
5746 * @param stdClass $user A {@link $USER} object
5747 * @return bool Returns true if mail was sent OK and false if there was an error.
5749 function reset_password_and_mail($user) {
5750 global $CFG;
5752 $site = get_site();
5753 $supportuser = core_user::get_support_user();
5755 $userauth = get_auth_plugin($user->auth);
5756 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
5757 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
5758 return false;
5761 $newpassword = generate_password();
5763 if (!$userauth->user_update_password($user, $newpassword)) {
5764 print_error("cannotsetpassword");
5767 $a = new stdClass();
5768 $a->firstname = $user->firstname;
5769 $a->lastname = $user->lastname;
5770 $a->sitename = format_string($site->fullname);
5771 $a->username = $user->username;
5772 $a->newpassword = $newpassword;
5773 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
5774 $a->signoff = generate_email_signoff();
5776 $message = get_string('newpasswordtext', '', $a);
5778 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
5780 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
5782 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5783 return email_to_user($user, $supportuser, $subject, $message);
5787 * Send email to specified user with confirmation text and activation link.
5789 * @param stdClass $user A {@link $USER} object
5790 * @return bool Returns true if mail was sent OK and false if there was an error.
5792 function send_confirmation_email($user) {
5793 global $CFG;
5795 $site = get_site();
5796 $supportuser = core_user::get_support_user();
5798 $data = new stdClass();
5799 $data->firstname = fullname($user);
5800 $data->sitename = format_string($site->fullname);
5801 $data->admin = generate_email_signoff();
5803 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
5805 $username = urlencode($user->username);
5806 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
5807 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
5808 $message = get_string('emailconfirmation', '', $data);
5809 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
5811 $user->mailformat = 1; // Always send HTML version as well.
5813 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5814 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
5818 * Sends a password change confirmation email.
5820 * @param stdClass $user A {@link $USER} object
5821 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
5822 * @return bool Returns true if mail was sent OK and false if there was an error.
5824 function send_password_change_confirmation_email($user, $resetrecord) {
5825 global $CFG;
5827 $site = get_site();
5828 $supportuser = core_user::get_support_user();
5829 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
5831 $data = new stdClass();
5832 $data->firstname = $user->firstname;
5833 $data->lastname = $user->lastname;
5834 $data->username = $user->username;
5835 $data->sitename = format_string($site->fullname);
5836 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
5837 $data->admin = generate_email_signoff();
5838 $data->resetminutes = $pwresetmins;
5840 $message = get_string('emailresetconfirmation', '', $data);
5841 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
5843 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5844 return email_to_user($user, $supportuser, $subject, $message);
5849 * Sends an email containinginformation on how to change your password.
5851 * @param stdClass $user A {@link $USER} object
5852 * @return bool Returns true if mail was sent OK and false if there was an error.
5854 function send_password_change_info($user) {
5855 global $CFG;
5857 $site = get_site();
5858 $supportuser = core_user::get_support_user();
5859 $systemcontext = context_system::instance();
5861 $data = new stdClass();
5862 $data->firstname = $user->firstname;
5863 $data->lastname = $user->lastname;
5864 $data->sitename = format_string($site->fullname);
5865 $data->admin = generate_email_signoff();
5867 $userauth = get_auth_plugin($user->auth);
5869 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
5870 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
5871 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5872 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5873 return email_to_user($user, $supportuser, $subject, $message);
5876 if ($userauth->can_change_password() and $userauth->change_password_url()) {
5877 // We have some external url for password changing.
5878 $data->link .= $userauth->change_password_url();
5880 } else {
5881 // No way to change password, sorry.
5882 $data->link = '';
5885 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
5886 $message = get_string('emailpasswordchangeinfo', '', $data);
5887 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5888 } else {
5889 $message = get_string('emailpasswordchangeinfofail', '', $data);
5890 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5893 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5894 return email_to_user($user, $supportuser, $subject, $message);
5899 * Check that an email is allowed. It returns an error message if there was a problem.
5901 * @param string $email Content of email
5902 * @return string|false
5904 function email_is_not_allowed($email) {
5905 global $CFG;
5907 if (!empty($CFG->allowemailaddresses)) {
5908 $allowed = explode(' ', $CFG->allowemailaddresses);
5909 foreach ($allowed as $allowedpattern) {
5910 $allowedpattern = trim($allowedpattern);
5911 if (!$allowedpattern) {
5912 continue;
5914 if (strpos($allowedpattern, '.') === 0) {
5915 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
5916 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
5917 return false;
5920 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
5921 return false;
5924 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
5926 } else if (!empty($CFG->denyemailaddresses)) {
5927 $denied = explode(' ', $CFG->denyemailaddresses);
5928 foreach ($denied as $deniedpattern) {
5929 $deniedpattern = trim($deniedpattern);
5930 if (!$deniedpattern) {
5931 continue;
5933 if (strpos($deniedpattern, '.') === 0) {
5934 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
5935 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
5936 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
5939 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
5940 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
5945 return false;
5948 // FILE HANDLING.
5951 * Returns local file storage instance
5953 * @return file_storage
5955 function get_file_storage() {
5956 global $CFG;
5958 static $fs = null;
5960 if ($fs) {
5961 return $fs;
5964 require_once("$CFG->libdir/filelib.php");
5966 if (isset($CFG->filedir)) {
5967 $filedir = $CFG->filedir;
5968 } else {
5969 $filedir = $CFG->dataroot.'/filedir';
5972 if (isset($CFG->trashdir)) {
5973 $trashdirdir = $CFG->trashdir;
5974 } else {
5975 $trashdirdir = $CFG->dataroot.'/trashdir';
5978 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
5980 return $fs;
5984 * Returns local file storage instance
5986 * @return file_browser
5988 function get_file_browser() {
5989 global $CFG;
5991 static $fb = null;
5993 if ($fb) {
5994 return $fb;
5997 require_once("$CFG->libdir/filelib.php");
5999 $fb = new file_browser();
6001 return $fb;
6005 * Returns file packer
6007 * @param string $mimetype default application/zip
6008 * @return file_packer
6010 function get_file_packer($mimetype='application/zip') {
6011 global $CFG;
6013 static $fp = array();
6015 if (isset($fp[$mimetype])) {
6016 return $fp[$mimetype];
6019 switch ($mimetype) {
6020 case 'application/zip':
6021 case 'application/vnd.moodle.profiling':
6022 $classname = 'zip_packer';
6023 break;
6025 case 'application/x-gzip' :
6026 $classname = 'tgz_packer';
6027 break;
6029 case 'application/vnd.moodle.backup':
6030 $classname = 'mbz_packer';
6031 break;
6033 default:
6034 return false;
6037 require_once("$CFG->libdir/filestorage/$classname.php");
6038 $fp[$mimetype] = new $classname();
6040 return $fp[$mimetype];
6044 * Returns current name of file on disk if it exists.
6046 * @param string $newfile File to be verified
6047 * @return string Current name of file on disk if true
6049 function valid_uploaded_file($newfile) {
6050 if (empty($newfile)) {
6051 return '';
6053 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6054 return $newfile['tmp_name'];
6055 } else {
6056 return '';
6061 * Returns the maximum size for uploading files.
6063 * There are seven possible upload limits:
6064 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6065 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6066 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6067 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6068 * 5. by the Moodle admin in $CFG->maxbytes
6069 * 6. by the teacher in the current course $course->maxbytes
6070 * 7. by the teacher for the current module, eg $assignment->maxbytes
6072 * These last two are passed to this function as arguments (in bytes).
6073 * Anything defined as 0 is ignored.
6074 * The smallest of all the non-zero numbers is returned.
6076 * @todo Finish documenting this function
6078 * @param int $sitebytes Set maximum size
6079 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6080 * @param int $modulebytes Current module ->maxbytes (in bytes)
6081 * @return int The maximum size for uploading files.
6083 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6085 if (! $filesize = ini_get('upload_max_filesize')) {
6086 $filesize = '5M';
6088 $minimumsize = get_real_size($filesize);
6090 if ($postsize = ini_get('post_max_size')) {
6091 $postsize = get_real_size($postsize);
6092 if ($postsize < $minimumsize) {
6093 $minimumsize = $postsize;
6097 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6098 $minimumsize = $sitebytes;
6101 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6102 $minimumsize = $coursebytes;
6105 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6106 $minimumsize = $modulebytes;
6109 return $minimumsize;
6113 * Returns the maximum size for uploading files for the current user
6115 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6117 * @param context $context The context in which to check user capabilities
6118 * @param int $sitebytes Set maximum size
6119 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6120 * @param int $modulebytes Current module ->maxbytes (in bytes)
6121 * @param stdClass $user The user
6122 * @return int The maximum size for uploading files.
6124 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6125 global $USER;
6127 if (empty($user)) {
6128 $user = $USER;
6131 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6132 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6135 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6139 * Returns an array of possible sizes in local language
6141 * Related to {@link get_max_upload_file_size()} - this function returns an
6142 * array of possible sizes in an array, translated to the
6143 * local language.
6145 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6147 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6148 * with the value set to 0. This option will be the first in the list.
6150 * @uses SORT_NUMERIC
6151 * @param int $sitebytes Set maximum size
6152 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6153 * @param int $modulebytes Current module ->maxbytes (in bytes)
6154 * @param int|array $custombytes custom upload size/s which will be added to list,
6155 * Only value/s smaller then maxsize will be added to list.
6156 * @return array
6158 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6159 global $CFG;
6161 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6162 return array();
6165 if ($sitebytes == 0) {
6166 // Will get the minimum of upload_max_filesize or post_max_size.
6167 $sitebytes = get_max_upload_file_size();
6170 $filesize = array();
6171 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6172 5242880, 10485760, 20971520, 52428800, 104857600);
6174 // If custombytes is given and is valid then add it to the list.
6175 if (is_number($custombytes) and $custombytes > 0) {
6176 $custombytes = (int)$custombytes;
6177 if (!in_array($custombytes, $sizelist)) {
6178 $sizelist[] = $custombytes;
6180 } else if (is_array($custombytes)) {
6181 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6184 // Allow maxbytes to be selected if it falls outside the above boundaries.
6185 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6186 // Note: get_real_size() is used in order to prevent problems with invalid values.
6187 $sizelist[] = get_real_size($CFG->maxbytes);
6190 foreach ($sizelist as $sizebytes) {
6191 if ($sizebytes < $maxsize && $sizebytes > 0) {
6192 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6196 $limitlevel = '';
6197 $displaysize = '';
6198 if ($modulebytes &&
6199 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6200 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6201 $limitlevel = get_string('activity', 'core');
6202 $displaysize = display_size($modulebytes);
6203 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6205 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6206 $limitlevel = get_string('course', 'core');
6207 $displaysize = display_size($coursebytes);
6208 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6210 } else if ($sitebytes) {
6211 $limitlevel = get_string('site', 'core');
6212 $displaysize = display_size($sitebytes);
6213 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6216 krsort($filesize, SORT_NUMERIC);
6217 if ($limitlevel) {
6218 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6219 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6222 return $filesize;
6226 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6228 * If excludefiles is defined, then that file/directory is ignored
6229 * If getdirs is true, then (sub)directories are included in the output
6230 * If getfiles is true, then files are included in the output
6231 * (at least one of these must be true!)
6233 * @todo Finish documenting this function. Add examples of $excludefile usage.
6235 * @param string $rootdir A given root directory to start from
6236 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6237 * @param bool $descend If true then subdirectories are recursed as well
6238 * @param bool $getdirs If true then (sub)directories are included in the output
6239 * @param bool $getfiles If true then files are included in the output
6240 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6242 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6244 $dirs = array();
6246 if (!$getdirs and !$getfiles) { // Nothing to show.
6247 return $dirs;
6250 if (!is_dir($rootdir)) { // Must be a directory.
6251 return $dirs;
6254 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6255 return $dirs;
6258 if (!is_array($excludefiles)) {
6259 $excludefiles = array($excludefiles);
6262 while (false !== ($file = readdir($dir))) {
6263 $firstchar = substr($file, 0, 1);
6264 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6265 continue;
6267 $fullfile = $rootdir .'/'. $file;
6268 if (filetype($fullfile) == 'dir') {
6269 if ($getdirs) {
6270 $dirs[] = $file;
6272 if ($descend) {
6273 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6274 foreach ($subdirs as $subdir) {
6275 $dirs[] = $file .'/'. $subdir;
6278 } else if ($getfiles) {
6279 $dirs[] = $file;
6282 closedir($dir);
6284 asort($dirs);
6286 return $dirs;
6291 * Adds up all the files in a directory and works out the size.
6293 * @param string $rootdir The directory to start from
6294 * @param string $excludefile A file to exclude when summing directory size
6295 * @return int The summed size of all files and subfiles within the root directory
6297 function get_directory_size($rootdir, $excludefile='') {
6298 global $CFG;
6300 // Do it this way if we can, it's much faster.
6301 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6302 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6303 $output = null;
6304 $return = null;
6305 exec($command, $output, $return);
6306 if (is_array($output)) {
6307 // We told it to return k.
6308 return get_real_size(intval($output[0]).'k');
6312 if (!is_dir($rootdir)) {
6313 // Must be a directory.
6314 return 0;
6317 if (!$dir = @opendir($rootdir)) {
6318 // Can't open it for some reason.
6319 return 0;
6322 $size = 0;
6324 while (false !== ($file = readdir($dir))) {
6325 $firstchar = substr($file, 0, 1);
6326 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6327 continue;
6329 $fullfile = $rootdir .'/'. $file;
6330 if (filetype($fullfile) == 'dir') {
6331 $size += get_directory_size($fullfile, $excludefile);
6332 } else {
6333 $size += filesize($fullfile);
6336 closedir($dir);
6338 return $size;
6342 * Converts bytes into display form
6344 * @static string $gb Localized string for size in gigabytes
6345 * @static string $mb Localized string for size in megabytes
6346 * @static string $kb Localized string for size in kilobytes
6347 * @static string $b Localized string for size in bytes
6348 * @param int $size The size to convert to human readable form
6349 * @return string
6351 function display_size($size) {
6353 static $gb, $mb, $kb, $b;
6355 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6356 return get_string('unlimited');
6359 if (empty($gb)) {
6360 $gb = get_string('sizegb');
6361 $mb = get_string('sizemb');
6362 $kb = get_string('sizekb');
6363 $b = get_string('sizeb');
6366 if ($size >= 1073741824) {
6367 $size = round($size / 1073741824 * 10) / 10 . $gb;
6368 } else if ($size >= 1048576) {
6369 $size = round($size / 1048576 * 10) / 10 . $mb;
6370 } else if ($size >= 1024) {
6371 $size = round($size / 1024 * 10) / 10 . $kb;
6372 } else {
6373 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6375 return $size;
6379 * Cleans a given filename by removing suspicious or troublesome characters
6381 * @see clean_param()
6382 * @param string $string file name
6383 * @return string cleaned file name
6385 function clean_filename($string) {
6386 return clean_param($string, PARAM_FILE);
6390 // STRING TRANSLATION.
6393 * Returns the code for the current language
6395 * @category string
6396 * @return string
6398 function current_language() {
6399 global $CFG, $USER, $SESSION, $COURSE;
6401 if (!empty($SESSION->forcelang)) {
6402 // Allows overriding course-forced language (useful for admins to check
6403 // issues in courses whose language they don't understand).
6404 // Also used by some code to temporarily get language-related information in a
6405 // specific language (see force_current_language()).
6406 $return = $SESSION->forcelang;
6408 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6409 // Course language can override all other settings for this page.
6410 $return = $COURSE->lang;
6412 } else if (!empty($SESSION->lang)) {
6413 // Session language can override other settings.
6414 $return = $SESSION->lang;
6416 } else if (!empty($USER->lang)) {
6417 $return = $USER->lang;
6419 } else if (isset($CFG->lang)) {
6420 $return = $CFG->lang;
6422 } else {
6423 $return = 'en';
6426 // Just in case this slipped in from somewhere by accident.
6427 $return = str_replace('_utf8', '', $return);
6429 return $return;
6433 * Returns parent language of current active language if defined
6435 * @category string
6436 * @param string $lang null means current language
6437 * @return string
6439 function get_parent_language($lang=null) {
6441 // Let's hack around the current language.
6442 if (!empty($lang)) {
6443 $oldforcelang = force_current_language($lang);
6446 $parentlang = get_string('parentlanguage', 'langconfig');
6447 if ($parentlang === 'en') {
6448 $parentlang = '';
6451 // Let's hack around the current language.
6452 if (!empty($lang)) {
6453 force_current_language($oldforcelang);
6456 return $parentlang;
6460 * Force the current language to get strings and dates localised in the given language.
6462 * After calling this function, all strings will be provided in the given language
6463 * until this function is called again, or equivalent code is run.
6465 * @param string $language
6466 * @return string previous $SESSION->forcelang value
6468 function force_current_language($language) {
6469 global $SESSION;
6470 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6471 if ($language !== $sessionforcelang) {
6472 // Seting forcelang to null or an empty string disables it's effect.
6473 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6474 $SESSION->forcelang = $language;
6475 moodle_setlocale();
6478 return $sessionforcelang;
6482 * Returns current string_manager instance.
6484 * The param $forcereload is needed for CLI installer only where the string_manager instance
6485 * must be replaced during the install.php script life time.
6487 * @category string
6488 * @param bool $forcereload shall the singleton be released and new instance created instead?
6489 * @return core_string_manager
6491 function get_string_manager($forcereload=false) {
6492 global $CFG;
6494 static $singleton = null;
6496 if ($forcereload) {
6497 $singleton = null;
6499 if ($singleton === null) {
6500 if (empty($CFG->early_install_lang)) {
6502 if (empty($CFG->langlist)) {
6503 $translist = array();
6504 } else {
6505 $translist = explode(',', $CFG->langlist);
6508 if (!empty($CFG->config_php_settings['customstringmanager'])) {
6509 $classname = $CFG->config_php_settings['customstringmanager'];
6511 if (class_exists($classname)) {
6512 $implements = class_implements($classname);
6514 if (isset($implements['core_string_manager'])) {
6515 $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist);
6516 return $singleton;
6518 } else {
6519 debugging('Unable to instantiate custom string manager: class '.$classname.
6520 ' does not implement the core_string_manager interface.');
6523 } else {
6524 debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6528 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6530 } else {
6531 $singleton = new core_string_manager_install();
6535 return $singleton;
6539 * Returns a localized string.
6541 * Returns the translated string specified by $identifier as
6542 * for $module. Uses the same format files as STphp.
6543 * $a is an object, string or number that can be used
6544 * within translation strings
6546 * eg 'hello {$a->firstname} {$a->lastname}'
6547 * or 'hello {$a}'
6549 * If you would like to directly echo the localized string use
6550 * the function {@link print_string()}
6552 * Example usage of this function involves finding the string you would
6553 * like a local equivalent of and using its identifier and module information
6554 * to retrieve it.<br/>
6555 * If you open moodle/lang/en/moodle.php and look near line 278
6556 * you will find a string to prompt a user for their word for 'course'
6557 * <code>
6558 * $string['course'] = 'Course';
6559 * </code>
6560 * So if you want to display the string 'Course'
6561 * in any language that supports it on your site
6562 * you just need to use the identifier 'course'
6563 * <code>
6564 * $mystring = '<strong>'. get_string('course') .'</strong>';
6565 * or
6566 * </code>
6567 * If the string you want is in another file you'd take a slightly
6568 * different approach. Looking in moodle/lang/en/calendar.php you find
6569 * around line 75:
6570 * <code>
6571 * $string['typecourse'] = 'Course event';
6572 * </code>
6573 * If you want to display the string "Course event" in any language
6574 * supported you would use the identifier 'typecourse' and the module 'calendar'
6575 * (because it is in the file calendar.php):
6576 * <code>
6577 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6578 * </code>
6580 * As a last resort, should the identifier fail to map to a string
6581 * the returned string will be [[ $identifier ]]
6583 * In Moodle 2.3 there is a new argument to this function $lazyload.
6584 * Setting $lazyload to true causes get_string to return a lang_string object
6585 * rather than the string itself. The fetching of the string is then put off until
6586 * the string object is first used. The object can be used by calling it's out
6587 * method or by casting the object to a string, either directly e.g.
6588 * (string)$stringobject
6589 * or indirectly by using the string within another string or echoing it out e.g.
6590 * echo $stringobject
6591 * return "<p>{$stringobject}</p>";
6592 * It is worth noting that using $lazyload and attempting to use the string as an
6593 * array key will cause a fatal error as objects cannot be used as array keys.
6594 * But you should never do that anyway!
6595 * For more information {@link lang_string}
6597 * @category string
6598 * @param string $identifier The key identifier for the localized string
6599 * @param string $component The module where the key identifier is stored,
6600 * usually expressed as the filename in the language pack without the
6601 * .php on the end but can also be written as mod/forum or grade/export/xls.
6602 * If none is specified then moodle.php is used.
6603 * @param string|object|array $a An object, string or number that can be used
6604 * within translation strings
6605 * @param bool $lazyload If set to true a string object is returned instead of
6606 * the string itself. The string then isn't calculated until it is first used.
6607 * @return string The localized string.
6608 * @throws coding_exception
6610 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6611 global $CFG;
6613 // If the lazy load argument has been supplied return a lang_string object
6614 // instead.
6615 // We need to make sure it is true (and a bool) as you will see below there
6616 // used to be a forth argument at one point.
6617 if ($lazyload === true) {
6618 return new lang_string($identifier, $component, $a);
6621 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6622 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6625 // There is now a forth argument again, this time it is a boolean however so
6626 // we can still check for the old extralocations parameter.
6627 if (!is_bool($lazyload) && !empty($lazyload)) {
6628 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6631 if (strpos($component, '/') !== false) {
6632 debugging('The module name you passed to get_string is the deprecated format ' .
6633 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6634 $componentpath = explode('/', $component);
6636 switch ($componentpath[0]) {
6637 case 'mod':
6638 $component = $componentpath[1];
6639 break;
6640 case 'blocks':
6641 case 'block':
6642 $component = 'block_'.$componentpath[1];
6643 break;
6644 case 'enrol':
6645 $component = 'enrol_'.$componentpath[1];
6646 break;
6647 case 'format':
6648 $component = 'format_'.$componentpath[1];
6649 break;
6650 case 'grade':
6651 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6652 break;
6656 $result = get_string_manager()->get_string($identifier, $component, $a);
6658 // Debugging feature lets you display string identifier and component.
6659 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6660 $result .= ' {' . $identifier . '/' . $component . '}';
6662 return $result;
6666 * Converts an array of strings to their localized value.
6668 * @param array $array An array of strings
6669 * @param string $component The language module that these strings can be found in.
6670 * @return stdClass translated strings.
6672 function get_strings($array, $component = '') {
6673 $string = new stdClass;
6674 foreach ($array as $item) {
6675 $string->$item = get_string($item, $component);
6677 return $string;
6681 * Prints out a translated string.
6683 * Prints out a translated string using the return value from the {@link get_string()} function.
6685 * Example usage of this function when the string is in the moodle.php file:<br/>
6686 * <code>
6687 * echo '<strong>';
6688 * print_string('course');
6689 * echo '</strong>';
6690 * </code>
6692 * Example usage of this function when the string is not in the moodle.php file:<br/>
6693 * <code>
6694 * echo '<h1>';
6695 * print_string('typecourse', 'calendar');
6696 * echo '</h1>';
6697 * </code>
6699 * @category string
6700 * @param string $identifier The key identifier for the localized string
6701 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6702 * @param string|object|array $a An object, string or number that can be used within translation strings
6704 function print_string($identifier, $component = '', $a = null) {
6705 echo get_string($identifier, $component, $a);
6709 * Returns a list of charset codes
6711 * Returns a list of charset codes. It's hardcoded, so they should be added manually
6712 * (checking that such charset is supported by the texlib library!)
6714 * @return array And associative array with contents in the form of charset => charset
6716 function get_list_of_charsets() {
6718 $charsets = array(
6719 'EUC-JP' => 'EUC-JP',
6720 'ISO-2022-JP'=> 'ISO-2022-JP',
6721 'ISO-8859-1' => 'ISO-8859-1',
6722 'SHIFT-JIS' => 'SHIFT-JIS',
6723 'GB2312' => 'GB2312',
6724 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
6725 'UTF-8' => 'UTF-8');
6727 asort($charsets);
6729 return $charsets;
6733 * Returns a list of valid and compatible themes
6735 * @return array
6737 function get_list_of_themes() {
6738 global $CFG;
6740 $themes = array();
6742 if (!empty($CFG->themelist)) { // Use admin's list of themes.
6743 $themelist = explode(',', $CFG->themelist);
6744 } else {
6745 $themelist = array_keys(core_component::get_plugin_list("theme"));
6748 foreach ($themelist as $key => $themename) {
6749 $theme = theme_config::load($themename);
6750 $themes[$themename] = $theme;
6753 core_collator::asort_objects_by_method($themes, 'get_theme_name');
6755 return $themes;
6759 * Factory function for emoticon_manager
6761 * @return emoticon_manager singleton
6763 function get_emoticon_manager() {
6764 static $singleton = null;
6766 if (is_null($singleton)) {
6767 $singleton = new emoticon_manager();
6770 return $singleton;
6774 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
6776 * Whenever this manager mentiones 'emoticon object', the following data
6777 * structure is expected: stdClass with properties text, imagename, imagecomponent,
6778 * altidentifier and altcomponent
6780 * @see admin_setting_emoticons
6782 * @copyright 2010 David Mudrak
6783 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6785 class emoticon_manager {
6788 * Returns the currently enabled emoticons
6790 * @return array of emoticon objects
6792 public function get_emoticons() {
6793 global $CFG;
6795 if (empty($CFG->emoticons)) {
6796 return array();
6799 $emoticons = $this->decode_stored_config($CFG->emoticons);
6801 if (!is_array($emoticons)) {
6802 // Something is wrong with the format of stored setting.
6803 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
6804 return array();
6807 return $emoticons;
6811 * Converts emoticon object into renderable pix_emoticon object
6813 * @param stdClass $emoticon emoticon object
6814 * @param array $attributes explicit HTML attributes to set
6815 * @return pix_emoticon
6817 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
6818 $stringmanager = get_string_manager();
6819 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
6820 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
6821 } else {
6822 $alt = s($emoticon->text);
6824 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
6828 * Encodes the array of emoticon objects into a string storable in config table
6830 * @see self::decode_stored_config()
6831 * @param array $emoticons array of emtocion objects
6832 * @return string
6834 public function encode_stored_config(array $emoticons) {
6835 return json_encode($emoticons);
6839 * Decodes the string into an array of emoticon objects
6841 * @see self::encode_stored_config()
6842 * @param string $encoded
6843 * @return string|null
6845 public function decode_stored_config($encoded) {
6846 $decoded = json_decode($encoded);
6847 if (!is_array($decoded)) {
6848 return null;
6850 return $decoded;
6854 * Returns default set of emoticons supported by Moodle
6856 * @return array of sdtClasses
6858 public function default_emoticons() {
6859 return array(
6860 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
6861 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
6862 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
6863 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
6864 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
6865 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
6866 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
6867 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
6868 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
6869 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
6870 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
6871 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
6872 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
6873 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
6874 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
6875 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
6876 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
6877 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
6878 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
6879 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
6880 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
6881 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
6882 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
6883 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
6884 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
6885 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
6886 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
6887 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
6888 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
6889 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
6894 * Helper method preparing the stdClass with the emoticon properties
6896 * @param string|array $text or array of strings
6897 * @param string $imagename to be used by {@link pix_emoticon}
6898 * @param string $altidentifier alternative string identifier, null for no alt
6899 * @param string $altcomponent where the alternative string is defined
6900 * @param string $imagecomponent to be used by {@link pix_emoticon}
6901 * @return stdClass
6903 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
6904 $altcomponent = 'core_pix', $imagecomponent = 'core') {
6905 return (object)array(
6906 'text' => $text,
6907 'imagename' => $imagename,
6908 'imagecomponent' => $imagecomponent,
6909 'altidentifier' => $altidentifier,
6910 'altcomponent' => $altcomponent,
6915 // ENCRYPTION.
6918 * rc4encrypt
6920 * @param string $data Data to encrypt.
6921 * @return string The now encrypted data.
6923 function rc4encrypt($data) {
6924 return endecrypt(get_site_identifier(), $data, '');
6928 * rc4decrypt
6930 * @param string $data Data to decrypt.
6931 * @return string The now decrypted data.
6933 function rc4decrypt($data) {
6934 return endecrypt(get_site_identifier(), $data, 'de');
6938 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
6940 * @todo Finish documenting this function
6942 * @param string $pwd The password to use when encrypting or decrypting
6943 * @param string $data The data to be decrypted/encrypted
6944 * @param string $case Either 'de' for decrypt or '' for encrypt
6945 * @return string
6947 function endecrypt ($pwd, $data, $case) {
6949 if ($case == 'de') {
6950 $data = urldecode($data);
6953 $key[] = '';
6954 $box[] = '';
6955 $pwdlength = strlen($pwd);
6957 for ($i = 0; $i <= 255; $i++) {
6958 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
6959 $box[$i] = $i;
6962 $x = 0;
6964 for ($i = 0; $i <= 255; $i++) {
6965 $x = ($x + $box[$i] + $key[$i]) % 256;
6966 $tempswap = $box[$i];
6967 $box[$i] = $box[$x];
6968 $box[$x] = $tempswap;
6971 $cipher = '';
6973 $a = 0;
6974 $j = 0;
6976 for ($i = 0; $i < strlen($data); $i++) {
6977 $a = ($a + 1) % 256;
6978 $j = ($j + $box[$a]) % 256;
6979 $temp = $box[$a];
6980 $box[$a] = $box[$j];
6981 $box[$j] = $temp;
6982 $k = $box[(($box[$a] + $box[$j]) % 256)];
6983 $cipherby = ord(substr($data, $i, 1)) ^ $k;
6984 $cipher .= chr($cipherby);
6987 if ($case == 'de') {
6988 $cipher = urldecode(urlencode($cipher));
6989 } else {
6990 $cipher = urlencode($cipher);
6993 return $cipher;
6996 // ENVIRONMENT CHECKING.
6999 * This method validates a plug name. It is much faster than calling clean_param.
7001 * @param string $name a string that might be a plugin name.
7002 * @return bool if this string is a valid plugin name.
7004 function is_valid_plugin_name($name) {
7005 // This does not work for 'mod', bad luck, use any other type.
7006 return core_component::is_valid_plugin_name('tool', $name);
7010 * Get a list of all the plugins of a given type that define a certain API function
7011 * in a certain file. The plugin component names and function names are returned.
7013 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7014 * @param string $function the part of the name of the function after the
7015 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7016 * names like report_courselist_hook.
7017 * @param string $file the name of file within the plugin that defines the
7018 * function. Defaults to lib.php.
7019 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7020 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7022 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7023 $pluginfunctions = array();
7024 $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, $file, true);
7025 foreach ($pluginswithfile as $plugin => $notused) {
7026 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7028 if (function_exists($fullfunction)) {
7029 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7030 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
7032 } else if ($plugintype === 'mod') {
7033 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7034 $shortfunction = $plugin . '_' . $function;
7035 if (function_exists($shortfunction)) {
7036 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
7040 return $pluginfunctions;
7044 * Lists plugin-like directories within specified directory
7046 * This function was originally used for standard Moodle plugins, please use
7047 * new core_component::get_plugin_list() now.
7049 * This function is used for general directory listing and backwards compatility.
7051 * @param string $directory relative directory from root
7052 * @param string $exclude dir name to exclude from the list (defaults to none)
7053 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7054 * @return array Sorted array of directory names found under the requested parameters
7056 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7057 global $CFG;
7059 $plugins = array();
7061 if (empty($basedir)) {
7062 $basedir = $CFG->dirroot .'/'. $directory;
7064 } else {
7065 $basedir = $basedir .'/'. $directory;
7068 if ($CFG->debugdeveloper and empty($exclude)) {
7069 // Make sure devs do not use this to list normal plugins,
7070 // this is intended for general directories that are not plugins!
7072 $subtypes = core_component::get_plugin_types();
7073 if (in_array($basedir, $subtypes)) {
7074 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7076 unset($subtypes);
7079 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7080 if (!$dirhandle = opendir($basedir)) {
7081 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7082 return array();
7084 while (false !== ($dir = readdir($dirhandle))) {
7085 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7086 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7087 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7088 continue;
7090 if (filetype($basedir .'/'. $dir) != 'dir') {
7091 continue;
7093 $plugins[] = $dir;
7095 closedir($dirhandle);
7097 if ($plugins) {
7098 asort($plugins);
7100 return $plugins;
7104 * Invoke plugin's callback functions
7106 * @param string $type plugin type e.g. 'mod'
7107 * @param string $name plugin name
7108 * @param string $feature feature name
7109 * @param string $action feature's action
7110 * @param array $params parameters of callback function, should be an array
7111 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7112 * @return mixed
7114 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7116 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7117 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7121 * Invoke component's callback functions
7123 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7124 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7125 * @param array $params parameters of callback function
7126 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7127 * @return mixed
7129 function component_callback($component, $function, array $params = array(), $default = null) {
7131 $functionname = component_callback_exists($component, $function);
7133 if ($functionname) {
7134 // Function exists, so just return function result.
7135 $ret = call_user_func_array($functionname, $params);
7136 if (is_null($ret)) {
7137 return $default;
7138 } else {
7139 return $ret;
7142 return $default;
7146 * Determine if a component callback exists and return the function name to call. Note that this
7147 * function will include the required library files so that the functioname returned can be
7148 * called directly.
7150 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7151 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7152 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7153 * @throws coding_exception if invalid component specfied
7155 function component_callback_exists($component, $function) {
7156 global $CFG; // This is needed for the inclusions.
7158 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7159 if (empty($cleancomponent)) {
7160 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7162 $component = $cleancomponent;
7164 list($type, $name) = core_component::normalize_component($component);
7165 $component = $type . '_' . $name;
7167 $oldfunction = $name.'_'.$function;
7168 $function = $component.'_'.$function;
7170 $dir = core_component::get_component_directory($component);
7171 if (empty($dir)) {
7172 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7175 // Load library and look for function.
7176 if (file_exists($dir.'/lib.php')) {
7177 require_once($dir.'/lib.php');
7180 if (!function_exists($function) and function_exists($oldfunction)) {
7181 if ($type !== 'mod' and $type !== 'core') {
7182 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7184 $function = $oldfunction;
7187 if (function_exists($function)) {
7188 return $function;
7190 return false;
7194 * Checks whether a plugin supports a specified feature.
7196 * @param string $type Plugin type e.g. 'mod'
7197 * @param string $name Plugin name e.g. 'forum'
7198 * @param string $feature Feature code (FEATURE_xx constant)
7199 * @param mixed $default default value if feature support unknown
7200 * @return mixed Feature result (false if not supported, null if feature is unknown,
7201 * otherwise usually true but may have other feature-specific value such as array)
7202 * @throws coding_exception
7204 function plugin_supports($type, $name, $feature, $default = null) {
7205 global $CFG;
7207 if ($type === 'mod' and $name === 'NEWMODULE') {
7208 // Somebody forgot to rename the module template.
7209 return false;
7212 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7213 if (empty($component)) {
7214 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7217 $function = null;
7219 if ($type === 'mod') {
7220 // We need this special case because we support subplugins in modules,
7221 // otherwise it would end up in infinite loop.
7222 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7223 include_once("$CFG->dirroot/mod/$name/lib.php");
7224 $function = $component.'_supports';
7225 if (!function_exists($function)) {
7226 // Legacy non-frankenstyle function name.
7227 $function = $name.'_supports';
7231 } else {
7232 if (!$path = core_component::get_plugin_directory($type, $name)) {
7233 // Non existent plugin type.
7234 return false;
7236 if (file_exists("$path/lib.php")) {
7237 include_once("$path/lib.php");
7238 $function = $component.'_supports';
7242 if ($function and function_exists($function)) {
7243 $supports = $function($feature);
7244 if (is_null($supports)) {
7245 // Plugin does not know - use default.
7246 return $default;
7247 } else {
7248 return $supports;
7252 // Plugin does not care, so use default.
7253 return $default;
7257 * Returns true if the current version of PHP is greater that the specified one.
7259 * @todo Check PHP version being required here is it too low?
7261 * @param string $version The version of php being tested.
7262 * @return bool
7264 function check_php_version($version='5.2.4') {
7265 return (version_compare(phpversion(), $version) >= 0);
7269 * Determine if moodle installation requires update.
7271 * Checks version numbers of main code and all plugins to see
7272 * if there are any mismatches.
7274 * @return bool
7276 function moodle_needs_upgrading() {
7277 global $CFG;
7279 if (empty($CFG->version)) {
7280 return true;
7283 // There is no need to purge plugininfo caches here because
7284 // these caches are not used during upgrade and they are purged after
7285 // every upgrade.
7287 if (empty($CFG->allversionshash)) {
7288 return true;
7291 $hash = core_component::get_all_versions_hash();
7293 return ($hash !== $CFG->allversionshash);
7297 * Returns the major version of this site
7299 * Moodle version numbers consist of three numbers separated by a dot, for
7300 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7301 * called major version. This function extracts the major version from either
7302 * $CFG->release (default) or eventually from the $release variable defined in
7303 * the main version.php.
7305 * @param bool $fromdisk should the version if source code files be used
7306 * @return string|false the major version like '2.3', false if could not be determined
7308 function moodle_major_version($fromdisk = false) {
7309 global $CFG;
7311 if ($fromdisk) {
7312 $release = null;
7313 require($CFG->dirroot.'/version.php');
7314 if (empty($release)) {
7315 return false;
7318 } else {
7319 if (empty($CFG->release)) {
7320 return false;
7322 $release = $CFG->release;
7325 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7326 return $matches[0];
7327 } else {
7328 return false;
7332 // MISCELLANEOUS.
7335 * Sets the system locale
7337 * @category string
7338 * @param string $locale Can be used to force a locale
7340 function moodle_setlocale($locale='') {
7341 global $CFG;
7343 static $currentlocale = ''; // Last locale caching.
7345 $oldlocale = $currentlocale;
7347 // Fetch the correct locale based on ostype.
7348 if ($CFG->ostype == 'WINDOWS') {
7349 $stringtofetch = 'localewin';
7350 } else {
7351 $stringtofetch = 'locale';
7354 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7355 if (!empty($locale)) {
7356 $currentlocale = $locale;
7357 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7358 $currentlocale = $CFG->locale;
7359 } else {
7360 $currentlocale = get_string($stringtofetch, 'langconfig');
7363 // Do nothing if locale already set up.
7364 if ($oldlocale == $currentlocale) {
7365 return;
7368 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7369 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7370 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7372 // Get current values.
7373 $monetary= setlocale (LC_MONETARY, 0);
7374 $numeric = setlocale (LC_NUMERIC, 0);
7375 $ctype = setlocale (LC_CTYPE, 0);
7376 if ($CFG->ostype != 'WINDOWS') {
7377 $messages= setlocale (LC_MESSAGES, 0);
7379 // Set locale to all.
7380 $result = setlocale (LC_ALL, $currentlocale);
7381 // If setting of locale fails try the other utf8 or utf-8 variant,
7382 // some operating systems support both (Debian), others just one (OSX).
7383 if ($result === false) {
7384 if (stripos($currentlocale, '.UTF-8') !== false) {
7385 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7386 setlocale (LC_ALL, $newlocale);
7387 } else if (stripos($currentlocale, '.UTF8') !== false) {
7388 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7389 setlocale (LC_ALL, $newlocale);
7392 // Set old values.
7393 setlocale (LC_MONETARY, $monetary);
7394 setlocale (LC_NUMERIC, $numeric);
7395 if ($CFG->ostype != 'WINDOWS') {
7396 setlocale (LC_MESSAGES, $messages);
7398 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7399 // To workaround a well-known PHP problem with Turkish letter Ii.
7400 setlocale (LC_CTYPE, $ctype);
7405 * Count words in a string.
7407 * Words are defined as things between whitespace.
7409 * @category string
7410 * @param string $string The text to be searched for words.
7411 * @return int The count of words in the specified string
7413 function count_words($string) {
7414 $string = strip_tags($string);
7415 // Decode HTML entities.
7416 $string = html_entity_decode($string);
7417 // Replace underscores (which are classed as word characters) with spaces.
7418 $string = preg_replace('/_/u', ' ', $string);
7419 // Remove any characters that shouldn't be treated as word boundaries.
7420 $string = preg_replace('/[\'’-]/u', '', $string);
7421 // Remove dots and commas from within numbers only.
7422 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7424 return count(preg_split('/\w\b/u', $string)) - 1;
7428 * Count letters in a string.
7430 * Letters are defined as chars not in tags and different from whitespace.
7432 * @category string
7433 * @param string $string The text to be searched for letters.
7434 * @return int The count of letters in the specified text.
7436 function count_letters($string) {
7437 $string = strip_tags($string); // Tags are out now.
7438 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7440 return core_text::strlen($string);
7444 * Generate and return a random string of the specified length.
7446 * @param int $length The length of the string to be created.
7447 * @return string
7449 function random_string ($length=15) {
7450 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7451 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7452 $pool .= '0123456789';
7453 $poollen = strlen($pool);
7454 $string = '';
7455 for ($i = 0; $i < $length; $i++) {
7456 $string .= substr($pool, (mt_rand()%($poollen)), 1);
7458 return $string;
7462 * Generate a complex random string (useful for md5 salts)
7464 * This function is based on the above {@link random_string()} however it uses a
7465 * larger pool of characters and generates a string between 24 and 32 characters
7467 * @param int $length Optional if set generates a string to exactly this length
7468 * @return string
7470 function complex_random_string($length=null) {
7471 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7472 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7473 $poollen = strlen($pool);
7474 if ($length===null) {
7475 $length = floor(rand(24, 32));
7477 $string = '';
7478 for ($i = 0; $i < $length; $i++) {
7479 $string .= $pool[(mt_rand()%$poollen)];
7481 return $string;
7485 * Given some text (which may contain HTML) and an ideal length,
7486 * this function truncates the text neatly on a word boundary if possible
7488 * @category string
7489 * @param string $text text to be shortened
7490 * @param int $ideal ideal string length
7491 * @param boolean $exact if false, $text will not be cut mid-word
7492 * @param string $ending The string to append if the passed string is truncated
7493 * @return string $truncate shortened string
7495 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7496 // If the plain text is shorter than the maximum length, return the whole text.
7497 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7498 return $text;
7501 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7502 // and only tag in its 'line'.
7503 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7505 $totallength = core_text::strlen($ending);
7506 $truncate = '';
7508 // This array stores information about open and close tags and their position
7509 // in the truncated string. Each item in the array is an object with fields
7510 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7511 // (byte position in truncated text).
7512 $tagdetails = array();
7514 foreach ($lines as $linematchings) {
7515 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7516 if (!empty($linematchings[1])) {
7517 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7518 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7519 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7520 // Record closing tag.
7521 $tagdetails[] = (object) array(
7522 'open' => false,
7523 'tag' => core_text::strtolower($tagmatchings[1]),
7524 'pos' => core_text::strlen($truncate),
7527 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7528 // Record opening tag.
7529 $tagdetails[] = (object) array(
7530 'open' => true,
7531 'tag' => core_text::strtolower($tagmatchings[1]),
7532 'pos' => core_text::strlen($truncate),
7536 // Add html-tag to $truncate'd text.
7537 $truncate .= $linematchings[1];
7540 // Calculate the length of the plain text part of the line; handle entities as one character.
7541 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7542 if ($totallength + $contentlength > $ideal) {
7543 // The number of characters which are left.
7544 $left = $ideal - $totallength;
7545 $entitieslength = 0;
7546 // Search for html entities.
7547 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)) {
7548 // Calculate the real length of all entities in the legal range.
7549 foreach ($entities[0] as $entity) {
7550 if ($entity[1]+1-$entitieslength <= $left) {
7551 $left--;
7552 $entitieslength += core_text::strlen($entity[0]);
7553 } else {
7554 // No more characters left.
7555 break;
7559 $breakpos = $left + $entitieslength;
7561 // If the words shouldn't be cut in the middle...
7562 if (!$exact) {
7563 // Search the last occurence of a space.
7564 for (; $breakpos > 0; $breakpos--) {
7565 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
7566 if ($char === '.' or $char === ' ') {
7567 $breakpos += 1;
7568 break;
7569 } else if (strlen($char) > 2) {
7570 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7571 $breakpos += 1;
7572 break;
7577 if ($breakpos == 0) {
7578 // This deals with the test_shorten_text_no_spaces case.
7579 $breakpos = $left + $entitieslength;
7580 } else if ($breakpos > $left + $entitieslength) {
7581 // This deals with the previous for loop breaking on the first char.
7582 $breakpos = $left + $entitieslength;
7585 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
7586 // Maximum length is reached, so get off the loop.
7587 break;
7588 } else {
7589 $truncate .= $linematchings[2];
7590 $totallength += $contentlength;
7593 // If the maximum length is reached, get off the loop.
7594 if ($totallength >= $ideal) {
7595 break;
7599 // Add the defined ending to the text.
7600 $truncate .= $ending;
7602 // Now calculate the list of open html tags based on the truncate position.
7603 $opentags = array();
7604 foreach ($tagdetails as $taginfo) {
7605 if ($taginfo->open) {
7606 // Add tag to the beginning of $opentags list.
7607 array_unshift($opentags, $taginfo->tag);
7608 } else {
7609 // Can have multiple exact same open tags, close the last one.
7610 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
7611 if ($pos !== false) {
7612 unset($opentags[$pos]);
7617 // Close all unclosed html-tags.
7618 foreach ($opentags as $tag) {
7619 $truncate .= '</' . $tag . '>';
7622 return $truncate;
7627 * Given dates in seconds, how many weeks is the date from startdate
7628 * The first week is 1, the second 2 etc ...
7630 * @param int $startdate Timestamp for the start date
7631 * @param int $thedate Timestamp for the end date
7632 * @return string
7634 function getweek ($startdate, $thedate) {
7635 if ($thedate < $startdate) {
7636 return 0;
7639 return floor(($thedate - $startdate) / WEEKSECS) + 1;
7643 * Returns a randomly generated password of length $maxlen. inspired by
7645 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
7646 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
7648 * @param int $maxlen The maximum size of the password being generated.
7649 * @return string
7651 function generate_password($maxlen=10) {
7652 global $CFG;
7654 if (empty($CFG->passwordpolicy)) {
7655 $fillers = PASSWORD_DIGITS;
7656 $wordlist = file($CFG->wordlist);
7657 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7658 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7659 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
7660 $password = $word1 . $filler1 . $word2;
7661 } else {
7662 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
7663 $digits = $CFG->minpassworddigits;
7664 $lower = $CFG->minpasswordlower;
7665 $upper = $CFG->minpasswordupper;
7666 $nonalphanum = $CFG->minpasswordnonalphanum;
7667 $total = $lower + $upper + $digits + $nonalphanum;
7668 // Var minlength should be the greater one of the two ( $minlen and $total ).
7669 $minlen = $minlen < $total ? $total : $minlen;
7670 // Var maxlen can never be smaller than minlen.
7671 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
7672 $additional = $maxlen - $total;
7674 // Make sure we have enough characters to fulfill
7675 // complexity requirements.
7676 $passworddigits = PASSWORD_DIGITS;
7677 while ($digits > strlen($passworddigits)) {
7678 $passworddigits .= PASSWORD_DIGITS;
7680 $passwordlower = PASSWORD_LOWER;
7681 while ($lower > strlen($passwordlower)) {
7682 $passwordlower .= PASSWORD_LOWER;
7684 $passwordupper = PASSWORD_UPPER;
7685 while ($upper > strlen($passwordupper)) {
7686 $passwordupper .= PASSWORD_UPPER;
7688 $passwordnonalphanum = PASSWORD_NONALPHANUM;
7689 while ($nonalphanum > strlen($passwordnonalphanum)) {
7690 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
7693 // Now mix and shuffle it all.
7694 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
7695 substr(str_shuffle ($passwordupper), 0, $upper) .
7696 substr(str_shuffle ($passworddigits), 0, $digits) .
7697 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
7698 substr(str_shuffle ($passwordlower .
7699 $passwordupper .
7700 $passworddigits .
7701 $passwordnonalphanum), 0 , $additional));
7704 return substr ($password, 0, $maxlen);
7708 * Given a float, prints it nicely.
7709 * Localized floats must not be used in calculations!
7711 * The stripzeros feature is intended for making numbers look nicer in small
7712 * areas where it is not necessary to indicate the degree of accuracy by showing
7713 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
7714 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
7716 * @param float $float The float to print
7717 * @param int $decimalpoints The number of decimal places to print.
7718 * @param bool $localized use localized decimal separator
7719 * @param bool $stripzeros If true, removes final zeros after decimal point
7720 * @return string locale float
7722 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
7723 if (is_null($float)) {
7724 return '';
7726 if ($localized) {
7727 $separator = get_string('decsep', 'langconfig');
7728 } else {
7729 $separator = '.';
7731 $result = number_format($float, $decimalpoints, $separator, '');
7732 if ($stripzeros) {
7733 // Remove zeros and final dot if not needed.
7734 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
7736 return $result;
7740 * Converts locale specific floating point/comma number back to standard PHP float value
7741 * Do NOT try to do any math operations before this conversion on any user submitted floats!
7743 * @param string $localefloat locale aware float representation
7744 * @param bool $strict If true, then check the input and return false if it is not a valid number.
7745 * @return mixed float|bool - false or the parsed float.
7747 function unformat_float($localefloat, $strict = false) {
7748 $localefloat = trim($localefloat);
7750 if ($localefloat == '') {
7751 return null;
7754 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
7755 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
7757 if ($strict && !is_numeric($localefloat)) {
7758 return false;
7761 return (float)$localefloat;
7765 * Given a simple array, this shuffles it up just like shuffle()
7766 * Unlike PHP's shuffle() this function works on any machine.
7768 * @param array $array The array to be rearranged
7769 * @return array
7771 function swapshuffle($array) {
7773 $last = count($array) - 1;
7774 for ($i = 0; $i <= $last; $i++) {
7775 $from = rand(0, $last);
7776 $curr = $array[$i];
7777 $array[$i] = $array[$from];
7778 $array[$from] = $curr;
7780 return $array;
7784 * Like {@link swapshuffle()}, but works on associative arrays
7786 * @param array $array The associative array to be rearranged
7787 * @return array
7789 function swapshuffle_assoc($array) {
7791 $newarray = array();
7792 $newkeys = swapshuffle(array_keys($array));
7794 foreach ($newkeys as $newkey) {
7795 $newarray[$newkey] = $array[$newkey];
7797 return $newarray;
7801 * Given an arbitrary array, and a number of draws,
7802 * this function returns an array with that amount
7803 * of items. The indexes are retained.
7805 * @todo Finish documenting this function
7807 * @param array $array
7808 * @param int $draws
7809 * @return array
7811 function draw_rand_array($array, $draws) {
7813 $return = array();
7815 $last = count($array);
7817 if ($draws > $last) {
7818 $draws = $last;
7821 while ($draws > 0) {
7822 $last--;
7824 $keys = array_keys($array);
7825 $rand = rand(0, $last);
7827 $return[$keys[$rand]] = $array[$keys[$rand]];
7828 unset($array[$keys[$rand]]);
7830 $draws--;
7833 return $return;
7837 * Calculate the difference between two microtimes
7839 * @param string $a The first Microtime
7840 * @param string $b The second Microtime
7841 * @return string
7843 function microtime_diff($a, $b) {
7844 list($adec, $asec) = explode(' ', $a);
7845 list($bdec, $bsec) = explode(' ', $b);
7846 return $bsec - $asec + $bdec - $adec;
7850 * Given a list (eg a,b,c,d,e) this function returns
7851 * an array of 1->a, 2->b, 3->c etc
7853 * @param string $list The string to explode into array bits
7854 * @param string $separator The separator used within the list string
7855 * @return array The now assembled array
7857 function make_menu_from_list($list, $separator=',') {
7859 $array = array_reverse(explode($separator, $list), true);
7860 foreach ($array as $key => $item) {
7861 $outarray[$key+1] = trim($item);
7863 return $outarray;
7867 * Creates an array that represents all the current grades that
7868 * can be chosen using the given grading type.
7870 * Negative numbers
7871 * are scales, zero is no grade, and positive numbers are maximum
7872 * grades.
7874 * @todo Finish documenting this function or better deprecated this completely!
7876 * @param int $gradingtype
7877 * @return array
7879 function make_grades_menu($gradingtype) {
7880 global $DB;
7882 $grades = array();
7883 if ($gradingtype < 0) {
7884 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
7885 return make_menu_from_list($scale->scale);
7887 } else if ($gradingtype > 0) {
7888 for ($i=$gradingtype; $i>=0; $i--) {
7889 $grades[$i] = $i .' / '. $gradingtype;
7891 return $grades;
7893 return $grades;
7897 * This function returns the number of activities using the given scale in the given course.
7899 * @param int $courseid The course ID to check.
7900 * @param int $scaleid The scale ID to check
7901 * @return int
7903 function course_scale_used($courseid, $scaleid) {
7904 global $CFG, $DB;
7906 $return = 0;
7908 if (!empty($scaleid)) {
7909 if ($cms = get_course_mods($courseid)) {
7910 foreach ($cms as $cm) {
7911 // Check cm->name/lib.php exists.
7912 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
7913 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
7914 $functionname = $cm->modname.'_scale_used';
7915 if (function_exists($functionname)) {
7916 if ($functionname($cm->instance, $scaleid)) {
7917 $return++;
7924 // Check if any course grade item makes use of the scale.
7925 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
7927 // Check if any outcome in the course makes use of the scale.
7928 $return += $DB->count_records_sql("SELECT COUNT('x')
7929 FROM {grade_outcomes_courses} goc,
7930 {grade_outcomes} go
7931 WHERE go.id = goc.outcomeid
7932 AND go.scaleid = ? AND goc.courseid = ?",
7933 array($scaleid, $courseid));
7935 return $return;
7939 * This function returns the number of activities using scaleid in the entire site
7941 * @param int $scaleid
7942 * @param array $courses
7943 * @return int
7945 function site_scale_used($scaleid, &$courses) {
7946 $return = 0;
7948 if (!is_array($courses) || count($courses) == 0) {
7949 $courses = get_courses("all", false, "c.id, c.shortname");
7952 if (!empty($scaleid)) {
7953 if (is_array($courses) && count($courses) > 0) {
7954 foreach ($courses as $course) {
7955 $return += course_scale_used($course->id, $scaleid);
7959 return $return;
7963 * make_unique_id_code
7965 * @todo Finish documenting this function
7967 * @uses $_SERVER
7968 * @param string $extra Extra string to append to the end of the code
7969 * @return string
7971 function make_unique_id_code($extra = '') {
7973 $hostname = 'unknownhost';
7974 if (!empty($_SERVER['HTTP_HOST'])) {
7975 $hostname = $_SERVER['HTTP_HOST'];
7976 } else if (!empty($_ENV['HTTP_HOST'])) {
7977 $hostname = $_ENV['HTTP_HOST'];
7978 } else if (!empty($_SERVER['SERVER_NAME'])) {
7979 $hostname = $_SERVER['SERVER_NAME'];
7980 } else if (!empty($_ENV['SERVER_NAME'])) {
7981 $hostname = $_ENV['SERVER_NAME'];
7984 $date = gmdate("ymdHis");
7986 $random = random_string(6);
7988 if ($extra) {
7989 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
7990 } else {
7991 return $hostname .'+'. $date .'+'. $random;
7997 * Function to check the passed address is within the passed subnet
7999 * The parameter is a comma separated string of subnet definitions.
8000 * Subnet strings can be in one of three formats:
8001 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8002 * 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)
8003 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8004 * Code for type 1 modified from user posted comments by mediator at
8005 * {@link http://au.php.net/manual/en/function.ip2long.php}
8007 * @param string $addr The address you are checking
8008 * @param string $subnetstr The string of subnet addresses
8009 * @return bool
8011 function address_in_subnet($addr, $subnetstr) {
8013 if ($addr == '0.0.0.0') {
8014 return false;
8016 $subnets = explode(',', $subnetstr);
8017 $found = false;
8018 $addr = trim($addr);
8019 $addr = cleanremoteaddr($addr, false); // Normalise.
8020 if ($addr === null) {
8021 return false;
8023 $addrparts = explode(':', $addr);
8025 $ipv6 = strpos($addr, ':');
8027 foreach ($subnets as $subnet) {
8028 $subnet = trim($subnet);
8029 if ($subnet === '') {
8030 continue;
8033 if (strpos($subnet, '/') !== false) {
8034 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8035 list($ip, $mask) = explode('/', $subnet);
8036 $mask = trim($mask);
8037 if (!is_number($mask)) {
8038 continue; // Incorect mask number, eh?
8040 $ip = cleanremoteaddr($ip, false); // Normalise.
8041 if ($ip === null) {
8042 continue;
8044 if (strpos($ip, ':') !== false) {
8045 // IPv6.
8046 if (!$ipv6) {
8047 continue;
8049 if ($mask > 128 or $mask < 0) {
8050 continue; // Nonsense.
8052 if ($mask == 0) {
8053 return true; // Any address.
8055 if ($mask == 128) {
8056 if ($ip === $addr) {
8057 return true;
8059 continue;
8061 $ipparts = explode(':', $ip);
8062 $modulo = $mask % 16;
8063 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8064 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8065 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8066 if ($modulo == 0) {
8067 return true;
8069 $pos = ($mask-$modulo)/16;
8070 $ipnet = hexdec($ipparts[$pos]);
8071 $addrnet = hexdec($addrparts[$pos]);
8072 $mask = 0xffff << (16 - $modulo);
8073 if (($addrnet & $mask) == ($ipnet & $mask)) {
8074 return true;
8078 } else {
8079 // IPv4.
8080 if ($ipv6) {
8081 continue;
8083 if ($mask > 32 or $mask < 0) {
8084 continue; // Nonsense.
8086 if ($mask == 0) {
8087 return true;
8089 if ($mask == 32) {
8090 if ($ip === $addr) {
8091 return true;
8093 continue;
8095 $mask = 0xffffffff << (32 - $mask);
8096 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8097 return true;
8101 } else if (strpos($subnet, '-') !== false) {
8102 // 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.
8103 $parts = explode('-', $subnet);
8104 if (count($parts) != 2) {
8105 continue;
8108 if (strpos($subnet, ':') !== false) {
8109 // IPv6.
8110 if (!$ipv6) {
8111 continue;
8113 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8114 if ($ipstart === null) {
8115 continue;
8117 $ipparts = explode(':', $ipstart);
8118 $start = hexdec(array_pop($ipparts));
8119 $ipparts[] = trim($parts[1]);
8120 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8121 if ($ipend === null) {
8122 continue;
8124 $ipparts[7] = '';
8125 $ipnet = implode(':', $ipparts);
8126 if (strpos($addr, $ipnet) !== 0) {
8127 continue;
8129 $ipparts = explode(':', $ipend);
8130 $end = hexdec($ipparts[7]);
8132 $addrend = hexdec($addrparts[7]);
8134 if (($addrend >= $start) and ($addrend <= $end)) {
8135 return true;
8138 } else {
8139 // IPv4.
8140 if ($ipv6) {
8141 continue;
8143 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8144 if ($ipstart === null) {
8145 continue;
8147 $ipparts = explode('.', $ipstart);
8148 $ipparts[3] = trim($parts[1]);
8149 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8150 if ($ipend === null) {
8151 continue;
8154 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8155 return true;
8159 } else {
8160 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8161 if (strpos($subnet, ':') !== false) {
8162 // IPv6.
8163 if (!$ipv6) {
8164 continue;
8166 $parts = explode(':', $subnet);
8167 $count = count($parts);
8168 if ($parts[$count-1] === '') {
8169 unset($parts[$count-1]); // Trim trailing :'s.
8170 $count--;
8171 $subnet = implode('.', $parts);
8173 $isip = cleanremoteaddr($subnet, false); // Normalise.
8174 if ($isip !== null) {
8175 if ($isip === $addr) {
8176 return true;
8178 continue;
8179 } else if ($count > 8) {
8180 continue;
8182 $zeros = array_fill(0, 8-$count, '0');
8183 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8184 if (address_in_subnet($addr, $subnet)) {
8185 return true;
8188 } else {
8189 // IPv4.
8190 if ($ipv6) {
8191 continue;
8193 $parts = explode('.', $subnet);
8194 $count = count($parts);
8195 if ($parts[$count-1] === '') {
8196 unset($parts[$count-1]); // Trim trailing .
8197 $count--;
8198 $subnet = implode('.', $parts);
8200 if ($count == 4) {
8201 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8202 if ($subnet === $addr) {
8203 return true;
8205 continue;
8206 } else if ($count > 4) {
8207 continue;
8209 $zeros = array_fill(0, 4-$count, '0');
8210 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8211 if (address_in_subnet($addr, $subnet)) {
8212 return true;
8218 return false;
8222 * For outputting debugging info
8224 * @param string $string The string to write
8225 * @param string $eol The end of line char(s) to use
8226 * @param string $sleep Period to make the application sleep
8227 * This ensures any messages have time to display before redirect
8229 function mtrace($string, $eol="\n", $sleep=0) {
8231 if (defined('STDOUT') and !PHPUNIT_TEST) {
8232 fwrite(STDOUT, $string.$eol);
8233 } else {
8234 echo $string . $eol;
8237 flush();
8239 // Delay to keep message on user's screen in case of subsequent redirect.
8240 if ($sleep) {
8241 sleep($sleep);
8246 * Replace 1 or more slashes or backslashes to 1 slash
8248 * @param string $path The path to strip
8249 * @return string the path with double slashes removed
8251 function cleardoubleslashes ($path) {
8252 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8256 * Is current ip in give list?
8258 * @param string $list
8259 * @return bool
8261 function remoteip_in_list($list) {
8262 $inlist = false;
8263 $clientip = getremoteaddr(null);
8265 if (!$clientip) {
8266 // Ensure access on cli.
8267 return true;
8270 $list = explode("\n", $list);
8271 foreach ($list as $subnet) {
8272 $subnet = trim($subnet);
8273 if (address_in_subnet($clientip, $subnet)) {
8274 $inlist = true;
8275 break;
8278 return $inlist;
8282 * Returns most reliable client address
8284 * @param string $default If an address can't be determined, then return this
8285 * @return string The remote IP address
8287 function getremoteaddr($default='0.0.0.0') {
8288 global $CFG;
8290 if (empty($CFG->getremoteaddrconf)) {
8291 // This will happen, for example, before just after the upgrade, as the
8292 // user is redirected to the admin screen.
8293 $variablestoskip = 0;
8294 } else {
8295 $variablestoskip = $CFG->getremoteaddrconf;
8297 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8298 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8299 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8300 return $address ? $address : $default;
8303 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8304 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8305 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8306 $address = $forwardedaddresses[0];
8308 if (substr_count($address, ":") > 1) {
8309 // Remove port and brackets from IPv6.
8310 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8311 $address = $matches[1];
8313 } else {
8314 // Remove port from IPv4.
8315 if (substr_count($address, ":") == 1) {
8316 $parts = explode(":", $address);
8317 $address = $parts[0];
8321 $address = cleanremoteaddr($address);
8322 return $address ? $address : $default;
8325 if (!empty($_SERVER['REMOTE_ADDR'])) {
8326 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8327 return $address ? $address : $default;
8328 } else {
8329 return $default;
8334 * Cleans an ip address. Internal addresses are now allowed.
8335 * (Originally local addresses were not allowed.)
8337 * @param string $addr IPv4 or IPv6 address
8338 * @param bool $compress use IPv6 address compression
8339 * @return string normalised ip address string, null if error
8341 function cleanremoteaddr($addr, $compress=false) {
8342 $addr = trim($addr);
8344 // TODO: maybe add a separate function is_addr_public() or something like this.
8346 if (strpos($addr, ':') !== false) {
8347 // Can be only IPv6.
8348 $parts = explode(':', $addr);
8349 $count = count($parts);
8351 if (strpos($parts[$count-1], '.') !== false) {
8352 // Legacy ipv4 notation.
8353 $last = array_pop($parts);
8354 $ipv4 = cleanremoteaddr($last, true);
8355 if ($ipv4 === null) {
8356 return null;
8358 $bits = explode('.', $ipv4);
8359 $parts[] = dechex($bits[0]).dechex($bits[1]);
8360 $parts[] = dechex($bits[2]).dechex($bits[3]);
8361 $count = count($parts);
8362 $addr = implode(':', $parts);
8365 if ($count < 3 or $count > 8) {
8366 return null; // Severly malformed.
8369 if ($count != 8) {
8370 if (strpos($addr, '::') === false) {
8371 return null; // Malformed.
8373 // Uncompress.
8374 $insertat = array_search('', $parts, true);
8375 $missing = array_fill(0, 1 + 8 - $count, '0');
8376 array_splice($parts, $insertat, 1, $missing);
8377 foreach ($parts as $key => $part) {
8378 if ($part === '') {
8379 $parts[$key] = '0';
8384 $adr = implode(':', $parts);
8385 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8386 return null; // Incorrect format - sorry.
8389 // Normalise 0s and case.
8390 $parts = array_map('hexdec', $parts);
8391 $parts = array_map('dechex', $parts);
8393 $result = implode(':', $parts);
8395 if (!$compress) {
8396 return $result;
8399 if ($result === '0:0:0:0:0:0:0:0') {
8400 return '::'; // All addresses.
8403 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8404 if ($compressed !== $result) {
8405 return $compressed;
8408 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8409 if ($compressed !== $result) {
8410 return $compressed;
8413 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8414 if ($compressed !== $result) {
8415 return $compressed;
8418 return $result;
8421 // First get all things that look like IPv4 addresses.
8422 $parts = array();
8423 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8424 return null;
8426 unset($parts[0]);
8428 foreach ($parts as $key => $match) {
8429 if ($match > 255) {
8430 return null;
8432 $parts[$key] = (int)$match; // Normalise 0s.
8435 return implode('.', $parts);
8439 * This function will make a complete copy of anything it's given,
8440 * regardless of whether it's an object or not.
8442 * @param mixed $thing Something you want cloned
8443 * @return mixed What ever it is you passed it
8445 function fullclone($thing) {
8446 return unserialize(serialize($thing));
8450 * If new messages are waiting for the current user, then insert
8451 * JavaScript to pop up the messaging window into the page
8453 * @return void
8455 function message_popup_window() {
8456 global $USER, $DB, $PAGE, $CFG;
8458 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
8459 return;
8462 if (!isloggedin() || isguestuser()) {
8463 return;
8466 if (!isset($USER->message_lastpopup)) {
8467 $USER->message_lastpopup = 0;
8468 } else if ($USER->message_lastpopup > (time()-120)) {
8469 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8470 return;
8473 // A quick query to check whether the user has new messages.
8474 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
8475 if ($messagecount < 1) {
8476 return;
8479 // There are unread messages so now do a more complex but slower query.
8480 $messagesql = "SELECT m.id, c.blocked
8481 FROM {message} m
8482 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8483 JOIN {message_processors} p ON mw.processorid=p.id
8484 JOIN {user} u ON m.useridfrom=u.id
8485 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8486 AND c.userid = m.useridto
8487 WHERE m.useridto = :userid
8488 AND p.name='popup'";
8490 // If the user was last notified over an hour ago we can re-notify them of old messages
8491 // so don't worry about when the new message was sent.
8492 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
8493 if (!$lastnotifiedlongago) {
8494 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8497 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
8499 $validmessages = 0;
8500 foreach ($waitingmessages as $messageinfo) {
8501 if ($messageinfo->blocked) {
8502 // Message is from a user who has since been blocked so just mark it read.
8503 // Get the full message to mark as read.
8504 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id));
8505 message_mark_message_read($messageobject, time());
8506 } else {
8507 $validmessages++;
8511 if ($validmessages > 0) {
8512 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8513 $strgomessage = get_string('gotomessages', 'message');
8514 $strstaymessage = get_string('ignore', 'admin');
8516 $notificationsound = null;
8517 $beep = get_user_preferences('message_beepnewmessage', '');
8518 if (!empty($beep)) {
8519 // Browsers will work down this list until they find something they support.
8520 $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
8521 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
8522 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8523 $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8525 $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8528 $url = $CFG->wwwroot.'/message/index.php';
8529 $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8530 html_writer::start_tag('div', array('id' => 'newmessagetext')).
8531 $strmessages.
8532 html_writer::end_tag('div').
8534 $notificationsound.
8535 html_writer::start_tag('div', array('id' => 'newmessagelinks')).
8536 html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
8537 html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
8538 html_writer::end_tag('div');
8539 html_writer::end_tag('div');
8541 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
8543 $USER->message_lastpopup = time();
8548 * Used to make sure that $min <= $value <= $max
8550 * Make sure that value is between min, and max
8552 * @param int $min The minimum value
8553 * @param int $value The value to check
8554 * @param int $max The maximum value
8555 * @return int
8557 function bounded_number($min, $value, $max) {
8558 if ($value < $min) {
8559 return $min;
8561 if ($value > $max) {
8562 return $max;
8564 return $value;
8568 * Check if there is a nested array within the passed array
8570 * @param array $array
8571 * @return bool true if there is a nested array false otherwise
8573 function array_is_nested($array) {
8574 foreach ($array as $value) {
8575 if (is_array($value)) {
8576 return true;
8579 return false;
8583 * get_performance_info() pairs up with init_performance_info()
8584 * loaded in setup.php. Returns an array with 'html' and 'txt'
8585 * values ready for use, and each of the individual stats provided
8586 * separately as well.
8588 * @return array
8590 function get_performance_info() {
8591 global $CFG, $PERF, $DB, $PAGE;
8593 $info = array();
8594 $info['html'] = ''; // Holds userfriendly HTML representation.
8595 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8597 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8599 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8600 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8602 if (function_exists('memory_get_usage')) {
8603 $info['memory_total'] = memory_get_usage();
8604 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8605 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8606 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8607 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8610 if (function_exists('memory_get_peak_usage')) {
8611 $info['memory_peak'] = memory_get_peak_usage();
8612 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8613 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8616 $inc = get_included_files();
8617 $info['includecount'] = count($inc);
8618 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8619 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8621 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8622 // We can not track more performance before installation or before PAGE init, sorry.
8623 return $info;
8626 $filtermanager = filter_manager::instance();
8627 if (method_exists($filtermanager, 'get_performance_summary')) {
8628 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8629 $info = array_merge($filterinfo, $info);
8630 foreach ($filterinfo as $key => $value) {
8631 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8632 $info['txt'] .= "$key: $value ";
8636 $stringmanager = get_string_manager();
8637 if (method_exists($stringmanager, 'get_performance_summary')) {
8638 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8639 $info = array_merge($filterinfo, $info);
8640 foreach ($filterinfo as $key => $value) {
8641 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8642 $info['txt'] .= "$key: $value ";
8646 if (!empty($PERF->logwrites)) {
8647 $info['logwrites'] = $PERF->logwrites;
8648 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8649 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8652 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
8653 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
8654 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8656 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
8657 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
8658 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
8660 if (function_exists('posix_times')) {
8661 $ptimes = posix_times();
8662 if (is_array($ptimes)) {
8663 foreach ($ptimes as $key => $val) {
8664 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
8666 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
8667 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8671 // Grab the load average for the last minute.
8672 // /proc will only work under some linux configurations
8673 // while uptime is there under MacOSX/Darwin and other unices.
8674 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
8675 list($serverload) = explode(' ', $loadavg[0]);
8676 unset($loadavg);
8677 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
8678 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
8679 $serverload = $matches[1];
8680 } else {
8681 trigger_error('Could not parse uptime output!');
8684 if (!empty($serverload)) {
8685 $info['serverload'] = $serverload;
8686 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
8687 $info['txt'] .= "serverload: {$info['serverload']} ";
8690 // Display size of session if session started.
8691 if ($si = \core\session\manager::get_performance_info()) {
8692 $info['sessionsize'] = $si['size'];
8693 $info['html'] .= $si['html'];
8694 $info['txt'] .= $si['txt'];
8697 if ($stats = cache_helper::get_stats()) {
8698 $html = '<span class="cachesused">';
8699 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
8700 $text = 'Caches used (hits/misses/sets): ';
8701 $hits = 0;
8702 $misses = 0;
8703 $sets = 0;
8704 foreach ($stats as $definition => $details) {
8705 switch ($details['mode']) {
8706 case cache_store::MODE_APPLICATION:
8707 $modeclass = 'application';
8708 $mode = ' <span title="application cache">[a]</span>';
8709 break;
8710 case cache_store::MODE_SESSION:
8711 $modeclass = 'session';
8712 $mode = ' <span title="session cache">[s]</span>';
8713 break;
8714 case cache_store::MODE_REQUEST:
8715 $modeclass = 'request';
8716 $mode = ' <span title="request cache">[r]</span>';
8717 break;
8719 $html .= '<span class="cache-definition-stats cache-mode-'.$modeclass.'">';
8720 $html .= '<span class="cache-definition-stats-heading">'.$definition.$mode.'</span>';
8721 $text .= "$definition {";
8722 foreach ($details['stores'] as $store => $data) {
8723 $hits += $data['hits'];
8724 $misses += $data['misses'];
8725 $sets += $data['sets'];
8726 if ($data['hits'] == 0 and $data['misses'] > 0) {
8727 $cachestoreclass = 'nohits';
8728 } else if ($data['hits'] < $data['misses']) {
8729 $cachestoreclass = 'lowhits';
8730 } else {
8731 $cachestoreclass = 'hihits';
8733 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
8734 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
8736 $html .= '</span>';
8737 $text .= '} ';
8739 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
8740 $html .= '</span> ';
8741 $info['cachesused'] = "$hits / $misses / $sets";
8742 $info['html'] .= $html;
8743 $info['txt'] .= $text.'. ';
8744 } else {
8745 $info['cachesused'] = '0 / 0 / 0';
8746 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
8747 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
8750 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
8751 return $info;
8755 * Legacy function.
8757 * @todo Document this function linux people
8759 function apd_get_profiling() {
8760 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
8764 * Delete directory or only its content
8766 * @param string $dir directory path
8767 * @param bool $contentonly
8768 * @return bool success, true also if dir does not exist
8770 function remove_dir($dir, $contentonly=false) {
8771 if (!file_exists($dir)) {
8772 // Nothing to do.
8773 return true;
8775 if (!$handle = opendir($dir)) {
8776 return false;
8778 $result = true;
8779 while (false!==($item = readdir($handle))) {
8780 if ($item != '.' && $item != '..') {
8781 if (is_dir($dir.'/'.$item)) {
8782 $result = remove_dir($dir.'/'.$item) && $result;
8783 } else {
8784 $result = unlink($dir.'/'.$item) && $result;
8788 closedir($handle);
8789 if ($contentonly) {
8790 clearstatcache(); // Make sure file stat cache is properly invalidated.
8791 return $result;
8793 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
8794 clearstatcache(); // Make sure file stat cache is properly invalidated.
8795 return $result;
8799 * Detect if an object or a class contains a given property
8800 * will take an actual object or the name of a class
8802 * @param mix $obj Name of class or real object to test
8803 * @param string $property name of property to find
8804 * @return bool true if property exists
8806 function object_property_exists( $obj, $property ) {
8807 if (is_string( $obj )) {
8808 $properties = get_class_vars( $obj );
8809 } else {
8810 $properties = get_object_vars( $obj );
8812 return array_key_exists( $property, $properties );
8816 * Converts an object into an associative array
8818 * This function converts an object into an associative array by iterating
8819 * over its public properties. Because this function uses the foreach
8820 * construct, Iterators are respected. It works recursively on arrays of objects.
8821 * Arrays and simple values are returned as is.
8823 * If class has magic properties, it can implement IteratorAggregate
8824 * and return all available properties in getIterator()
8826 * @param mixed $var
8827 * @return array
8829 function convert_to_array($var) {
8830 $result = array();
8832 // Loop over elements/properties.
8833 foreach ($var as $key => $value) {
8834 // Recursively convert objects.
8835 if (is_object($value) || is_array($value)) {
8836 $result[$key] = convert_to_array($value);
8837 } else {
8838 // Simple values are untouched.
8839 $result[$key] = $value;
8842 return $result;
8846 * Detect a custom script replacement in the data directory that will
8847 * replace an existing moodle script
8849 * @return string|bool full path name if a custom script exists, false if no custom script exists
8851 function custom_script_path() {
8852 global $CFG, $SCRIPT;
8854 if ($SCRIPT === null) {
8855 // Probably some weird external script.
8856 return false;
8859 $scriptpath = $CFG->customscripts . $SCRIPT;
8861 // Check the custom script exists.
8862 if (file_exists($scriptpath) and is_file($scriptpath)) {
8863 return $scriptpath;
8864 } else {
8865 return false;
8870 * Returns whether or not the user object is a remote MNET user. This function
8871 * is in moodlelib because it does not rely on loading any of the MNET code.
8873 * @param object $user A valid user object
8874 * @return bool True if the user is from a remote Moodle.
8876 function is_mnet_remote_user($user) {
8877 global $CFG;
8879 if (!isset($CFG->mnet_localhost_id)) {
8880 include_once($CFG->dirroot . '/mnet/lib.php');
8881 $env = new mnet_environment();
8882 $env->init();
8883 unset($env);
8886 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
8890 * This function will search for browser prefereed languages, setting Moodle
8891 * to use the best one available if $SESSION->lang is undefined
8893 function setup_lang_from_browser() {
8894 global $CFG, $SESSION, $USER;
8896 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
8897 // Lang is defined in session or user profile, nothing to do.
8898 return;
8901 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
8902 return;
8905 // Extract and clean langs from headers.
8906 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
8907 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
8908 $rawlangs = explode(',', $rawlangs); // Convert to array.
8909 $langs = array();
8911 $order = 1.0;
8912 foreach ($rawlangs as $lang) {
8913 if (strpos($lang, ';') === false) {
8914 $langs[(string)$order] = $lang;
8915 $order = $order-0.01;
8916 } else {
8917 $parts = explode(';', $lang);
8918 $pos = strpos($parts[1], '=');
8919 $langs[substr($parts[1], $pos+1)] = $parts[0];
8922 krsort($langs, SORT_NUMERIC);
8924 // Look for such langs under standard locations.
8925 foreach ($langs as $lang) {
8926 // Clean it properly for include.
8927 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
8928 if (get_string_manager()->translation_exists($lang, false)) {
8929 // Lang exists, set it in session.
8930 $SESSION->lang = $lang;
8931 // We have finished. Go out.
8932 break;
8935 return;
8939 * Check if $url matches anything in proxybypass list
8941 * Any errors just result in the proxy being used (least bad)
8943 * @param string $url url to check
8944 * @return boolean true if we should bypass the proxy
8946 function is_proxybypass( $url ) {
8947 global $CFG;
8949 // Sanity check.
8950 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
8951 return false;
8954 // Get the host part out of the url.
8955 if (!$host = parse_url( $url, PHP_URL_HOST )) {
8956 return false;
8959 // Get the possible bypass hosts into an array.
8960 $matches = explode( ',', $CFG->proxybypass );
8962 // Check for a match.
8963 // (IPs need to match the left hand side and hosts the right of the url,
8964 // but we can recklessly check both as there can't be a false +ve).
8965 foreach ($matches as $match) {
8966 $match = trim($match);
8968 // Try for IP match (Left side).
8969 $lhs = substr($host, 0, strlen($match));
8970 if (strcasecmp($match, $lhs)==0) {
8971 return true;
8974 // Try for host match (Right side).
8975 $rhs = substr($host, -strlen($match));
8976 if (strcasecmp($match, $rhs)==0) {
8977 return true;
8981 // Nothing matched.
8982 return false;
8986 * Check if the passed navigation is of the new style
8988 * @param mixed $navigation
8989 * @return bool true for yes false for no
8991 function is_newnav($navigation) {
8992 if (is_array($navigation) && !empty($navigation['newnav'])) {
8993 return true;
8994 } else {
8995 return false;
9000 * Checks whether the given variable name is defined as a variable within the given object.
9002 * This will NOT work with stdClass objects, which have no class variables.
9004 * @param string $var The variable name
9005 * @param object $object The object to check
9006 * @return boolean
9008 function in_object_vars($var, $object) {
9009 $classvars = get_class_vars(get_class($object));
9010 $classvars = array_keys($classvars);
9011 return in_array($var, $classvars);
9015 * Returns an array without repeated objects.
9016 * This function is similar to array_unique, but for arrays that have objects as values
9018 * @param array $array
9019 * @param bool $keepkeyassoc
9020 * @return array
9022 function object_array_unique($array, $keepkeyassoc = true) {
9023 $duplicatekeys = array();
9024 $tmp = array();
9026 foreach ($array as $key => $val) {
9027 // Convert objects to arrays, in_array() does not support objects.
9028 if (is_object($val)) {
9029 $val = (array)$val;
9032 if (!in_array($val, $tmp)) {
9033 $tmp[] = $val;
9034 } else {
9035 $duplicatekeys[] = $key;
9039 foreach ($duplicatekeys as $key) {
9040 unset($array[$key]);
9043 return $keepkeyassoc ? $array : array_values($array);
9047 * Is a userid the primary administrator?
9049 * @param int $userid int id of user to check
9050 * @return boolean
9052 function is_primary_admin($userid) {
9053 $primaryadmin = get_admin();
9055 if ($userid == $primaryadmin->id) {
9056 return true;
9057 } else {
9058 return false;
9063 * Returns the site identifier
9065 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9067 function get_site_identifier() {
9068 global $CFG;
9069 // Check to see if it is missing. If so, initialise it.
9070 if (empty($CFG->siteidentifier)) {
9071 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9073 // Return it.
9074 return $CFG->siteidentifier;
9078 * Check whether the given password has no more than the specified
9079 * number of consecutive identical characters.
9081 * @param string $password password to be checked against the password policy
9082 * @param integer $maxchars maximum number of consecutive identical characters
9083 * @return bool
9085 function check_consecutive_identical_characters($password, $maxchars) {
9087 if ($maxchars < 1) {
9088 return true; // Zero 0 is to disable this check.
9090 if (strlen($password) <= $maxchars) {
9091 return true; // Too short to fail this test.
9094 $previouschar = '';
9095 $consecutivecount = 1;
9096 foreach (str_split($password) as $char) {
9097 if ($char != $previouschar) {
9098 $consecutivecount = 1;
9099 } else {
9100 $consecutivecount++;
9101 if ($consecutivecount > $maxchars) {
9102 return false; // Check failed already.
9106 $previouschar = $char;
9109 return true;
9113 * Helper function to do partial function binding.
9114 * so we can use it for preg_replace_callback, for example
9115 * this works with php functions, user functions, static methods and class methods
9116 * it returns you a callback that you can pass on like so:
9118 * $callback = partial('somefunction', $arg1, $arg2);
9119 * or
9120 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9121 * or even
9122 * $obj = new someclass();
9123 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9125 * and then the arguments that are passed through at calltime are appended to the argument list.
9127 * @param mixed $function a php callback
9128 * @param mixed $arg1,... $argv arguments to partially bind with
9129 * @return array Array callback
9131 function partial() {
9132 if (!class_exists('partial')) {
9134 * Used to manage function binding.
9135 * @copyright 2009 Penny Leach
9136 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9138 class partial{
9139 /** @var array */
9140 public $values = array();
9141 /** @var string The function to call as a callback. */
9142 public $func;
9144 * Constructor
9145 * @param string $func
9146 * @param array $args
9148 public function __construct($func, $args) {
9149 $this->values = $args;
9150 $this->func = $func;
9153 * Calls the callback function.
9154 * @return mixed
9156 public function method() {
9157 $args = func_get_args();
9158 return call_user_func_array($this->func, array_merge($this->values, $args));
9162 $args = func_get_args();
9163 $func = array_shift($args);
9164 $p = new partial($func, $args);
9165 return array($p, 'method');
9169 * helper function to load up and initialise the mnet environment
9170 * this must be called before you use mnet functions.
9172 * @return mnet_environment the equivalent of old $MNET global
9174 function get_mnet_environment() {
9175 global $CFG;
9176 require_once($CFG->dirroot . '/mnet/lib.php');
9177 static $instance = null;
9178 if (empty($instance)) {
9179 $instance = new mnet_environment();
9180 $instance->init();
9182 return $instance;
9186 * during xmlrpc server code execution, any code wishing to access
9187 * information about the remote peer must use this to get it.
9189 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9191 function get_mnet_remote_client() {
9192 if (!defined('MNET_SERVER')) {
9193 debugging(get_string('notinxmlrpcserver', 'mnet'));
9194 return false;
9196 global $MNET_REMOTE_CLIENT;
9197 if (isset($MNET_REMOTE_CLIENT)) {
9198 return $MNET_REMOTE_CLIENT;
9200 return false;
9204 * during the xmlrpc server code execution, this will be called
9205 * to setup the object returned by {@link get_mnet_remote_client}
9207 * @param mnet_remote_client $client the client to set up
9208 * @throws moodle_exception
9210 function set_mnet_remote_client($client) {
9211 if (!defined('MNET_SERVER')) {
9212 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9214 global $MNET_REMOTE_CLIENT;
9215 $MNET_REMOTE_CLIENT = $client;
9219 * return the jump url for a given remote user
9220 * this is used for rewriting forum post links in emails, etc
9222 * @param stdclass $user the user to get the idp url for
9224 function mnet_get_idp_jump_url($user) {
9225 global $CFG;
9227 static $mnetjumps = array();
9228 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9229 $idp = mnet_get_peer_host($user->mnethostid);
9230 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9231 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9233 return $mnetjumps[$user->mnethostid];
9237 * Gets the homepage to use for the current user
9239 * @return int One of HOMEPAGE_*
9241 function get_home_page() {
9242 global $CFG;
9244 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9245 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9246 return HOMEPAGE_MY;
9247 } else {
9248 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9251 return HOMEPAGE_SITE;
9255 * Gets the name of a course to be displayed when showing a list of courses.
9256 * By default this is just $course->fullname but user can configure it. The
9257 * result of this function should be passed through print_string.
9258 * @param stdClass|course_in_list $course Moodle course object
9259 * @return string Display name of course (either fullname or short + fullname)
9261 function get_course_display_name_for_list($course) {
9262 global $CFG;
9263 if (!empty($CFG->courselistshortnames)) {
9264 if (!($course instanceof stdClass)) {
9265 $course = (object)convert_to_array($course);
9267 return get_string('courseextendednamedisplay', '', $course);
9268 } else {
9269 return $course->fullname;
9274 * The lang_string class
9276 * This special class is used to create an object representation of a string request.
9277 * It is special because processing doesn't occur until the object is first used.
9278 * The class was created especially to aid performance in areas where strings were
9279 * required to be generated but were not necessarily used.
9280 * As an example the admin tree when generated uses over 1500 strings, of which
9281 * normally only 1/3 are ever actually printed at any time.
9282 * The performance advantage is achieved by not actually processing strings that
9283 * arn't being used, as such reducing the processing required for the page.
9285 * How to use the lang_string class?
9286 * There are two methods of using the lang_string class, first through the
9287 * forth argument of the get_string function, and secondly directly.
9288 * The following are examples of both.
9289 * 1. Through get_string calls e.g.
9290 * $string = get_string($identifier, $component, $a, true);
9291 * $string = get_string('yes', 'moodle', null, true);
9292 * 2. Direct instantiation
9293 * $string = new lang_string($identifier, $component, $a, $lang);
9294 * $string = new lang_string('yes');
9296 * How do I use a lang_string object?
9297 * The lang_string object makes use of a magic __toString method so that you
9298 * are able to use the object exactly as you would use a string in most cases.
9299 * This means you are able to collect it into a variable and then directly
9300 * echo it, or concatenate it into another string, or similar.
9301 * The other thing you can do is manually get the string by calling the
9302 * lang_strings out method e.g.
9303 * $string = new lang_string('yes');
9304 * $string->out();
9305 * Also worth noting is that the out method can take one argument, $lang which
9306 * allows the developer to change the language on the fly.
9308 * When should I use a lang_string object?
9309 * The lang_string object is designed to be used in any situation where a
9310 * string may not be needed, but needs to be generated.
9311 * The admin tree is a good example of where lang_string objects should be
9312 * used.
9313 * A more practical example would be any class that requries strings that may
9314 * not be printed (after all classes get renderer by renderers and who knows
9315 * what they will do ;))
9317 * When should I not use a lang_string object?
9318 * Don't use lang_strings when you are going to use a string immediately.
9319 * There is no need as it will be processed immediately and there will be no
9320 * advantage, and in fact perhaps a negative hit as a class has to be
9321 * instantiated for a lang_string object, however get_string won't require
9322 * that.
9324 * Limitations:
9325 * 1. You cannot use a lang_string object as an array offset. Doing so will
9326 * result in PHP throwing an error. (You can use it as an object property!)
9328 * @package core
9329 * @category string
9330 * @copyright 2011 Sam Hemelryk
9331 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9333 class lang_string {
9335 /** @var string The strings identifier */
9336 protected $identifier;
9337 /** @var string The strings component. Default '' */
9338 protected $component = '';
9339 /** @var array|stdClass Any arguments required for the string. Default null */
9340 protected $a = null;
9341 /** @var string The language to use when processing the string. Default null */
9342 protected $lang = null;
9344 /** @var string The processed string (once processed) */
9345 protected $string = null;
9348 * A special boolean. If set to true then the object has been woken up and
9349 * cannot be regenerated. If this is set then $this->string MUST be used.
9350 * @var bool
9352 protected $forcedstring = false;
9355 * Constructs a lang_string object
9357 * This function should do as little processing as possible to ensure the best
9358 * performance for strings that won't be used.
9360 * @param string $identifier The strings identifier
9361 * @param string $component The strings component
9362 * @param stdClass|array $a Any arguments the string requires
9363 * @param string $lang The language to use when processing the string.
9364 * @throws coding_exception
9366 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9367 if (empty($component)) {
9368 $component = 'moodle';
9371 $this->identifier = $identifier;
9372 $this->component = $component;
9373 $this->lang = $lang;
9375 // We MUST duplicate $a to ensure that it if it changes by reference those
9376 // changes are not carried across.
9377 // To do this we always ensure $a or its properties/values are strings
9378 // and that any properties/values that arn't convertable are forgotten.
9379 if (!empty($a)) {
9380 if (is_scalar($a)) {
9381 $this->a = $a;
9382 } else if ($a instanceof lang_string) {
9383 $this->a = $a->out();
9384 } else if (is_object($a) or is_array($a)) {
9385 $a = (array)$a;
9386 $this->a = array();
9387 foreach ($a as $key => $value) {
9388 // Make sure conversion errors don't get displayed (results in '').
9389 if (is_array($value)) {
9390 $this->a[$key] = '';
9391 } else if (is_object($value)) {
9392 if (method_exists($value, '__toString')) {
9393 $this->a[$key] = $value->__toString();
9394 } else {
9395 $this->a[$key] = '';
9397 } else {
9398 $this->a[$key] = (string)$value;
9404 if (debugging(false, DEBUG_DEVELOPER)) {
9405 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9406 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9408 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9409 throw new coding_exception('Invalid string compontent. Please check your string definition');
9411 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9412 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9418 * Processes the string.
9420 * This function actually processes the string, stores it in the string property
9421 * and then returns it.
9422 * You will notice that this function is VERY similar to the get_string method.
9423 * That is because it is pretty much doing the same thing.
9424 * However as this function is an upgrade it isn't as tolerant to backwards
9425 * compatibility.
9427 * @return string
9428 * @throws coding_exception
9430 protected function get_string() {
9431 global $CFG;
9433 // Check if we need to process the string.
9434 if ($this->string === null) {
9435 // Check the quality of the identifier.
9436 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9437 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);
9440 // Process the string.
9441 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9442 // Debugging feature lets you display string identifier and component.
9443 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9444 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9447 // Return the string.
9448 return $this->string;
9452 * Returns the string
9454 * @param string $lang The langauge to use when processing the string
9455 * @return string
9457 public function out($lang = null) {
9458 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9459 if ($this->forcedstring) {
9460 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9461 return $this->get_string();
9463 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9464 return $translatedstring->out();
9466 return $this->get_string();
9470 * Magic __toString method for printing a string
9472 * @return string
9474 public function __toString() {
9475 return $this->get_string();
9479 * Magic __set_state method used for var_export
9481 * @return string
9483 public function __set_state() {
9484 return $this->get_string();
9488 * Prepares the lang_string for sleep and stores only the forcedstring and
9489 * string properties... the string cannot be regenerated so we need to ensure
9490 * it is generated for this.
9492 * @return string
9494 public function __sleep() {
9495 $this->get_string();
9496 $this->forcedstring = true;
9497 return array('forcedstring', 'string', 'lang');