Moodle release 2.8.8
[moodle.git] / lib / moodlelib.php
blob4df751311467453d92534f9a9aac95528a978a78
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.')');
626 if (!isset($default)) {
627 $default = null;
630 // POST has precedence.
631 if (isset($_POST[$parname])) {
632 $param = $_POST[$parname];
633 } else if (isset($_GET[$parname])) {
634 $param = $_GET[$parname];
635 } else {
636 return $default;
639 if (is_array($param)) {
640 debugging('Invalid array parameter detected in required_param(): '.$parname);
641 // TODO: switch to $default in Moodle 2.3.
642 return optional_param_array($parname, $default, $type);
645 return clean_param($param, $type);
649 * Returns a particular array value for the named variable, taken from
650 * POST or GET, otherwise returning a given default.
652 * This function should be used to initialise all optional values
653 * in a script that are based on parameters. Usually it will be
654 * used like this:
655 * $ids = optional_param('id', array(), PARAM_INT);
657 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
659 * @param string $parname the name of the page parameter we want
660 * @param mixed $default the default value to return if nothing is found
661 * @param string $type expected type of parameter
662 * @return array
663 * @throws coding_exception
665 function optional_param_array($parname, $default, $type) {
666 if (func_num_args() != 3 or empty($parname) or empty($type)) {
667 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
670 // POST has precedence.
671 if (isset($_POST[$parname])) {
672 $param = $_POST[$parname];
673 } else if (isset($_GET[$parname])) {
674 $param = $_GET[$parname];
675 } else {
676 return $default;
678 if (!is_array($param)) {
679 debugging('optional_param_array() expects array parameters only: '.$parname);
680 return $default;
683 $result = array();
684 foreach ($param as $key => $value) {
685 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
686 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
687 continue;
689 $result[$key] = clean_param($value, $type);
692 return $result;
696 * Strict validation of parameter values, the values are only converted
697 * to requested PHP type. Internally it is using clean_param, the values
698 * before and after cleaning must be equal - otherwise
699 * an invalid_parameter_exception is thrown.
700 * Objects and classes are not accepted.
702 * @param mixed $param
703 * @param string $type PARAM_ constant
704 * @param bool $allownull are nulls valid value?
705 * @param string $debuginfo optional debug information
706 * @return mixed the $param value converted to PHP type
707 * @throws invalid_parameter_exception if $param is not of given type
709 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
710 if (is_null($param)) {
711 if ($allownull == NULL_ALLOWED) {
712 return null;
713 } else {
714 throw new invalid_parameter_exception($debuginfo);
717 if (is_array($param) or is_object($param)) {
718 throw new invalid_parameter_exception($debuginfo);
721 $cleaned = clean_param($param, $type);
723 if ($type == PARAM_FLOAT) {
724 // Do not detect precision loss here.
725 if (is_float($param) or is_int($param)) {
726 // These always fit.
727 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
728 throw new invalid_parameter_exception($debuginfo);
730 } else if ((string)$param !== (string)$cleaned) {
731 // Conversion to string is usually lossless.
732 throw new invalid_parameter_exception($debuginfo);
735 return $cleaned;
739 * Makes sure array contains only the allowed types, this function does not validate array key names!
741 * <code>
742 * $options = clean_param($options, PARAM_INT);
743 * </code>
745 * @param array $param the variable array we are cleaning
746 * @param string $type expected format of param after cleaning.
747 * @param bool $recursive clean recursive arrays
748 * @return array
749 * @throws coding_exception
751 function clean_param_array(array $param = null, $type, $recursive = false) {
752 // Convert null to empty array.
753 $param = (array)$param;
754 foreach ($param as $key => $value) {
755 if (is_array($value)) {
756 if ($recursive) {
757 $param[$key] = clean_param_array($value, $type, true);
758 } else {
759 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
761 } else {
762 $param[$key] = clean_param($value, $type);
765 return $param;
769 * Used by {@link optional_param()} and {@link required_param()} to
770 * clean the variables and/or cast to specific types, based on
771 * an options field.
772 * <code>
773 * $course->format = clean_param($course->format, PARAM_ALPHA);
774 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
775 * </code>
777 * @param mixed $param the variable we are cleaning
778 * @param string $type expected format of param after cleaning.
779 * @return mixed
780 * @throws coding_exception
782 function clean_param($param, $type) {
783 global $CFG;
785 if (is_array($param)) {
786 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
787 } else if (is_object($param)) {
788 if (method_exists($param, '__toString')) {
789 $param = $param->__toString();
790 } else {
791 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
795 switch ($type) {
796 case PARAM_RAW:
797 // No cleaning at all.
798 $param = fix_utf8($param);
799 return $param;
801 case PARAM_RAW_TRIMMED:
802 // No cleaning, but strip leading and trailing whitespace.
803 $param = fix_utf8($param);
804 return trim($param);
806 case PARAM_CLEAN:
807 // General HTML cleaning, try to use more specific type if possible this is deprecated!
808 // Please use more specific type instead.
809 if (is_numeric($param)) {
810 return $param;
812 $param = fix_utf8($param);
813 // Sweep for scripts, etc.
814 return clean_text($param);
816 case PARAM_CLEANHTML:
817 // Clean html fragment.
818 $param = fix_utf8($param);
819 // Sweep for scripts, etc.
820 $param = clean_text($param, FORMAT_HTML);
821 return trim($param);
823 case PARAM_INT:
824 // Convert to integer.
825 return (int)$param;
827 case PARAM_FLOAT:
828 // Convert to float.
829 return (float)$param;
831 case PARAM_ALPHA:
832 // Remove everything not `a-z`.
833 return preg_replace('/[^a-zA-Z]/i', '', $param);
835 case PARAM_ALPHAEXT:
836 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
837 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
839 case PARAM_ALPHANUM:
840 // Remove everything not `a-zA-Z0-9`.
841 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
843 case PARAM_ALPHANUMEXT:
844 // Remove everything not `a-zA-Z0-9_-`.
845 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
847 case PARAM_SEQUENCE:
848 // Remove everything not `0-9,`.
849 return preg_replace('/[^0-9,]/i', '', $param);
851 case PARAM_BOOL:
852 // Convert to 1 or 0.
853 $tempstr = strtolower($param);
854 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
855 $param = 1;
856 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
857 $param = 0;
858 } else {
859 $param = empty($param) ? 0 : 1;
861 return $param;
863 case PARAM_NOTAGS:
864 // Strip all tags.
865 $param = fix_utf8($param);
866 return strip_tags($param);
868 case PARAM_TEXT:
869 // Leave only tags needed for multilang.
870 $param = fix_utf8($param);
871 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
872 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
873 do {
874 if (strpos($param, '</lang>') !== false) {
875 // Old and future mutilang syntax.
876 $param = strip_tags($param, '<lang>');
877 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
878 break;
880 $open = false;
881 foreach ($matches[0] as $match) {
882 if ($match === '</lang>') {
883 if ($open) {
884 $open = false;
885 continue;
886 } else {
887 break 2;
890 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
891 break 2;
892 } else {
893 $open = true;
896 if ($open) {
897 break;
899 return $param;
901 } else if (strpos($param, '</span>') !== false) {
902 // Current problematic multilang syntax.
903 $param = strip_tags($param, '<span>');
904 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
905 break;
907 $open = false;
908 foreach ($matches[0] as $match) {
909 if ($match === '</span>') {
910 if ($open) {
911 $open = false;
912 continue;
913 } else {
914 break 2;
917 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
918 break 2;
919 } else {
920 $open = true;
923 if ($open) {
924 break;
926 return $param;
928 } while (false);
929 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
930 return strip_tags($param);
932 case PARAM_COMPONENT:
933 // We do not want any guessing here, either the name is correct or not
934 // please note only normalised component names are accepted.
935 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
936 return '';
938 if (strpos($param, '__') !== false) {
939 return '';
941 if (strpos($param, 'mod_') === 0) {
942 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
943 if (substr_count($param, '_') != 1) {
944 return '';
947 return $param;
949 case PARAM_PLUGIN:
950 case PARAM_AREA:
951 // We do not want any guessing here, either the name is correct or not.
952 if (!is_valid_plugin_name($param)) {
953 return '';
955 return $param;
957 case PARAM_SAFEDIR:
958 // Remove everything not a-zA-Z0-9_- .
959 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
961 case PARAM_SAFEPATH:
962 // Remove everything not a-zA-Z0-9/_- .
963 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
965 case PARAM_FILE:
966 // Strip all suspicious characters from filename.
967 $param = fix_utf8($param);
968 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
969 if ($param === '.' || $param === '..') {
970 $param = '';
972 return $param;
974 case PARAM_PATH:
975 // Strip all suspicious characters from file path.
976 $param = fix_utf8($param);
977 $param = str_replace('\\', '/', $param);
979 // Explode the path and clean each element using the PARAM_FILE rules.
980 $breadcrumb = explode('/', $param);
981 foreach ($breadcrumb as $key => $crumb) {
982 if ($crumb === '.' && $key === 0) {
983 // Special condition to allow for relative current path such as ./currentdirfile.txt.
984 } else {
985 $crumb = clean_param($crumb, PARAM_FILE);
987 $breadcrumb[$key] = $crumb;
989 $param = implode('/', $breadcrumb);
991 // Remove multiple current path (./././) and multiple slashes (///).
992 $param = preg_replace('~//+~', '/', $param);
993 $param = preg_replace('~/(\./)+~', '/', $param);
994 return $param;
996 case PARAM_HOST:
997 // Allow FQDN or IPv4 dotted quad.
998 $param = preg_replace('/[^\.\d\w-]/', '', $param );
999 // Match ipv4 dotted quad.
1000 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1001 // Confirm values are ok.
1002 if ( $match[0] > 255
1003 || $match[1] > 255
1004 || $match[3] > 255
1005 || $match[4] > 255 ) {
1006 // Hmmm, what kind of dotted quad is this?
1007 $param = '';
1009 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1010 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1011 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1013 // All is ok - $param is respected.
1014 } else {
1015 // All is not ok...
1016 $param='';
1018 return $param;
1020 case PARAM_URL: // Allow safe ftp, http, mailto urls.
1021 $param = fix_utf8($param);
1022 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1023 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1024 // All is ok, param is respected.
1025 } else {
1026 // Not really ok.
1027 $param ='';
1029 return $param;
1031 case PARAM_LOCALURL:
1032 // Allow http absolute, root relative and relative URLs within wwwroot.
1033 $param = clean_param($param, PARAM_URL);
1034 if (!empty($param)) {
1036 // Simulate the HTTPS version of the site.
1037 $httpswwwroot = str_replace('http://', 'https://', $CFG->wwwroot);
1039 if ($param === $CFG->wwwroot) {
1040 // Exact match;
1041 } else if (!empty($CFG->loginhttps) && $param === $httpswwwroot) {
1042 // Exact match;
1043 } else if (preg_match(':^/:', $param)) {
1044 // Root-relative, ok!
1045 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1046 // Absolute, and matches our wwwroot.
1047 } else if (!empty($CFG->loginhttps) && preg_match('/^' . preg_quote($httpswwwroot . '/', '/') . '/i', $param)) {
1048 // Absolute, and matches our httpswwwroot.
1049 } else {
1050 // Relative - let's make sure there are no tricks.
1051 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1052 // Looks ok.
1053 } else {
1054 $param = '';
1058 return $param;
1060 case PARAM_PEM:
1061 $param = trim($param);
1062 // PEM formatted strings may contain letters/numbers and the symbols:
1063 // forward slash: /
1064 // plus sign: +
1065 // equal sign: =
1066 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1067 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1068 list($wholething, $body) = $matches;
1069 unset($wholething, $matches);
1070 $b64 = clean_param($body, PARAM_BASE64);
1071 if (!empty($b64)) {
1072 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1073 } else {
1074 return '';
1077 return '';
1079 case PARAM_BASE64:
1080 if (!empty($param)) {
1081 // PEM formatted strings may contain letters/numbers and the symbols
1082 // forward slash: /
1083 // plus sign: +
1084 // equal sign: =.
1085 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1086 return '';
1088 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1089 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1090 // than (or equal to) 64 characters long.
1091 for ($i=0, $j=count($lines); $i < $j; $i++) {
1092 if ($i + 1 == $j) {
1093 if (64 < strlen($lines[$i])) {
1094 return '';
1096 continue;
1099 if (64 != strlen($lines[$i])) {
1100 return '';
1103 return implode("\n", $lines);
1104 } else {
1105 return '';
1108 case PARAM_TAG:
1109 $param = fix_utf8($param);
1110 // Please note it is not safe to use the tag name directly anywhere,
1111 // it must be processed with s(), urlencode() before embedding anywhere.
1112 // Remove some nasties.
1113 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1114 // Convert many whitespace chars into one.
1115 $param = preg_replace('/\s+/u', ' ', $param);
1116 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1117 return $param;
1119 case PARAM_TAGLIST:
1120 $param = fix_utf8($param);
1121 $tags = explode(',', $param);
1122 $result = array();
1123 foreach ($tags as $tag) {
1124 $res = clean_param($tag, PARAM_TAG);
1125 if ($res !== '') {
1126 $result[] = $res;
1129 if ($result) {
1130 return implode(',', $result);
1131 } else {
1132 return '';
1135 case PARAM_CAPABILITY:
1136 if (get_capability_info($param)) {
1137 return $param;
1138 } else {
1139 return '';
1142 case PARAM_PERMISSION:
1143 $param = (int)$param;
1144 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1145 return $param;
1146 } else {
1147 return CAP_INHERIT;
1150 case PARAM_AUTH:
1151 $param = clean_param($param, PARAM_PLUGIN);
1152 if (empty($param)) {
1153 return '';
1154 } else if (exists_auth_plugin($param)) {
1155 return $param;
1156 } else {
1157 return '';
1160 case PARAM_LANG:
1161 $param = clean_param($param, PARAM_SAFEDIR);
1162 if (get_string_manager()->translation_exists($param)) {
1163 return $param;
1164 } else {
1165 // Specified language is not installed or param malformed.
1166 return '';
1169 case PARAM_THEME:
1170 $param = clean_param($param, PARAM_PLUGIN);
1171 if (empty($param)) {
1172 return '';
1173 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1174 return $param;
1175 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1176 return $param;
1177 } else {
1178 // Specified theme is not installed.
1179 return '';
1182 case PARAM_USERNAME:
1183 $param = fix_utf8($param);
1184 $param = trim($param);
1185 // Convert uppercase to lowercase MDL-16919.
1186 $param = core_text::strtolower($param);
1187 if (empty($CFG->extendedusernamechars)) {
1188 $param = str_replace(" " , "", $param);
1189 // Regular expression, eliminate all chars EXCEPT:
1190 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1191 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1193 return $param;
1195 case PARAM_EMAIL:
1196 $param = fix_utf8($param);
1197 if (validate_email($param)) {
1198 return $param;
1199 } else {
1200 return '';
1203 case PARAM_STRINGID:
1204 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1205 return $param;
1206 } else {
1207 return '';
1210 case PARAM_TIMEZONE:
1211 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1212 $param = fix_utf8($param);
1213 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1214 if (preg_match($timezonepattern, $param)) {
1215 return $param;
1216 } else {
1217 return '';
1220 default:
1221 // Doh! throw error, switched parameters in optional_param or another serious problem.
1222 print_error("unknownparamtype", '', '', $type);
1227 * Makes sure the data is using valid utf8, invalid characters are discarded.
1229 * Note: this function is not intended for full objects with methods and private properties.
1231 * @param mixed $value
1232 * @return mixed with proper utf-8 encoding
1234 function fix_utf8($value) {
1235 if (is_null($value) or $value === '') {
1236 return $value;
1238 } else if (is_string($value)) {
1239 if ((string)(int)$value === $value) {
1240 // Shortcut.
1241 return $value;
1243 // No null bytes expected in our data, so let's remove it.
1244 $value = str_replace("\0", '', $value);
1246 // Note: this duplicates min_fix_utf8() intentionally.
1247 static $buggyiconv = null;
1248 if ($buggyiconv === null) {
1249 $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1252 if ($buggyiconv) {
1253 if (function_exists('mb_convert_encoding')) {
1254 $subst = mb_substitute_character();
1255 mb_substitute_character('');
1256 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1257 mb_substitute_character($subst);
1259 } else {
1260 // Warn admins on admin/index.php page.
1261 $result = $value;
1264 } else {
1265 $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1268 return $result;
1270 } else if (is_array($value)) {
1271 foreach ($value as $k => $v) {
1272 $value[$k] = fix_utf8($v);
1274 return $value;
1276 } else if (is_object($value)) {
1277 // Do not modify original.
1278 $value = clone($value);
1279 foreach ($value as $k => $v) {
1280 $value->$k = fix_utf8($v);
1282 return $value;
1284 } else {
1285 // This is some other type, no utf-8 here.
1286 return $value;
1291 * Return true if given value is integer or string with integer value
1293 * @param mixed $value String or Int
1294 * @return bool true if number, false if not
1296 function is_number($value) {
1297 if (is_int($value)) {
1298 return true;
1299 } else if (is_string($value)) {
1300 return ((string)(int)$value) === $value;
1301 } else {
1302 return false;
1307 * Returns host part from url.
1309 * @param string $url full url
1310 * @return string host, null if not found
1312 function get_host_from_url($url) {
1313 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1314 if ($matches) {
1315 return $matches[1];
1317 return null;
1321 * Tests whether anything was returned by text editor
1323 * This function is useful for testing whether something you got back from
1324 * the HTML editor actually contains anything. Sometimes the HTML editor
1325 * appear to be empty, but actually you get back a <br> tag or something.
1327 * @param string $string a string containing HTML.
1328 * @return boolean does the string contain any actual content - that is text,
1329 * images, objects, etc.
1331 function html_is_blank($string) {
1332 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1336 * Set a key in global configuration
1338 * Set a key/value pair in both this session's {@link $CFG} global variable
1339 * and in the 'config' database table for future sessions.
1341 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1342 * In that case it doesn't affect $CFG.
1344 * A NULL value will delete the entry.
1346 * NOTE: this function is called from lib/db/upgrade.php
1348 * @param string $name the key to set
1349 * @param string $value the value to set (without magic quotes)
1350 * @param string $plugin (optional) the plugin scope, default null
1351 * @return bool true or exception
1353 function set_config($name, $value, $plugin=null) {
1354 global $CFG, $DB;
1356 if (empty($plugin)) {
1357 if (!array_key_exists($name, $CFG->config_php_settings)) {
1358 // So it's defined for this invocation at least.
1359 if (is_null($value)) {
1360 unset($CFG->$name);
1361 } else {
1362 // Settings from db are always strings.
1363 $CFG->$name = (string)$value;
1367 if ($DB->get_field('config', 'name', array('name' => $name))) {
1368 if ($value === null) {
1369 $DB->delete_records('config', array('name' => $name));
1370 } else {
1371 $DB->set_field('config', 'value', $value, array('name' => $name));
1373 } else {
1374 if ($value !== null) {
1375 $config = new stdClass();
1376 $config->name = $name;
1377 $config->value = $value;
1378 $DB->insert_record('config', $config, false);
1381 if ($name === 'siteidentifier') {
1382 cache_helper::update_site_identifier($value);
1384 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1385 } else {
1386 // Plugin scope.
1387 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1388 if ($value===null) {
1389 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1390 } else {
1391 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1393 } else {
1394 if ($value !== null) {
1395 $config = new stdClass();
1396 $config->plugin = $plugin;
1397 $config->name = $name;
1398 $config->value = $value;
1399 $DB->insert_record('config_plugins', $config, false);
1402 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1405 return true;
1409 * Get configuration values from the global config table
1410 * or the config_plugins table.
1412 * If called with one parameter, it will load all the config
1413 * variables for one plugin, and return them as an object.
1415 * If called with 2 parameters it will return a string single
1416 * value or false if the value is not found.
1418 * NOTE: this function is called from lib/db/upgrade.php
1420 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1421 * that we need only fetch it once per request.
1422 * @param string $plugin full component name
1423 * @param string $name default null
1424 * @return mixed hash-like object or single value, return false no config found
1425 * @throws dml_exception
1427 function get_config($plugin, $name = null) {
1428 global $CFG, $DB;
1430 static $siteidentifier = null;
1432 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1433 $forced =& $CFG->config_php_settings;
1434 $iscore = true;
1435 $plugin = 'core';
1436 } else {
1437 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1438 $forced =& $CFG->forced_plugin_settings[$plugin];
1439 } else {
1440 $forced = array();
1442 $iscore = false;
1445 if ($siteidentifier === null) {
1446 try {
1447 // This may fail during installation.
1448 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1449 // install the database.
1450 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1451 } catch (dml_exception $ex) {
1452 // Set siteidentifier to false. We don't want to trip this continually.
1453 $siteidentifier = false;
1454 throw $ex;
1458 if (!empty($name)) {
1459 if (array_key_exists($name, $forced)) {
1460 return (string)$forced[$name];
1461 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1462 return $siteidentifier;
1466 $cache = cache::make('core', 'config');
1467 $result = $cache->get($plugin);
1468 if ($result === false) {
1469 // The user is after a recordset.
1470 if (!$iscore) {
1471 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1472 } else {
1473 // This part is not really used any more, but anyway...
1474 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1476 $cache->set($plugin, $result);
1479 if (!empty($name)) {
1480 if (array_key_exists($name, $result)) {
1481 return $result[$name];
1483 return false;
1486 if ($plugin === 'core') {
1487 $result['siteidentifier'] = $siteidentifier;
1490 foreach ($forced as $key => $value) {
1491 if (is_null($value) or is_array($value) or is_object($value)) {
1492 // We do not want any extra mess here, just real settings that could be saved in db.
1493 unset($result[$key]);
1494 } else {
1495 // Convert to string as if it went through the DB.
1496 $result[$key] = (string)$value;
1500 return (object)$result;
1504 * Removes a key from global configuration.
1506 * NOTE: this function is called from lib/db/upgrade.php
1508 * @param string $name the key to set
1509 * @param string $plugin (optional) the plugin scope
1510 * @return boolean whether the operation succeeded.
1512 function unset_config($name, $plugin=null) {
1513 global $CFG, $DB;
1515 if (empty($plugin)) {
1516 unset($CFG->$name);
1517 $DB->delete_records('config', array('name' => $name));
1518 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1519 } else {
1520 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1521 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1524 return true;
1528 * Remove all the config variables for a given plugin.
1530 * NOTE: this function is called from lib/db/upgrade.php
1532 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1533 * @return boolean whether the operation succeeded.
1535 function unset_all_config_for_plugin($plugin) {
1536 global $DB;
1537 // Delete from the obvious config_plugins first.
1538 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1539 // Next delete any suspect settings from config.
1540 $like = $DB->sql_like('name', '?', true, true, false, '|');
1541 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1542 $DB->delete_records_select('config', $like, $params);
1543 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1544 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1546 return true;
1550 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1552 * All users are verified if they still have the necessary capability.
1554 * @param string $value the value of the config setting.
1555 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1556 * @param bool $includeadmins include administrators.
1557 * @return array of user objects.
1559 function get_users_from_config($value, $capability, $includeadmins = true) {
1560 if (empty($value) or $value === '$@NONE@$') {
1561 return array();
1564 // We have to make sure that users still have the necessary capability,
1565 // it should be faster to fetch them all first and then test if they are present
1566 // instead of validating them one-by-one.
1567 $users = get_users_by_capability(context_system::instance(), $capability);
1568 if ($includeadmins) {
1569 $admins = get_admins();
1570 foreach ($admins as $admin) {
1571 $users[$admin->id] = $admin;
1575 if ($value === '$@ALL@$') {
1576 return $users;
1579 $result = array(); // Result in correct order.
1580 $allowed = explode(',', $value);
1581 foreach ($allowed as $uid) {
1582 if (isset($users[$uid])) {
1583 $user = $users[$uid];
1584 $result[$user->id] = $user;
1588 return $result;
1593 * Invalidates browser caches and cached data in temp.
1595 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1596 * {@link phpunit_util::reset_dataroot()}
1598 * @return void
1600 function purge_all_caches() {
1601 global $CFG, $DB;
1603 reset_text_filters_cache();
1604 js_reset_all_caches();
1605 theme_reset_all_caches();
1606 get_string_manager()->reset_caches();
1607 core_text::reset_caches();
1608 if (class_exists('core_plugin_manager')) {
1609 core_plugin_manager::reset_caches();
1612 // Bump up cacherev field for all courses.
1613 try {
1614 increment_revision_number('course', 'cacherev', '');
1615 } catch (moodle_exception $e) {
1616 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1619 $DB->reset_caches();
1620 cache_helper::purge_all();
1622 // Purge all other caches: rss, simplepie, etc.
1623 remove_dir($CFG->cachedir.'', true);
1625 // Make sure cache dir is writable, throws exception if not.
1626 make_cache_directory('');
1628 // This is the only place where we purge local caches, we are only adding files there.
1629 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1630 remove_dir($CFG->localcachedir, true);
1631 set_config('localcachedirpurged', time());
1632 make_localcache_directory('', true);
1633 \core\task\manager::clear_static_caches();
1637 * Get volatile flags
1639 * @param string $type
1640 * @param int $changedsince default null
1641 * @return array records array
1643 function get_cache_flags($type, $changedsince = null) {
1644 global $DB;
1646 $params = array('type' => $type, 'expiry' => time());
1647 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1648 if ($changedsince !== null) {
1649 $params['changedsince'] = $changedsince;
1650 $sqlwhere .= " AND timemodified > :changedsince";
1652 $cf = array();
1653 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1654 foreach ($flags as $flag) {
1655 $cf[$flag->name] = $flag->value;
1658 return $cf;
1662 * Get volatile flags
1664 * @param string $type
1665 * @param string $name
1666 * @param int $changedsince default null
1667 * @return string|false The cache flag value or false
1669 function get_cache_flag($type, $name, $changedsince=null) {
1670 global $DB;
1672 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1674 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1675 if ($changedsince !== null) {
1676 $params['changedsince'] = $changedsince;
1677 $sqlwhere .= " AND timemodified > :changedsince";
1680 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1684 * Set a volatile flag
1686 * @param string $type the "type" namespace for the key
1687 * @param string $name the key to set
1688 * @param string $value the value to set (without magic quotes) - null will remove the flag
1689 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1690 * @return bool Always returns true
1692 function set_cache_flag($type, $name, $value, $expiry = null) {
1693 global $DB;
1695 $timemodified = time();
1696 if ($expiry === null || $expiry < $timemodified) {
1697 $expiry = $timemodified + 24 * 60 * 60;
1698 } else {
1699 $expiry = (int)$expiry;
1702 if ($value === null) {
1703 unset_cache_flag($type, $name);
1704 return true;
1707 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1708 // This is a potential problem in DEBUG_DEVELOPER.
1709 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1710 return true; // No need to update.
1712 $f->value = $value;
1713 $f->expiry = $expiry;
1714 $f->timemodified = $timemodified;
1715 $DB->update_record('cache_flags', $f);
1716 } else {
1717 $f = new stdClass();
1718 $f->flagtype = $type;
1719 $f->name = $name;
1720 $f->value = $value;
1721 $f->expiry = $expiry;
1722 $f->timemodified = $timemodified;
1723 $DB->insert_record('cache_flags', $f);
1725 return true;
1729 * Removes a single volatile flag
1731 * @param string $type the "type" namespace for the key
1732 * @param string $name the key to set
1733 * @return bool
1735 function unset_cache_flag($type, $name) {
1736 global $DB;
1737 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1738 return true;
1742 * Garbage-collect volatile flags
1744 * @return bool Always returns true
1746 function gc_cache_flags() {
1747 global $DB;
1748 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1749 return true;
1752 // USER PREFERENCE API.
1755 * Refresh user preference cache. This is used most often for $USER
1756 * object that is stored in session, but it also helps with performance in cron script.
1758 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1760 * @package core
1761 * @category preference
1762 * @access public
1763 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1764 * @param int $cachelifetime Cache life time on the current page (in seconds)
1765 * @throws coding_exception
1766 * @return null
1768 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1769 global $DB;
1770 // Static cache, we need to check on each page load, not only every 2 minutes.
1771 static $loadedusers = array();
1773 if (!isset($user->id)) {
1774 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1777 if (empty($user->id) or isguestuser($user->id)) {
1778 // No permanent storage for not-logged-in users and guest.
1779 if (!isset($user->preference)) {
1780 $user->preference = array();
1782 return;
1785 $timenow = time();
1787 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1788 // Already loaded at least once on this page. Are we up to date?
1789 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1790 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1791 return;
1793 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1794 // No change since the lastcheck on this page.
1795 $user->preference['_lastloaded'] = $timenow;
1796 return;
1800 // OK, so we have to reload all preferences.
1801 $loadedusers[$user->id] = true;
1802 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1803 $user->preference['_lastloaded'] = $timenow;
1807 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1809 * NOTE: internal function, do not call from other code.
1811 * @package core
1812 * @access private
1813 * @param integer $userid the user whose prefs were changed.
1815 function mark_user_preferences_changed($userid) {
1816 global $CFG;
1818 if (empty($userid) or isguestuser($userid)) {
1819 // No cache flags for guest and not-logged-in users.
1820 return;
1823 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1827 * Sets a preference for the specified user.
1829 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1831 * @package core
1832 * @category preference
1833 * @access public
1834 * @param string $name The key to set as preference for the specified user
1835 * @param string $value The value to set for the $name key in the specified user's
1836 * record, null means delete current value.
1837 * @param stdClass|int|null $user A moodle user object or id, null means current user
1838 * @throws coding_exception
1839 * @return bool Always true or exception
1841 function set_user_preference($name, $value, $user = null) {
1842 global $USER, $DB;
1844 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1845 throw new coding_exception('Invalid preference name in set_user_preference() call');
1848 if (is_null($value)) {
1849 // Null means delete current.
1850 return unset_user_preference($name, $user);
1851 } else if (is_object($value)) {
1852 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1853 } else if (is_array($value)) {
1854 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1856 // Value column maximum length is 1333 characters.
1857 $value = (string)$value;
1858 if (core_text::strlen($value) > 1333) {
1859 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1862 if (is_null($user)) {
1863 $user = $USER;
1864 } else if (isset($user->id)) {
1865 // It is a valid object.
1866 } else if (is_numeric($user)) {
1867 $user = (object)array('id' => (int)$user);
1868 } else {
1869 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1872 check_user_preferences_loaded($user);
1874 if (empty($user->id) or isguestuser($user->id)) {
1875 // No permanent storage for not-logged-in users and guest.
1876 $user->preference[$name] = $value;
1877 return true;
1880 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1881 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1882 // Preference already set to this value.
1883 return true;
1885 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1887 } else {
1888 $preference = new stdClass();
1889 $preference->userid = $user->id;
1890 $preference->name = $name;
1891 $preference->value = $value;
1892 $DB->insert_record('user_preferences', $preference);
1895 // Update value in cache.
1896 $user->preference[$name] = $value;
1898 // Set reload flag for other sessions.
1899 mark_user_preferences_changed($user->id);
1901 return true;
1905 * Sets a whole array of preferences for the current user
1907 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1909 * @package core
1910 * @category preference
1911 * @access public
1912 * @param array $prefarray An array of key/value pairs to be set
1913 * @param stdClass|int|null $user A moodle user object or id, null means current user
1914 * @return bool Always true or exception
1916 function set_user_preferences(array $prefarray, $user = null) {
1917 foreach ($prefarray as $name => $value) {
1918 set_user_preference($name, $value, $user);
1920 return true;
1924 * Unsets a preference completely by deleting it from the database
1926 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1928 * @package core
1929 * @category preference
1930 * @access public
1931 * @param string $name The key to unset as preference for the specified user
1932 * @param stdClass|int|null $user A moodle user object or id, null means current user
1933 * @throws coding_exception
1934 * @return bool Always true or exception
1936 function unset_user_preference($name, $user = null) {
1937 global $USER, $DB;
1939 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1940 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1943 if (is_null($user)) {
1944 $user = $USER;
1945 } else if (isset($user->id)) {
1946 // It is a valid object.
1947 } else if (is_numeric($user)) {
1948 $user = (object)array('id' => (int)$user);
1949 } else {
1950 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1953 check_user_preferences_loaded($user);
1955 if (empty($user->id) or isguestuser($user->id)) {
1956 // No permanent storage for not-logged-in user and guest.
1957 unset($user->preference[$name]);
1958 return true;
1961 // Delete from DB.
1962 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1964 // Delete the preference from cache.
1965 unset($user->preference[$name]);
1967 // Set reload flag for other sessions.
1968 mark_user_preferences_changed($user->id);
1970 return true;
1974 * Used to fetch user preference(s)
1976 * If no arguments are supplied this function will return
1977 * all of the current user preferences as an array.
1979 * If a name is specified then this function
1980 * attempts to return that particular preference value. If
1981 * none is found, then the optional value $default is returned,
1982 * otherwise null.
1984 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1986 * @package core
1987 * @category preference
1988 * @access public
1989 * @param string $name Name of the key to use in finding a preference value
1990 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1991 * @param stdClass|int|null $user A moodle user object or id, null means current user
1992 * @throws coding_exception
1993 * @return string|mixed|null A string containing the value of a single preference. An
1994 * array with all of the preferences or null
1996 function get_user_preferences($name = null, $default = null, $user = null) {
1997 global $USER;
1999 if (is_null($name)) {
2000 // All prefs.
2001 } else if (is_numeric($name) or $name === '_lastloaded') {
2002 throw new coding_exception('Invalid preference name in get_user_preferences() call');
2005 if (is_null($user)) {
2006 $user = $USER;
2007 } else if (isset($user->id)) {
2008 // Is a valid object.
2009 } else if (is_numeric($user)) {
2010 $user = (object)array('id' => (int)$user);
2011 } else {
2012 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2015 check_user_preferences_loaded($user);
2017 if (empty($name)) {
2018 // All values.
2019 return $user->preference;
2020 } else if (isset($user->preference[$name])) {
2021 // The single string value.
2022 return $user->preference[$name];
2023 } else {
2024 // Default value (null if not specified).
2025 return $default;
2029 // FUNCTIONS FOR HANDLING TIME.
2032 * Given date parts in user time produce a GMT timestamp.
2034 * @package core
2035 * @category time
2036 * @param int $year The year part to create timestamp of
2037 * @param int $month The month part to create timestamp of
2038 * @param int $day The day part to create timestamp of
2039 * @param int $hour The hour part to create timestamp of
2040 * @param int $minute The minute part to create timestamp of
2041 * @param int $second The second part to create timestamp of
2042 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2043 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2044 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2045 * applied only if timezone is 99 or string.
2046 * @return int GMT timestamp
2048 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2050 // Save input timezone, required for dst offset check.
2051 $passedtimezone = $timezone;
2053 $timezone = get_user_timezone_offset($timezone);
2055 if (abs($timezone) > 13) {
2056 // Server time.
2057 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2058 } else {
2059 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2060 $time = usertime($time, $timezone);
2062 // Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
2063 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
2064 $time -= dst_offset_on($time, $passedtimezone);
2068 return $time;
2073 * Format a date/time (seconds) as weeks, days, hours etc as needed
2075 * Given an amount of time in seconds, returns string
2076 * formatted nicely as weeks, days, hours etc as needed
2078 * @package core
2079 * @category time
2080 * @uses MINSECS
2081 * @uses HOURSECS
2082 * @uses DAYSECS
2083 * @uses YEARSECS
2084 * @param int $totalsecs Time in seconds
2085 * @param stdClass $str Should be a time object
2086 * @return string A nicely formatted date/time string
2088 function format_time($totalsecs, $str = null) {
2090 $totalsecs = abs($totalsecs);
2092 if (!$str) {
2093 // Create the str structure the slow way.
2094 $str = new stdClass();
2095 $str->day = get_string('day');
2096 $str->days = get_string('days');
2097 $str->hour = get_string('hour');
2098 $str->hours = get_string('hours');
2099 $str->min = get_string('min');
2100 $str->mins = get_string('mins');
2101 $str->sec = get_string('sec');
2102 $str->secs = get_string('secs');
2103 $str->year = get_string('year');
2104 $str->years = get_string('years');
2107 $years = floor($totalsecs/YEARSECS);
2108 $remainder = $totalsecs - ($years*YEARSECS);
2109 $days = floor($remainder/DAYSECS);
2110 $remainder = $totalsecs - ($days*DAYSECS);
2111 $hours = floor($remainder/HOURSECS);
2112 $remainder = $remainder - ($hours*HOURSECS);
2113 $mins = floor($remainder/MINSECS);
2114 $secs = $remainder - ($mins*MINSECS);
2116 $ss = ($secs == 1) ? $str->sec : $str->secs;
2117 $sm = ($mins == 1) ? $str->min : $str->mins;
2118 $sh = ($hours == 1) ? $str->hour : $str->hours;
2119 $sd = ($days == 1) ? $str->day : $str->days;
2120 $sy = ($years == 1) ? $str->year : $str->years;
2122 $oyears = '';
2123 $odays = '';
2124 $ohours = '';
2125 $omins = '';
2126 $osecs = '';
2128 if ($years) {
2129 $oyears = $years .' '. $sy;
2131 if ($days) {
2132 $odays = $days .' '. $sd;
2134 if ($hours) {
2135 $ohours = $hours .' '. $sh;
2137 if ($mins) {
2138 $omins = $mins .' '. $sm;
2140 if ($secs) {
2141 $osecs = $secs .' '. $ss;
2144 if ($years) {
2145 return trim($oyears .' '. $odays);
2147 if ($days) {
2148 return trim($odays .' '. $ohours);
2150 if ($hours) {
2151 return trim($ohours .' '. $omins);
2153 if ($mins) {
2154 return trim($omins .' '. $osecs);
2156 if ($secs) {
2157 return $osecs;
2159 return get_string('now');
2163 * Returns a formatted string that represents a date in user time.
2165 * @package core
2166 * @category time
2167 * @param int $date the timestamp in UTC, as obtained from the database.
2168 * @param string $format strftime format. You should probably get this using
2169 * get_string('strftime...', 'langconfig');
2170 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2171 * not 99 then daylight saving will not be added.
2172 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2173 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2174 * If false then the leading zero is maintained.
2175 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2176 * @return string the formatted date/time.
2178 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2179 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2180 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2184 * Returns a formatted date ensuring it is UTF-8.
2186 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2187 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2189 * This function does not do any calculation regarding the user preferences and should
2190 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2191 * to differentiate the use of server time or not (strftime() against gmstrftime()).
2193 * @param int $date the timestamp.
2194 * @param string $format strftime format.
2195 * @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2196 * @return string the formatted date/time.
2197 * @since Moodle 2.3.3
2199 function date_format_string($date, $format, $tz = 99) {
2200 global $CFG;
2202 $localewincharset = null;
2203 // Get the calendar type user is using.
2204 if ($CFG->ostype == 'WINDOWS') {
2205 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2206 $localewincharset = $calendartype->locale_win_charset();
2209 if (abs($tz) > 13) {
2210 if ($localewincharset) {
2211 $format = core_text::convert($format, 'utf-8', $localewincharset);
2212 $datestring = strftime($format, $date);
2213 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2214 } else {
2215 $datestring = strftime($format, $date);
2217 } else {
2218 if ($localewincharset) {
2219 $format = core_text::convert($format, 'utf-8', $localewincharset);
2220 $datestring = gmstrftime($format, $date);
2221 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2222 } else {
2223 $datestring = gmstrftime($format, $date);
2226 return $datestring;
2230 * Given a $time timestamp in GMT (seconds since epoch),
2231 * returns an array that represents the date in user time
2233 * @package core
2234 * @category time
2235 * @uses HOURSECS
2236 * @param int $time Timestamp in GMT
2237 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2238 * dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
2239 * @return array An array that represents the date in user time
2241 function usergetdate($time, $timezone=99) {
2243 // Save input timezone, required for dst offset check.
2244 $passedtimezone = $timezone;
2246 $timezone = get_user_timezone_offset($timezone);
2248 if (abs($timezone) > 13) {
2249 // Server time.
2250 return getdate($time);
2253 // Add daylight saving offset for string timezones only, as we can't get dst for
2254 // float values. if timezone is 99 (user default timezone), then try update dst.
2255 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2256 $time += dst_offset_on($time, $passedtimezone);
2259 $time += intval((float)$timezone * HOURSECS);
2261 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2263 // Be careful to ensure the returned array matches that produced by getdate() above.
2264 list(
2265 $getdate['month'],
2266 $getdate['weekday'],
2267 $getdate['yday'],
2268 $getdate['year'],
2269 $getdate['mon'],
2270 $getdate['wday'],
2271 $getdate['mday'],
2272 $getdate['hours'],
2273 $getdate['minutes'],
2274 $getdate['seconds']
2275 ) = explode('_', $datestring);
2277 // Set correct datatype to match with getdate().
2278 $getdate['seconds'] = (int)$getdate['seconds'];
2279 $getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
2280 $getdate['year'] = (int)$getdate['year'];
2281 $getdate['mon'] = (int)$getdate['mon'];
2282 $getdate['wday'] = (int)$getdate['wday'];
2283 $getdate['mday'] = (int)$getdate['mday'];
2284 $getdate['hours'] = (int)$getdate['hours'];
2285 $getdate['minutes'] = (int)$getdate['minutes'];
2286 return $getdate;
2290 * Given a GMT timestamp (seconds since epoch), offsets it by
2291 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2293 * @package core
2294 * @category time
2295 * @uses HOURSECS
2296 * @param int $date Timestamp in GMT
2297 * @param float|int|string $timezone timezone to calculate GMT time offset before
2298 * calculating user time, 99 is default user timezone
2299 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2300 * @return int
2302 function usertime($date, $timezone=99) {
2304 $timezone = get_user_timezone_offset($timezone);
2306 if (abs($timezone) > 13) {
2307 return $date;
2309 return $date - (int)($timezone * HOURSECS);
2313 * Given a time, return the GMT timestamp of the most recent midnight
2314 * for the current user.
2316 * @package core
2317 * @category time
2318 * @param int $date Timestamp in GMT
2319 * @param float|int|string $timezone timezone to calculate GMT time offset before
2320 * calculating user midnight time, 99 is default user timezone
2321 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2322 * @return int Returns a GMT timestamp
2324 function usergetmidnight($date, $timezone=99) {
2326 $userdate = usergetdate($date, $timezone);
2328 // Time of midnight of this user's day, in GMT.
2329 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2334 * Returns a string that prints the user's timezone
2336 * @package core
2337 * @category time
2338 * @param float|int|string $timezone timezone to calculate GMT time offset before
2339 * calculating user timezone, 99 is default user timezone
2340 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2341 * @return string
2343 function usertimezone($timezone=99) {
2345 $tz = get_user_timezone($timezone);
2347 if (!is_float($tz)) {
2348 return $tz;
2351 if (abs($tz) > 13) {
2352 // Server time.
2353 return get_string('serverlocaltime');
2356 if ($tz == intval($tz)) {
2357 // Don't show .0 for whole hours.
2358 $tz = intval($tz);
2361 if ($tz == 0) {
2362 return 'UTC';
2363 } else if ($tz > 0) {
2364 return 'UTC+'.$tz;
2365 } else {
2366 return 'UTC'.$tz;
2372 * Returns a float which represents the user's timezone difference from GMT in hours
2373 * Checks various settings and picks the most dominant of those which have a value
2375 * @package core
2376 * @category time
2377 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2378 * 99 is default user timezone
2379 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2380 * @return float
2382 function get_user_timezone_offset($tz = 99) {
2383 $tz = get_user_timezone($tz);
2385 if (is_float($tz)) {
2386 return $tz;
2387 } else {
2388 $tzrecord = get_timezone_record($tz);
2389 if (empty($tzrecord)) {
2390 return 99.0;
2392 return (float)$tzrecord->gmtoff / HOURMINS;
2397 * Returns an int which represents the systems's timezone difference from GMT in seconds
2399 * @package core
2400 * @category time
2401 * @param float|int|string $tz timezone for which offset is required.
2402 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2403 * @return int|bool if found, false is timezone 99 or error
2405 function get_timezone_offset($tz) {
2406 if ($tz == 99) {
2407 return false;
2410 if (is_numeric($tz)) {
2411 return intval($tz * 60*60);
2414 if (!$tzrecord = get_timezone_record($tz)) {
2415 return false;
2417 return intval($tzrecord->gmtoff * 60);
2421 * Returns a float or a string which denotes the user's timezone
2422 * 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)
2423 * means that for this timezone there are also DST rules to be taken into account
2424 * Checks various settings and picks the most dominant of those which have a value
2426 * @package core
2427 * @category time
2428 * @param float|int|string $tz timezone to calculate GMT time offset before
2429 * calculating user timezone, 99 is default user timezone
2430 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2431 * @return float|string
2433 function get_user_timezone($tz = 99) {
2434 global $USER, $CFG;
2436 $timezones = array(
2437 $tz,
2438 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2439 isset($USER->timezone) ? $USER->timezone : 99,
2440 isset($CFG->timezone) ? $CFG->timezone : 99,
2443 $tz = 99;
2445 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2446 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2447 $tz = $next['value'];
2449 return is_numeric($tz) ? (float) $tz : $tz;
2453 * Returns cached timezone record for given $timezonename
2455 * @package core
2456 * @param string $timezonename name of the timezone
2457 * @return stdClass|bool timezonerecord or false
2459 function get_timezone_record($timezonename) {
2460 global $DB;
2461 static $cache = null;
2463 if ($cache === null) {
2464 $cache = array();
2467 if (isset($cache[$timezonename])) {
2468 return $cache[$timezonename];
2471 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2472 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2476 * Build and store the users Daylight Saving Time (DST) table
2478 * @package core
2479 * @param int $fromyear Start year for the table, defaults to 1971
2480 * @param int $toyear End year for the table, defaults to 2035
2481 * @param int|float|string $strtimezone timezone to check if dst should be applied.
2482 * @return bool
2484 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2485 global $SESSION, $DB;
2487 $usertz = get_user_timezone($strtimezone);
2489 if (is_float($usertz)) {
2490 // Trivial timezone, no DST.
2491 return false;
2494 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2495 // We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
2496 unset($SESSION->dst_offsets);
2497 unset($SESSION->dst_range);
2500 if (!empty($SESSION->dst_offsets) && empty($fromyear) && empty($toyear)) {
2501 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
2502 // This will be the return path most of the time, pretty light computationally.
2503 return true;
2506 // Reaching here means we either need to extend our table or create it from scratch.
2508 // Remember which TZ we calculated these changes for.
2509 $SESSION->dst_offsettz = $usertz;
2511 if (empty($SESSION->dst_offsets)) {
2512 // If we 're creating from scratch, put the two guard elements in there.
2513 $SESSION->dst_offsets = array(1 => null, 0 => null);
2515 if (empty($SESSION->dst_range)) {
2516 // If creating from scratch.
2517 $from = max((empty($fromyear) ? intval(date('Y')) - 3 : $fromyear), 1971);
2518 $to = min((empty($toyear) ? intval(date('Y')) + 3 : $toyear), 2035);
2520 // Fill in the array with the extra years we need to process.
2521 $yearstoprocess = array();
2522 for ($i = $from; $i <= $to; ++$i) {
2523 $yearstoprocess[] = $i;
2526 // Take note of which years we have processed for future calls.
2527 $SESSION->dst_range = array($from, $to);
2528 } else {
2529 // If needing to extend the table, do the same.
2530 $yearstoprocess = array();
2532 $from = max((empty($fromyear) ? $SESSION->dst_range[0] : $fromyear), 1971);
2533 $to = min((empty($toyear) ? $SESSION->dst_range[1] : $toyear), 2035);
2535 if ($from < $SESSION->dst_range[0]) {
2536 // Take note of which years we need to process and then note that we have processed them for future calls.
2537 for ($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2538 $yearstoprocess[] = $i;
2540 $SESSION->dst_range[0] = $from;
2542 if ($to > $SESSION->dst_range[1]) {
2543 // Take note of which years we need to process and then note that we have processed them for future calls.
2544 for ($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2545 $yearstoprocess[] = $i;
2547 $SESSION->dst_range[1] = $to;
2551 if (empty($yearstoprocess)) {
2552 // This means that there was a call requesting a SMALLER range than we have already calculated.
2553 return true;
2556 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2557 // Also, the array is sorted in descending timestamp order!
2559 // Get DB data.
2561 static $presetscache = array();
2562 if (!isset($presetscache[$usertz])) {
2563 $presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
2564 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
2565 'std_startday, std_weekday, std_skipweeks, std_time');
2567 if (empty($presetscache[$usertz])) {
2568 return false;
2571 // Remove ending guard (first element of the array).
2572 reset($SESSION->dst_offsets);
2573 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2575 // Add all required change timestamps.
2576 foreach ($yearstoprocess as $y) {
2577 // Find the record which is in effect for the year $y.
2578 foreach ($presetscache[$usertz] as $year => $preset) {
2579 if ($year <= $y) {
2580 break;
2584 $changes = dst_changes_for_year($y, $preset);
2586 if ($changes === null) {
2587 continue;
2589 if ($changes['dst'] != 0) {
2590 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2592 if ($changes['std'] != 0) {
2593 $SESSION->dst_offsets[$changes['std']] = 0;
2597 // Put in a guard element at the top.
2598 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2599 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = null; // DAYSECS is arbitrary, any "small" number will do.
2601 // Sort again.
2602 krsort($SESSION->dst_offsets);
2604 return true;
2608 * Calculates the required DST change and returns a Timestamp Array
2610 * @package core
2611 * @category time
2612 * @uses HOURSECS
2613 * @uses MINSECS
2614 * @param int|string $year Int or String Year to focus on
2615 * @param object $timezone Instatiated Timezone object
2616 * @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
2618 function dst_changes_for_year($year, $timezone) {
2620 if ($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 &&
2621 $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2622 return null;
2625 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2626 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2628 list($dsthour, $dstmin) = explode(':', $timezone->dst_time);
2629 list($stdhour, $stdmin) = explode(':', $timezone->std_time);
2631 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2632 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2634 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2635 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2636 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2638 $timedst += $dsthour * HOURSECS + $dstmin * MINSECS;
2639 $timestd += $stdhour * HOURSECS + $stdmin * MINSECS;
2641 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2645 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2646 * - Note: Daylight saving only works for string timezones and not for float.
2648 * @package core
2649 * @category time
2650 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2651 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2652 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2653 * @return int
2655 function dst_offset_on($time, $strtimezone = null) {
2656 global $SESSION;
2658 if (!calculate_user_dst_table(null, null, $strtimezone) || empty($SESSION->dst_offsets)) {
2659 return 0;
2662 reset($SESSION->dst_offsets);
2663 while (list($from, $offset) = each($SESSION->dst_offsets)) {
2664 if ($from <= $time) {
2665 break;
2669 // This is the normal return path.
2670 if ($offset !== null) {
2671 return $offset;
2674 // Reaching this point means we haven't calculated far enough, do it now:
2675 // Calculate extra DST changes if needed and recurse. The recursion always
2676 // moves toward the stopping condition, so will always end.
2678 if ($from == 0) {
2679 // We need a year smaller than $SESSION->dst_range[0].
2680 if ($SESSION->dst_range[0] == 1971) {
2681 return 0;
2683 calculate_user_dst_table($SESSION->dst_range[0] - 5, null, $strtimezone);
2684 return dst_offset_on($time, $strtimezone);
2685 } else {
2686 // We need a year larger than $SESSION->dst_range[1].
2687 if ($SESSION->dst_range[1] == 2035) {
2688 return 0;
2690 calculate_user_dst_table(null, $SESSION->dst_range[1] + 5, $strtimezone);
2691 return dst_offset_on($time, $strtimezone);
2696 * Calculates when the day appears in specific month
2698 * @package core
2699 * @category time
2700 * @param int $startday starting day of the month
2701 * @param int $weekday The day when week starts (normally taken from user preferences)
2702 * @param int $month The month whose day is sought
2703 * @param int $year The year of the month whose day is sought
2704 * @return int
2706 function find_day_in_month($startday, $weekday, $month, $year) {
2707 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2709 $daysinmonth = days_in_month($month, $year);
2710 $daysinweek = count($calendartype->get_weekdays());
2712 if ($weekday == -1) {
2713 // Don't care about weekday, so return:
2714 // abs($startday) if $startday != -1
2715 // $daysinmonth otherwise.
2716 return ($startday == -1) ? $daysinmonth : abs($startday);
2719 // From now on we 're looking for a specific weekday.
2720 // Give "end of month" its actual value, since we know it.
2721 if ($startday == -1) {
2722 $startday = -1 * $daysinmonth;
2725 // Starting from day $startday, the sign is the direction.
2726 if ($startday < 1) {
2727 $startday = abs($startday);
2728 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2730 // This is the last such weekday of the month.
2731 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2732 if ($lastinmonth > $daysinmonth) {
2733 $lastinmonth -= $daysinweek;
2736 // Find the first such weekday <= $startday.
2737 while ($lastinmonth > $startday) {
2738 $lastinmonth -= $daysinweek;
2741 return $lastinmonth;
2742 } else {
2743 $indexweekday = dayofweek($startday, $month, $year);
2745 $diff = $weekday - $indexweekday;
2746 if ($diff < 0) {
2747 $diff += $daysinweek;
2750 // This is the first such weekday of the month equal to or after $startday.
2751 $firstfromindex = $startday + $diff;
2753 return $firstfromindex;
2758 * Calculate the number of days in a given month
2760 * @package core
2761 * @category time
2762 * @param int $month The month whose day count is sought
2763 * @param int $year The year of the month whose day count is sought
2764 * @return int
2766 function days_in_month($month, $year) {
2767 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2768 return $calendartype->get_num_days_in_month($year, $month);
2772 * Calculate the position in the week of a specific calendar day
2774 * @package core
2775 * @category time
2776 * @param int $day The day of the date whose position in the week is sought
2777 * @param int $month The month of the date whose position in the week is sought
2778 * @param int $year The year of the date whose position in the week is sought
2779 * @return int
2781 function dayofweek($day, $month, $year) {
2782 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2783 return $calendartype->get_weekday($year, $month, $day);
2786 // USER AUTHENTICATION AND LOGIN.
2789 * Returns full login url.
2791 * @return string login url
2793 function get_login_url() {
2794 global $CFG;
2796 $url = "$CFG->wwwroot/login/index.php";
2798 if (!empty($CFG->loginhttps)) {
2799 $url = str_replace('http:', 'https:', $url);
2802 return $url;
2806 * This function checks that the current user is logged in and has the
2807 * required privileges
2809 * This function checks that the current user is logged in, and optionally
2810 * whether they are allowed to be in a particular course and view a particular
2811 * course module.
2812 * If they are not logged in, then it redirects them to the site login unless
2813 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2814 * case they are automatically logged in as guests.
2815 * If $courseid is given and the user is not enrolled in that course then the
2816 * user is redirected to the course enrolment page.
2817 * If $cm is given and the course module is hidden and the user is not a teacher
2818 * in the course then the user is redirected to the course home page.
2820 * When $cm parameter specified, this function sets page layout to 'module'.
2821 * You need to change it manually later if some other layout needed.
2823 * @package core_access
2824 * @category access
2826 * @param mixed $courseorid id of the course or course object
2827 * @param bool $autologinguest default true
2828 * @param object $cm course module object
2829 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2830 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2831 * in order to keep redirects working properly. MDL-14495
2832 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2833 * @return mixed Void, exit, and die depending on path
2834 * @throws coding_exception
2835 * @throws require_login_exception
2837 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2838 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2840 // Must not redirect when byteserving already started.
2841 if (!empty($_SERVER['HTTP_RANGE'])) {
2842 $preventredirect = true;
2845 if (AJAX_SCRIPT) {
2846 // We cannot redirect for AJAX scripts either.
2847 $preventredirect = true;
2850 // Setup global $COURSE, themes, language and locale.
2851 if (!empty($courseorid)) {
2852 if (is_object($courseorid)) {
2853 $course = $courseorid;
2854 } else if ($courseorid == SITEID) {
2855 $course = clone($SITE);
2856 } else {
2857 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2859 if ($cm) {
2860 if ($cm->course != $course->id) {
2861 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2863 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2864 if (!($cm instanceof cm_info)) {
2865 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2866 // db queries so this is not really a performance concern, however it is obviously
2867 // better if you use get_fast_modinfo to get the cm before calling this.
2868 $modinfo = get_fast_modinfo($course);
2869 $cm = $modinfo->get_cm($cm->id);
2872 } else {
2873 // Do not touch global $COURSE via $PAGE->set_course(),
2874 // the reasons is we need to be able to call require_login() at any time!!
2875 $course = $SITE;
2876 if ($cm) {
2877 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2881 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2882 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2883 // risk leading the user back to the AJAX request URL.
2884 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2885 $setwantsurltome = false;
2888 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2889 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2890 if ($preventredirect) {
2891 throw new require_login_session_timeout_exception();
2892 } else {
2893 if ($setwantsurltome) {
2894 $SESSION->wantsurl = qualified_me();
2896 redirect(get_login_url());
2900 // If the user is not even logged in yet then make sure they are.
2901 if (!isloggedin()) {
2902 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2903 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2904 // Misconfigured site guest, just redirect to login page.
2905 redirect(get_login_url());
2906 exit; // Never reached.
2908 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2909 complete_user_login($guest);
2910 $USER->autologinguest = true;
2911 $SESSION->lang = $lang;
2912 } else {
2913 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2914 if ($preventredirect) {
2915 throw new require_login_exception('You are not logged in');
2918 if ($setwantsurltome) {
2919 $SESSION->wantsurl = qualified_me();
2922 $referer = get_local_referer(false);
2923 if (!empty($referer)) {
2924 $SESSION->fromurl = $referer;
2926 redirect(get_login_url());
2927 exit; // Never reached.
2931 // Loginas as redirection if needed.
2932 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2933 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2934 if ($USER->loginascontext->instanceid != $course->id) {
2935 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2940 // Check whether the user should be changing password (but only if it is REALLY them).
2941 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2942 $userauth = get_auth_plugin($USER->auth);
2943 if ($userauth->can_change_password() and !$preventredirect) {
2944 if ($setwantsurltome) {
2945 $SESSION->wantsurl = qualified_me();
2947 if ($changeurl = $userauth->change_password_url()) {
2948 // Use plugin custom url.
2949 redirect($changeurl);
2950 } else {
2951 // Use moodle internal method.
2952 if (empty($CFG->loginhttps)) {
2953 redirect($CFG->wwwroot .'/login/change_password.php');
2954 } else {
2955 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2956 redirect($wwwroot .'/login/change_password.php');
2959 } else {
2960 print_error('nopasswordchangeforced', 'auth');
2964 // Check that the user account is properly set up.
2965 if (user_not_fully_set_up($USER)) {
2966 if ($preventredirect) {
2967 throw new require_login_exception('User not fully set-up');
2969 if ($setwantsurltome) {
2970 $SESSION->wantsurl = qualified_me();
2972 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2975 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2976 sesskey();
2978 // Do not bother admins with any formalities.
2979 if (is_siteadmin()) {
2980 // Set the global $COURSE.
2981 if ($cm) {
2982 $PAGE->set_cm($cm, $course);
2983 $PAGE->set_pagelayout('incourse');
2984 } else if (!empty($courseorid)) {
2985 $PAGE->set_course($course);
2987 // Set accesstime or the user will appear offline which messes up messaging.
2988 user_accesstime_log($course->id);
2989 return;
2992 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2993 if (!$USER->policyagreed and !is_siteadmin()) {
2994 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2995 if ($preventredirect) {
2996 throw new require_login_exception('Policy not agreed');
2998 if ($setwantsurltome) {
2999 $SESSION->wantsurl = qualified_me();
3001 redirect($CFG->wwwroot .'/user/policy.php');
3002 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
3003 if ($preventredirect) {
3004 throw new require_login_exception('Policy not agreed');
3006 if ($setwantsurltome) {
3007 $SESSION->wantsurl = qualified_me();
3009 redirect($CFG->wwwroot .'/user/policy.php');
3013 // Fetch the system context, the course context, and prefetch its child contexts.
3014 $sysctx = context_system::instance();
3015 $coursecontext = context_course::instance($course->id, MUST_EXIST);
3016 if ($cm) {
3017 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
3018 } else {
3019 $cmcontext = null;
3022 // If the site is currently under maintenance, then print a message.
3023 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
3024 if ($preventredirect) {
3025 throw new require_login_exception('Maintenance in progress');
3028 print_maintenance_message();
3031 // Make sure the course itself is not hidden.
3032 if ($course->id == SITEID) {
3033 // Frontpage can not be hidden.
3034 } else {
3035 if (is_role_switched($course->id)) {
3036 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
3037 } else {
3038 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3039 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
3040 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
3041 if ($preventredirect) {
3042 throw new require_login_exception('Course is hidden');
3044 $PAGE->set_context(null);
3045 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3046 // the navigation will mess up when trying to find it.
3047 navigation_node::override_active_url(new moodle_url('/'));
3048 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3053 // Is the user enrolled?
3054 if ($course->id == SITEID) {
3055 // Everybody is enrolled on the frontpage.
3056 } else {
3057 if (\core\session\manager::is_loggedinas()) {
3058 // Make sure the REAL person can access this course first.
3059 $realuser = \core\session\manager::get_realuser();
3060 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
3061 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
3062 if ($preventredirect) {
3063 throw new require_login_exception('Invalid course login-as access');
3065 $PAGE->set_context(null);
3066 echo $OUTPUT->header();
3067 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
3071 $access = false;
3073 if (is_role_switched($course->id)) {
3074 // Ok, user had to be inside this course before the switch.
3075 $access = true;
3077 } else if (is_viewing($coursecontext, $USER)) {
3078 // Ok, no need to mess with enrol.
3079 $access = true;
3081 } else {
3082 if (isset($USER->enrol['enrolled'][$course->id])) {
3083 if ($USER->enrol['enrolled'][$course->id] > time()) {
3084 $access = true;
3085 if (isset($USER->enrol['tempguest'][$course->id])) {
3086 unset($USER->enrol['tempguest'][$course->id]);
3087 remove_temp_course_roles($coursecontext);
3089 } else {
3090 // Expired.
3091 unset($USER->enrol['enrolled'][$course->id]);
3094 if (isset($USER->enrol['tempguest'][$course->id])) {
3095 if ($USER->enrol['tempguest'][$course->id] == 0) {
3096 $access = true;
3097 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3098 $access = true;
3099 } else {
3100 // Expired.
3101 unset($USER->enrol['tempguest'][$course->id]);
3102 remove_temp_course_roles($coursecontext);
3106 if (!$access) {
3107 // Cache not ok.
3108 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3109 if ($until !== false) {
3110 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3111 if ($until == 0) {
3112 $until = ENROL_MAX_TIMESTAMP;
3114 $USER->enrol['enrolled'][$course->id] = $until;
3115 $access = true;
3117 } else {
3118 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3119 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3120 $enrols = enrol_get_plugins(true);
3121 // First ask all enabled enrol instances in course if they want to auto enrol user.
3122 foreach ($instances as $instance) {
3123 if (!isset($enrols[$instance->enrol])) {
3124 continue;
3126 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3127 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3128 if ($until !== false) {
3129 if ($until == 0) {
3130 $until = ENROL_MAX_TIMESTAMP;
3132 $USER->enrol['enrolled'][$course->id] = $until;
3133 $access = true;
3134 break;
3137 // If not enrolled yet try to gain temporary guest access.
3138 if (!$access) {
3139 foreach ($instances as $instance) {
3140 if (!isset($enrols[$instance->enrol])) {
3141 continue;
3143 // Get a duration for the guest access, a timestamp in the future or false.
3144 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3145 if ($until !== false and $until > time()) {
3146 $USER->enrol['tempguest'][$course->id] = $until;
3147 $access = true;
3148 break;
3156 if (!$access) {
3157 if ($preventredirect) {
3158 throw new require_login_exception('Not enrolled');
3160 if ($setwantsurltome) {
3161 $SESSION->wantsurl = qualified_me();
3163 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3167 // Set the global $COURSE.
3168 // TODO MDL-49434: setting current course/cm should be after the check $cm->uservisible .
3169 if ($cm) {
3170 $PAGE->set_cm($cm, $course);
3171 $PAGE->set_pagelayout('incourse');
3172 } else if (!empty($courseorid)) {
3173 $PAGE->set_course($course);
3176 // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3177 if ($cm && !$cm->uservisible) {
3178 if ($preventredirect) {
3179 throw new require_login_exception('Activity is hidden');
3181 if ($course->id != SITEID) {
3182 $url = new moodle_url('/course/view.php', array('id' => $course->id));
3183 } else {
3184 $url = new moodle_url('/');
3186 redirect($url, get_string('activityiscurrentlyhidden'));
3189 // Finally access granted, update lastaccess times.
3190 user_accesstime_log($course->id);
3195 * This function just makes sure a user is logged out.
3197 * @package core_access
3198 * @category access
3200 function require_logout() {
3201 global $USER, $DB;
3203 if (!isloggedin()) {
3204 // This should not happen often, no need for hooks or events here.
3205 \core\session\manager::terminate_current();
3206 return;
3209 // Execute hooks before action.
3210 $authplugins = array();
3211 $authsequence = get_enabled_auth_plugins();
3212 foreach ($authsequence as $authname) {
3213 $authplugins[$authname] = get_auth_plugin($authname);
3214 $authplugins[$authname]->prelogout_hook();
3217 // Store info that gets removed during logout.
3218 $sid = session_id();
3219 $event = \core\event\user_loggedout::create(
3220 array(
3221 'userid' => $USER->id,
3222 'objectid' => $USER->id,
3223 'other' => array('sessionid' => $sid),
3226 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3227 $event->add_record_snapshot('sessions', $session);
3230 // Clone of $USER object to be used by auth plugins.
3231 $user = fullclone($USER);
3233 // Delete session record and drop $_SESSION content.
3234 \core\session\manager::terminate_current();
3236 // Trigger event AFTER action.
3237 $event->trigger();
3239 // Hook to execute auth plugins redirection after event trigger.
3240 foreach ($authplugins as $authplugin) {
3241 $authplugin->postlogout_hook($user);
3246 * Weaker version of require_login()
3248 * This is a weaker version of {@link require_login()} which only requires login
3249 * when called from within a course rather than the site page, unless
3250 * the forcelogin option is turned on.
3251 * @see require_login()
3253 * @package core_access
3254 * @category access
3256 * @param mixed $courseorid The course object or id in question
3257 * @param bool $autologinguest Allow autologin guests if that is wanted
3258 * @param object $cm Course activity module if known
3259 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3260 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3261 * in order to keep redirects working properly. MDL-14495
3262 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3263 * @return void
3264 * @throws coding_exception
3266 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3267 global $CFG, $PAGE, $SITE;
3268 $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3269 or (!is_object($courseorid) and $courseorid == SITEID));
3270 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3271 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3272 // db queries so this is not really a performance concern, however it is obviously
3273 // better if you use get_fast_modinfo to get the cm before calling this.
3274 if (is_object($courseorid)) {
3275 $course = $courseorid;
3276 } else {
3277 $course = clone($SITE);
3279 $modinfo = get_fast_modinfo($course);
3280 $cm = $modinfo->get_cm($cm->id);
3282 if (!empty($CFG->forcelogin)) {
3283 // Login required for both SITE and courses.
3284 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3286 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3287 // Always login for hidden activities.
3288 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3290 } else if ($issite) {
3291 // Login for SITE not required.
3292 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3293 if (!empty($courseorid)) {
3294 if (is_object($courseorid)) {
3295 $course = $courseorid;
3296 } else {
3297 $course = clone $SITE;
3299 if ($cm) {
3300 if ($cm->course != $course->id) {
3301 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3303 $PAGE->set_cm($cm, $course);
3304 $PAGE->set_pagelayout('incourse');
3305 } else {
3306 $PAGE->set_course($course);
3308 } else {
3309 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3310 $PAGE->set_course($PAGE->course);
3312 user_accesstime_log(SITEID);
3313 return;
3315 } else {
3316 // Course login always required.
3317 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3322 * Require key login. Function terminates with error if key not found or incorrect.
3324 * @uses NO_MOODLE_COOKIES
3325 * @uses PARAM_ALPHANUM
3326 * @param string $script unique script identifier
3327 * @param int $instance optional instance id
3328 * @return int Instance ID
3330 function require_user_key_login($script, $instance=null) {
3331 global $DB;
3333 if (!NO_MOODLE_COOKIES) {
3334 print_error('sessioncookiesdisable');
3337 // Extra safety.
3338 \core\session\manager::write_close();
3340 $keyvalue = required_param('key', PARAM_ALPHANUM);
3342 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3343 print_error('invalidkey');
3346 if (!empty($key->validuntil) and $key->validuntil < time()) {
3347 print_error('expiredkey');
3350 if ($key->iprestriction) {
3351 $remoteaddr = getremoteaddr(null);
3352 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3353 print_error('ipmismatch');
3357 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3358 print_error('invaliduserid');
3361 // Emulate normal session.
3362 enrol_check_plugins($user);
3363 \core\session\manager::set_user($user);
3365 // Note we are not using normal login.
3366 if (!defined('USER_KEY_LOGIN')) {
3367 define('USER_KEY_LOGIN', true);
3370 // Return instance id - it might be empty.
3371 return $key->instance;
3375 * Creates a new private user access key.
3377 * @param string $script unique target identifier
3378 * @param int $userid
3379 * @param int $instance optional instance id
3380 * @param string $iprestriction optional ip restricted access
3381 * @param timestamp $validuntil key valid only until given data
3382 * @return string access key value
3384 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3385 global $DB;
3387 $key = new stdClass();
3388 $key->script = $script;
3389 $key->userid = $userid;
3390 $key->instance = $instance;
3391 $key->iprestriction = $iprestriction;
3392 $key->validuntil = $validuntil;
3393 $key->timecreated = time();
3395 // Something long and unique.
3396 $key->value = md5($userid.'_'.time().random_string(40));
3397 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3398 // Must be unique.
3399 $key->value = md5($userid.'_'.time().random_string(40));
3401 $DB->insert_record('user_private_key', $key);
3402 return $key->value;
3406 * Delete the user's new private user access keys for a particular script.
3408 * @param string $script unique target identifier
3409 * @param int $userid
3410 * @return void
3412 function delete_user_key($script, $userid) {
3413 global $DB;
3414 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3418 * Gets a private user access key (and creates one if one doesn't exist).
3420 * @param string $script unique target identifier
3421 * @param int $userid
3422 * @param int $instance optional instance id
3423 * @param string $iprestriction optional ip restricted access
3424 * @param timestamp $validuntil key valid only until given data
3425 * @return string access key value
3427 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3428 global $DB;
3430 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3431 'instance' => $instance, 'iprestriction' => $iprestriction,
3432 'validuntil' => $validuntil))) {
3433 return $key->value;
3434 } else {
3435 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3441 * Modify the user table by setting the currently logged in user's last login to now.
3443 * @return bool Always returns true
3445 function update_user_login_times() {
3446 global $USER, $DB;
3448 if (isguestuser()) {
3449 // Do not update guest access times/ips for performance.
3450 return true;
3453 $now = time();
3455 $user = new stdClass();
3456 $user->id = $USER->id;
3458 // Make sure all users that logged in have some firstaccess.
3459 if ($USER->firstaccess == 0) {
3460 $USER->firstaccess = $user->firstaccess = $now;
3463 // Store the previous current as lastlogin.
3464 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3466 $USER->currentlogin = $user->currentlogin = $now;
3468 // Function user_accesstime_log() may not update immediately, better do it here.
3469 $USER->lastaccess = $user->lastaccess = $now;
3470 $USER->lastip = $user->lastip = getremoteaddr();
3472 // Note: do not call user_update_user() here because this is part of the login process,
3473 // the login event means that these fields were updated.
3474 $DB->update_record('user', $user);
3475 return true;
3479 * Determines if a user has completed setting up their account.
3481 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3482 * @return bool
3484 function user_not_fully_set_up($user) {
3485 if (isguestuser($user)) {
3486 return false;
3488 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3492 * Check whether the user has exceeded the bounce threshold
3494 * @param stdClass $user A {@link $USER} object
3495 * @return bool true => User has exceeded bounce threshold
3497 function over_bounce_threshold($user) {
3498 global $CFG, $DB;
3500 if (empty($CFG->handlebounces)) {
3501 return false;
3504 if (empty($user->id)) {
3505 // No real (DB) user, nothing to do here.
3506 return false;
3509 // Set sensible defaults.
3510 if (empty($CFG->minbounces)) {
3511 $CFG->minbounces = 10;
3513 if (empty($CFG->bounceratio)) {
3514 $CFG->bounceratio = .20;
3516 $bouncecount = 0;
3517 $sendcount = 0;
3518 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3519 $bouncecount = $bounce->value;
3521 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3522 $sendcount = $send->value;
3524 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3528 * Used to increment or reset email sent count
3530 * @param stdClass $user object containing an id
3531 * @param bool $reset will reset the count to 0
3532 * @return void
3534 function set_send_count($user, $reset=false) {
3535 global $DB;
3537 if (empty($user->id)) {
3538 // No real (DB) user, nothing to do here.
3539 return;
3542 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3543 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3544 $DB->update_record('user_preferences', $pref);
3545 } else if (!empty($reset)) {
3546 // If it's not there and we're resetting, don't bother. Make a new one.
3547 $pref = new stdClass();
3548 $pref->name = 'email_send_count';
3549 $pref->value = 1;
3550 $pref->userid = $user->id;
3551 $DB->insert_record('user_preferences', $pref, false);
3556 * Increment or reset user's email bounce count
3558 * @param stdClass $user object containing an id
3559 * @param bool $reset will reset the count to 0
3561 function set_bounce_count($user, $reset=false) {
3562 global $DB;
3564 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3565 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3566 $DB->update_record('user_preferences', $pref);
3567 } else if (!empty($reset)) {
3568 // If it's not there and we're resetting, don't bother. Make a new one.
3569 $pref = new stdClass();
3570 $pref->name = 'email_bounce_count';
3571 $pref->value = 1;
3572 $pref->userid = $user->id;
3573 $DB->insert_record('user_preferences', $pref, false);
3578 * Determines if the logged in user is currently moving an activity
3580 * @param int $courseid The id of the course being tested
3581 * @return bool
3583 function ismoving($courseid) {
3584 global $USER;
3586 if (!empty($USER->activitycopy)) {
3587 return ($USER->activitycopycourse == $courseid);
3589 return false;
3593 * Returns a persons full name
3595 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3596 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3597 * specify one.
3599 * @param stdClass $user A {@link $USER} object to get full name of.
3600 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3601 * @return string
3603 function fullname($user, $override=false) {
3604 global $CFG, $SESSION;
3606 if (!isset($user->firstname) and !isset($user->lastname)) {
3607 return '';
3610 // Get all of the name fields.
3611 $allnames = get_all_user_name_fields();
3612 if ($CFG->debugdeveloper) {
3613 foreach ($allnames as $allname) {
3614 if (!array_key_exists($allname, $user)) {
3615 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3616 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3617 // Message has been sent, no point in sending the message multiple times.
3618 break;
3623 if (!$override) {
3624 if (!empty($CFG->forcefirstname)) {
3625 $user->firstname = $CFG->forcefirstname;
3627 if (!empty($CFG->forcelastname)) {
3628 $user->lastname = $CFG->forcelastname;
3632 if (!empty($SESSION->fullnamedisplay)) {
3633 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3636 $template = null;
3637 // If the fullnamedisplay setting is available, set the template to that.
3638 if (isset($CFG->fullnamedisplay)) {
3639 $template = $CFG->fullnamedisplay;
3641 // If the template is empty, or set to language, return the language string.
3642 if ((empty($template) || $template == 'language') && !$override) {
3643 return get_string('fullnamedisplay', null, $user);
3646 // Check to see if we are displaying according to the alternative full name format.
3647 if ($override) {
3648 if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3649 // Default to show just the user names according to the fullnamedisplay string.
3650 return get_string('fullnamedisplay', null, $user);
3651 } else {
3652 // If the override is true, then change the template to use the complete name.
3653 $template = $CFG->alternativefullnameformat;
3657 $requirednames = array();
3658 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3659 foreach ($allnames as $allname) {
3660 if (strpos($template, $allname) !== false) {
3661 $requirednames[] = $allname;
3665 $displayname = $template;
3666 // Switch in the actual data into the template.
3667 foreach ($requirednames as $altname) {
3668 if (isset($user->$altname)) {
3669 // Using empty() on the below if statement causes breakages.
3670 if ((string)$user->$altname == '') {
3671 $displayname = str_replace($altname, 'EMPTY', $displayname);
3672 } else {
3673 $displayname = str_replace($altname, $user->$altname, $displayname);
3675 } else {
3676 $displayname = str_replace($altname, 'EMPTY', $displayname);
3679 // Tidy up any misc. characters (Not perfect, but gets most characters).
3680 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3681 // katakana and parenthesis.
3682 $patterns = array();
3683 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3684 // filled in by a user.
3685 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3686 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3687 // This regular expression is to remove any double spaces in the display name.
3688 $patterns[] = '/\s{2,}/u';
3689 foreach ($patterns as $pattern) {
3690 $displayname = preg_replace($pattern, ' ', $displayname);
3693 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3694 $displayname = trim($displayname);
3695 if (empty($displayname)) {
3696 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3697 // people in general feel is a good setting to fall back on.
3698 $displayname = $user->firstname;
3700 return $displayname;
3704 * A centralised location for the all name fields. Returns an array / sql string snippet.
3706 * @param bool $returnsql True for an sql select field snippet.
3707 * @param string $tableprefix table query prefix to use in front of each field.
3708 * @param string $prefix prefix added to the name fields e.g. authorfirstname.
3709 * @param string $fieldprefix sql field prefix e.g. id AS userid.
3710 * @param bool $order moves firstname and lastname to the top of the array / start of the string.
3711 * @return array|string All name fields.
3713 function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null, $order = false) {
3714 // This array is provided in this order because when called by fullname() (above) if firstname is before
3715 // firstnamephonetic str_replace() will change the wrong placeholder.
3716 $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
3717 'lastnamephonetic' => 'lastnamephonetic',
3718 'middlename' => 'middlename',
3719 'alternatename' => 'alternatename',
3720 'firstname' => 'firstname',
3721 'lastname' => 'lastname');
3723 // Let's add a prefix to the array of user name fields if provided.
3724 if ($prefix) {
3725 foreach ($alternatenames as $key => $altname) {
3726 $alternatenames[$key] = $prefix . $altname;
3730 // If we want the end result to have firstname and lastname at the front / top of the result.
3731 if ($order) {
3732 // Move the last two elements (firstname, lastname) off the array and put them at the top.
3733 for ($i = 0; $i < 2; $i++) {
3734 // Get the last element.
3735 $lastelement = end($alternatenames);
3736 // Remove it from the array.
3737 unset($alternatenames[$lastelement]);
3738 // Put the element back on the top of the array.
3739 $alternatenames = array_merge(array($lastelement => $lastelement), $alternatenames);
3743 // Create an sql field snippet if requested.
3744 if ($returnsql) {
3745 if ($tableprefix) {
3746 if ($fieldprefix) {
3747 foreach ($alternatenames as $key => $altname) {
3748 $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
3750 } else {
3751 foreach ($alternatenames as $key => $altname) {
3752 $alternatenames[$key] = $tableprefix . '.' . $altname;
3756 $alternatenames = implode(',', $alternatenames);
3758 return $alternatenames;
3762 * Reduces lines of duplicated code for getting user name fields.
3764 * See also {@link user_picture::unalias()}
3766 * @param object $addtoobject Object to add user name fields to.
3767 * @param object $secondobject Object that contains user name field information.
3768 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3769 * @param array $additionalfields Additional fields to be matched with data in the second object.
3770 * The key can be set to the user table field name.
3771 * @return object User name fields.
3773 function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3774 $fields = get_all_user_name_fields(false, null, $prefix);
3775 if ($additionalfields) {
3776 // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3777 // the key is a number and then sets the key to the array value.
3778 foreach ($additionalfields as $key => $value) {
3779 if (is_numeric($key)) {
3780 $additionalfields[$value] = $prefix . $value;
3781 unset($additionalfields[$key]);
3782 } else {
3783 $additionalfields[$key] = $prefix . $value;
3786 $fields = array_merge($fields, $additionalfields);
3788 foreach ($fields as $key => $field) {
3789 // Important that we have all of the user name fields present in the object that we are sending back.
3790 $addtoobject->$key = '';
3791 if (isset($secondobject->$field)) {
3792 $addtoobject->$key = $secondobject->$field;
3795 return $addtoobject;
3799 * Returns an array of values in order of occurance in a provided string.
3800 * The key in the result is the character postion in the string.
3802 * @param array $values Values to be found in the string format
3803 * @param string $stringformat The string which may contain values being searched for.
3804 * @return array An array of values in order according to placement in the string format.
3806 function order_in_string($values, $stringformat) {
3807 $valuearray = array();
3808 foreach ($values as $value) {
3809 $pattern = "/$value\b/";
3810 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3811 if (preg_match($pattern, $stringformat)) {
3812 $replacement = "thing";
3813 // Replace the value with something more unique to ensure we get the right position when using strpos().
3814 $newformat = preg_replace($pattern, $replacement, $stringformat);
3815 $position = strpos($newformat, $replacement);
3816 $valuearray[$position] = $value;
3819 ksort($valuearray);
3820 return $valuearray;
3824 * Checks if current user is shown any extra fields when listing users.
3826 * @param object $context Context
3827 * @param array $already Array of fields that we're going to show anyway
3828 * so don't bother listing them
3829 * @return array Array of field names from user table, not including anything
3830 * listed in $already
3832 function get_extra_user_fields($context, $already = array()) {
3833 global $CFG;
3835 // Only users with permission get the extra fields.
3836 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3837 return array();
3840 // Split showuseridentity on comma.
3841 if (empty($CFG->showuseridentity)) {
3842 // Explode gives wrong result with empty string.
3843 $extra = array();
3844 } else {
3845 $extra = explode(',', $CFG->showuseridentity);
3847 $renumber = false;
3848 foreach ($extra as $key => $field) {
3849 if (in_array($field, $already)) {
3850 unset($extra[$key]);
3851 $renumber = true;
3854 if ($renumber) {
3855 // For consistency, if entries are removed from array, renumber it
3856 // so they are numbered as you would expect.
3857 $extra = array_merge($extra);
3859 return $extra;
3863 * If the current user is to be shown extra user fields when listing or
3864 * selecting users, returns a string suitable for including in an SQL select
3865 * clause to retrieve those fields.
3867 * @param context $context Context
3868 * @param string $alias Alias of user table, e.g. 'u' (default none)
3869 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3870 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3871 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3873 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3874 $fields = get_extra_user_fields($context, $already);
3875 $result = '';
3876 // Add punctuation for alias.
3877 if ($alias !== '') {
3878 $alias .= '.';
3880 foreach ($fields as $field) {
3881 $result .= ', ' . $alias . $field;
3882 if ($prefix) {
3883 $result .= ' AS ' . $prefix . $field;
3886 return $result;
3890 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3891 * @param string $field Field name, e.g. 'phone1'
3892 * @return string Text description taken from language file, e.g. 'Phone number'
3894 function get_user_field_name($field) {
3895 // Some fields have language strings which are not the same as field name.
3896 switch ($field) {
3897 case 'phone1' : {
3898 return get_string('phone');
3900 case 'url' : {
3901 return get_string('webpage');
3903 case 'icq' : {
3904 return get_string('icqnumber');
3906 case 'skype' : {
3907 return get_string('skypeid');
3909 case 'aim' : {
3910 return get_string('aimid');
3912 case 'yahoo' : {
3913 return get_string('yahooid');
3915 case 'msn' : {
3916 return get_string('msnid');
3919 // Otherwise just use the same lang string.
3920 return get_string($field);
3924 * Returns whether a given authentication plugin exists.
3926 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3927 * @return boolean Whether the plugin is available.
3929 function exists_auth_plugin($auth) {
3930 global $CFG;
3932 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3933 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3935 return false;
3939 * Checks if a given plugin is in the list of enabled authentication plugins.
3941 * @param string $auth Authentication plugin.
3942 * @return boolean Whether the plugin is enabled.
3944 function is_enabled_auth($auth) {
3945 if (empty($auth)) {
3946 return false;
3949 $enabled = get_enabled_auth_plugins();
3951 return in_array($auth, $enabled);
3955 * Returns an authentication plugin instance.
3957 * @param string $auth name of authentication plugin
3958 * @return auth_plugin_base An instance of the required authentication plugin.
3960 function get_auth_plugin($auth) {
3961 global $CFG;
3963 // Check the plugin exists first.
3964 if (! exists_auth_plugin($auth)) {
3965 print_error('authpluginnotfound', 'debug', '', $auth);
3968 // Return auth plugin instance.
3969 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3970 $class = "auth_plugin_$auth";
3971 return new $class;
3975 * Returns array of active auth plugins.
3977 * @param bool $fix fix $CFG->auth if needed
3978 * @return array
3980 function get_enabled_auth_plugins($fix=false) {
3981 global $CFG;
3983 $default = array('manual', 'nologin');
3985 if (empty($CFG->auth)) {
3986 $auths = array();
3987 } else {
3988 $auths = explode(',', $CFG->auth);
3991 if ($fix) {
3992 $auths = array_unique($auths);
3993 foreach ($auths as $k => $authname) {
3994 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3995 unset($auths[$k]);
3998 $newconfig = implode(',', $auths);
3999 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
4000 set_config('auth', $newconfig);
4004 return (array_merge($default, $auths));
4008 * Returns true if an internal authentication method is being used.
4009 * if method not specified then, global default is assumed
4011 * @param string $auth Form of authentication required
4012 * @return bool
4014 function is_internal_auth($auth) {
4015 // Throws error if bad $auth.
4016 $authplugin = get_auth_plugin($auth);
4017 return $authplugin->is_internal();
4021 * Returns true if the user is a 'restored' one.
4023 * Used in the login process to inform the user and allow him/her to reset the password
4025 * @param string $username username to be checked
4026 * @return bool
4028 function is_restored_user($username) {
4029 global $CFG, $DB;
4031 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
4035 * Returns an array of user fields
4037 * @return array User field/column names
4039 function get_user_fieldnames() {
4040 global $DB;
4042 $fieldarray = $DB->get_columns('user');
4043 unset($fieldarray['id']);
4044 $fieldarray = array_keys($fieldarray);
4046 return $fieldarray;
4050 * Creates a bare-bones user record
4052 * @todo Outline auth types and provide code example
4054 * @param string $username New user's username to add to record
4055 * @param string $password New user's password to add to record
4056 * @param string $auth Form of authentication required
4057 * @return stdClass A complete user object
4059 function create_user_record($username, $password, $auth = 'manual') {
4060 global $CFG, $DB;
4061 require_once($CFG->dirroot.'/user/profile/lib.php');
4062 require_once($CFG->dirroot.'/user/lib.php');
4064 // Just in case check text case.
4065 $username = trim(core_text::strtolower($username));
4067 $authplugin = get_auth_plugin($auth);
4068 $customfields = $authplugin->get_custom_user_profile_fields();
4069 $newuser = new stdClass();
4070 if ($newinfo = $authplugin->get_userinfo($username)) {
4071 $newinfo = truncate_userinfo($newinfo);
4072 foreach ($newinfo as $key => $value) {
4073 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
4074 $newuser->$key = $value;
4079 if (!empty($newuser->email)) {
4080 if (email_is_not_allowed($newuser->email)) {
4081 unset($newuser->email);
4085 if (!isset($newuser->city)) {
4086 $newuser->city = '';
4089 $newuser->auth = $auth;
4090 $newuser->username = $username;
4092 // Fix for MDL-8480
4093 // user CFG lang for user if $newuser->lang is empty
4094 // or $user->lang is not an installed language.
4095 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
4096 $newuser->lang = $CFG->lang;
4098 $newuser->confirmed = 1;
4099 $newuser->lastip = getremoteaddr();
4100 $newuser->timecreated = time();
4101 $newuser->timemodified = $newuser->timecreated;
4102 $newuser->mnethostid = $CFG->mnet_localhost_id;
4104 $newuser->id = user_create_user($newuser, false, false);
4106 // Save user profile data.
4107 profile_save_data($newuser);
4109 $user = get_complete_user_data('id', $newuser->id);
4110 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
4111 set_user_preference('auth_forcepasswordchange', 1, $user);
4113 // Set the password.
4114 update_internal_user_password($user, $password);
4116 // Trigger event.
4117 \core\event\user_created::create_from_userid($newuser->id)->trigger();
4119 return $user;
4123 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4125 * @param string $username user's username to update the record
4126 * @return stdClass A complete user object
4128 function update_user_record($username) {
4129 global $DB, $CFG;
4130 // Just in case check text case.
4131 $username = trim(core_text::strtolower($username));
4133 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
4134 return update_user_record_by_id($oldinfo->id);
4138 * Will update a local user record from an external source (MNET users can not be updated using this method!).
4140 * @param int $id user id
4141 * @return stdClass A complete user object
4143 function update_user_record_by_id($id) {
4144 global $DB, $CFG;
4145 require_once($CFG->dirroot."/user/profile/lib.php");
4146 require_once($CFG->dirroot.'/user/lib.php');
4148 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
4149 $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
4151 $newuser = array();
4152 $userauth = get_auth_plugin($oldinfo->auth);
4154 if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
4155 $newinfo = truncate_userinfo($newinfo);
4156 $customfields = $userauth->get_custom_user_profile_fields();
4158 foreach ($newinfo as $key => $value) {
4159 $key = strtolower($key);
4160 $iscustom = in_array($key, $customfields);
4161 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4162 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4163 // Unknown or must not be changed.
4164 continue;
4166 $confval = $userauth->config->{'field_updatelocal_' . $key};
4167 $lockval = $userauth->config->{'field_lock_' . $key};
4168 if (empty($confval) || empty($lockval)) {
4169 continue;
4171 if ($confval === 'onlogin') {
4172 // MDL-4207 Don't overwrite modified user profile values with
4173 // empty LDAP values when 'unlocked if empty' is set. The purpose
4174 // of the setting 'unlocked if empty' is to allow the user to fill
4175 // in a value for the selected field _if LDAP is giving
4176 // nothing_ for this field. Thus it makes sense to let this value
4177 // stand in until LDAP is giving a value for this field.
4178 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4179 if ($iscustom || (in_array($key, $userauth->userfields) &&
4180 ((string)$oldinfo->$key !== (string)$value))) {
4181 $newuser[$key] = (string)$value;
4186 if ($newuser) {
4187 $newuser['id'] = $oldinfo->id;
4188 $newuser['timemodified'] = time();
4189 user_update_user((object) $newuser, false, false);
4191 // Save user profile data.
4192 profile_save_data((object) $newuser);
4194 // Trigger event.
4195 \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4199 return get_complete_user_data('id', $oldinfo->id);
4203 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4205 * @param array $info Array of user properties to truncate if needed
4206 * @return array The now truncated information that was passed in
4208 function truncate_userinfo(array $info) {
4209 // Define the limits.
4210 $limit = array(
4211 'username' => 100,
4212 'idnumber' => 255,
4213 'firstname' => 100,
4214 'lastname' => 100,
4215 'email' => 100,
4216 'icq' => 15,
4217 'phone1' => 20,
4218 'phone2' => 20,
4219 'institution' => 255,
4220 'department' => 255,
4221 'address' => 255,
4222 'city' => 120,
4223 'country' => 2,
4224 'url' => 255,
4227 // Apply where needed.
4228 foreach (array_keys($info) as $key) {
4229 if (!empty($limit[$key])) {
4230 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4234 return $info;
4238 * Marks user deleted in internal user database and notifies the auth plugin.
4239 * Also unenrols user from all roles and does other cleanup.
4241 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4243 * @param stdClass $user full user object before delete
4244 * @return boolean success
4245 * @throws coding_exception if invalid $user parameter detected
4247 function delete_user(stdClass $user) {
4248 global $CFG, $DB;
4249 require_once($CFG->libdir.'/grouplib.php');
4250 require_once($CFG->libdir.'/gradelib.php');
4251 require_once($CFG->dirroot.'/message/lib.php');
4252 require_once($CFG->dirroot.'/tag/lib.php');
4253 require_once($CFG->dirroot.'/user/lib.php');
4255 // Make sure nobody sends bogus record type as parameter.
4256 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4257 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4260 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4261 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4262 debugging('Attempt to delete unknown user account.');
4263 return false;
4266 // There must be always exactly one guest record, originally the guest account was identified by username only,
4267 // now we use $CFG->siteguest for performance reasons.
4268 if ($user->username === 'guest' or isguestuser($user)) {
4269 debugging('Guest user account can not be deleted.');
4270 return false;
4273 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4274 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4275 if ($user->auth === 'manual' and is_siteadmin($user)) {
4276 debugging('Local administrator accounts can not be deleted.');
4277 return false;
4280 // Keep user record before updating it, as we have to pass this to user_deleted event.
4281 $olduser = clone $user;
4283 // Keep a copy of user context, we need it for event.
4284 $usercontext = context_user::instance($user->id);
4286 // Delete all grades - backup is kept in grade_grades_history table.
4287 grade_user_delete($user->id);
4289 // Move unread messages from this user to read.
4290 message_move_userfrom_unread2read($user->id);
4292 // TODO: remove from cohorts using standard API here.
4294 // Remove user tags.
4295 tag_set('user', $user->id, array(), 'core', $usercontext->id);
4297 // Unconditionally unenrol from all courses.
4298 enrol_user_delete($user);
4300 // Unenrol from all roles in all contexts.
4301 // This might be slow but it is really needed - modules might do some extra cleanup!
4302 role_unassign_all(array('userid' => $user->id));
4304 // Now do a brute force cleanup.
4306 // Remove from all cohorts.
4307 $DB->delete_records('cohort_members', array('userid' => $user->id));
4309 // Remove from all groups.
4310 $DB->delete_records('groups_members', array('userid' => $user->id));
4312 // Brute force unenrol from all courses.
4313 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4315 // Purge user preferences.
4316 $DB->delete_records('user_preferences', array('userid' => $user->id));
4318 // Purge user extra profile info.
4319 $DB->delete_records('user_info_data', array('userid' => $user->id));
4321 // Last course access not necessary either.
4322 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4323 // Remove all user tokens.
4324 $DB->delete_records('external_tokens', array('userid' => $user->id));
4326 // Unauthorise the user for all services.
4327 $DB->delete_records('external_services_users', array('userid' => $user->id));
4329 // Remove users private keys.
4330 $DB->delete_records('user_private_key', array('userid' => $user->id));
4332 // Remove users customised pages.
4333 $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4335 // Force logout - may fail if file based sessions used, sorry.
4336 \core\session\manager::kill_user_sessions($user->id);
4338 // Generate username from email address, or a fake email.
4339 $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4340 $delname = clean_param($delemail . "." . time(), PARAM_USERNAME);
4342 // Workaround for bulk deletes of users with the same email address.
4343 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4344 $delname++;
4347 // Mark internal user record as "deleted".
4348 $updateuser = new stdClass();
4349 $updateuser->id = $user->id;
4350 $updateuser->deleted = 1;
4351 $updateuser->username = $delname; // Remember it just in case.
4352 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4353 $updateuser->idnumber = ''; // Clear this field to free it up.
4354 $updateuser->picture = 0;
4355 $updateuser->timemodified = time();
4357 // Don't trigger update event, as user is being deleted.
4358 user_update_user($updateuser, false, false);
4360 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4361 context_helper::delete_instance(CONTEXT_USER, $user->id);
4363 // Any plugin that needs to cleanup should register this event.
4364 // Trigger event.
4365 $event = \core\event\user_deleted::create(
4366 array(
4367 'objectid' => $user->id,
4368 'relateduserid' => $user->id,
4369 'context' => $usercontext,
4370 'other' => array(
4371 'username' => $user->username,
4372 'email' => $user->email,
4373 'idnumber' => $user->idnumber,
4374 'picture' => $user->picture,
4375 'mnethostid' => $user->mnethostid
4379 $event->add_record_snapshot('user', $olduser);
4380 $event->trigger();
4382 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4383 // should know about this updated property persisted to the user's table.
4384 $user->timemodified = $updateuser->timemodified;
4386 // Notify auth plugin - do not block the delete even when plugin fails.
4387 $authplugin = get_auth_plugin($user->auth);
4388 $authplugin->user_delete($user);
4390 return true;
4394 * Retrieve the guest user object.
4396 * @return stdClass A {@link $USER} object
4398 function guest_user() {
4399 global $CFG, $DB;
4401 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4402 $newuser->confirmed = 1;
4403 $newuser->lang = $CFG->lang;
4404 $newuser->lastip = getremoteaddr();
4407 return $newuser;
4411 * Authenticates a user against the chosen authentication mechanism
4413 * Given a username and password, this function looks them
4414 * up using the currently selected authentication mechanism,
4415 * and if the authentication is successful, it returns a
4416 * valid $user object from the 'user' table.
4418 * Uses auth_ functions from the currently active auth module
4420 * After authenticate_user_login() returns success, you will need to
4421 * log that the user has logged in, and call complete_user_login() to set
4422 * the session up.
4424 * Note: this function works only with non-mnet accounts!
4426 * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
4427 * @param string $password User's password
4428 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4429 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4430 * @return stdClass|false A {@link $USER} object or false if error
4432 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4433 global $CFG, $DB;
4434 require_once("$CFG->libdir/authlib.php");
4436 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4437 // we have found the user
4439 } else if (!empty($CFG->authloginviaemail)) {
4440 if ($email = clean_param($username, PARAM_EMAIL)) {
4441 $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4442 $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4443 $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4444 if (count($users) === 1) {
4445 // Use email for login only if unique.
4446 $user = reset($users);
4447 $user = get_complete_user_data('id', $user->id);
4448 $username = $user->username;
4450 unset($users);
4454 $authsenabled = get_enabled_auth_plugins();
4456 if ($user) {
4457 // Use manual if auth not set.
4458 $auth = empty($user->auth) ? 'manual' : $user->auth;
4459 if (!empty($user->suspended)) {
4460 $failurereason = AUTH_LOGIN_SUSPENDED;
4462 // Trigger login failed event.
4463 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4464 'other' => array('username' => $username, 'reason' => $failurereason)));
4465 $event->trigger();
4466 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4467 return false;
4469 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4470 // Legacy way to suspend user.
4471 $failurereason = AUTH_LOGIN_SUSPENDED;
4473 // Trigger login failed event.
4474 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4475 'other' => array('username' => $username, 'reason' => $failurereason)));
4476 $event->trigger();
4477 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4478 return false;
4480 $auths = array($auth);
4482 } else {
4483 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4484 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4485 $failurereason = AUTH_LOGIN_NOUSER;
4487 // Trigger login failed event.
4488 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4489 'reason' => $failurereason)));
4490 $event->trigger();
4491 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4492 return false;
4495 // User does not exist.
4496 $auths = $authsenabled;
4497 $user = new stdClass();
4498 $user->id = 0;
4501 if ($ignorelockout) {
4502 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4503 // or this function is called from a SSO script.
4504 } else if ($user->id) {
4505 // Verify login lockout after other ways that may prevent user login.
4506 if (login_is_lockedout($user)) {
4507 $failurereason = AUTH_LOGIN_LOCKOUT;
4509 // Trigger login failed event.
4510 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4511 'other' => array('username' => $username, 'reason' => $failurereason)));
4512 $event->trigger();
4514 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4515 return false;
4517 } else {
4518 // We can not lockout non-existing accounts.
4521 foreach ($auths as $auth) {
4522 $authplugin = get_auth_plugin($auth);
4524 // On auth fail fall through to the next plugin.
4525 if (!$authplugin->user_login($username, $password)) {
4526 continue;
4529 // Successful authentication.
4530 if ($user->id) {
4531 // User already exists in database.
4532 if (empty($user->auth)) {
4533 // For some reason auth isn't set yet.
4534 $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4535 $user->auth = $auth;
4538 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4539 // the current hash algorithm while we have access to the user's password.
4540 update_internal_user_password($user, $password);
4542 if ($authplugin->is_synchronised_with_external()) {
4543 // Update user record from external DB.
4544 $user = update_user_record_by_id($user->id);
4546 } else {
4547 // The user is authenticated but user creation may be disabled.
4548 if (!empty($CFG->authpreventaccountcreation)) {
4549 $failurereason = AUTH_LOGIN_UNAUTHORISED;
4551 // Trigger login failed event.
4552 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4553 'reason' => $failurereason)));
4554 $event->trigger();
4556 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
4557 $_SERVER['HTTP_USER_AGENT']);
4558 return false;
4559 } else {
4560 $user = create_user_record($username, $password, $auth);
4564 $authplugin->sync_roles($user);
4566 foreach ($authsenabled as $hau) {
4567 $hauth = get_auth_plugin($hau);
4568 $hauth->user_authenticated_hook($user, $username, $password);
4571 if (empty($user->id)) {
4572 $failurereason = AUTH_LOGIN_NOUSER;
4573 // Trigger login failed event.
4574 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4575 'reason' => $failurereason)));
4576 $event->trigger();
4577 return false;
4580 if (!empty($user->suspended)) {
4581 // Just in case some auth plugin suspended account.
4582 $failurereason = AUTH_LOGIN_SUSPENDED;
4583 // Trigger login failed event.
4584 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4585 'other' => array('username' => $username, 'reason' => $failurereason)));
4586 $event->trigger();
4587 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4588 return false;
4591 login_attempt_valid($user);
4592 $failurereason = AUTH_LOGIN_OK;
4593 return $user;
4596 // Failed if all the plugins have failed.
4597 if (debugging('', DEBUG_ALL)) {
4598 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4601 if ($user->id) {
4602 login_attempt_failed($user);
4603 $failurereason = AUTH_LOGIN_FAILED;
4604 // Trigger login failed event.
4605 $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4606 'other' => array('username' => $username, 'reason' => $failurereason)));
4607 $event->trigger();
4608 } else {
4609 $failurereason = AUTH_LOGIN_NOUSER;
4610 // Trigger login failed event.
4611 $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4612 'reason' => $failurereason)));
4613 $event->trigger();
4616 return false;
4620 * Call to complete the user login process after authenticate_user_login()
4621 * has succeeded. It will setup the $USER variable and other required bits
4622 * and pieces.
4624 * NOTE:
4625 * - It will NOT log anything -- up to the caller to decide what to log.
4626 * - this function does not set any cookies any more!
4628 * @param stdClass $user
4629 * @return stdClass A {@link $USER} object - BC only, do not use
4631 function complete_user_login($user) {
4632 global $CFG, $USER;
4634 \core\session\manager::login_user($user);
4636 // Reload preferences from DB.
4637 unset($USER->preference);
4638 check_user_preferences_loaded($USER);
4640 // Update login times.
4641 update_user_login_times();
4643 // Extra session prefs init.
4644 set_login_session_preferences();
4646 // Trigger login event.
4647 $event = \core\event\user_loggedin::create(
4648 array(
4649 'userid' => $USER->id,
4650 'objectid' => $USER->id,
4651 'other' => array('username' => $USER->username),
4654 $event->trigger();
4656 if (isguestuser()) {
4657 // No need to continue when user is THE guest.
4658 return $USER;
4661 if (CLI_SCRIPT) {
4662 // We can redirect to password change URL only in browser.
4663 return $USER;
4666 // Select password change url.
4667 $userauth = get_auth_plugin($USER->auth);
4669 // Check whether the user should be changing password.
4670 if (get_user_preferences('auth_forcepasswordchange', false)) {
4671 if ($userauth->can_change_password()) {
4672 if ($changeurl = $userauth->change_password_url()) {
4673 redirect($changeurl);
4674 } else {
4675 redirect($CFG->httpswwwroot.'/login/change_password.php');
4677 } else {
4678 print_error('nopasswordchangeforced', 'auth');
4681 return $USER;
4685 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4687 * @param string $password String to check.
4688 * @return boolean True if the $password matches the format of an md5 sum.
4690 function password_is_legacy_hash($password) {
4691 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4695 * Compare password against hash stored in user object to determine if it is valid.
4697 * If necessary it also updates the stored hash to the current format.
4699 * @param stdClass $user (Password property may be updated).
4700 * @param string $password Plain text password.
4701 * @return bool True if password is valid.
4703 function validate_internal_user_password($user, $password) {
4704 global $CFG;
4705 require_once($CFG->libdir.'/password_compat/lib/password.php');
4707 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4708 // Internal password is not used at all, it can not validate.
4709 return false;
4712 // If hash isn't a legacy (md5) hash, validate using the library function.
4713 if (!password_is_legacy_hash($user->password)) {
4714 return password_verify($password, $user->password);
4717 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4718 // is valid we can then update it to the new algorithm.
4720 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4721 $validated = false;
4723 if ($user->password === md5($password.$sitesalt)
4724 or $user->password === md5($password)
4725 or $user->password === md5(addslashes($password).$sitesalt)
4726 or $user->password === md5(addslashes($password))) {
4727 // Note: we are intentionally using the addslashes() here because we
4728 // need to accept old password hashes of passwords with magic quotes.
4729 $validated = true;
4731 } else {
4732 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4733 $alt = 'passwordsaltalt'.$i;
4734 if (!empty($CFG->$alt)) {
4735 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4736 $validated = true;
4737 break;
4743 if ($validated) {
4744 // If the password matches the existing md5 hash, update to the
4745 // current hash algorithm while we have access to the user's password.
4746 update_internal_user_password($user, $password);
4749 return $validated;
4753 * Calculate hash for a plain text password.
4755 * @param string $password Plain text password to be hashed.
4756 * @param bool $fasthash If true, use a low cost factor when generating the hash
4757 * This is much faster to generate but makes the hash
4758 * less secure. It is used when lots of hashes need to
4759 * be generated quickly.
4760 * @return string The hashed password.
4762 * @throws moodle_exception If a problem occurs while generating the hash.
4764 function hash_internal_user_password($password, $fasthash = false) {
4765 global $CFG;
4766 require_once($CFG->libdir.'/password_compat/lib/password.php');
4768 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4769 $options = ($fasthash) ? array('cost' => 4) : array();
4771 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4773 if ($generatedhash === false || $generatedhash === null) {
4774 throw new moodle_exception('Failed to generate password hash.');
4777 return $generatedhash;
4781 * Update password hash in user object (if necessary).
4783 * The password is updated if:
4784 * 1. The password has changed (the hash of $user->password is different
4785 * to the hash of $password).
4786 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4787 * md5 algorithm).
4789 * Updating the password will modify the $user object and the database
4790 * record to use the current hashing algorithm.
4792 * @param stdClass $user User object (password property may be updated).
4793 * @param string $password Plain text password.
4794 * @param bool $fasthash If true, use a low cost factor when generating the hash
4795 * This is much faster to generate but makes the hash
4796 * less secure. It is used when lots of hashes need to
4797 * be generated quickly.
4798 * @return bool Always returns true.
4800 function update_internal_user_password($user, $password, $fasthash = false) {
4801 global $CFG, $DB;
4802 require_once($CFG->libdir.'/password_compat/lib/password.php');
4804 // Figure out what the hashed password should be.
4805 if (!isset($user->auth)) {
4806 debugging('User record in update_internal_user_password() must include field auth',
4807 DEBUG_DEVELOPER);
4808 $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4810 $authplugin = get_auth_plugin($user->auth);
4811 if ($authplugin->prevent_local_passwords()) {
4812 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4813 } else {
4814 $hashedpassword = hash_internal_user_password($password, $fasthash);
4817 $algorithmchanged = false;
4819 if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4820 // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4821 $passwordchanged = ($user->password !== $hashedpassword);
4823 } else if (isset($user->password)) {
4824 // If verification fails then it means the password has changed.
4825 $passwordchanged = !password_verify($password, $user->password);
4826 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4827 } else {
4828 // While creating new user, password in unset in $user object, to avoid
4829 // saving it with user_create()
4830 $passwordchanged = true;
4833 if ($passwordchanged || $algorithmchanged) {
4834 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4835 $user->password = $hashedpassword;
4837 // Trigger event.
4838 $user = $DB->get_record('user', array('id' => $user->id));
4839 \core\event\user_password_updated::create_from_user($user)->trigger();
4842 return true;
4846 * Get a complete user record, which includes all the info in the user record.
4848 * Intended for setting as $USER session variable
4850 * @param string $field The user field to be checked for a given value.
4851 * @param string $value The value to match for $field.
4852 * @param int $mnethostid
4853 * @return mixed False, or A {@link $USER} object.
4855 function get_complete_user_data($field, $value, $mnethostid = null) {
4856 global $CFG, $DB;
4858 if (!$field || !$value) {
4859 return false;
4862 // Build the WHERE clause for an SQL query.
4863 $params = array('fieldval' => $value);
4864 $constraints = "$field = :fieldval AND deleted <> 1";
4866 // If we are loading user data based on anything other than id,
4867 // we must also restrict our search based on mnet host.
4868 if ($field != 'id') {
4869 if (empty($mnethostid)) {
4870 // If empty, we restrict to local users.
4871 $mnethostid = $CFG->mnet_localhost_id;
4874 if (!empty($mnethostid)) {
4875 $params['mnethostid'] = $mnethostid;
4876 $constraints .= " AND mnethostid = :mnethostid";
4879 // Get all the basic user data.
4880 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4881 return false;
4884 // Get various settings and preferences.
4886 // Preload preference cache.
4887 check_user_preferences_loaded($user);
4889 // Load course enrolment related stuff.
4890 $user->lastcourseaccess = array(); // During last session.
4891 $user->currentcourseaccess = array(); // During current session.
4892 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4893 foreach ($lastaccesses as $lastaccess) {
4894 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4898 $sql = "SELECT g.id, g.courseid
4899 FROM {groups} g, {groups_members} gm
4900 WHERE gm.groupid=g.id AND gm.userid=?";
4902 // This is a special hack to speedup calendar display.
4903 $user->groupmember = array();
4904 if (!isguestuser($user)) {
4905 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4906 foreach ($groups as $group) {
4907 if (!array_key_exists($group->courseid, $user->groupmember)) {
4908 $user->groupmember[$group->courseid] = array();
4910 $user->groupmember[$group->courseid][$group->id] = $group->id;
4915 // Add the custom profile fields to the user record.
4916 $user->profile = array();
4917 if (!isguestuser($user)) {
4918 require_once($CFG->dirroot.'/user/profile/lib.php');
4919 profile_load_custom_fields($user);
4922 // Rewrite some variables if necessary.
4923 if (!empty($user->description)) {
4924 // No need to cart all of it around.
4925 $user->description = true;
4927 if (isguestuser($user)) {
4928 // Guest language always same as site.
4929 $user->lang = $CFG->lang;
4930 // Name always in current language.
4931 $user->firstname = get_string('guestuser');
4932 $user->lastname = ' ';
4935 return $user;
4939 * Validate a password against the configured password policy
4941 * @param string $password the password to be checked against the password policy
4942 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4943 * @return bool true if the password is valid according to the policy. false otherwise.
4945 function check_password_policy($password, &$errmsg) {
4946 global $CFG;
4948 if (empty($CFG->passwordpolicy)) {
4949 return true;
4952 $errmsg = '';
4953 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4954 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4957 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4958 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4961 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4962 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4965 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4966 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4969 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4970 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4972 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4973 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4976 if ($errmsg == '') {
4977 return true;
4978 } else {
4979 return false;
4985 * When logging in, this function is run to set certain preferences for the current SESSION.
4987 function set_login_session_preferences() {
4988 global $SESSION;
4990 $SESSION->justloggedin = true;
4992 unset($SESSION->lang);
4993 unset($SESSION->forcelang);
4994 unset($SESSION->load_navigation_admin);
4999 * Delete a course, including all related data from the database, and any associated files.
5001 * @param mixed $courseorid The id of the course or course object to delete.
5002 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5003 * @return bool true if all the removals succeeded. false if there were any failures. If this
5004 * method returns false, some of the removals will probably have succeeded, and others
5005 * failed, but you have no way of knowing which.
5007 function delete_course($courseorid, $showfeedback = true) {
5008 global $DB;
5010 if (is_object($courseorid)) {
5011 $courseid = $courseorid->id;
5012 $course = $courseorid;
5013 } else {
5014 $courseid = $courseorid;
5015 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5016 return false;
5019 $context = context_course::instance($courseid);
5021 // Frontpage course can not be deleted!!
5022 if ($courseid == SITEID) {
5023 return false;
5026 // Make the course completely empty.
5027 remove_course_contents($courseid, $showfeedback);
5029 // Delete the course and related context instance.
5030 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5032 $DB->delete_records("course", array("id" => $courseid));
5033 $DB->delete_records("course_format_options", array("courseid" => $courseid));
5035 // Reset all course related caches here.
5036 if (class_exists('format_base', false)) {
5037 format_base::reset_course_cache($courseid);
5040 // Trigger a course deleted event.
5041 $event = \core\event\course_deleted::create(array(
5042 'objectid' => $course->id,
5043 'context' => $context,
5044 'other' => array(
5045 'shortname' => $course->shortname,
5046 'fullname' => $course->fullname,
5047 'idnumber' => $course->idnumber
5050 $event->add_record_snapshot('course', $course);
5051 $event->trigger();
5053 return true;
5057 * Clear a course out completely, deleting all content but don't delete the course itself.
5059 * This function does not verify any permissions.
5061 * Please note this function also deletes all user enrolments,
5062 * enrolment instances and role assignments by default.
5064 * $options:
5065 * - 'keep_roles_and_enrolments' - false by default
5066 * - 'keep_groups_and_groupings' - false by default
5068 * @param int $courseid The id of the course that is being deleted
5069 * @param bool $showfeedback Whether to display notifications of each action the function performs.
5070 * @param array $options extra options
5071 * @return bool true if all the removals succeeded. false if there were any failures. If this
5072 * method returns false, some of the removals will probably have succeeded, and others
5073 * failed, but you have no way of knowing which.
5075 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5076 global $CFG, $DB, $OUTPUT;
5078 require_once($CFG->libdir.'/badgeslib.php');
5079 require_once($CFG->libdir.'/completionlib.php');
5080 require_once($CFG->libdir.'/questionlib.php');
5081 require_once($CFG->libdir.'/gradelib.php');
5082 require_once($CFG->dirroot.'/group/lib.php');
5083 require_once($CFG->dirroot.'/tag/coursetagslib.php');
5084 require_once($CFG->dirroot.'/comment/lib.php');
5085 require_once($CFG->dirroot.'/rating/lib.php');
5086 require_once($CFG->dirroot.'/notes/lib.php');
5088 // Handle course badges.
5089 badges_handle_course_deletion($courseid);
5091 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5092 $strdeleted = get_string('deleted').' - ';
5094 // Some crazy wishlist of stuff we should skip during purging of course content.
5095 $options = (array)$options;
5097 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5098 $coursecontext = context_course::instance($courseid);
5099 $fs = get_file_storage();
5101 // Delete course completion information, this has to be done before grades and enrols.
5102 $cc = new completion_info($course);
5103 $cc->clear_criteria();
5104 if ($showfeedback) {
5105 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5108 // Remove all data from gradebook - this needs to be done before course modules
5109 // because while deleting this information, the system may need to reference
5110 // the course modules that own the grades.
5111 remove_course_grades($courseid, $showfeedback);
5112 remove_grade_letters($coursecontext, $showfeedback);
5114 // Delete course blocks in any all child contexts,
5115 // they may depend on modules so delete them first.
5116 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5117 foreach ($childcontexts as $childcontext) {
5118 blocks_delete_all_for_context($childcontext->id);
5120 unset($childcontexts);
5121 blocks_delete_all_for_context($coursecontext->id);
5122 if ($showfeedback) {
5123 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5126 // Delete every instance of every module,
5127 // this has to be done before deleting of course level stuff.
5128 $locations = core_component::get_plugin_list('mod');
5129 foreach ($locations as $modname => $moddir) {
5130 if ($modname === 'NEWMODULE') {
5131 continue;
5133 if ($module = $DB->get_record('modules', array('name' => $modname))) {
5134 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
5135 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
5136 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
5138 if ($instances = $DB->get_records($modname, array('course' => $course->id))) {
5139 foreach ($instances as $instance) {
5140 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
5141 // Delete activity context questions and question categories.
5142 question_delete_activity($cm, $showfeedback);
5144 if (function_exists($moddelete)) {
5145 // This purges all module data in related tables, extra user prefs, settings, etc.
5146 $moddelete($instance->id);
5147 } else {
5148 // NOTE: we should not allow installation of modules with missing delete support!
5149 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5150 $DB->delete_records($modname, array('id' => $instance->id));
5153 if ($cm) {
5154 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5155 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5156 $DB->delete_records('course_modules', array('id' => $cm->id));
5160 if (function_exists($moddeletecourse)) {
5161 // Execute ptional course cleanup callback.
5162 $moddeletecourse($course, $showfeedback);
5164 if ($instances and $showfeedback) {
5165 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5167 } else {
5168 // Ooops, this module is not properly installed, force-delete it in the next block.
5172 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5174 // Remove all data from availability and completion tables that is associated
5175 // with course-modules belonging to this course. Note this is done even if the
5176 // features are not enabled now, in case they were enabled previously.
5177 $DB->delete_records_select('course_modules_completion',
5178 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5179 array($courseid));
5181 // Remove course-module data.
5182 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5183 foreach ($cms as $cm) {
5184 if ($module = $DB->get_record('modules', array('id' => $cm->module))) {
5185 try {
5186 $DB->delete_records($module->name, array('id' => $cm->instance));
5187 } catch (Exception $e) {
5188 // Ignore weird or missing table problems.
5191 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5192 $DB->delete_records('course_modules', array('id' => $cm->id));
5195 if ($showfeedback) {
5196 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5199 // Cleanup the rest of plugins.
5200 $cleanuplugintypes = array('report', 'coursereport', 'format');
5201 foreach ($cleanuplugintypes as $type) {
5202 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
5203 foreach ($plugins as $plugin => $pluginfunction) {
5204 $pluginfunction($course->id, $showfeedback);
5206 if ($showfeedback) {
5207 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5211 // Delete questions and question categories.
5212 question_delete_course($course, $showfeedback);
5213 if ($showfeedback) {
5214 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5217 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5218 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5219 foreach ($childcontexts as $childcontext) {
5220 $childcontext->delete();
5222 unset($childcontexts);
5224 // Remove all roles and enrolments by default.
5225 if (empty($options['keep_roles_and_enrolments'])) {
5226 // This hack is used in restore when deleting contents of existing course.
5227 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5228 enrol_course_delete($course);
5229 if ($showfeedback) {
5230 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5234 // Delete any groups, removing members and grouping/course links first.
5235 if (empty($options['keep_groups_and_groupings'])) {
5236 groups_delete_groupings($course->id, $showfeedback);
5237 groups_delete_groups($course->id, $showfeedback);
5240 // Filters be gone!
5241 filter_delete_all_for_context($coursecontext->id);
5243 // Notes, you shall not pass!
5244 note_delete_all($course->id);
5246 // Die comments!
5247 comment::delete_comments($coursecontext->id);
5249 // Ratings are history too.
5250 $delopt = new stdclass();
5251 $delopt->contextid = $coursecontext->id;
5252 $rm = new rating_manager();
5253 $rm->delete_ratings($delopt);
5255 // Delete course tags.
5256 coursetag_delete_course_tags($course->id, $showfeedback);
5258 // Delete calendar events.
5259 $DB->delete_records('event', array('courseid' => $course->id));
5260 $fs->delete_area_files($coursecontext->id, 'calendar');
5262 // Delete all related records in other core tables that may have a courseid
5263 // This array stores the tables that need to be cleared, as
5264 // table_name => column_name that contains the course id.
5265 $tablestoclear = array(
5266 'backup_courses' => 'courseid', // Scheduled backup stuff.
5267 'user_lastaccess' => 'courseid', // User access info.
5269 foreach ($tablestoclear as $table => $col) {
5270 $DB->delete_records($table, array($col => $course->id));
5273 // Delete all course backup files.
5274 $fs->delete_area_files($coursecontext->id, 'backup');
5276 // Cleanup course record - remove links to deleted stuff.
5277 $oldcourse = new stdClass();
5278 $oldcourse->id = $course->id;
5279 $oldcourse->summary = '';
5280 $oldcourse->cacherev = 0;
5281 $oldcourse->legacyfiles = 0;
5282 $oldcourse->enablecompletion = 0;
5283 if (!empty($options['keep_groups_and_groupings'])) {
5284 $oldcourse->defaultgroupingid = 0;
5286 $DB->update_record('course', $oldcourse);
5288 // Delete course sections.
5289 $DB->delete_records('course_sections', array('course' => $course->id));
5291 // Delete legacy, section and any other course files.
5292 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5294 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5295 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5296 // Easy, do not delete the context itself...
5297 $coursecontext->delete_content();
5298 } else {
5299 // Hack alert!!!!
5300 // We can not drop all context stuff because it would bork enrolments and roles,
5301 // there might be also files used by enrol plugins...
5304 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5305 // also some non-standard unsupported plugins may try to store something there.
5306 fulldelete($CFG->dataroot.'/'.$course->id);
5308 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5309 $cachemodinfo = cache::make('core', 'coursemodinfo');
5310 $cachemodinfo->delete($courseid);
5312 // Trigger a course content deleted event.
5313 $event = \core\event\course_content_deleted::create(array(
5314 'objectid' => $course->id,
5315 'context' => $coursecontext,
5316 'other' => array('shortname' => $course->shortname,
5317 'fullname' => $course->fullname,
5318 'options' => $options) // Passing this for legacy reasons.
5320 $event->add_record_snapshot('course', $course);
5321 $event->trigger();
5323 return true;
5327 * Change dates in module - used from course reset.
5329 * @param string $modname forum, assignment, etc
5330 * @param array $fields array of date fields from mod table
5331 * @param int $timeshift time difference
5332 * @param int $courseid
5333 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5334 * @return bool success
5336 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5337 global $CFG, $DB;
5338 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5340 $return = true;
5341 $params = array($timeshift, $courseid);
5342 foreach ($fields as $field) {
5343 $updatesql = "UPDATE {".$modname."}
5344 SET $field = $field + ?
5345 WHERE course=? AND $field<>0";
5346 if ($modid) {
5347 $updatesql .= ' AND id=?';
5348 $params[] = $modid;
5350 $return = $DB->execute($updatesql, $params) && $return;
5353 $refreshfunction = $modname.'_refresh_events';
5354 if (function_exists($refreshfunction)) {
5355 $refreshfunction($courseid);
5358 return $return;
5362 * This function will empty a course of user data.
5363 * It will retain the activities and the structure of the course.
5365 * @param object $data an object containing all the settings including courseid (without magic quotes)
5366 * @return array status array of array component, item, error
5368 function reset_course_userdata($data) {
5369 global $CFG, $DB;
5370 require_once($CFG->libdir.'/gradelib.php');
5371 require_once($CFG->libdir.'/completionlib.php');
5372 require_once($CFG->dirroot.'/group/lib.php');
5374 $data->courseid = $data->id;
5375 $context = context_course::instance($data->courseid);
5377 $eventparams = array(
5378 'context' => $context,
5379 'courseid' => $data->id,
5380 'other' => array(
5381 'reset_options' => (array) $data
5384 $event = \core\event\course_reset_started::create($eventparams);
5385 $event->trigger();
5387 // Calculate the time shift of dates.
5388 if (!empty($data->reset_start_date)) {
5389 // Time part of course startdate should be zero.
5390 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5391 } else {
5392 $data->timeshift = 0;
5395 // Result array: component, item, error.
5396 $status = array();
5398 // Start the resetting.
5399 $componentstr = get_string('general');
5401 // Move the course start time.
5402 if (!empty($data->reset_start_date) and $data->timeshift) {
5403 // Change course start data.
5404 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5405 // Update all course and group events - do not move activity events.
5406 $updatesql = "UPDATE {event}
5407 SET timestart = timestart + ?
5408 WHERE courseid=? AND instance=0";
5409 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5411 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5414 if (!empty($data->reset_events)) {
5415 $DB->delete_records('event', array('courseid' => $data->courseid));
5416 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5419 if (!empty($data->reset_notes)) {
5420 require_once($CFG->dirroot.'/notes/lib.php');
5421 note_delete_all($data->courseid);
5422 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5425 if (!empty($data->delete_blog_associations)) {
5426 require_once($CFG->dirroot.'/blog/lib.php');
5427 blog_remove_associations_for_course($data->courseid);
5428 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5431 if (!empty($data->reset_completion)) {
5432 // Delete course and activity completion information.
5433 $course = $DB->get_record('course', array('id' => $data->courseid));
5434 $cc = new completion_info($course);
5435 $cc->delete_all_completion_data();
5436 $status[] = array('component' => $componentstr,
5437 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5440 $componentstr = get_string('roles');
5442 if (!empty($data->reset_roles_overrides)) {
5443 $children = $context->get_child_contexts();
5444 foreach ($children as $child) {
5445 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5447 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5448 // Force refresh for logged in users.
5449 $context->mark_dirty();
5450 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5453 if (!empty($data->reset_roles_local)) {
5454 $children = $context->get_child_contexts();
5455 foreach ($children as $child) {
5456 role_unassign_all(array('contextid' => $child->id));
5458 // Force refresh for logged in users.
5459 $context->mark_dirty();
5460 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5463 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5464 $data->unenrolled = array();
5465 if (!empty($data->unenrol_users)) {
5466 $plugins = enrol_get_plugins(true);
5467 $instances = enrol_get_instances($data->courseid, true);
5468 foreach ($instances as $key => $instance) {
5469 if (!isset($plugins[$instance->enrol])) {
5470 unset($instances[$key]);
5471 continue;
5475 foreach ($data->unenrol_users as $withroleid) {
5476 if ($withroleid) {
5477 $sql = "SELECT ue.*
5478 FROM {user_enrolments} ue
5479 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5480 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5481 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5482 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5484 } else {
5485 // Without any role assigned at course context.
5486 $sql = "SELECT ue.*
5487 FROM {user_enrolments} ue
5488 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5489 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5490 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5491 WHERE ra.id IS null";
5492 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5495 $rs = $DB->get_recordset_sql($sql, $params);
5496 foreach ($rs as $ue) {
5497 if (!isset($instances[$ue->enrolid])) {
5498 continue;
5500 $instance = $instances[$ue->enrolid];
5501 $plugin = $plugins[$instance->enrol];
5502 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5503 continue;
5506 $plugin->unenrol_user($instance, $ue->userid);
5507 $data->unenrolled[$ue->userid] = $ue->userid;
5509 $rs->close();
5512 if (!empty($data->unenrolled)) {
5513 $status[] = array(
5514 'component' => $componentstr,
5515 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5516 'error' => false
5520 $componentstr = get_string('groups');
5522 // Remove all group members.
5523 if (!empty($data->reset_groups_members)) {
5524 groups_delete_group_members($data->courseid);
5525 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5528 // Remove all groups.
5529 if (!empty($data->reset_groups_remove)) {
5530 groups_delete_groups($data->courseid, false);
5531 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5534 // Remove all grouping members.
5535 if (!empty($data->reset_groupings_members)) {
5536 groups_delete_groupings_groups($data->courseid, false);
5537 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5540 // Remove all groupings.
5541 if (!empty($data->reset_groupings_remove)) {
5542 groups_delete_groupings($data->courseid, false);
5543 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5546 // Look in every instance of every module for data to delete.
5547 $unsupportedmods = array();
5548 if ($allmods = $DB->get_records('modules') ) {
5549 foreach ($allmods as $mod) {
5550 $modname = $mod->name;
5551 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5552 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5553 if (file_exists($modfile)) {
5554 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5555 continue; // Skip mods with no instances.
5557 include_once($modfile);
5558 if (function_exists($moddeleteuserdata)) {
5559 $modstatus = $moddeleteuserdata($data);
5560 if (is_array($modstatus)) {
5561 $status = array_merge($status, $modstatus);
5562 } else {
5563 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5565 } else {
5566 $unsupportedmods[] = $mod;
5568 } else {
5569 debugging('Missing lib.php in '.$modname.' module!');
5574 // Mention unsupported mods.
5575 if (!empty($unsupportedmods)) {
5576 foreach ($unsupportedmods as $mod) {
5577 $status[] = array(
5578 'component' => get_string('modulenameplural', $mod->name),
5579 'item' => '',
5580 'error' => get_string('resetnotimplemented')
5585 $componentstr = get_string('gradebook', 'grades');
5586 // Reset gradebook,.
5587 if (!empty($data->reset_gradebook_items)) {
5588 remove_course_grades($data->courseid, false);
5589 grade_grab_course_grades($data->courseid);
5590 grade_regrade_final_grades($data->courseid);
5591 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5593 } else if (!empty($data->reset_gradebook_grades)) {
5594 grade_course_reset($data->courseid);
5595 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5597 // Reset comments.
5598 if (!empty($data->reset_comments)) {
5599 require_once($CFG->dirroot.'/comment/lib.php');
5600 comment::reset_course_page_comments($context);
5603 $event = \core\event\course_reset_ended::create($eventparams);
5604 $event->trigger();
5606 return $status;
5610 * Generate an email processing address.
5612 * @param int $modid
5613 * @param string $modargs
5614 * @return string Returns email processing address
5616 function generate_email_processing_address($modid, $modargs) {
5617 global $CFG;
5619 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5620 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5626 * @todo Finish documenting this function
5628 * @param string $modargs
5629 * @param string $body Currently unused
5631 function moodle_process_email($modargs, $body) {
5632 global $DB;
5634 // The first char should be an unencoded letter. We'll take this as an action.
5635 switch ($modargs{0}) {
5636 case 'B': { // Bounce.
5637 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5638 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5639 // Check the half md5 of their email.
5640 $md5check = substr(md5($user->email), 0, 16);
5641 if ($md5check == substr($modargs, -16)) {
5642 set_bounce_count($user);
5644 // Else maybe they've already changed it?
5647 break;
5648 // Maybe more later?
5652 // CORRESPONDENCE.
5655 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5657 * @param string $action 'get', 'buffer', 'close' or 'flush'
5658 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5660 function get_mailer($action='get') {
5661 global $CFG;
5663 /** @var moodle_phpmailer $mailer */
5664 static $mailer = null;
5665 static $counter = 0;
5667 if (!isset($CFG->smtpmaxbulk)) {
5668 $CFG->smtpmaxbulk = 1;
5671 if ($action == 'get') {
5672 $prevkeepalive = false;
5674 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5675 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5676 $counter++;
5677 // Reset the mailer.
5678 $mailer->Priority = 3;
5679 $mailer->CharSet = 'UTF-8'; // Our default.
5680 $mailer->ContentType = "text/plain";
5681 $mailer->Encoding = "8bit";
5682 $mailer->From = "root@localhost";
5683 $mailer->FromName = "Root User";
5684 $mailer->Sender = "";
5685 $mailer->Subject = "";
5686 $mailer->Body = "";
5687 $mailer->AltBody = "";
5688 $mailer->ConfirmReadingTo = "";
5690 $mailer->clearAllRecipients();
5691 $mailer->clearReplyTos();
5692 $mailer->clearAttachments();
5693 $mailer->clearCustomHeaders();
5694 return $mailer;
5697 $prevkeepalive = $mailer->SMTPKeepAlive;
5698 get_mailer('flush');
5701 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5702 $mailer = new moodle_phpmailer();
5704 $counter = 1;
5706 if ($CFG->smtphosts == 'qmail') {
5707 // Use Qmail system.
5708 $mailer->isQmail();
5710 } else if (empty($CFG->smtphosts)) {
5711 // Use PHP mail() = sendmail.
5712 $mailer->isMail();
5714 } else {
5715 // Use SMTP directly.
5716 $mailer->isSMTP();
5717 if (!empty($CFG->debugsmtp)) {
5718 $mailer->SMTPDebug = true;
5720 // Specify main and backup servers.
5721 $mailer->Host = $CFG->smtphosts;
5722 // Specify secure connection protocol.
5723 $mailer->SMTPSecure = $CFG->smtpsecure;
5724 // Use previous keepalive.
5725 $mailer->SMTPKeepAlive = $prevkeepalive;
5727 if ($CFG->smtpuser) {
5728 // Use SMTP authentication.
5729 $mailer->SMTPAuth = true;
5730 $mailer->Username = $CFG->smtpuser;
5731 $mailer->Password = $CFG->smtppass;
5735 return $mailer;
5738 $nothing = null;
5740 // Keep smtp session open after sending.
5741 if ($action == 'buffer') {
5742 if (!empty($CFG->smtpmaxbulk)) {
5743 get_mailer('flush');
5744 $m = get_mailer();
5745 if ($m->Mailer == 'smtp') {
5746 $m->SMTPKeepAlive = true;
5749 return $nothing;
5752 // Close smtp session, but continue buffering.
5753 if ($action == 'flush') {
5754 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5755 if (!empty($mailer->SMTPDebug)) {
5756 echo '<pre>'."\n";
5758 $mailer->SmtpClose();
5759 if (!empty($mailer->SMTPDebug)) {
5760 echo '</pre>';
5763 return $nothing;
5766 // Close smtp session, do not buffer anymore.
5767 if ($action == 'close') {
5768 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5769 get_mailer('flush');
5770 $mailer->SMTPKeepAlive = false;
5772 $mailer = null; // Better force new instance.
5773 return $nothing;
5778 * Send an email to a specified user
5780 * @param stdClass $user A {@link $USER} object
5781 * @param stdClass $from A {@link $USER} object
5782 * @param string $subject plain text subject line of the email
5783 * @param string $messagetext plain text version of the message
5784 * @param string $messagehtml complete html version of the message (optional)
5785 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
5786 * @param string $attachname the name of the file (extension indicates MIME)
5787 * @param bool $usetrueaddress determines whether $from email address should
5788 * be sent out. Will be overruled by user profile setting for maildisplay
5789 * @param string $replyto Email address to reply to
5790 * @param string $replytoname Name of reply to recipient
5791 * @param int $wordwrapwidth custom word wrap width, default 79
5792 * @return bool Returns true if mail was sent OK and false if there was an error.
5794 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5795 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5797 global $CFG;
5799 if (empty($user) or empty($user->id)) {
5800 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5801 return false;
5804 if (empty($user->email)) {
5805 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5806 return false;
5809 if (!empty($user->deleted)) {
5810 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5811 return false;
5814 if (defined('BEHAT_SITE_RUNNING')) {
5815 // Fake email sending in behat.
5816 return true;
5819 if (!empty($CFG->noemailever)) {
5820 // Hidden setting for development sites, set in config.php if needed.
5821 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5822 return true;
5825 if (!empty($CFG->divertallemailsto)) {
5826 $subject = "[DIVERTED {$user->email}] $subject";
5827 $user = clone($user);
5828 $user->email = $CFG->divertallemailsto;
5831 // Skip mail to suspended users.
5832 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5833 return true;
5836 if (!validate_email($user->email)) {
5837 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5838 $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
5839 error_log($invalidemail);
5840 if (CLI_SCRIPT) {
5841 mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
5843 return false;
5846 if (over_bounce_threshold($user)) {
5847 $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
5848 error_log($bouncemsg);
5849 if (CLI_SCRIPT) {
5850 mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
5852 return false;
5855 // If the user is a remote mnet user, parse the email text for URL to the
5856 // wwwroot and modify the url to direct the user's browser to login at their
5857 // home site (identity provider - idp) before hitting the link itself.
5858 if (is_mnet_remote_user($user)) {
5859 require_once($CFG->dirroot.'/mnet/lib.php');
5861 $jumpurl = mnet_get_idp_jump_url($user);
5862 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5864 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5865 $callback,
5866 $messagetext);
5867 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5868 $callback,
5869 $messagehtml);
5871 $mail = get_mailer();
5873 if (!empty($mail->SMTPDebug)) {
5874 echo '<pre>' . "\n";
5877 $temprecipients = array();
5878 $tempreplyto = array();
5880 $supportuser = core_user::get_support_user();
5882 // Make up an email address for handling bounces.
5883 if (!empty($CFG->handlebounces)) {
5884 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5885 $mail->Sender = generate_email_processing_address(0, $modargs);
5886 } else {
5887 $mail->Sender = $supportuser->email;
5890 if (!empty($CFG->emailonlyfromnoreplyaddress)) {
5891 $usetrueaddress = false;
5892 if (empty($replyto) && $from->maildisplay) {
5893 $replyto = $from->email;
5894 $replytoname = fullname($from);
5898 if (is_string($from)) { // So we can pass whatever we want if there is need.
5899 $mail->From = $CFG->noreplyaddress;
5900 $mail->FromName = $from;
5901 } else if ($usetrueaddress and $from->maildisplay) {
5902 $mail->From = $from->email;
5903 $mail->FromName = fullname($from);
5904 } else {
5905 $mail->From = $CFG->noreplyaddress;
5906 $mail->FromName = fullname($from);
5907 if (empty($replyto)) {
5908 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5912 if (!empty($replyto)) {
5913 $tempreplyto[] = array($replyto, $replytoname);
5916 $mail->Subject = substr($subject, 0, 900);
5918 $temprecipients[] = array($user->email, fullname($user));
5920 // Set word wrap.
5921 $mail->WordWrap = $wordwrapwidth;
5923 if (!empty($from->customheaders)) {
5924 // Add custom headers.
5925 if (is_array($from->customheaders)) {
5926 foreach ($from->customheaders as $customheader) {
5927 $mail->addCustomHeader($customheader);
5929 } else {
5930 $mail->addCustomHeader($from->customheaders);
5934 if (!empty($from->priority)) {
5935 $mail->Priority = $from->priority;
5938 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5939 // Don't ever send HTML to users who don't want it.
5940 $mail->isHTML(true);
5941 $mail->Encoding = 'quoted-printable';
5942 $mail->Body = $messagehtml;
5943 $mail->AltBody = "\n$messagetext\n";
5944 } else {
5945 $mail->IsHTML(false);
5946 $mail->Body = "\n$messagetext\n";
5949 if ($attachment && $attachname) {
5950 if (preg_match( "~\\.\\.~" , $attachment )) {
5951 // Security check for ".." in dir path.
5952 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5953 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5954 } else {
5955 require_once($CFG->libdir.'/filelib.php');
5956 $mimetype = mimeinfo('type', $attachname);
5958 $attachmentpath = $attachment;
5960 // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5961 $attachpath = str_replace('\\', '/', $attachmentpath);
5962 // Make sure both variables are normalised before comparing.
5963 $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
5965 // If the attachment is a full path to a file in the tempdir, use it as is,
5966 // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5967 if (strpos($attachpath, $temppath) !== 0) {
5968 $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
5971 $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
5975 // Check if the email should be sent in an other charset then the default UTF-8.
5976 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5978 // Use the defined site mail charset or eventually the one preferred by the recipient.
5979 $charset = $CFG->sitemailcharset;
5980 if (!empty($CFG->allowusermailcharset)) {
5981 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5982 $charset = $useremailcharset;
5986 // Convert all the necessary strings if the charset is supported.
5987 $charsets = get_list_of_charsets();
5988 unset($charsets['UTF-8']);
5989 if (in_array($charset, $charsets)) {
5990 $mail->CharSet = $charset;
5991 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5992 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5993 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5994 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5996 foreach ($temprecipients as $key => $values) {
5997 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5999 foreach ($tempreplyto as $key => $values) {
6000 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6005 foreach ($temprecipients as $values) {
6006 $mail->addAddress($values[0], $values[1]);
6008 foreach ($tempreplyto as $values) {
6009 $mail->addReplyTo($values[0], $values[1]);
6012 if ($mail->send()) {
6013 set_send_count($user);
6014 if (!empty($mail->SMTPDebug)) {
6015 echo '</pre>';
6017 return true;
6018 } else {
6019 // Trigger event for failing to send email.
6020 $event = \core\event\email_failed::create(array(
6021 'context' => context_system::instance(),
6022 'userid' => $from->id,
6023 'relateduserid' => $user->id,
6024 'other' => array(
6025 'subject' => $subject,
6026 'message' => $messagetext,
6027 'errorinfo' => $mail->ErrorInfo
6030 $event->trigger();
6031 if (CLI_SCRIPT) {
6032 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6034 if (!empty($mail->SMTPDebug)) {
6035 echo '</pre>';
6037 return false;
6042 * Generate a signoff for emails based on support settings
6044 * @return string
6046 function generate_email_signoff() {
6047 global $CFG;
6049 $signoff = "\n";
6050 if (!empty($CFG->supportname)) {
6051 $signoff .= $CFG->supportname."\n";
6053 if (!empty($CFG->supportemail)) {
6054 $signoff .= $CFG->supportemail."\n";
6056 if (!empty($CFG->supportpage)) {
6057 $signoff .= $CFG->supportpage."\n";
6059 return $signoff;
6063 * Sets specified user's password and send the new password to the user via email.
6065 * @param stdClass $user A {@link $USER} object
6066 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6067 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6069 function setnew_password_and_mail($user, $fasthash = false) {
6070 global $CFG, $DB;
6072 // We try to send the mail in language the user understands,
6073 // unfortunately the filter_string() does not support alternative langs yet
6074 // so multilang will not work properly for site->fullname.
6075 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
6077 $site = get_site();
6079 $supportuser = core_user::get_support_user();
6081 $newpassword = generate_password();
6083 update_internal_user_password($user, $newpassword, $fasthash);
6085 $a = new stdClass();
6086 $a->firstname = fullname($user, true);
6087 $a->sitename = format_string($site->fullname);
6088 $a->username = $user->username;
6089 $a->newpassword = $newpassword;
6090 $a->link = $CFG->wwwroot .'/login/';
6091 $a->signoff = generate_email_signoff();
6093 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6095 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6097 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6098 return email_to_user($user, $supportuser, $subject, $message);
6103 * Resets specified user's password and send the new password to the user via email.
6105 * @param stdClass $user A {@link $USER} object
6106 * @return bool Returns true if mail was sent OK and false if there was an error.
6108 function reset_password_and_mail($user) {
6109 global $CFG;
6111 $site = get_site();
6112 $supportuser = core_user::get_support_user();
6114 $userauth = get_auth_plugin($user->auth);
6115 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6116 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6117 return false;
6120 $newpassword = generate_password();
6122 if (!$userauth->user_update_password($user, $newpassword)) {
6123 print_error("cannotsetpassword");
6126 $a = new stdClass();
6127 $a->firstname = $user->firstname;
6128 $a->lastname = $user->lastname;
6129 $a->sitename = format_string($site->fullname);
6130 $a->username = $user->username;
6131 $a->newpassword = $newpassword;
6132 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
6133 $a->signoff = generate_email_signoff();
6135 $message = get_string('newpasswordtext', '', $a);
6137 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
6139 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6141 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6142 return email_to_user($user, $supportuser, $subject, $message);
6146 * Send email to specified user with confirmation text and activation link.
6148 * @param stdClass $user A {@link $USER} object
6149 * @return bool Returns true if mail was sent OK and false if there was an error.
6151 function send_confirmation_email($user) {
6152 global $CFG;
6154 $site = get_site();
6155 $supportuser = core_user::get_support_user();
6157 $data = new stdClass();
6158 $data->firstname = fullname($user);
6159 $data->sitename = format_string($site->fullname);
6160 $data->admin = generate_email_signoff();
6162 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6164 $username = urlencode($user->username);
6165 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
6166 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
6167 $message = get_string('emailconfirmation', '', $data);
6168 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6170 $user->mailformat = 1; // Always send HTML version as well.
6172 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6173 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6177 * Sends a password change confirmation email.
6179 * @param stdClass $user A {@link $USER} object
6180 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6181 * @return bool Returns true if mail was sent OK and false if there was an error.
6183 function send_password_change_confirmation_email($user, $resetrecord) {
6184 global $CFG;
6186 $site = get_site();
6187 $supportuser = core_user::get_support_user();
6188 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6190 $data = new stdClass();
6191 $data->firstname = $user->firstname;
6192 $data->lastname = $user->lastname;
6193 $data->username = $user->username;
6194 $data->sitename = format_string($site->fullname);
6195 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6196 $data->admin = generate_email_signoff();
6197 $data->resetminutes = $pwresetmins;
6199 $message = get_string('emailresetconfirmation', '', $data);
6200 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6202 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6203 return email_to_user($user, $supportuser, $subject, $message);
6208 * Sends an email containinginformation on how to change your password.
6210 * @param stdClass $user A {@link $USER} object
6211 * @return bool Returns true if mail was sent OK and false if there was an error.
6213 function send_password_change_info($user) {
6214 global $CFG;
6216 $site = get_site();
6217 $supportuser = core_user::get_support_user();
6218 $systemcontext = context_system::instance();
6220 $data = new stdClass();
6221 $data->firstname = $user->firstname;
6222 $data->lastname = $user->lastname;
6223 $data->sitename = format_string($site->fullname);
6224 $data->admin = generate_email_signoff();
6226 $userauth = get_auth_plugin($user->auth);
6228 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6229 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6230 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6231 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6232 return email_to_user($user, $supportuser, $subject, $message);
6235 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6236 // We have some external url for password changing.
6237 $data->link .= $userauth->change_password_url();
6239 } else {
6240 // No way to change password, sorry.
6241 $data->link = '';
6244 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6245 $message = get_string('emailpasswordchangeinfo', '', $data);
6246 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6247 } else {
6248 $message = get_string('emailpasswordchangeinfofail', '', $data);
6249 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6252 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6253 return email_to_user($user, $supportuser, $subject, $message);
6258 * Check that an email is allowed. It returns an error message if there was a problem.
6260 * @param string $email Content of email
6261 * @return string|false
6263 function email_is_not_allowed($email) {
6264 global $CFG;
6266 if (!empty($CFG->allowemailaddresses)) {
6267 $allowed = explode(' ', $CFG->allowemailaddresses);
6268 foreach ($allowed as $allowedpattern) {
6269 $allowedpattern = trim($allowedpattern);
6270 if (!$allowedpattern) {
6271 continue;
6273 if (strpos($allowedpattern, '.') === 0) {
6274 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6275 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6276 return false;
6279 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6280 return false;
6283 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6285 } else if (!empty($CFG->denyemailaddresses)) {
6286 $denied = explode(' ', $CFG->denyemailaddresses);
6287 foreach ($denied as $deniedpattern) {
6288 $deniedpattern = trim($deniedpattern);
6289 if (!$deniedpattern) {
6290 continue;
6292 if (strpos($deniedpattern, '.') === 0) {
6293 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6294 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6295 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6298 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6299 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6304 return false;
6307 // FILE HANDLING.
6310 * Returns local file storage instance
6312 * @return file_storage
6314 function get_file_storage() {
6315 global $CFG;
6317 static $fs = null;
6319 if ($fs) {
6320 return $fs;
6323 require_once("$CFG->libdir/filelib.php");
6325 if (isset($CFG->filedir)) {
6326 $filedir = $CFG->filedir;
6327 } else {
6328 $filedir = $CFG->dataroot.'/filedir';
6331 if (isset($CFG->trashdir)) {
6332 $trashdirdir = $CFG->trashdir;
6333 } else {
6334 $trashdirdir = $CFG->dataroot.'/trashdir';
6337 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6339 return $fs;
6343 * Returns local file storage instance
6345 * @return file_browser
6347 function get_file_browser() {
6348 global $CFG;
6350 static $fb = null;
6352 if ($fb) {
6353 return $fb;
6356 require_once("$CFG->libdir/filelib.php");
6358 $fb = new file_browser();
6360 return $fb;
6364 * Returns file packer
6366 * @param string $mimetype default application/zip
6367 * @return file_packer
6369 function get_file_packer($mimetype='application/zip') {
6370 global $CFG;
6372 static $fp = array();
6374 if (isset($fp[$mimetype])) {
6375 return $fp[$mimetype];
6378 switch ($mimetype) {
6379 case 'application/zip':
6380 case 'application/vnd.moodle.profiling':
6381 $classname = 'zip_packer';
6382 break;
6384 case 'application/x-gzip' :
6385 $classname = 'tgz_packer';
6386 break;
6388 case 'application/vnd.moodle.backup':
6389 $classname = 'mbz_packer';
6390 break;
6392 default:
6393 return false;
6396 require_once("$CFG->libdir/filestorage/$classname.php");
6397 $fp[$mimetype] = new $classname();
6399 return $fp[$mimetype];
6403 * Returns current name of file on disk if it exists.
6405 * @param string $newfile File to be verified
6406 * @return string Current name of file on disk if true
6408 function valid_uploaded_file($newfile) {
6409 if (empty($newfile)) {
6410 return '';
6412 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6413 return $newfile['tmp_name'];
6414 } else {
6415 return '';
6420 * Returns the maximum size for uploading files.
6422 * There are seven possible upload limits:
6423 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6424 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6425 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6426 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6427 * 5. by the Moodle admin in $CFG->maxbytes
6428 * 6. by the teacher in the current course $course->maxbytes
6429 * 7. by the teacher for the current module, eg $assignment->maxbytes
6431 * These last two are passed to this function as arguments (in bytes).
6432 * Anything defined as 0 is ignored.
6433 * The smallest of all the non-zero numbers is returned.
6435 * @todo Finish documenting this function
6437 * @param int $sitebytes Set maximum size
6438 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6439 * @param int $modulebytes Current module ->maxbytes (in bytes)
6440 * @return int The maximum size for uploading files.
6442 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6444 if (! $filesize = ini_get('upload_max_filesize')) {
6445 $filesize = '5M';
6447 $minimumsize = get_real_size($filesize);
6449 if ($postsize = ini_get('post_max_size')) {
6450 $postsize = get_real_size($postsize);
6451 if ($postsize < $minimumsize) {
6452 $minimumsize = $postsize;
6456 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6457 $minimumsize = $sitebytes;
6460 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6461 $minimumsize = $coursebytes;
6464 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6465 $minimumsize = $modulebytes;
6468 return $minimumsize;
6472 * Returns the maximum size for uploading files for the current user
6474 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6476 * @param context $context The context in which to check user capabilities
6477 * @param int $sitebytes Set maximum size
6478 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6479 * @param int $modulebytes Current module ->maxbytes (in bytes)
6480 * @param stdClass $user The user
6481 * @return int The maximum size for uploading files.
6483 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6484 global $USER;
6486 if (empty($user)) {
6487 $user = $USER;
6490 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6491 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6494 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6498 * Returns an array of possible sizes in local language
6500 * Related to {@link get_max_upload_file_size()} - this function returns an
6501 * array of possible sizes in an array, translated to the
6502 * local language.
6504 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6506 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6507 * with the value set to 0. This option will be the first in the list.
6509 * @uses SORT_NUMERIC
6510 * @param int $sitebytes Set maximum size
6511 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6512 * @param int $modulebytes Current module ->maxbytes (in bytes)
6513 * @param int|array $custombytes custom upload size/s which will be added to list,
6514 * Only value/s smaller then maxsize will be added to list.
6515 * @return array
6517 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6518 global $CFG;
6520 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6521 return array();
6524 if ($sitebytes == 0) {
6525 // Will get the minimum of upload_max_filesize or post_max_size.
6526 $sitebytes = get_max_upload_file_size();
6529 $filesize = array();
6530 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6531 5242880, 10485760, 20971520, 52428800, 104857600);
6533 // If custombytes is given and is valid then add it to the list.
6534 if (is_number($custombytes) and $custombytes > 0) {
6535 $custombytes = (int)$custombytes;
6536 if (!in_array($custombytes, $sizelist)) {
6537 $sizelist[] = $custombytes;
6539 } else if (is_array($custombytes)) {
6540 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6543 // Allow maxbytes to be selected if it falls outside the above boundaries.
6544 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6545 // Note: get_real_size() is used in order to prevent problems with invalid values.
6546 $sizelist[] = get_real_size($CFG->maxbytes);
6549 foreach ($sizelist as $sizebytes) {
6550 if ($sizebytes < $maxsize && $sizebytes > 0) {
6551 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6555 $limitlevel = '';
6556 $displaysize = '';
6557 if ($modulebytes &&
6558 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6559 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6560 $limitlevel = get_string('activity', 'core');
6561 $displaysize = display_size($modulebytes);
6562 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6564 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6565 $limitlevel = get_string('course', 'core');
6566 $displaysize = display_size($coursebytes);
6567 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6569 } else if ($sitebytes) {
6570 $limitlevel = get_string('site', 'core');
6571 $displaysize = display_size($sitebytes);
6572 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6575 krsort($filesize, SORT_NUMERIC);
6576 if ($limitlevel) {
6577 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6578 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6581 return $filesize;
6585 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6587 * If excludefiles is defined, then that file/directory is ignored
6588 * If getdirs is true, then (sub)directories are included in the output
6589 * If getfiles is true, then files are included in the output
6590 * (at least one of these must be true!)
6592 * @todo Finish documenting this function. Add examples of $excludefile usage.
6594 * @param string $rootdir A given root directory to start from
6595 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6596 * @param bool $descend If true then subdirectories are recursed as well
6597 * @param bool $getdirs If true then (sub)directories are included in the output
6598 * @param bool $getfiles If true then files are included in the output
6599 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6601 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6603 $dirs = array();
6605 if (!$getdirs and !$getfiles) { // Nothing to show.
6606 return $dirs;
6609 if (!is_dir($rootdir)) { // Must be a directory.
6610 return $dirs;
6613 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6614 return $dirs;
6617 if (!is_array($excludefiles)) {
6618 $excludefiles = array($excludefiles);
6621 while (false !== ($file = readdir($dir))) {
6622 $firstchar = substr($file, 0, 1);
6623 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6624 continue;
6626 $fullfile = $rootdir .'/'. $file;
6627 if (filetype($fullfile) == 'dir') {
6628 if ($getdirs) {
6629 $dirs[] = $file;
6631 if ($descend) {
6632 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6633 foreach ($subdirs as $subdir) {
6634 $dirs[] = $file .'/'. $subdir;
6637 } else if ($getfiles) {
6638 $dirs[] = $file;
6641 closedir($dir);
6643 asort($dirs);
6645 return $dirs;
6650 * Adds up all the files in a directory and works out the size.
6652 * @param string $rootdir The directory to start from
6653 * @param string $excludefile A file to exclude when summing directory size
6654 * @return int The summed size of all files and subfiles within the root directory
6656 function get_directory_size($rootdir, $excludefile='') {
6657 global $CFG;
6659 // Do it this way if we can, it's much faster.
6660 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6661 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6662 $output = null;
6663 $return = null;
6664 exec($command, $output, $return);
6665 if (is_array($output)) {
6666 // We told it to return k.
6667 return get_real_size(intval($output[0]).'k');
6671 if (!is_dir($rootdir)) {
6672 // Must be a directory.
6673 return 0;
6676 if (!$dir = @opendir($rootdir)) {
6677 // Can't open it for some reason.
6678 return 0;
6681 $size = 0;
6683 while (false !== ($file = readdir($dir))) {
6684 $firstchar = substr($file, 0, 1);
6685 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6686 continue;
6688 $fullfile = $rootdir .'/'. $file;
6689 if (filetype($fullfile) == 'dir') {
6690 $size += get_directory_size($fullfile, $excludefile);
6691 } else {
6692 $size += filesize($fullfile);
6695 closedir($dir);
6697 return $size;
6701 * Converts bytes into display form
6703 * @static string $gb Localized string for size in gigabytes
6704 * @static string $mb Localized string for size in megabytes
6705 * @static string $kb Localized string for size in kilobytes
6706 * @static string $b Localized string for size in bytes
6707 * @param int $size The size to convert to human readable form
6708 * @return string
6710 function display_size($size) {
6712 static $gb, $mb, $kb, $b;
6714 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6715 return get_string('unlimited');
6718 if (empty($gb)) {
6719 $gb = get_string('sizegb');
6720 $mb = get_string('sizemb');
6721 $kb = get_string('sizekb');
6722 $b = get_string('sizeb');
6725 if ($size >= 1073741824) {
6726 $size = round($size / 1073741824 * 10) / 10 . $gb;
6727 } else if ($size >= 1048576) {
6728 $size = round($size / 1048576 * 10) / 10 . $mb;
6729 } else if ($size >= 1024) {
6730 $size = round($size / 1024 * 10) / 10 . $kb;
6731 } else {
6732 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6734 return $size;
6738 * Cleans a given filename by removing suspicious or troublesome characters
6740 * @see clean_param()
6741 * @param string $string file name
6742 * @return string cleaned file name
6744 function clean_filename($string) {
6745 return clean_param($string, PARAM_FILE);
6749 // STRING TRANSLATION.
6752 * Returns the code for the current language
6754 * @category string
6755 * @return string
6757 function current_language() {
6758 global $CFG, $USER, $SESSION, $COURSE;
6760 if (!empty($SESSION->forcelang)) {
6761 // Allows overriding course-forced language (useful for admins to check
6762 // issues in courses whose language they don't understand).
6763 // Also used by some code to temporarily get language-related information in a
6764 // specific language (see force_current_language()).
6765 $return = $SESSION->forcelang;
6767 } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6768 // Course language can override all other settings for this page.
6769 $return = $COURSE->lang;
6771 } else if (!empty($SESSION->lang)) {
6772 // Session language can override other settings.
6773 $return = $SESSION->lang;
6775 } else if (!empty($USER->lang)) {
6776 $return = $USER->lang;
6778 } else if (isset($CFG->lang)) {
6779 $return = $CFG->lang;
6781 } else {
6782 $return = 'en';
6785 // Just in case this slipped in from somewhere by accident.
6786 $return = str_replace('_utf8', '', $return);
6788 return $return;
6792 * Returns parent language of current active language if defined
6794 * @category string
6795 * @param string $lang null means current language
6796 * @return string
6798 function get_parent_language($lang=null) {
6800 // Let's hack around the current language.
6801 if (!empty($lang)) {
6802 $oldforcelang = force_current_language($lang);
6805 $parentlang = get_string('parentlanguage', 'langconfig');
6806 if ($parentlang === 'en') {
6807 $parentlang = '';
6810 // Let's hack around the current language.
6811 if (!empty($lang)) {
6812 force_current_language($oldforcelang);
6815 return $parentlang;
6819 * Force the current language to get strings and dates localised in the given language.
6821 * After calling this function, all strings will be provided in the given language
6822 * until this function is called again, or equivalent code is run.
6824 * @param string $language
6825 * @return string previous $SESSION->forcelang value
6827 function force_current_language($language) {
6828 global $SESSION;
6829 $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6830 if ($language !== $sessionforcelang) {
6831 // Seting forcelang to null or an empty string disables it's effect.
6832 if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6833 $SESSION->forcelang = $language;
6834 moodle_setlocale();
6837 return $sessionforcelang;
6841 * Returns current string_manager instance.
6843 * The param $forcereload is needed for CLI installer only where the string_manager instance
6844 * must be replaced during the install.php script life time.
6846 * @category string
6847 * @param bool $forcereload shall the singleton be released and new instance created instead?
6848 * @return core_string_manager
6850 function get_string_manager($forcereload=false) {
6851 global $CFG;
6853 static $singleton = null;
6855 if ($forcereload) {
6856 $singleton = null;
6858 if ($singleton === null) {
6859 if (empty($CFG->early_install_lang)) {
6861 if (empty($CFG->langlist)) {
6862 $translist = array();
6863 } else {
6864 $translist = explode(',', $CFG->langlist);
6867 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6869 } else {
6870 $singleton = new core_string_manager_install();
6874 return $singleton;
6878 * Returns a localized string.
6880 * Returns the translated string specified by $identifier as
6881 * for $module. Uses the same format files as STphp.
6882 * $a is an object, string or number that can be used
6883 * within translation strings
6885 * eg 'hello {$a->firstname} {$a->lastname}'
6886 * or 'hello {$a}'
6888 * If you would like to directly echo the localized string use
6889 * the function {@link print_string()}
6891 * Example usage of this function involves finding the string you would
6892 * like a local equivalent of and using its identifier and module information
6893 * to retrieve it.<br/>
6894 * If you open moodle/lang/en/moodle.php and look near line 278
6895 * you will find a string to prompt a user for their word for 'course'
6896 * <code>
6897 * $string['course'] = 'Course';
6898 * </code>
6899 * So if you want to display the string 'Course'
6900 * in any language that supports it on your site
6901 * you just need to use the identifier 'course'
6902 * <code>
6903 * $mystring = '<strong>'. get_string('course') .'</strong>';
6904 * or
6905 * </code>
6906 * If the string you want is in another file you'd take a slightly
6907 * different approach. Looking in moodle/lang/en/calendar.php you find
6908 * around line 75:
6909 * <code>
6910 * $string['typecourse'] = 'Course event';
6911 * </code>
6912 * If you want to display the string "Course event" in any language
6913 * supported you would use the identifier 'typecourse' and the module 'calendar'
6914 * (because it is in the file calendar.php):
6915 * <code>
6916 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6917 * </code>
6919 * As a last resort, should the identifier fail to map to a string
6920 * the returned string will be [[ $identifier ]]
6922 * In Moodle 2.3 there is a new argument to this function $lazyload.
6923 * Setting $lazyload to true causes get_string to return a lang_string object
6924 * rather than the string itself. The fetching of the string is then put off until
6925 * the string object is first used. The object can be used by calling it's out
6926 * method or by casting the object to a string, either directly e.g.
6927 * (string)$stringobject
6928 * or indirectly by using the string within another string or echoing it out e.g.
6929 * echo $stringobject
6930 * return "<p>{$stringobject}</p>";
6931 * It is worth noting that using $lazyload and attempting to use the string as an
6932 * array key will cause a fatal error as objects cannot be used as array keys.
6933 * But you should never do that anyway!
6934 * For more information {@link lang_string}
6936 * @category string
6937 * @param string $identifier The key identifier for the localized string
6938 * @param string $component The module where the key identifier is stored,
6939 * usually expressed as the filename in the language pack without the
6940 * .php on the end but can also be written as mod/forum or grade/export/xls.
6941 * If none is specified then moodle.php is used.
6942 * @param string|object|array $a An object, string or number that can be used
6943 * within translation strings
6944 * @param bool $lazyload If set to true a string object is returned instead of
6945 * the string itself. The string then isn't calculated until it is first used.
6946 * @return string The localized string.
6947 * @throws coding_exception
6949 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6950 global $CFG;
6952 // If the lazy load argument has been supplied return a lang_string object
6953 // instead.
6954 // We need to make sure it is true (and a bool) as you will see below there
6955 // used to be a forth argument at one point.
6956 if ($lazyload === true) {
6957 return new lang_string($identifier, $component, $a);
6960 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6961 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6964 // There is now a forth argument again, this time it is a boolean however so
6965 // we can still check for the old extralocations parameter.
6966 if (!is_bool($lazyload) && !empty($lazyload)) {
6967 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6970 if (strpos($component, '/') !== false) {
6971 debugging('The module name you passed to get_string is the deprecated format ' .
6972 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6973 $componentpath = explode('/', $component);
6975 switch ($componentpath[0]) {
6976 case 'mod':
6977 $component = $componentpath[1];
6978 break;
6979 case 'blocks':
6980 case 'block':
6981 $component = 'block_'.$componentpath[1];
6982 break;
6983 case 'enrol':
6984 $component = 'enrol_'.$componentpath[1];
6985 break;
6986 case 'format':
6987 $component = 'format_'.$componentpath[1];
6988 break;
6989 case 'grade':
6990 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6991 break;
6995 $result = get_string_manager()->get_string($identifier, $component, $a);
6997 // Debugging feature lets you display string identifier and component.
6998 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6999 $result .= ' {' . $identifier . '/' . $component . '}';
7001 return $result;
7005 * Converts an array of strings to their localized value.
7007 * @param array $array An array of strings
7008 * @param string $component The language module that these strings can be found in.
7009 * @return stdClass translated strings.
7011 function get_strings($array, $component = '') {
7012 $string = new stdClass;
7013 foreach ($array as $item) {
7014 $string->$item = get_string($item, $component);
7016 return $string;
7020 * Prints out a translated string.
7022 * Prints out a translated string using the return value from the {@link get_string()} function.
7024 * Example usage of this function when the string is in the moodle.php file:<br/>
7025 * <code>
7026 * echo '<strong>';
7027 * print_string('course');
7028 * echo '</strong>';
7029 * </code>
7031 * Example usage of this function when the string is not in the moodle.php file:<br/>
7032 * <code>
7033 * echo '<h1>';
7034 * print_string('typecourse', 'calendar');
7035 * echo '</h1>';
7036 * </code>
7038 * @category string
7039 * @param string $identifier The key identifier for the localized string
7040 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7041 * @param string|object|array $a An object, string or number that can be used within translation strings
7043 function print_string($identifier, $component = '', $a = null) {
7044 echo get_string($identifier, $component, $a);
7048 * Returns a list of charset codes
7050 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7051 * (checking that such charset is supported by the texlib library!)
7053 * @return array And associative array with contents in the form of charset => charset
7055 function get_list_of_charsets() {
7057 $charsets = array(
7058 'EUC-JP' => 'EUC-JP',
7059 'ISO-2022-JP'=> 'ISO-2022-JP',
7060 'ISO-8859-1' => 'ISO-8859-1',
7061 'SHIFT-JIS' => 'SHIFT-JIS',
7062 'GB2312' => 'GB2312',
7063 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
7064 'UTF-8' => 'UTF-8');
7066 asort($charsets);
7068 return $charsets;
7072 * Returns a list of valid and compatible themes
7074 * @return array
7076 function get_list_of_themes() {
7077 global $CFG;
7079 $themes = array();
7081 if (!empty($CFG->themelist)) { // Use admin's list of themes.
7082 $themelist = explode(',', $CFG->themelist);
7083 } else {
7084 $themelist = array_keys(core_component::get_plugin_list("theme"));
7087 foreach ($themelist as $key => $themename) {
7088 $theme = theme_config::load($themename);
7089 $themes[$themename] = $theme;
7092 core_collator::asort_objects_by_method($themes, 'get_theme_name');
7094 return $themes;
7098 * Returns a list of timezones in the current language
7100 * @return array
7102 function get_list_of_timezones() {
7103 global $DB;
7105 static $timezones;
7107 if (!empty($timezones)) { // This function has been called recently.
7108 return $timezones;
7111 $timezones = array();
7113 if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
7114 foreach ($rawtimezones as $timezone) {
7115 if (!empty($timezone->name)) {
7116 if (get_string_manager()->string_exists(strtolower($timezone->name), 'timezones')) {
7117 $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
7118 } else {
7119 $timezones[$timezone->name] = $timezone->name;
7121 if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found.
7122 $timezones[$timezone->name] = $timezone->name;
7128 asort($timezones);
7130 for ($i = -13; $i <= 13; $i += .5) {
7131 $tzstring = 'UTC';
7132 if ($i < 0) {
7133 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
7134 } else if ($i > 0) {
7135 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
7136 } else {
7137 $timezones[sprintf("%.1f", $i)] = $tzstring;
7141 return $timezones;
7145 * Factory function for emoticon_manager
7147 * @return emoticon_manager singleton
7149 function get_emoticon_manager() {
7150 static $singleton = null;
7152 if (is_null($singleton)) {
7153 $singleton = new emoticon_manager();
7156 return $singleton;
7160 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7162 * Whenever this manager mentiones 'emoticon object', the following data
7163 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7164 * altidentifier and altcomponent
7166 * @see admin_setting_emoticons
7168 * @copyright 2010 David Mudrak
7169 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7171 class emoticon_manager {
7174 * Returns the currently enabled emoticons
7176 * @return array of emoticon objects
7178 public function get_emoticons() {
7179 global $CFG;
7181 if (empty($CFG->emoticons)) {
7182 return array();
7185 $emoticons = $this->decode_stored_config($CFG->emoticons);
7187 if (!is_array($emoticons)) {
7188 // Something is wrong with the format of stored setting.
7189 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7190 return array();
7193 return $emoticons;
7197 * Converts emoticon object into renderable pix_emoticon object
7199 * @param stdClass $emoticon emoticon object
7200 * @param array $attributes explicit HTML attributes to set
7201 * @return pix_emoticon
7203 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7204 $stringmanager = get_string_manager();
7205 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7206 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7207 } else {
7208 $alt = s($emoticon->text);
7210 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7214 * Encodes the array of emoticon objects into a string storable in config table
7216 * @see self::decode_stored_config()
7217 * @param array $emoticons array of emtocion objects
7218 * @return string
7220 public function encode_stored_config(array $emoticons) {
7221 return json_encode($emoticons);
7225 * Decodes the string into an array of emoticon objects
7227 * @see self::encode_stored_config()
7228 * @param string $encoded
7229 * @return string|null
7231 public function decode_stored_config($encoded) {
7232 $decoded = json_decode($encoded);
7233 if (!is_array($decoded)) {
7234 return null;
7236 return $decoded;
7240 * Returns default set of emoticons supported by Moodle
7242 * @return array of sdtClasses
7244 public function default_emoticons() {
7245 return array(
7246 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7247 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7248 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7249 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7250 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7251 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7252 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7253 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7254 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7255 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7256 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7257 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7258 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7259 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7260 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7261 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7262 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7263 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7264 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7265 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7266 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7267 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7268 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7269 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7270 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7271 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7272 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7273 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7274 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7275 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7280 * Helper method preparing the stdClass with the emoticon properties
7282 * @param string|array $text or array of strings
7283 * @param string $imagename to be used by {@link pix_emoticon}
7284 * @param string $altidentifier alternative string identifier, null for no alt
7285 * @param string $altcomponent where the alternative string is defined
7286 * @param string $imagecomponent to be used by {@link pix_emoticon}
7287 * @return stdClass
7289 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7290 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7291 return (object)array(
7292 'text' => $text,
7293 'imagename' => $imagename,
7294 'imagecomponent' => $imagecomponent,
7295 'altidentifier' => $altidentifier,
7296 'altcomponent' => $altcomponent,
7301 // ENCRYPTION.
7304 * rc4encrypt
7306 * @param string $data Data to encrypt.
7307 * @return string The now encrypted data.
7309 function rc4encrypt($data) {
7310 return endecrypt(get_site_identifier(), $data, '');
7314 * rc4decrypt
7316 * @param string $data Data to decrypt.
7317 * @return string The now decrypted data.
7319 function rc4decrypt($data) {
7320 return endecrypt(get_site_identifier(), $data, 'de');
7324 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7326 * @todo Finish documenting this function
7328 * @param string $pwd The password to use when encrypting or decrypting
7329 * @param string $data The data to be decrypted/encrypted
7330 * @param string $case Either 'de' for decrypt or '' for encrypt
7331 * @return string
7333 function endecrypt ($pwd, $data, $case) {
7335 if ($case == 'de') {
7336 $data = urldecode($data);
7339 $key[] = '';
7340 $box[] = '';
7341 $pwdlength = strlen($pwd);
7343 for ($i = 0; $i <= 255; $i++) {
7344 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7345 $box[$i] = $i;
7348 $x = 0;
7350 for ($i = 0; $i <= 255; $i++) {
7351 $x = ($x + $box[$i] + $key[$i]) % 256;
7352 $tempswap = $box[$i];
7353 $box[$i] = $box[$x];
7354 $box[$x] = $tempswap;
7357 $cipher = '';
7359 $a = 0;
7360 $j = 0;
7362 for ($i = 0; $i < strlen($data); $i++) {
7363 $a = ($a + 1) % 256;
7364 $j = ($j + $box[$a]) % 256;
7365 $temp = $box[$a];
7366 $box[$a] = $box[$j];
7367 $box[$j] = $temp;
7368 $k = $box[(($box[$a] + $box[$j]) % 256)];
7369 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7370 $cipher .= chr($cipherby);
7373 if ($case == 'de') {
7374 $cipher = urldecode(urlencode($cipher));
7375 } else {
7376 $cipher = urlencode($cipher);
7379 return $cipher;
7382 // ENVIRONMENT CHECKING.
7385 * This method validates a plug name. It is much faster than calling clean_param.
7387 * @param string $name a string that might be a plugin name.
7388 * @return bool if this string is a valid plugin name.
7390 function is_valid_plugin_name($name) {
7391 // This does not work for 'mod', bad luck, use any other type.
7392 return core_component::is_valid_plugin_name('tool', $name);
7396 * Get a list of all the plugins of a given type that define a certain API function
7397 * in a certain file. The plugin component names and function names are returned.
7399 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7400 * @param string $function the part of the name of the function after the
7401 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7402 * names like report_courselist_hook.
7403 * @param string $file the name of file within the plugin that defines the
7404 * function. Defaults to lib.php.
7405 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7406 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7408 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7409 $pluginfunctions = array();
7410 $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, $file, true);
7411 foreach ($pluginswithfile as $plugin => $notused) {
7412 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7414 if (function_exists($fullfunction)) {
7415 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7416 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
7418 } else if ($plugintype === 'mod') {
7419 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7420 $shortfunction = $plugin . '_' . $function;
7421 if (function_exists($shortfunction)) {
7422 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
7426 return $pluginfunctions;
7430 * Lists plugin-like directories within specified directory
7432 * This function was originally used for standard Moodle plugins, please use
7433 * new core_component::get_plugin_list() now.
7435 * This function is used for general directory listing and backwards compatility.
7437 * @param string $directory relative directory from root
7438 * @param string $exclude dir name to exclude from the list (defaults to none)
7439 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7440 * @return array Sorted array of directory names found under the requested parameters
7442 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7443 global $CFG;
7445 $plugins = array();
7447 if (empty($basedir)) {
7448 $basedir = $CFG->dirroot .'/'. $directory;
7450 } else {
7451 $basedir = $basedir .'/'. $directory;
7454 if ($CFG->debugdeveloper and empty($exclude)) {
7455 // Make sure devs do not use this to list normal plugins,
7456 // this is intended for general directories that are not plugins!
7458 $subtypes = core_component::get_plugin_types();
7459 if (in_array($basedir, $subtypes)) {
7460 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7462 unset($subtypes);
7465 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7466 if (!$dirhandle = opendir($basedir)) {
7467 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7468 return array();
7470 while (false !== ($dir = readdir($dirhandle))) {
7471 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7472 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7473 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7474 continue;
7476 if (filetype($basedir .'/'. $dir) != 'dir') {
7477 continue;
7479 $plugins[] = $dir;
7481 closedir($dirhandle);
7483 if ($plugins) {
7484 asort($plugins);
7486 return $plugins;
7490 * Invoke plugin's callback functions
7492 * @param string $type plugin type e.g. 'mod'
7493 * @param string $name plugin name
7494 * @param string $feature feature name
7495 * @param string $action feature's action
7496 * @param array $params parameters of callback function, should be an array
7497 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7498 * @return mixed
7500 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7502 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7503 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7507 * Invoke component's callback functions
7509 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7510 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7511 * @param array $params parameters of callback function
7512 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7513 * @return mixed
7515 function component_callback($component, $function, array $params = array(), $default = null) {
7517 $functionname = component_callback_exists($component, $function);
7519 if ($functionname) {
7520 // Function exists, so just return function result.
7521 $ret = call_user_func_array($functionname, $params);
7522 if (is_null($ret)) {
7523 return $default;
7524 } else {
7525 return $ret;
7528 return $default;
7532 * Determine if a component callback exists and return the function name to call. Note that this
7533 * function will include the required library files so that the functioname returned can be
7534 * called directly.
7536 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7537 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7538 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7539 * @throws coding_exception if invalid component specfied
7541 function component_callback_exists($component, $function) {
7542 global $CFG; // This is needed for the inclusions.
7544 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7545 if (empty($cleancomponent)) {
7546 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7548 $component = $cleancomponent;
7550 list($type, $name) = core_component::normalize_component($component);
7551 $component = $type . '_' . $name;
7553 $oldfunction = $name.'_'.$function;
7554 $function = $component.'_'.$function;
7556 $dir = core_component::get_component_directory($component);
7557 if (empty($dir)) {
7558 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7561 // Load library and look for function.
7562 if (file_exists($dir.'/lib.php')) {
7563 require_once($dir.'/lib.php');
7566 if (!function_exists($function) and function_exists($oldfunction)) {
7567 if ($type !== 'mod' and $type !== 'core') {
7568 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7570 $function = $oldfunction;
7573 if (function_exists($function)) {
7574 return $function;
7576 return false;
7580 * Checks whether a plugin supports a specified feature.
7582 * @param string $type Plugin type e.g. 'mod'
7583 * @param string $name Plugin name e.g. 'forum'
7584 * @param string $feature Feature code (FEATURE_xx constant)
7585 * @param mixed $default default value if feature support unknown
7586 * @return mixed Feature result (false if not supported, null if feature is unknown,
7587 * otherwise usually true but may have other feature-specific value such as array)
7588 * @throws coding_exception
7590 function plugin_supports($type, $name, $feature, $default = null) {
7591 global $CFG;
7593 if ($type === 'mod' and $name === 'NEWMODULE') {
7594 // Somebody forgot to rename the module template.
7595 return false;
7598 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7599 if (empty($component)) {
7600 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7603 $function = null;
7605 if ($type === 'mod') {
7606 // We need this special case because we support subplugins in modules,
7607 // otherwise it would end up in infinite loop.
7608 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7609 include_once("$CFG->dirroot/mod/$name/lib.php");
7610 $function = $component.'_supports';
7611 if (!function_exists($function)) {
7612 // Legacy non-frankenstyle function name.
7613 $function = $name.'_supports';
7617 } else {
7618 if (!$path = core_component::get_plugin_directory($type, $name)) {
7619 // Non existent plugin type.
7620 return false;
7622 if (file_exists("$path/lib.php")) {
7623 include_once("$path/lib.php");
7624 $function = $component.'_supports';
7628 if ($function and function_exists($function)) {
7629 $supports = $function($feature);
7630 if (is_null($supports)) {
7631 // Plugin does not know - use default.
7632 return $default;
7633 } else {
7634 return $supports;
7638 // Plugin does not care, so use default.
7639 return $default;
7643 * Returns true if the current version of PHP is greater that the specified one.
7645 * @todo Check PHP version being required here is it too low?
7647 * @param string $version The version of php being tested.
7648 * @return bool
7650 function check_php_version($version='5.2.4') {
7651 return (version_compare(phpversion(), $version) >= 0);
7655 * Determine if moodle installation requires update.
7657 * Checks version numbers of main code and all plugins to see
7658 * if there are any mismatches.
7660 * @return bool
7662 function moodle_needs_upgrading() {
7663 global $CFG;
7665 if (empty($CFG->version)) {
7666 return true;
7669 // There is no need to purge plugininfo caches here because
7670 // these caches are not used during upgrade and they are purged after
7671 // every upgrade.
7673 if (empty($CFG->allversionshash)) {
7674 return true;
7677 $hash = core_component::get_all_versions_hash();
7679 return ($hash !== $CFG->allversionshash);
7683 * Returns the major version of this site
7685 * Moodle version numbers consist of three numbers separated by a dot, for
7686 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7687 * called major version. This function extracts the major version from either
7688 * $CFG->release (default) or eventually from the $release variable defined in
7689 * the main version.php.
7691 * @param bool $fromdisk should the version if source code files be used
7692 * @return string|false the major version like '2.3', false if could not be determined
7694 function moodle_major_version($fromdisk = false) {
7695 global $CFG;
7697 if ($fromdisk) {
7698 $release = null;
7699 require($CFG->dirroot.'/version.php');
7700 if (empty($release)) {
7701 return false;
7704 } else {
7705 if (empty($CFG->release)) {
7706 return false;
7708 $release = $CFG->release;
7711 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7712 return $matches[0];
7713 } else {
7714 return false;
7718 // MISCELLANEOUS.
7721 * Sets the system locale
7723 * @category string
7724 * @param string $locale Can be used to force a locale
7726 function moodle_setlocale($locale='') {
7727 global $CFG;
7729 static $currentlocale = ''; // Last locale caching.
7731 $oldlocale = $currentlocale;
7733 // Fetch the correct locale based on ostype.
7734 if ($CFG->ostype == 'WINDOWS') {
7735 $stringtofetch = 'localewin';
7736 } else {
7737 $stringtofetch = 'locale';
7740 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7741 if (!empty($locale)) {
7742 $currentlocale = $locale;
7743 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7744 $currentlocale = $CFG->locale;
7745 } else {
7746 $currentlocale = get_string($stringtofetch, 'langconfig');
7749 // Do nothing if locale already set up.
7750 if ($oldlocale == $currentlocale) {
7751 return;
7754 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7755 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7756 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7758 // Get current values.
7759 $monetary= setlocale (LC_MONETARY, 0);
7760 $numeric = setlocale (LC_NUMERIC, 0);
7761 $ctype = setlocale (LC_CTYPE, 0);
7762 if ($CFG->ostype != 'WINDOWS') {
7763 $messages= setlocale (LC_MESSAGES, 0);
7765 // Set locale to all.
7766 $result = setlocale (LC_ALL, $currentlocale);
7767 // If setting of locale fails try the other utf8 or utf-8 variant,
7768 // some operating systems support both (Debian), others just one (OSX).
7769 if ($result === false) {
7770 if (stripos($currentlocale, '.UTF-8') !== false) {
7771 $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
7772 setlocale (LC_ALL, $newlocale);
7773 } else if (stripos($currentlocale, '.UTF8') !== false) {
7774 $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
7775 setlocale (LC_ALL, $newlocale);
7778 // Set old values.
7779 setlocale (LC_MONETARY, $monetary);
7780 setlocale (LC_NUMERIC, $numeric);
7781 if ($CFG->ostype != 'WINDOWS') {
7782 setlocale (LC_MESSAGES, $messages);
7784 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7785 // To workaround a well-known PHP problem with Turkish letter Ii.
7786 setlocale (LC_CTYPE, $ctype);
7791 * Count words in a string.
7793 * Words are defined as things between whitespace.
7795 * @category string
7796 * @param string $string The text to be searched for words.
7797 * @return int The count of words in the specified string
7799 function count_words($string) {
7800 $string = strip_tags($string);
7801 // Decode HTML entities.
7802 $string = html_entity_decode($string);
7803 // Replace underscores (which are classed as word characters) with spaces.
7804 $string = preg_replace('/_/u', ' ', $string);
7805 // Remove any characters that shouldn't be treated as word boundaries.
7806 $string = preg_replace('/[\'’-]/u', '', $string);
7807 // Remove dots and commas from within numbers only.
7808 $string = preg_replace('/([0-9])[.,]([0-9])/u', '$1$2', $string);
7810 return count(preg_split('/\w\b/u', $string)) - 1;
7814 * Count letters in a string.
7816 * Letters are defined as chars not in tags and different from whitespace.
7818 * @category string
7819 * @param string $string The text to be searched for letters.
7820 * @return int The count of letters in the specified text.
7822 function count_letters($string) {
7823 $string = strip_tags($string); // Tags are out now.
7824 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7826 return core_text::strlen($string);
7830 * Generate and return a random string of the specified length.
7832 * @param int $length The length of the string to be created.
7833 * @return string
7835 function random_string($length=15) {
7836 $randombytes = random_bytes_emulate($length);
7837 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7838 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7839 $pool .= '0123456789';
7840 $poollen = strlen($pool);
7841 $string = '';
7842 for ($i = 0; $i < $length; $i++) {
7843 $rand = ord($randombytes[$i]);
7844 $string .= substr($pool, ($rand%($poollen)), 1);
7846 return $string;
7850 * Generate a complex random string (useful for md5 salts)
7852 * This function is based on the above {@link random_string()} however it uses a
7853 * larger pool of characters and generates a string between 24 and 32 characters
7855 * @param int $length Optional if set generates a string to exactly this length
7856 * @return string
7858 function complex_random_string($length=null) {
7859 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7860 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7861 $poollen = strlen($pool);
7862 if ($length===null) {
7863 $length = floor(rand(24, 32));
7865 $randombytes = random_bytes_emulate($length);
7866 $string = '';
7867 for ($i = 0; $i < $length; $i++) {
7868 $rand = ord($randombytes[$i]);
7869 $string .= $pool[($rand%$poollen)];
7871 return $string;
7875 * Try to generates cryptographically secure pseudo-random bytes.
7877 * Note this is achieved by fallbacking between:
7878 * - PHP 7 random_bytes().
7879 * - OpenSSL openssl_random_pseudo_bytes().
7880 * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
7882 * @param int $length requested length in bytes
7883 * @return string binary data
7885 function random_bytes_emulate($length) {
7886 global $CFG;
7887 if ($length <= 0) {
7888 debugging('Invalid random bytes length', DEBUG_DEVELOPER);
7889 return '';
7891 if (function_exists('random_bytes')) {
7892 // Use PHP 7 goodness.
7893 $hash = @random_bytes($length);
7894 if ($hash !== false) {
7895 return $hash;
7898 if (function_exists('openssl_random_pseudo_bytes')) {
7899 // For PHP 5.3 and later with openssl extension.
7900 $hash = openssl_random_pseudo_bytes($length);
7901 if ($hash !== false) {
7902 return $hash;
7906 // Bad luck, there is no reliable random generator, let's just hash some unique stuff that is hard to guess.
7907 $hash = sha1(serialize($CFG) . serialize($_SERVER) . microtime(true) . uniqid('', true), true);
7908 // NOTE: the last param in sha1() is true, this means we are getting 20 bytes, not 40 chars as usual.
7909 if ($length <= 20) {
7910 return substr($hash, 0, $length);
7912 return $hash . random_bytes_emulate($length - 20);
7916 * Given some text (which may contain HTML) and an ideal length,
7917 * this function truncates the text neatly on a word boundary if possible
7919 * @category string
7920 * @param string $text text to be shortened
7921 * @param int $ideal ideal string length
7922 * @param boolean $exact if false, $text will not be cut mid-word
7923 * @param string $ending The string to append if the passed string is truncated
7924 * @return string $truncate shortened string
7926 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7927 // If the plain text is shorter than the maximum length, return the whole text.
7928 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7929 return $text;
7932 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7933 // and only tag in its 'line'.
7934 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7936 $totallength = core_text::strlen($ending);
7937 $truncate = '';
7939 // This array stores information about open and close tags and their position
7940 // in the truncated string. Each item in the array is an object with fields
7941 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7942 // (byte position in truncated text).
7943 $tagdetails = array();
7945 foreach ($lines as $linematchings) {
7946 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7947 if (!empty($linematchings[1])) {
7948 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7949 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7950 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7951 // Record closing tag.
7952 $tagdetails[] = (object) array(
7953 'open' => false,
7954 'tag' => core_text::strtolower($tagmatchings[1]),
7955 'pos' => core_text::strlen($truncate),
7958 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7959 // Record opening tag.
7960 $tagdetails[] = (object) array(
7961 'open' => true,
7962 'tag' => core_text::strtolower($tagmatchings[1]),
7963 'pos' => core_text::strlen($truncate),
7967 // Add html-tag to $truncate'd text.
7968 $truncate .= $linematchings[1];
7971 // Calculate the length of the plain text part of the line; handle entities as one character.
7972 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7973 if ($totallength + $contentlength > $ideal) {
7974 // The number of characters which are left.
7975 $left = $ideal - $totallength;
7976 $entitieslength = 0;
7977 // Search for html entities.
7978 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)) {
7979 // Calculate the real length of all entities in the legal range.
7980 foreach ($entities[0] as $entity) {
7981 if ($entity[1]+1-$entitieslength <= $left) {
7982 $left--;
7983 $entitieslength += core_text::strlen($entity[0]);
7984 } else {
7985 // No more characters left.
7986 break;
7990 $breakpos = $left + $entitieslength;
7992 // If the words shouldn't be cut in the middle...
7993 if (!$exact) {
7994 // Search the last occurence of a space.
7995 for (; $breakpos > 0; $breakpos--) {
7996 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
7997 if ($char === '.' or $char === ' ') {
7998 $breakpos += 1;
7999 break;
8000 } else if (strlen($char) > 2) {
8001 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8002 $breakpos += 1;
8003 break;
8008 if ($breakpos == 0) {
8009 // This deals with the test_shorten_text_no_spaces case.
8010 $breakpos = $left + $entitieslength;
8011 } else if ($breakpos > $left + $entitieslength) {
8012 // This deals with the previous for loop breaking on the first char.
8013 $breakpos = $left + $entitieslength;
8016 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8017 // Maximum length is reached, so get off the loop.
8018 break;
8019 } else {
8020 $truncate .= $linematchings[2];
8021 $totallength += $contentlength;
8024 // If the maximum length is reached, get off the loop.
8025 if ($totallength >= $ideal) {
8026 break;
8030 // Add the defined ending to the text.
8031 $truncate .= $ending;
8033 // Now calculate the list of open html tags based on the truncate position.
8034 $opentags = array();
8035 foreach ($tagdetails as $taginfo) {
8036 if ($taginfo->open) {
8037 // Add tag to the beginning of $opentags list.
8038 array_unshift($opentags, $taginfo->tag);
8039 } else {
8040 // Can have multiple exact same open tags, close the last one.
8041 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8042 if ($pos !== false) {
8043 unset($opentags[$pos]);
8048 // Close all unclosed html-tags.
8049 foreach ($opentags as $tag) {
8050 $truncate .= '</' . $tag . '>';
8053 return $truncate;
8058 * Given dates in seconds, how many weeks is the date from startdate
8059 * The first week is 1, the second 2 etc ...
8061 * @param int $startdate Timestamp for the start date
8062 * @param int $thedate Timestamp for the end date
8063 * @return string
8065 function getweek ($startdate, $thedate) {
8066 if ($thedate < $startdate) {
8067 return 0;
8070 return floor(($thedate - $startdate) / WEEKSECS) + 1;
8074 * Returns a randomly generated password of length $maxlen. inspired by
8076 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8077 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8079 * @param int $maxlen The maximum size of the password being generated.
8080 * @return string
8082 function generate_password($maxlen=10) {
8083 global $CFG;
8085 if (empty($CFG->passwordpolicy)) {
8086 $fillers = PASSWORD_DIGITS;
8087 $wordlist = file($CFG->wordlist);
8088 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8089 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8090 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8091 $password = $word1 . $filler1 . $word2;
8092 } else {
8093 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8094 $digits = $CFG->minpassworddigits;
8095 $lower = $CFG->minpasswordlower;
8096 $upper = $CFG->minpasswordupper;
8097 $nonalphanum = $CFG->minpasswordnonalphanum;
8098 $total = $lower + $upper + $digits + $nonalphanum;
8099 // Var minlength should be the greater one of the two ( $minlen and $total ).
8100 $minlen = $minlen < $total ? $total : $minlen;
8101 // Var maxlen can never be smaller than minlen.
8102 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8103 $additional = $maxlen - $total;
8105 // Make sure we have enough characters to fulfill
8106 // complexity requirements.
8107 $passworddigits = PASSWORD_DIGITS;
8108 while ($digits > strlen($passworddigits)) {
8109 $passworddigits .= PASSWORD_DIGITS;
8111 $passwordlower = PASSWORD_LOWER;
8112 while ($lower > strlen($passwordlower)) {
8113 $passwordlower .= PASSWORD_LOWER;
8115 $passwordupper = PASSWORD_UPPER;
8116 while ($upper > strlen($passwordupper)) {
8117 $passwordupper .= PASSWORD_UPPER;
8119 $passwordnonalphanum = PASSWORD_NONALPHANUM;
8120 while ($nonalphanum > strlen($passwordnonalphanum)) {
8121 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8124 // Now mix and shuffle it all.
8125 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8126 substr(str_shuffle ($passwordupper), 0, $upper) .
8127 substr(str_shuffle ($passworddigits), 0, $digits) .
8128 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8129 substr(str_shuffle ($passwordlower .
8130 $passwordupper .
8131 $passworddigits .
8132 $passwordnonalphanum), 0 , $additional));
8135 return substr ($password, 0, $maxlen);
8139 * Given a float, prints it nicely.
8140 * Localized floats must not be used in calculations!
8142 * The stripzeros feature is intended for making numbers look nicer in small
8143 * areas where it is not necessary to indicate the degree of accuracy by showing
8144 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8145 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8147 * @param float $float The float to print
8148 * @param int $decimalpoints The number of decimal places to print.
8149 * @param bool $localized use localized decimal separator
8150 * @param bool $stripzeros If true, removes final zeros after decimal point
8151 * @return string locale float
8153 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8154 if (is_null($float)) {
8155 return '';
8157 if ($localized) {
8158 $separator = get_string('decsep', 'langconfig');
8159 } else {
8160 $separator = '.';
8162 $result = number_format($float, $decimalpoints, $separator, '');
8163 if ($stripzeros) {
8164 // Remove zeros and final dot if not needed.
8165 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
8167 return $result;
8171 * Converts locale specific floating point/comma number back to standard PHP float value
8172 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8174 * @param string $localefloat locale aware float representation
8175 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8176 * @return mixed float|bool - false or the parsed float.
8178 function unformat_float($localefloat, $strict = false) {
8179 $localefloat = trim($localefloat);
8181 if ($localefloat == '') {
8182 return null;
8185 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8186 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8188 if ($strict && !is_numeric($localefloat)) {
8189 return false;
8192 return (float)$localefloat;
8196 * Given a simple array, this shuffles it up just like shuffle()
8197 * Unlike PHP's shuffle() this function works on any machine.
8199 * @param array $array The array to be rearranged
8200 * @return array
8202 function swapshuffle($array) {
8204 $last = count($array) - 1;
8205 for ($i = 0; $i <= $last; $i++) {
8206 $from = rand(0, $last);
8207 $curr = $array[$i];
8208 $array[$i] = $array[$from];
8209 $array[$from] = $curr;
8211 return $array;
8215 * Like {@link swapshuffle()}, but works on associative arrays
8217 * @param array $array The associative array to be rearranged
8218 * @return array
8220 function swapshuffle_assoc($array) {
8222 $newarray = array();
8223 $newkeys = swapshuffle(array_keys($array));
8225 foreach ($newkeys as $newkey) {
8226 $newarray[$newkey] = $array[$newkey];
8228 return $newarray;
8232 * Given an arbitrary array, and a number of draws,
8233 * this function returns an array with that amount
8234 * of items. The indexes are retained.
8236 * @todo Finish documenting this function
8238 * @param array $array
8239 * @param int $draws
8240 * @return array
8242 function draw_rand_array($array, $draws) {
8244 $return = array();
8246 $last = count($array);
8248 if ($draws > $last) {
8249 $draws = $last;
8252 while ($draws > 0) {
8253 $last--;
8255 $keys = array_keys($array);
8256 $rand = rand(0, $last);
8258 $return[$keys[$rand]] = $array[$keys[$rand]];
8259 unset($array[$keys[$rand]]);
8261 $draws--;
8264 return $return;
8268 * Calculate the difference between two microtimes
8270 * @param string $a The first Microtime
8271 * @param string $b The second Microtime
8272 * @return string
8274 function microtime_diff($a, $b) {
8275 list($adec, $asec) = explode(' ', $a);
8276 list($bdec, $bsec) = explode(' ', $b);
8277 return $bsec - $asec + $bdec - $adec;
8281 * Given a list (eg a,b,c,d,e) this function returns
8282 * an array of 1->a, 2->b, 3->c etc
8284 * @param string $list The string to explode into array bits
8285 * @param string $separator The separator used within the list string
8286 * @return array The now assembled array
8288 function make_menu_from_list($list, $separator=',') {
8290 $array = array_reverse(explode($separator, $list), true);
8291 foreach ($array as $key => $item) {
8292 $outarray[$key+1] = trim($item);
8294 return $outarray;
8298 * Creates an array that represents all the current grades that
8299 * can be chosen using the given grading type.
8301 * Negative numbers
8302 * are scales, zero is no grade, and positive numbers are maximum
8303 * grades.
8305 * @todo Finish documenting this function or better deprecated this completely!
8307 * @param int $gradingtype
8308 * @return array
8310 function make_grades_menu($gradingtype) {
8311 global $DB;
8313 $grades = array();
8314 if ($gradingtype < 0) {
8315 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8316 return make_menu_from_list($scale->scale);
8318 } else if ($gradingtype > 0) {
8319 for ($i=$gradingtype; $i>=0; $i--) {
8320 $grades[$i] = $i .' / '. $gradingtype;
8322 return $grades;
8324 return $grades;
8328 * This function returns the number of activities using the given scale in the given course.
8330 * @param int $courseid The course ID to check.
8331 * @param int $scaleid The scale ID to check
8332 * @return int
8334 function course_scale_used($courseid, $scaleid) {
8335 global $CFG, $DB;
8337 $return = 0;
8339 if (!empty($scaleid)) {
8340 if ($cms = get_course_mods($courseid)) {
8341 foreach ($cms as $cm) {
8342 // Check cm->name/lib.php exists.
8343 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
8344 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
8345 $functionname = $cm->modname.'_scale_used';
8346 if (function_exists($functionname)) {
8347 if ($functionname($cm->instance, $scaleid)) {
8348 $return++;
8355 // Check if any course grade item makes use of the scale.
8356 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8358 // Check if any outcome in the course makes use of the scale.
8359 $return += $DB->count_records_sql("SELECT COUNT('x')
8360 FROM {grade_outcomes_courses} goc,
8361 {grade_outcomes} go
8362 WHERE go.id = goc.outcomeid
8363 AND go.scaleid = ? AND goc.courseid = ?",
8364 array($scaleid, $courseid));
8366 return $return;
8370 * This function returns the number of activities using scaleid in the entire site
8372 * @param int $scaleid
8373 * @param array $courses
8374 * @return int
8376 function site_scale_used($scaleid, &$courses) {
8377 $return = 0;
8379 if (!is_array($courses) || count($courses) == 0) {
8380 $courses = get_courses("all", false, "c.id, c.shortname");
8383 if (!empty($scaleid)) {
8384 if (is_array($courses) && count($courses) > 0) {
8385 foreach ($courses as $course) {
8386 $return += course_scale_used($course->id, $scaleid);
8390 return $return;
8394 * make_unique_id_code
8396 * @todo Finish documenting this function
8398 * @uses $_SERVER
8399 * @param string $extra Extra string to append to the end of the code
8400 * @return string
8402 function make_unique_id_code($extra = '') {
8404 $hostname = 'unknownhost';
8405 if (!empty($_SERVER['HTTP_HOST'])) {
8406 $hostname = $_SERVER['HTTP_HOST'];
8407 } else if (!empty($_ENV['HTTP_HOST'])) {
8408 $hostname = $_ENV['HTTP_HOST'];
8409 } else if (!empty($_SERVER['SERVER_NAME'])) {
8410 $hostname = $_SERVER['SERVER_NAME'];
8411 } else if (!empty($_ENV['SERVER_NAME'])) {
8412 $hostname = $_ENV['SERVER_NAME'];
8415 $date = gmdate("ymdHis");
8417 $random = random_string(6);
8419 if ($extra) {
8420 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8421 } else {
8422 return $hostname .'+'. $date .'+'. $random;
8428 * Function to check the passed address is within the passed subnet
8430 * The parameter is a comma separated string of subnet definitions.
8431 * Subnet strings can be in one of three formats:
8432 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8433 * 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)
8434 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8435 * Code for type 1 modified from user posted comments by mediator at
8436 * {@link http://au.php.net/manual/en/function.ip2long.php}
8438 * @param string $addr The address you are checking
8439 * @param string $subnetstr The string of subnet addresses
8440 * @return bool
8442 function address_in_subnet($addr, $subnetstr) {
8444 if ($addr == '0.0.0.0') {
8445 return false;
8447 $subnets = explode(',', $subnetstr);
8448 $found = false;
8449 $addr = trim($addr);
8450 $addr = cleanremoteaddr($addr, false); // Normalise.
8451 if ($addr === null) {
8452 return false;
8454 $addrparts = explode(':', $addr);
8456 $ipv6 = strpos($addr, ':');
8458 foreach ($subnets as $subnet) {
8459 $subnet = trim($subnet);
8460 if ($subnet === '') {
8461 continue;
8464 if (strpos($subnet, '/') !== false) {
8465 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8466 list($ip, $mask) = explode('/', $subnet);
8467 $mask = trim($mask);
8468 if (!is_number($mask)) {
8469 continue; // Incorect mask number, eh?
8471 $ip = cleanremoteaddr($ip, false); // Normalise.
8472 if ($ip === null) {
8473 continue;
8475 if (strpos($ip, ':') !== false) {
8476 // IPv6.
8477 if (!$ipv6) {
8478 continue;
8480 if ($mask > 128 or $mask < 0) {
8481 continue; // Nonsense.
8483 if ($mask == 0) {
8484 return true; // Any address.
8486 if ($mask == 128) {
8487 if ($ip === $addr) {
8488 return true;
8490 continue;
8492 $ipparts = explode(':', $ip);
8493 $modulo = $mask % 16;
8494 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8495 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8496 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8497 if ($modulo == 0) {
8498 return true;
8500 $pos = ($mask-$modulo)/16;
8501 $ipnet = hexdec($ipparts[$pos]);
8502 $addrnet = hexdec($addrparts[$pos]);
8503 $mask = 0xffff << (16 - $modulo);
8504 if (($addrnet & $mask) == ($ipnet & $mask)) {
8505 return true;
8509 } else {
8510 // IPv4.
8511 if ($ipv6) {
8512 continue;
8514 if ($mask > 32 or $mask < 0) {
8515 continue; // Nonsense.
8517 if ($mask == 0) {
8518 return true;
8520 if ($mask == 32) {
8521 if ($ip === $addr) {
8522 return true;
8524 continue;
8526 $mask = 0xffffffff << (32 - $mask);
8527 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8528 return true;
8532 } else if (strpos($subnet, '-') !== false) {
8533 // 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.
8534 $parts = explode('-', $subnet);
8535 if (count($parts) != 2) {
8536 continue;
8539 if (strpos($subnet, ':') !== false) {
8540 // IPv6.
8541 if (!$ipv6) {
8542 continue;
8544 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8545 if ($ipstart === null) {
8546 continue;
8548 $ipparts = explode(':', $ipstart);
8549 $start = hexdec(array_pop($ipparts));
8550 $ipparts[] = trim($parts[1]);
8551 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8552 if ($ipend === null) {
8553 continue;
8555 $ipparts[7] = '';
8556 $ipnet = implode(':', $ipparts);
8557 if (strpos($addr, $ipnet) !== 0) {
8558 continue;
8560 $ipparts = explode(':', $ipend);
8561 $end = hexdec($ipparts[7]);
8563 $addrend = hexdec($addrparts[7]);
8565 if (($addrend >= $start) and ($addrend <= $end)) {
8566 return true;
8569 } else {
8570 // IPv4.
8571 if ($ipv6) {
8572 continue;
8574 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8575 if ($ipstart === null) {
8576 continue;
8578 $ipparts = explode('.', $ipstart);
8579 $ipparts[3] = trim($parts[1]);
8580 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8581 if ($ipend === null) {
8582 continue;
8585 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8586 return true;
8590 } else {
8591 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8592 if (strpos($subnet, ':') !== false) {
8593 // IPv6.
8594 if (!$ipv6) {
8595 continue;
8597 $parts = explode(':', $subnet);
8598 $count = count($parts);
8599 if ($parts[$count-1] === '') {
8600 unset($parts[$count-1]); // Trim trailing :'s.
8601 $count--;
8602 $subnet = implode('.', $parts);
8604 $isip = cleanremoteaddr($subnet, false); // Normalise.
8605 if ($isip !== null) {
8606 if ($isip === $addr) {
8607 return true;
8609 continue;
8610 } else if ($count > 8) {
8611 continue;
8613 $zeros = array_fill(0, 8-$count, '0');
8614 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8615 if (address_in_subnet($addr, $subnet)) {
8616 return true;
8619 } else {
8620 // IPv4.
8621 if ($ipv6) {
8622 continue;
8624 $parts = explode('.', $subnet);
8625 $count = count($parts);
8626 if ($parts[$count-1] === '') {
8627 unset($parts[$count-1]); // Trim trailing .
8628 $count--;
8629 $subnet = implode('.', $parts);
8631 if ($count == 4) {
8632 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8633 if ($subnet === $addr) {
8634 return true;
8636 continue;
8637 } else if ($count > 4) {
8638 continue;
8640 $zeros = array_fill(0, 4-$count, '0');
8641 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8642 if (address_in_subnet($addr, $subnet)) {
8643 return true;
8649 return false;
8653 * For outputting debugging info
8655 * @param string $string The string to write
8656 * @param string $eol The end of line char(s) to use
8657 * @param string $sleep Period to make the application sleep
8658 * This ensures any messages have time to display before redirect
8660 function mtrace($string, $eol="\n", $sleep=0) {
8662 if (defined('STDOUT') and !PHPUNIT_TEST) {
8663 fwrite(STDOUT, $string.$eol);
8664 } else {
8665 echo $string . $eol;
8668 flush();
8670 // Delay to keep message on user's screen in case of subsequent redirect.
8671 if ($sleep) {
8672 sleep($sleep);
8677 * Replace 1 or more slashes or backslashes to 1 slash
8679 * @param string $path The path to strip
8680 * @return string the path with double slashes removed
8682 function cleardoubleslashes ($path) {
8683 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8687 * Is current ip in give list?
8689 * @param string $list
8690 * @return bool
8692 function remoteip_in_list($list) {
8693 $inlist = false;
8694 $clientip = getremoteaddr(null);
8696 if (!$clientip) {
8697 // Ensure access on cli.
8698 return true;
8701 $list = explode("\n", $list);
8702 foreach ($list as $subnet) {
8703 $subnet = trim($subnet);
8704 if (address_in_subnet($clientip, $subnet)) {
8705 $inlist = true;
8706 break;
8709 return $inlist;
8713 * Returns most reliable client address
8715 * @param string $default If an address can't be determined, then return this
8716 * @return string The remote IP address
8718 function getremoteaddr($default='0.0.0.0') {
8719 global $CFG;
8721 if (empty($CFG->getremoteaddrconf)) {
8722 // This will happen, for example, before just after the upgrade, as the
8723 // user is redirected to the admin screen.
8724 $variablestoskip = 0;
8725 } else {
8726 $variablestoskip = $CFG->getremoteaddrconf;
8728 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8729 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8730 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8731 return $address ? $address : $default;
8734 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8735 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8736 $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
8737 $address = $forwardedaddresses[0];
8739 if (substr_count($address, ":") > 1) {
8740 // Remove port and brackets from IPv6.
8741 if (preg_match("/\[(.*)\]:/", $address, $matches)) {
8742 $address = $matches[1];
8744 } else {
8745 // Remove port from IPv4.
8746 if (substr_count($address, ":") == 1) {
8747 $parts = explode(":", $address);
8748 $address = $parts[0];
8752 $address = cleanremoteaddr($address);
8753 return $address ? $address : $default;
8756 if (!empty($_SERVER['REMOTE_ADDR'])) {
8757 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8758 return $address ? $address : $default;
8759 } else {
8760 return $default;
8765 * Cleans an ip address. Internal addresses are now allowed.
8766 * (Originally local addresses were not allowed.)
8768 * @param string $addr IPv4 or IPv6 address
8769 * @param bool $compress use IPv6 address compression
8770 * @return string normalised ip address string, null if error
8772 function cleanremoteaddr($addr, $compress=false) {
8773 $addr = trim($addr);
8775 // TODO: maybe add a separate function is_addr_public() or something like this.
8777 if (strpos($addr, ':') !== false) {
8778 // Can be only IPv6.
8779 $parts = explode(':', $addr);
8780 $count = count($parts);
8782 if (strpos($parts[$count-1], '.') !== false) {
8783 // Legacy ipv4 notation.
8784 $last = array_pop($parts);
8785 $ipv4 = cleanremoteaddr($last, true);
8786 if ($ipv4 === null) {
8787 return null;
8789 $bits = explode('.', $ipv4);
8790 $parts[] = dechex($bits[0]).dechex($bits[1]);
8791 $parts[] = dechex($bits[2]).dechex($bits[3]);
8792 $count = count($parts);
8793 $addr = implode(':', $parts);
8796 if ($count < 3 or $count > 8) {
8797 return null; // Severly malformed.
8800 if ($count != 8) {
8801 if (strpos($addr, '::') === false) {
8802 return null; // Malformed.
8804 // Uncompress.
8805 $insertat = array_search('', $parts, true);
8806 $missing = array_fill(0, 1 + 8 - $count, '0');
8807 array_splice($parts, $insertat, 1, $missing);
8808 foreach ($parts as $key => $part) {
8809 if ($part === '') {
8810 $parts[$key] = '0';
8815 $adr = implode(':', $parts);
8816 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8817 return null; // Incorrect format - sorry.
8820 // Normalise 0s and case.
8821 $parts = array_map('hexdec', $parts);
8822 $parts = array_map('dechex', $parts);
8824 $result = implode(':', $parts);
8826 if (!$compress) {
8827 return $result;
8830 if ($result === '0:0:0:0:0:0:0:0') {
8831 return '::'; // All addresses.
8834 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8835 if ($compressed !== $result) {
8836 return $compressed;
8839 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8840 if ($compressed !== $result) {
8841 return $compressed;
8844 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8845 if ($compressed !== $result) {
8846 return $compressed;
8849 return $result;
8852 // First get all things that look like IPv4 addresses.
8853 $parts = array();
8854 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8855 return null;
8857 unset($parts[0]);
8859 foreach ($parts as $key => $match) {
8860 if ($match > 255) {
8861 return null;
8863 $parts[$key] = (int)$match; // Normalise 0s.
8866 return implode('.', $parts);
8870 * This function will make a complete copy of anything it's given,
8871 * regardless of whether it's an object or not.
8873 * @param mixed $thing Something you want cloned
8874 * @return mixed What ever it is you passed it
8876 function fullclone($thing) {
8877 return unserialize(serialize($thing));
8881 * If new messages are waiting for the current user, then insert
8882 * JavaScript to pop up the messaging window into the page
8884 * @return void
8886 function message_popup_window() {
8887 global $USER, $DB, $PAGE, $CFG;
8889 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
8890 return;
8893 if (!isloggedin() || isguestuser()) {
8894 return;
8897 if (!isset($USER->message_lastpopup)) {
8898 $USER->message_lastpopup = 0;
8899 } else if ($USER->message_lastpopup > (time()-120)) {
8900 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8901 return;
8904 // A quick query to check whether the user has new messages.
8905 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
8906 if ($messagecount < 1) {
8907 return;
8910 // There are unread messages so now do a more complex but slower query.
8911 $messagesql = "SELECT m.id, c.blocked
8912 FROM {message} m
8913 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8914 JOIN {message_processors} p ON mw.processorid=p.id
8915 JOIN {user} u ON m.useridfrom=u.id
8916 LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
8917 AND c.userid = m.useridto
8918 WHERE m.useridto = :userid
8919 AND p.name='popup'";
8921 // If the user was last notified over an hour ago we can re-notify them of old messages
8922 // so don't worry about when the new message was sent.
8923 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
8924 if (!$lastnotifiedlongago) {
8925 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8928 $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
8930 $validmessages = 0;
8931 foreach ($waitingmessages as $messageinfo) {
8932 if ($messageinfo->blocked) {
8933 // Message is from a user who has since been blocked so just mark it read.
8934 // Get the full message to mark as read.
8935 $messageobject = $DB->get_record('message', array('id' => $messageinfo->id));
8936 message_mark_message_read($messageobject, time());
8937 } else {
8938 $validmessages++;
8942 if ($validmessages > 0) {
8943 $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
8944 $strgomessage = get_string('gotomessages', 'message');
8945 $strstaymessage = get_string('ignore', 'admin');
8947 $notificationsound = null;
8948 $beep = get_user_preferences('message_beepnewmessage', '');
8949 if (!empty($beep)) {
8950 // Browsers will work down this list until they find something they support.
8951 $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
8952 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
8953 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8954 $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8956 $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8959 $url = $CFG->wwwroot.'/message/index.php';
8960 $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8961 html_writer::start_tag('div', array('id' => 'newmessagetext')).
8962 $strmessages.
8963 html_writer::end_tag('div').
8965 $notificationsound.
8966 html_writer::start_tag('div', array('id' => 'newmessagelinks')).
8967 html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
8968 html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
8969 html_writer::end_tag('div');
8970 html_writer::end_tag('div');
8972 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
8974 $USER->message_lastpopup = time();
8979 * Used to make sure that $min <= $value <= $max
8981 * Make sure that value is between min, and max
8983 * @param int $min The minimum value
8984 * @param int $value The value to check
8985 * @param int $max The maximum value
8986 * @return int
8988 function bounded_number($min, $value, $max) {
8989 if ($value < $min) {
8990 return $min;
8992 if ($value > $max) {
8993 return $max;
8995 return $value;
8999 * Check if there is a nested array within the passed array
9001 * @param array $array
9002 * @return bool true if there is a nested array false otherwise
9004 function array_is_nested($array) {
9005 foreach ($array as $value) {
9006 if (is_array($value)) {
9007 return true;
9010 return false;
9014 * get_performance_info() pairs up with init_performance_info()
9015 * loaded in setup.php. Returns an array with 'html' and 'txt'
9016 * values ready for use, and each of the individual stats provided
9017 * separately as well.
9019 * @return array
9021 function get_performance_info() {
9022 global $CFG, $PERF, $DB, $PAGE;
9024 $info = array();
9025 $info['html'] = ''; // Holds userfriendly HTML representation.
9026 $info['txt'] = me() . ' '; // Holds log-friendly representation.
9028 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9030 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
9031 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9033 if (function_exists('memory_get_usage')) {
9034 $info['memory_total'] = memory_get_usage();
9035 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9036 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
9037 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9038 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9041 if (function_exists('memory_get_peak_usage')) {
9042 $info['memory_peak'] = memory_get_peak_usage();
9043 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
9044 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9047 $inc = get_included_files();
9048 $info['includecount'] = count($inc);
9049 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
9050 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9052 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9053 // We can not track more performance before installation or before PAGE init, sorry.
9054 return $info;
9057 $filtermanager = filter_manager::instance();
9058 if (method_exists($filtermanager, 'get_performance_summary')) {
9059 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9060 $info = array_merge($filterinfo, $info);
9061 foreach ($filterinfo as $key => $value) {
9062 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
9063 $info['txt'] .= "$key: $value ";
9067 $stringmanager = get_string_manager();
9068 if (method_exists($stringmanager, 'get_performance_summary')) {
9069 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9070 $info = array_merge($filterinfo, $info);
9071 foreach ($filterinfo as $key => $value) {
9072 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
9073 $info['txt'] .= "$key: $value ";
9077 if (!empty($PERF->logwrites)) {
9078 $info['logwrites'] = $PERF->logwrites;
9079 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
9080 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9083 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9084 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
9085 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9087 $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9088 $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
9089 $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9091 if (function_exists('posix_times')) {
9092 $ptimes = posix_times();
9093 if (is_array($ptimes)) {
9094 foreach ($ptimes as $key => $val) {
9095 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
9097 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
9098 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9102 // Grab the load average for the last minute.
9103 // /proc will only work under some linux configurations
9104 // while uptime is there under MacOSX/Darwin and other unices.
9105 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9106 list($serverload) = explode(' ', $loadavg[0]);
9107 unset($loadavg);
9108 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9109 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9110 $serverload = $matches[1];
9111 } else {
9112 trigger_error('Could not parse uptime output!');
9115 if (!empty($serverload)) {
9116 $info['serverload'] = $serverload;
9117 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
9118 $info['txt'] .= "serverload: {$info['serverload']} ";
9121 // Display size of session if session started.
9122 if ($si = \core\session\manager::get_performance_info()) {
9123 $info['sessionsize'] = $si['size'];
9124 $info['html'] .= $si['html'];
9125 $info['txt'] .= $si['txt'];
9128 if ($stats = cache_helper::get_stats()) {
9129 $html = '<span class="cachesused">';
9130 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
9131 $text = 'Caches used (hits/misses/sets): ';
9132 $hits = 0;
9133 $misses = 0;
9134 $sets = 0;
9135 foreach ($stats as $definition => $stores) {
9136 $html .= '<span class="cache-definition-stats">';
9137 $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
9138 $text .= "$definition {";
9139 foreach ($stores as $store => $data) {
9140 $hits += $data['hits'];
9141 $misses += $data['misses'];
9142 $sets += $data['sets'];
9143 if ($data['hits'] == 0 and $data['misses'] > 0) {
9144 $cachestoreclass = 'nohits';
9145 } else if ($data['hits'] < $data['misses']) {
9146 $cachestoreclass = 'lowhits';
9147 } else {
9148 $cachestoreclass = 'hihits';
9150 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9151 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
9153 $html .= '</span>';
9154 $text .= '} ';
9156 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
9157 $html .= '</span> ';
9158 $info['cachesused'] = "$hits / $misses / $sets";
9159 $info['html'] .= $html;
9160 $info['txt'] .= $text.'. ';
9161 } else {
9162 $info['cachesused'] = '0 / 0 / 0';
9163 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
9164 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9167 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
9168 return $info;
9172 * Legacy function.
9174 * @todo Document this function linux people
9176 function apd_get_profiling() {
9177 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
9181 * Delete directory or only its content
9183 * @param string $dir directory path
9184 * @param bool $contentonly
9185 * @return bool success, true also if dir does not exist
9187 function remove_dir($dir, $contentonly=false) {
9188 if (!file_exists($dir)) {
9189 // Nothing to do.
9190 return true;
9192 if (!$handle = opendir($dir)) {
9193 return false;
9195 $result = true;
9196 while (false!==($item = readdir($handle))) {
9197 if ($item != '.' && $item != '..') {
9198 if (is_dir($dir.'/'.$item)) {
9199 $result = remove_dir($dir.'/'.$item) && $result;
9200 } else {
9201 $result = unlink($dir.'/'.$item) && $result;
9205 closedir($handle);
9206 if ($contentonly) {
9207 clearstatcache(); // Make sure file stat cache is properly invalidated.
9208 return $result;
9210 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9211 clearstatcache(); // Make sure file stat cache is properly invalidated.
9212 return $result;
9216 * Detect if an object or a class contains a given property
9217 * will take an actual object or the name of a class
9219 * @param mix $obj Name of class or real object to test
9220 * @param string $property name of property to find
9221 * @return bool true if property exists
9223 function object_property_exists( $obj, $property ) {
9224 if (is_string( $obj )) {
9225 $properties = get_class_vars( $obj );
9226 } else {
9227 $properties = get_object_vars( $obj );
9229 return array_key_exists( $property, $properties );
9233 * Converts an object into an associative array
9235 * This function converts an object into an associative array by iterating
9236 * over its public properties. Because this function uses the foreach
9237 * construct, Iterators are respected. It works recursively on arrays of objects.
9238 * Arrays and simple values are returned as is.
9240 * If class has magic properties, it can implement IteratorAggregate
9241 * and return all available properties in getIterator()
9243 * @param mixed $var
9244 * @return array
9246 function convert_to_array($var) {
9247 $result = array();
9249 // Loop over elements/properties.
9250 foreach ($var as $key => $value) {
9251 // Recursively convert objects.
9252 if (is_object($value) || is_array($value)) {
9253 $result[$key] = convert_to_array($value);
9254 } else {
9255 // Simple values are untouched.
9256 $result[$key] = $value;
9259 return $result;
9263 * Detect a custom script replacement in the data directory that will
9264 * replace an existing moodle script
9266 * @return string|bool full path name if a custom script exists, false if no custom script exists
9268 function custom_script_path() {
9269 global $CFG, $SCRIPT;
9271 if ($SCRIPT === null) {
9272 // Probably some weird external script.
9273 return false;
9276 $scriptpath = $CFG->customscripts . $SCRIPT;
9278 // Check the custom script exists.
9279 if (file_exists($scriptpath) and is_file($scriptpath)) {
9280 return $scriptpath;
9281 } else {
9282 return false;
9287 * Returns whether or not the user object is a remote MNET user. This function
9288 * is in moodlelib because it does not rely on loading any of the MNET code.
9290 * @param object $user A valid user object
9291 * @return bool True if the user is from a remote Moodle.
9293 function is_mnet_remote_user($user) {
9294 global $CFG;
9296 if (!isset($CFG->mnet_localhost_id)) {
9297 include_once($CFG->dirroot . '/mnet/lib.php');
9298 $env = new mnet_environment();
9299 $env->init();
9300 unset($env);
9303 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9307 * This function will search for browser prefereed languages, setting Moodle
9308 * to use the best one available if $SESSION->lang is undefined
9310 function setup_lang_from_browser() {
9311 global $CFG, $SESSION, $USER;
9313 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9314 // Lang is defined in session or user profile, nothing to do.
9315 return;
9318 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9319 return;
9322 // Extract and clean langs from headers.
9323 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9324 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9325 $rawlangs = explode(',', $rawlangs); // Convert to array.
9326 $langs = array();
9328 $order = 1.0;
9329 foreach ($rawlangs as $lang) {
9330 if (strpos($lang, ';') === false) {
9331 $langs[(string)$order] = $lang;
9332 $order = $order-0.01;
9333 } else {
9334 $parts = explode(';', $lang);
9335 $pos = strpos($parts[1], '=');
9336 $langs[substr($parts[1], $pos+1)] = $parts[0];
9339 krsort($langs, SORT_NUMERIC);
9341 // Look for such langs under standard locations.
9342 foreach ($langs as $lang) {
9343 // Clean it properly for include.
9344 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9345 if (get_string_manager()->translation_exists($lang, false)) {
9346 // Lang exists, set it in session.
9347 $SESSION->lang = $lang;
9348 // We have finished. Go out.
9349 break;
9352 return;
9356 * Check if $url matches anything in proxybypass list
9358 * Any errors just result in the proxy being used (least bad)
9360 * @param string $url url to check
9361 * @return boolean true if we should bypass the proxy
9363 function is_proxybypass( $url ) {
9364 global $CFG;
9366 // Sanity check.
9367 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9368 return false;
9371 // Get the host part out of the url.
9372 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9373 return false;
9376 // Get the possible bypass hosts into an array.
9377 $matches = explode( ',', $CFG->proxybypass );
9379 // Check for a match.
9380 // (IPs need to match the left hand side and hosts the right of the url,
9381 // but we can recklessly check both as there can't be a false +ve).
9382 foreach ($matches as $match) {
9383 $match = trim($match);
9385 // Try for IP match (Left side).
9386 $lhs = substr($host, 0, strlen($match));
9387 if (strcasecmp($match, $lhs)==0) {
9388 return true;
9391 // Try for host match (Right side).
9392 $rhs = substr($host, -strlen($match));
9393 if (strcasecmp($match, $rhs)==0) {
9394 return true;
9398 // Nothing matched.
9399 return false;
9403 * Check if the passed navigation is of the new style
9405 * @param mixed $navigation
9406 * @return bool true for yes false for no
9408 function is_newnav($navigation) {
9409 if (is_array($navigation) && !empty($navigation['newnav'])) {
9410 return true;
9411 } else {
9412 return false;
9417 * Checks whether the given variable name is defined as a variable within the given object.
9419 * This will NOT work with stdClass objects, which have no class variables.
9421 * @param string $var The variable name
9422 * @param object $object The object to check
9423 * @return boolean
9425 function in_object_vars($var, $object) {
9426 $classvars = get_class_vars(get_class($object));
9427 $classvars = array_keys($classvars);
9428 return in_array($var, $classvars);
9432 * Returns an array without repeated objects.
9433 * This function is similar to array_unique, but for arrays that have objects as values
9435 * @param array $array
9436 * @param bool $keepkeyassoc
9437 * @return array
9439 function object_array_unique($array, $keepkeyassoc = true) {
9440 $duplicatekeys = array();
9441 $tmp = array();
9443 foreach ($array as $key => $val) {
9444 // Convert objects to arrays, in_array() does not support objects.
9445 if (is_object($val)) {
9446 $val = (array)$val;
9449 if (!in_array($val, $tmp)) {
9450 $tmp[] = $val;
9451 } else {
9452 $duplicatekeys[] = $key;
9456 foreach ($duplicatekeys as $key) {
9457 unset($array[$key]);
9460 return $keepkeyassoc ? $array : array_values($array);
9464 * Is a userid the primary administrator?
9466 * @param int $userid int id of user to check
9467 * @return boolean
9469 function is_primary_admin($userid) {
9470 $primaryadmin = get_admin();
9472 if ($userid == $primaryadmin->id) {
9473 return true;
9474 } else {
9475 return false;
9480 * Returns the site identifier
9482 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9484 function get_site_identifier() {
9485 global $CFG;
9486 // Check to see if it is missing. If so, initialise it.
9487 if (empty($CFG->siteidentifier)) {
9488 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9490 // Return it.
9491 return $CFG->siteidentifier;
9495 * Check whether the given password has no more than the specified
9496 * number of consecutive identical characters.
9498 * @param string $password password to be checked against the password policy
9499 * @param integer $maxchars maximum number of consecutive identical characters
9500 * @return bool
9502 function check_consecutive_identical_characters($password, $maxchars) {
9504 if ($maxchars < 1) {
9505 return true; // Zero 0 is to disable this check.
9507 if (strlen($password) <= $maxchars) {
9508 return true; // Too short to fail this test.
9511 $previouschar = '';
9512 $consecutivecount = 1;
9513 foreach (str_split($password) as $char) {
9514 if ($char != $previouschar) {
9515 $consecutivecount = 1;
9516 } else {
9517 $consecutivecount++;
9518 if ($consecutivecount > $maxchars) {
9519 return false; // Check failed already.
9523 $previouschar = $char;
9526 return true;
9530 * Helper function to do partial function binding.
9531 * so we can use it for preg_replace_callback, for example
9532 * this works with php functions, user functions, static methods and class methods
9533 * it returns you a callback that you can pass on like so:
9535 * $callback = partial('somefunction', $arg1, $arg2);
9536 * or
9537 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9538 * or even
9539 * $obj = new someclass();
9540 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9542 * and then the arguments that are passed through at calltime are appended to the argument list.
9544 * @param mixed $function a php callback
9545 * @param mixed $arg1,... $argv arguments to partially bind with
9546 * @return array Array callback
9548 function partial() {
9549 if (!class_exists('partial')) {
9551 * Used to manage function binding.
9552 * @copyright 2009 Penny Leach
9553 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9555 class partial{
9556 /** @var array */
9557 public $values = array();
9558 /** @var string The function to call as a callback. */
9559 public $func;
9561 * Constructor
9562 * @param string $func
9563 * @param array $args
9565 public function __construct($func, $args) {
9566 $this->values = $args;
9567 $this->func = $func;
9570 * Calls the callback function.
9571 * @return mixed
9573 public function method() {
9574 $args = func_get_args();
9575 return call_user_func_array($this->func, array_merge($this->values, $args));
9579 $args = func_get_args();
9580 $func = array_shift($args);
9581 $p = new partial($func, $args);
9582 return array($p, 'method');
9586 * helper function to load up and initialise the mnet environment
9587 * this must be called before you use mnet functions.
9589 * @return mnet_environment the equivalent of old $MNET global
9591 function get_mnet_environment() {
9592 global $CFG;
9593 require_once($CFG->dirroot . '/mnet/lib.php');
9594 static $instance = null;
9595 if (empty($instance)) {
9596 $instance = new mnet_environment();
9597 $instance->init();
9599 return $instance;
9603 * during xmlrpc server code execution, any code wishing to access
9604 * information about the remote peer must use this to get it.
9606 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9608 function get_mnet_remote_client() {
9609 if (!defined('MNET_SERVER')) {
9610 debugging(get_string('notinxmlrpcserver', 'mnet'));
9611 return false;
9613 global $MNET_REMOTE_CLIENT;
9614 if (isset($MNET_REMOTE_CLIENT)) {
9615 return $MNET_REMOTE_CLIENT;
9617 return false;
9621 * during the xmlrpc server code execution, this will be called
9622 * to setup the object returned by {@link get_mnet_remote_client}
9624 * @param mnet_remote_client $client the client to set up
9625 * @throws moodle_exception
9627 function set_mnet_remote_client($client) {
9628 if (!defined('MNET_SERVER')) {
9629 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9631 global $MNET_REMOTE_CLIENT;
9632 $MNET_REMOTE_CLIENT = $client;
9636 * return the jump url for a given remote user
9637 * this is used for rewriting forum post links in emails, etc
9639 * @param stdclass $user the user to get the idp url for
9641 function mnet_get_idp_jump_url($user) {
9642 global $CFG;
9644 static $mnetjumps = array();
9645 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9646 $idp = mnet_get_peer_host($user->mnethostid);
9647 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9648 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9650 return $mnetjumps[$user->mnethostid];
9654 * Gets the homepage to use for the current user
9656 * @return int One of HOMEPAGE_*
9658 function get_home_page() {
9659 global $CFG;
9661 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9662 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9663 return HOMEPAGE_MY;
9664 } else {
9665 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9668 return HOMEPAGE_SITE;
9672 * Gets the name of a course to be displayed when showing a list of courses.
9673 * By default this is just $course->fullname but user can configure it. The
9674 * result of this function should be passed through print_string.
9675 * @param stdClass|course_in_list $course Moodle course object
9676 * @return string Display name of course (either fullname or short + fullname)
9678 function get_course_display_name_for_list($course) {
9679 global $CFG;
9680 if (!empty($CFG->courselistshortnames)) {
9681 if (!($course instanceof stdClass)) {
9682 $course = (object)convert_to_array($course);
9684 return get_string('courseextendednamedisplay', '', $course);
9685 } else {
9686 return $course->fullname;
9691 * The lang_string class
9693 * This special class is used to create an object representation of a string request.
9694 * It is special because processing doesn't occur until the object is first used.
9695 * The class was created especially to aid performance in areas where strings were
9696 * required to be generated but were not necessarily used.
9697 * As an example the admin tree when generated uses over 1500 strings, of which
9698 * normally only 1/3 are ever actually printed at any time.
9699 * The performance advantage is achieved by not actually processing strings that
9700 * arn't being used, as such reducing the processing required for the page.
9702 * How to use the lang_string class?
9703 * There are two methods of using the lang_string class, first through the
9704 * forth argument of the get_string function, and secondly directly.
9705 * The following are examples of both.
9706 * 1. Through get_string calls e.g.
9707 * $string = get_string($identifier, $component, $a, true);
9708 * $string = get_string('yes', 'moodle', null, true);
9709 * 2. Direct instantiation
9710 * $string = new lang_string($identifier, $component, $a, $lang);
9711 * $string = new lang_string('yes');
9713 * How do I use a lang_string object?
9714 * The lang_string object makes use of a magic __toString method so that you
9715 * are able to use the object exactly as you would use a string in most cases.
9716 * This means you are able to collect it into a variable and then directly
9717 * echo it, or concatenate it into another string, or similar.
9718 * The other thing you can do is manually get the string by calling the
9719 * lang_strings out method e.g.
9720 * $string = new lang_string('yes');
9721 * $string->out();
9722 * Also worth noting is that the out method can take one argument, $lang which
9723 * allows the developer to change the language on the fly.
9725 * When should I use a lang_string object?
9726 * The lang_string object is designed to be used in any situation where a
9727 * string may not be needed, but needs to be generated.
9728 * The admin tree is a good example of where lang_string objects should be
9729 * used.
9730 * A more practical example would be any class that requries strings that may
9731 * not be printed (after all classes get renderer by renderers and who knows
9732 * what they will do ;))
9734 * When should I not use a lang_string object?
9735 * Don't use lang_strings when you are going to use a string immediately.
9736 * There is no need as it will be processed immediately and there will be no
9737 * advantage, and in fact perhaps a negative hit as a class has to be
9738 * instantiated for a lang_string object, however get_string won't require
9739 * that.
9741 * Limitations:
9742 * 1. You cannot use a lang_string object as an array offset. Doing so will
9743 * result in PHP throwing an error. (You can use it as an object property!)
9745 * @package core
9746 * @category string
9747 * @copyright 2011 Sam Hemelryk
9748 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9750 class lang_string {
9752 /** @var string The strings identifier */
9753 protected $identifier;
9754 /** @var string The strings component. Default '' */
9755 protected $component = '';
9756 /** @var array|stdClass Any arguments required for the string. Default null */
9757 protected $a = null;
9758 /** @var string The language to use when processing the string. Default null */
9759 protected $lang = null;
9761 /** @var string The processed string (once processed) */
9762 protected $string = null;
9765 * A special boolean. If set to true then the object has been woken up and
9766 * cannot be regenerated. If this is set then $this->string MUST be used.
9767 * @var bool
9769 protected $forcedstring = false;
9772 * Constructs a lang_string object
9774 * This function should do as little processing as possible to ensure the best
9775 * performance for strings that won't be used.
9777 * @param string $identifier The strings identifier
9778 * @param string $component The strings component
9779 * @param stdClass|array $a Any arguments the string requires
9780 * @param string $lang The language to use when processing the string.
9781 * @throws coding_exception
9783 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9784 if (empty($component)) {
9785 $component = 'moodle';
9788 $this->identifier = $identifier;
9789 $this->component = $component;
9790 $this->lang = $lang;
9792 // We MUST duplicate $a to ensure that it if it changes by reference those
9793 // changes are not carried across.
9794 // To do this we always ensure $a or its properties/values are strings
9795 // and that any properties/values that arn't convertable are forgotten.
9796 if (!empty($a)) {
9797 if (is_scalar($a)) {
9798 $this->a = $a;
9799 } else if ($a instanceof lang_string) {
9800 $this->a = $a->out();
9801 } else if (is_object($a) or is_array($a)) {
9802 $a = (array)$a;
9803 $this->a = array();
9804 foreach ($a as $key => $value) {
9805 // Make sure conversion errors don't get displayed (results in '').
9806 if (is_array($value)) {
9807 $this->a[$key] = '';
9808 } else if (is_object($value)) {
9809 if (method_exists($value, '__toString')) {
9810 $this->a[$key] = $value->__toString();
9811 } else {
9812 $this->a[$key] = '';
9814 } else {
9815 $this->a[$key] = (string)$value;
9821 if (debugging(false, DEBUG_DEVELOPER)) {
9822 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9823 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9825 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9826 throw new coding_exception('Invalid string compontent. Please check your string definition');
9828 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9829 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9835 * Processes the string.
9837 * This function actually processes the string, stores it in the string property
9838 * and then returns it.
9839 * You will notice that this function is VERY similar to the get_string method.
9840 * That is because it is pretty much doing the same thing.
9841 * However as this function is an upgrade it isn't as tolerant to backwards
9842 * compatibility.
9844 * @return string
9845 * @throws coding_exception
9847 protected function get_string() {
9848 global $CFG;
9850 // Check if we need to process the string.
9851 if ($this->string === null) {
9852 // Check the quality of the identifier.
9853 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9854 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);
9857 // Process the string.
9858 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9859 // Debugging feature lets you display string identifier and component.
9860 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9861 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9864 // Return the string.
9865 return $this->string;
9869 * Returns the string
9871 * @param string $lang The langauge to use when processing the string
9872 * @return string
9874 public function out($lang = null) {
9875 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9876 if ($this->forcedstring) {
9877 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9878 return $this->get_string();
9880 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9881 return $translatedstring->out();
9883 return $this->get_string();
9887 * Magic __toString method for printing a string
9889 * @return string
9891 public function __toString() {
9892 return $this->get_string();
9896 * Magic __set_state method used for var_export
9898 * @return string
9900 public function __set_state() {
9901 return $this->get_string();
9905 * Prepares the lang_string for sleep and stores only the forcedstring and
9906 * string properties... the string cannot be regenerated so we need to ensure
9907 * it is generated for this.
9909 * @return string
9911 public function __sleep() {
9912 $this->get_string();
9913 $this->forcedstring = true;
9914 return array('forcedstring', 'string', 'lang');