Merge branch 'MDL-41041-master' of git://github.com/FMCorz/moodle
[moodle.git] / lib / moodlelib.php
blob2cf904a3888898671ddf033b3662710127c55da5
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
25 * @package core
26 * @subpackage lib
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 // CONSTANTS (Encased in phpdoc proper comments).
35 // Date and time constants.
36 /**
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
41 /**
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
46 /**
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
51 /**
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
56 /**
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
61 /**
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
66 /**
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 // Parameter constants - every call to optional_param(), required_param()
72 // or clean_param() should have a specified type of parameter.
74 /**
75 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
77 define('PARAM_ALPHA', 'alpha');
79 /**
80 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
81 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
83 define('PARAM_ALPHAEXT', 'alphaext');
85 /**
86 * PARAM_ALPHANUM - expected numbers and letters only.
88 define('PARAM_ALPHANUM', 'alphanum');
90 /**
91 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
93 define('PARAM_ALPHANUMEXT', 'alphanumext');
95 /**
96 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
98 define('PARAM_AUTH', 'auth');
101 * PARAM_BASE64 - Base 64 encoded format
103 define('PARAM_BASE64', 'base64');
106 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
108 define('PARAM_BOOL', 'bool');
111 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
112 * checked against the list of capabilities in the database.
114 define('PARAM_CAPABILITY', 'capability');
117 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
118 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
119 * the input (required/optional_param or formslib) and then sanitse the HTML
120 * using format_text on output. This is for the rare cases when you want to
121 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
123 define('PARAM_CLEANHTML', 'cleanhtml');
126 * PARAM_EMAIL - an email address following the RFC
128 define('PARAM_EMAIL', 'email');
131 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
133 define('PARAM_FILE', 'file');
136 * PARAM_FLOAT - a real/floating point number.
138 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
139 * It does not work for languages that use , as a decimal separator.
140 * Instead, do something like
141 * $rawvalue = required_param('name', PARAM_RAW);
142 * // ... other code including require_login, which sets current lang ...
143 * $realvalue = unformat_float($rawvalue);
144 * // ... then use $realvalue
146 define('PARAM_FLOAT', 'float');
149 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
151 define('PARAM_HOST', 'host');
154 * PARAM_INT - integers only, use when expecting only numbers.
156 define('PARAM_INT', 'int');
159 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
161 define('PARAM_LANG', 'lang');
164 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
165 * others! Implies PARAM_URL!)
167 define('PARAM_LOCALURL', 'localurl');
170 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
172 define('PARAM_NOTAGS', 'notags');
175 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
176 * traversals note: the leading slash is not removed, window drive letter is not allowed
178 define('PARAM_PATH', 'path');
181 * PARAM_PEM - Privacy Enhanced Mail format
183 define('PARAM_PEM', 'pem');
186 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
188 define('PARAM_PERMISSION', 'permission');
191 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
193 define('PARAM_RAW', 'raw');
196 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
198 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
201 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
203 define('PARAM_SAFEDIR', 'safedir');
206 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
208 define('PARAM_SAFEPATH', 'safepath');
211 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
213 define('PARAM_SEQUENCE', 'sequence');
216 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
218 define('PARAM_TAG', 'tag');
221 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
223 define('PARAM_TAGLIST', 'taglist');
226 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
228 define('PARAM_TEXT', 'text');
231 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
233 define('PARAM_THEME', 'theme');
236 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
237 * http://localhost.localdomain/ is ok.
239 define('PARAM_URL', 'url');
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
243 * accounts, do NOT use when syncing with external systems!!
245 define('PARAM_USERNAME', 'username');
248 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
250 define('PARAM_STRINGID', 'stringid');
252 // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
254 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
255 * It was one of the first types, that is why it is abused so much ;-)
256 * @deprecated since 2.0
258 define('PARAM_CLEAN', 'clean');
261 * PARAM_INTEGER - deprecated alias for PARAM_INT
262 * @deprecated since 2.0
264 define('PARAM_INTEGER', 'int');
267 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
268 * @deprecated since 2.0
270 define('PARAM_NUMBER', 'float');
273 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
274 * NOTE: originally alias for PARAM_APLHA
275 * @deprecated since 2.0
277 define('PARAM_ACTION', 'alphanumext');
280 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
281 * NOTE: originally alias for PARAM_APLHA
282 * @deprecated since 2.0
284 define('PARAM_FORMAT', 'alphanumext');
287 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
288 * @deprecated since 2.0
290 define('PARAM_MULTILANG', 'text');
293 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
294 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
295 * America/Port-au-Prince)
297 define('PARAM_TIMEZONE', 'timezone');
300 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
302 define('PARAM_CLEANFILE', 'file');
305 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
306 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
307 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 * NOTE: numbers and underscores are strongly discouraged in plugin names!
310 define('PARAM_COMPONENT', 'component');
313 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
314 * It is usually used together with context id and component.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
317 define('PARAM_AREA', 'area');
320 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
321 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
322 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
324 define('PARAM_PLUGIN', 'plugin');
327 // Web Services.
330 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
332 define('VALUE_REQUIRED', 1);
335 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
337 define('VALUE_OPTIONAL', 2);
340 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
342 define('VALUE_DEFAULT', 0);
345 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
347 define('NULL_NOT_ALLOWED', false);
350 * NULL_ALLOWED - the parameter can be set to null in the database
352 define('NULL_ALLOWED', true);
354 // Page types.
357 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
359 define('PAGE_COURSE_VIEW', 'course-view');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
363 /** Get remote addr constant */
364 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
366 // Blog access level constant declaration.
367 define ('BLOG_USER_LEVEL', 1);
368 define ('BLOG_GROUP_LEVEL', 2);
369 define ('BLOG_COURSE_LEVEL', 3);
370 define ('BLOG_SITE_LEVEL', 4);
371 define ('BLOG_GLOBAL_LEVEL', 5);
374 // Tag constants.
376 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
377 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
378 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
380 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
382 define('TAG_MAX_LENGTH', 50);
384 // Password policy constants.
385 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
386 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
387 define ('PASSWORD_DIGITS', '0123456789');
388 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
390 // Feature constants.
391 // Used for plugin_supports() to report features that are, or are not, supported by a module.
393 /** True if module can provide a grade */
394 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
395 /** True if module supports outcomes */
396 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
397 /** True if module supports advanced grading methods */
398 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
399 /** True if module controls the grade visibility over the gradebook */
400 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
401 /** True if module supports plagiarism plugins */
402 define('FEATURE_PLAGIARISM', 'plagiarism');
404 /** True if module has code to track whether somebody viewed it */
405 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
406 /** True if module has custom completion rules */
407 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
409 /** True if module has no 'view' page (like label) */
410 define('FEATURE_NO_VIEW_LINK', 'viewlink');
411 /** True if module supports outcomes */
412 define('FEATURE_IDNUMBER', 'idnumber');
413 /** True if module supports groups */
414 define('FEATURE_GROUPS', 'groups');
415 /** True if module supports groupings */
416 define('FEATURE_GROUPINGS', 'groupings');
417 /** True if module supports groupmembersonly */
418 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
420 /** Type of module */
421 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
422 /** True if module supports intro editor */
423 define('FEATURE_MOD_INTRO', 'mod_intro');
424 /** True if module has default completion */
425 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
427 define('FEATURE_COMMENT', 'comment');
429 define('FEATURE_RATE', 'rate');
430 /** True if module supports backup/restore of moodle2 format */
431 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
433 /** True if module can show description on course main page */
434 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
436 /** True if module uses the question bank */
437 define('FEATURE_USES_QUESTIONS', 'usesquestions');
439 /** Unspecified module archetype */
440 define('MOD_ARCHETYPE_OTHER', 0);
441 /** Resource-like type module */
442 define('MOD_ARCHETYPE_RESOURCE', 1);
443 /** Assignment module archetype */
444 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
445 /** System (not user-addable) module archetype */
446 define('MOD_ARCHETYPE_SYSTEM', 3);
448 /** Return this from modname_get_types callback to use default display in activity chooser */
449 define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
452 * Security token used for allowing access
453 * from external application such as web services.
454 * Scripts do not use any session, performance is relatively
455 * low because we need to load access info in each request.
456 * Scripts are executed in parallel.
458 define('EXTERNAL_TOKEN_PERMANENT', 0);
461 * Security token used for allowing access
462 * of embedded applications, the code is executed in the
463 * active user session. Token is invalidated after user logs out.
464 * Scripts are executed serially - normal session locking is used.
466 define('EXTERNAL_TOKEN_EMBEDDED', 1);
469 * The home page should be the site home
471 define('HOMEPAGE_SITE', 0);
473 * The home page should be the users my page
475 define('HOMEPAGE_MY', 1);
477 * The home page can be chosen by the user
479 define('HOMEPAGE_USER', 2);
482 * Hub directory url (should be moodle.org)
484 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
488 * Moodle.org url (should be moodle.org)
490 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
493 * Moodle mobile app service name
495 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
498 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
500 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
503 * Course display settings: display all sections on one page.
505 define('COURSE_DISPLAY_SINGLEPAGE', 0);
507 * Course display settings: split pages into a page per section.
509 define('COURSE_DISPLAY_MULTIPAGE', 1);
512 * Authentication constant: String used in password field when password is not stored.
514 define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
516 // PARAMETER HANDLING.
519 * Returns a particular value for the named variable, taken from
520 * POST or GET. If the parameter doesn't exist then an error is
521 * thrown because we require this variable.
523 * This function should be used to initialise all required values
524 * in a script that are based on parameters. Usually it will be
525 * used like this:
526 * $id = required_param('id', PARAM_INT);
528 * Please note the $type parameter is now required and the value can not be array.
530 * @param string $parname the name of the page parameter we want
531 * @param string $type expected type of parameter
532 * @return mixed
533 * @throws coding_exception
535 function required_param($parname, $type) {
536 if (func_num_args() != 2 or empty($parname) or empty($type)) {
537 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
539 // POST has precedence.
540 if (isset($_POST[$parname])) {
541 $param = $_POST[$parname];
542 } else if (isset($_GET[$parname])) {
543 $param = $_GET[$parname];
544 } else {
545 print_error('missingparam', '', '', $parname);
548 if (is_array($param)) {
549 debugging('Invalid array parameter detected in required_param(): '.$parname);
550 // TODO: switch to fatal error in Moodle 2.3.
551 return required_param_array($parname, $type);
554 return clean_param($param, $type);
558 * Returns a particular array value for the named variable, taken from
559 * POST or GET. If the parameter doesn't exist then an error is
560 * thrown because we require this variable.
562 * This function should be used to initialise all required values
563 * in a script that are based on parameters. Usually it will be
564 * used like this:
565 * $ids = required_param_array('ids', PARAM_INT);
567 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
569 * @param string $parname the name of the page parameter we want
570 * @param string $type expected type of parameter
571 * @return array
572 * @throws coding_exception
574 function required_param_array($parname, $type) {
575 if (func_num_args() != 2 or empty($parname) or empty($type)) {
576 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
578 // POST has precedence.
579 if (isset($_POST[$parname])) {
580 $param = $_POST[$parname];
581 } else if (isset($_GET[$parname])) {
582 $param = $_GET[$parname];
583 } else {
584 print_error('missingparam', '', '', $parname);
586 if (!is_array($param)) {
587 print_error('missingparam', '', '', $parname);
590 $result = array();
591 foreach ($param as $key => $value) {
592 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
593 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
594 continue;
596 $result[$key] = clean_param($value, $type);
599 return $result;
603 * Returns a particular value for the named variable, taken from
604 * POST or GET, otherwise returning a given default.
606 * This function should be used to initialise all optional values
607 * in a script that are based on parameters. Usually it will be
608 * used like this:
609 * $name = optional_param('name', 'Fred', PARAM_TEXT);
611 * Please note the $type parameter is now required and the value can not be array.
613 * @param string $parname the name of the page parameter we want
614 * @param mixed $default the default value to return if nothing is found
615 * @param string $type expected type of parameter
616 * @return mixed
617 * @throws coding_exception
619 function optional_param($parname, $default, $type) {
620 if (func_num_args() != 3 or empty($parname) or empty($type)) {
621 throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
623 if (!isset($default)) {
624 $default = null;
627 // POST has precedence.
628 if (isset($_POST[$parname])) {
629 $param = $_POST[$parname];
630 } else if (isset($_GET[$parname])) {
631 $param = $_GET[$parname];
632 } else {
633 return $default;
636 if (is_array($param)) {
637 debugging('Invalid array parameter detected in required_param(): '.$parname);
638 // TODO: switch to $default in Moodle 2.3.
639 return optional_param_array($parname, $default, $type);
642 return clean_param($param, $type);
646 * Returns a particular array value for the named variable, taken from
647 * POST or GET, otherwise returning a given default.
649 * This function should be used to initialise all optional values
650 * in a script that are based on parameters. Usually it will be
651 * used like this:
652 * $ids = optional_param('id', array(), PARAM_INT);
654 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
656 * @param string $parname the name of the page parameter we want
657 * @param mixed $default the default value to return if nothing is found
658 * @param string $type expected type of parameter
659 * @return array
660 * @throws coding_exception
662 function optional_param_array($parname, $default, $type) {
663 if (func_num_args() != 3 or empty($parname) or empty($type)) {
664 throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
667 // POST has precedence.
668 if (isset($_POST[$parname])) {
669 $param = $_POST[$parname];
670 } else if (isset($_GET[$parname])) {
671 $param = $_GET[$parname];
672 } else {
673 return $default;
675 if (!is_array($param)) {
676 debugging('optional_param_array() expects array parameters only: '.$parname);
677 return $default;
680 $result = array();
681 foreach ($param as $key => $value) {
682 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
683 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
684 continue;
686 $result[$key] = clean_param($value, $type);
689 return $result;
693 * Strict validation of parameter values, the values are only converted
694 * to requested PHP type. Internally it is using clean_param, the values
695 * before and after cleaning must be equal - otherwise
696 * an invalid_parameter_exception is thrown.
697 * Objects and classes are not accepted.
699 * @param mixed $param
700 * @param string $type PARAM_ constant
701 * @param bool $allownull are nulls valid value?
702 * @param string $debuginfo optional debug information
703 * @return mixed the $param value converted to PHP type
704 * @throws invalid_parameter_exception if $param is not of given type
706 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
707 if (is_null($param)) {
708 if ($allownull == NULL_ALLOWED) {
709 return null;
710 } else {
711 throw new invalid_parameter_exception($debuginfo);
714 if (is_array($param) or is_object($param)) {
715 throw new invalid_parameter_exception($debuginfo);
718 $cleaned = clean_param($param, $type);
720 if ($type == PARAM_FLOAT) {
721 // Do not detect precision loss here.
722 if (is_float($param) or is_int($param)) {
723 // These always fit.
724 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
725 throw new invalid_parameter_exception($debuginfo);
727 } else if ((string)$param !== (string)$cleaned) {
728 // Conversion to string is usually lossless.
729 throw new invalid_parameter_exception($debuginfo);
732 return $cleaned;
736 * Makes sure array contains only the allowed types, this function does not validate array key names!
738 * <code>
739 * $options = clean_param($options, PARAM_INT);
740 * </code>
742 * @param array $param the variable array we are cleaning
743 * @param string $type expected format of param after cleaning.
744 * @param bool $recursive clean recursive arrays
745 * @return array
746 * @throws coding_exception
748 function clean_param_array(array $param = null, $type, $recursive = false) {
749 // Convert null to empty array.
750 $param = (array)$param;
751 foreach ($param as $key => $value) {
752 if (is_array($value)) {
753 if ($recursive) {
754 $param[$key] = clean_param_array($value, $type, true);
755 } else {
756 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
758 } else {
759 $param[$key] = clean_param($value, $type);
762 return $param;
766 * Used by {@link optional_param()} and {@link required_param()} to
767 * clean the variables and/or cast to specific types, based on
768 * an options field.
769 * <code>
770 * $course->format = clean_param($course->format, PARAM_ALPHA);
771 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
772 * </code>
774 * @param mixed $param the variable we are cleaning
775 * @param string $type expected format of param after cleaning.
776 * @return mixed
777 * @throws coding_exception
779 function clean_param($param, $type) {
780 global $CFG;
782 if (is_array($param)) {
783 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
784 } else if (is_object($param)) {
785 if (method_exists($param, '__toString')) {
786 $param = $param->__toString();
787 } else {
788 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
792 switch ($type) {
793 case PARAM_RAW:
794 // No cleaning at all.
795 $param = fix_utf8($param);
796 return $param;
798 case PARAM_RAW_TRIMMED:
799 // No cleaning, but strip leading and trailing whitespace.
800 $param = fix_utf8($param);
801 return trim($param);
803 case PARAM_CLEAN:
804 // General HTML cleaning, try to use more specific type if possible this is deprecated!
805 // Please use more specific type instead.
806 if (is_numeric($param)) {
807 return $param;
809 $param = fix_utf8($param);
810 // Sweep for scripts, etc.
811 return clean_text($param);
813 case PARAM_CLEANHTML:
814 // Clean html fragment.
815 $param = fix_utf8($param);
816 // Sweep for scripts, etc.
817 $param = clean_text($param, FORMAT_HTML);
818 return trim($param);
820 case PARAM_INT:
821 // Convert to integer.
822 return (int)$param;
824 case PARAM_FLOAT:
825 // Convert to float.
826 return (float)$param;
828 case PARAM_ALPHA:
829 // Remove everything not `a-z`.
830 return preg_replace('/[^a-zA-Z]/i', '', $param);
832 case PARAM_ALPHAEXT:
833 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
834 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
836 case PARAM_ALPHANUM:
837 // Remove everything not `a-zA-Z0-9`.
838 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
840 case PARAM_ALPHANUMEXT:
841 // Remove everything not `a-zA-Z0-9_-`.
842 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
844 case PARAM_SEQUENCE:
845 // Remove everything not `0-9,`.
846 return preg_replace('/[^0-9,]/i', '', $param);
848 case PARAM_BOOL:
849 // Convert to 1 or 0.
850 $tempstr = strtolower($param);
851 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
852 $param = 1;
853 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
854 $param = 0;
855 } else {
856 $param = empty($param) ? 0 : 1;
858 return $param;
860 case PARAM_NOTAGS:
861 // Strip all tags.
862 $param = fix_utf8($param);
863 return strip_tags($param);
865 case PARAM_TEXT:
866 // Leave only tags needed for multilang.
867 $param = fix_utf8($param);
868 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
869 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
870 do {
871 if (strpos($param, '</lang>') !== false) {
872 // Old and future mutilang syntax.
873 $param = strip_tags($param, '<lang>');
874 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
875 break;
877 $open = false;
878 foreach ($matches[0] as $match) {
879 if ($match === '</lang>') {
880 if ($open) {
881 $open = false;
882 continue;
883 } else {
884 break 2;
887 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
888 break 2;
889 } else {
890 $open = true;
893 if ($open) {
894 break;
896 return $param;
898 } else if (strpos($param, '</span>') !== false) {
899 // Current problematic multilang syntax.
900 $param = strip_tags($param, '<span>');
901 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
902 break;
904 $open = false;
905 foreach ($matches[0] as $match) {
906 if ($match === '</span>') {
907 if ($open) {
908 $open = false;
909 continue;
910 } else {
911 break 2;
914 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
915 break 2;
916 } else {
917 $open = true;
920 if ($open) {
921 break;
923 return $param;
925 } while (false);
926 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
927 return strip_tags($param);
929 case PARAM_COMPONENT:
930 // We do not want any guessing here, either the name is correct or not
931 // please note only normalised component names are accepted.
932 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
933 return '';
935 if (strpos($param, '__') !== false) {
936 return '';
938 if (strpos($param, 'mod_') === 0) {
939 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
940 if (substr_count($param, '_') != 1) {
941 return '';
944 return $param;
946 case PARAM_PLUGIN:
947 case PARAM_AREA:
948 // We do not want any guessing here, either the name is correct or not.
949 if (!is_valid_plugin_name($param)) {
950 return '';
952 return $param;
954 case PARAM_SAFEDIR:
955 // Remove everything not a-zA-Z0-9_- .
956 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
958 case PARAM_SAFEPATH:
959 // Remove everything not a-zA-Z0-9/_- .
960 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
962 case PARAM_FILE:
963 // Strip all suspicious characters from filename.
964 $param = fix_utf8($param);
965 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
966 if ($param === '.' || $param === '..') {
967 $param = '';
969 return $param;
971 case PARAM_PATH:
972 // Strip all suspicious characters from file path.
973 $param = fix_utf8($param);
974 $param = str_replace('\\', '/', $param);
976 // Explode the path and clean each element using the PARAM_FILE rules.
977 $breadcrumb = explode('/', $param);
978 foreach ($breadcrumb as $key => $crumb) {
979 if ($crumb === '.' && $key === 0) {
980 // Special condition to allow for relative current path such as ./currentdirfile.txt.
981 } else {
982 $crumb = clean_param($crumb, PARAM_FILE);
984 $breadcrumb[$key] = $crumb;
986 $param = implode('/', $breadcrumb);
988 // Remove multiple current path (./././) and multiple slashes (///).
989 $param = preg_replace('~//+~', '/', $param);
990 $param = preg_replace('~/(\./)+~', '/', $param);
991 return $param;
993 case PARAM_HOST:
994 // Allow FQDN or IPv4 dotted quad.
995 $param = preg_replace('/[^\.\d\w-]/', '', $param );
996 // Match ipv4 dotted quad.
997 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
998 // Confirm values are ok.
999 if ( $match[0] > 255
1000 || $match[1] > 255
1001 || $match[3] > 255
1002 || $match[4] > 255 ) {
1003 // Hmmm, what kind of dotted quad is this?
1004 $param = '';
1006 } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1007 && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
1008 && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
1010 // All is ok - $param is respected.
1011 } else {
1012 // All is not ok...
1013 $param='';
1015 return $param;
1017 case PARAM_URL: // Allow safe ftp, http, mailto urls.
1018 $param = fix_utf8($param);
1019 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1020 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
1021 // All is ok, param is respected.
1022 } else {
1023 // Not really ok.
1024 $param ='';
1026 return $param;
1028 case PARAM_LOCALURL:
1029 // Allow http absolute, root relative and relative URLs within wwwroot.
1030 $param = clean_param($param, PARAM_URL);
1031 if (!empty($param)) {
1032 if (preg_match(':^/:', $param)) {
1033 // Root-relative, ok!
1034 } else if (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i', $param)) {
1035 // Absolute, and matches our wwwroot.
1036 } else {
1037 // Relative - let's make sure there are no tricks.
1038 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
1039 // Looks ok.
1040 } else {
1041 $param = '';
1045 return $param;
1047 case PARAM_PEM:
1048 $param = trim($param);
1049 // PEM formatted strings may contain letters/numbers and the symbols:
1050 // forward slash: /
1051 // plus sign: +
1052 // equal sign: =
1053 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1054 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1055 list($wholething, $body) = $matches;
1056 unset($wholething, $matches);
1057 $b64 = clean_param($body, PARAM_BASE64);
1058 if (!empty($b64)) {
1059 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1060 } else {
1061 return '';
1064 return '';
1066 case PARAM_BASE64:
1067 if (!empty($param)) {
1068 // PEM formatted strings may contain letters/numbers and the symbols
1069 // forward slash: /
1070 // plus sign: +
1071 // equal sign: =.
1072 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1073 return '';
1075 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1076 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1077 // than (or equal to) 64 characters long.
1078 for ($i=0, $j=count($lines); $i < $j; $i++) {
1079 if ($i + 1 == $j) {
1080 if (64 < strlen($lines[$i])) {
1081 return '';
1083 continue;
1086 if (64 != strlen($lines[$i])) {
1087 return '';
1090 return implode("\n", $lines);
1091 } else {
1092 return '';
1095 case PARAM_TAG:
1096 $param = fix_utf8($param);
1097 // Please note it is not safe to use the tag name directly anywhere,
1098 // it must be processed with s(), urlencode() before embedding anywhere.
1099 // Remove some nasties.
1100 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1101 // Convert many whitespace chars into one.
1102 $param = preg_replace('/\s+/', ' ', $param);
1103 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1104 return $param;
1106 case PARAM_TAGLIST:
1107 $param = fix_utf8($param);
1108 $tags = explode(',', $param);
1109 $result = array();
1110 foreach ($tags as $tag) {
1111 $res = clean_param($tag, PARAM_TAG);
1112 if ($res !== '') {
1113 $result[] = $res;
1116 if ($result) {
1117 return implode(',', $result);
1118 } else {
1119 return '';
1122 case PARAM_CAPABILITY:
1123 if (get_capability_info($param)) {
1124 return $param;
1125 } else {
1126 return '';
1129 case PARAM_PERMISSION:
1130 $param = (int)$param;
1131 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1132 return $param;
1133 } else {
1134 return CAP_INHERIT;
1137 case PARAM_AUTH:
1138 $param = clean_param($param, PARAM_PLUGIN);
1139 if (empty($param)) {
1140 return '';
1141 } else if (exists_auth_plugin($param)) {
1142 return $param;
1143 } else {
1144 return '';
1147 case PARAM_LANG:
1148 $param = clean_param($param, PARAM_SAFEDIR);
1149 if (get_string_manager()->translation_exists($param)) {
1150 return $param;
1151 } else {
1152 // Specified language is not installed or param malformed.
1153 return '';
1156 case PARAM_THEME:
1157 $param = clean_param($param, PARAM_PLUGIN);
1158 if (empty($param)) {
1159 return '';
1160 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1161 return $param;
1162 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1163 return $param;
1164 } else {
1165 // Specified theme is not installed.
1166 return '';
1169 case PARAM_USERNAME:
1170 $param = fix_utf8($param);
1171 $param = str_replace(" " , "", $param);
1172 // Convert uppercase to lowercase MDL-16919.
1173 $param = core_text::strtolower($param);
1174 if (empty($CFG->extendedusernamechars)) {
1175 // Regular expression, eliminate all chars EXCEPT:
1176 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1177 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1179 return $param;
1181 case PARAM_EMAIL:
1182 $param = fix_utf8($param);
1183 if (validate_email($param)) {
1184 return $param;
1185 } else {
1186 return '';
1189 case PARAM_STRINGID:
1190 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1191 return $param;
1192 } else {
1193 return '';
1196 case PARAM_TIMEZONE:
1197 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1198 $param = fix_utf8($param);
1199 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1200 if (preg_match($timezonepattern, $param)) {
1201 return $param;
1202 } else {
1203 return '';
1206 default:
1207 // Doh! throw error, switched parameters in optional_param or another serious problem.
1208 print_error("unknownparamtype", '', '', $type);
1213 * Makes sure the data is using valid utf8, invalid characters are discarded.
1215 * Note: this function is not intended for full objects with methods and private properties.
1217 * @param mixed $value
1218 * @return mixed with proper utf-8 encoding
1220 function fix_utf8($value) {
1221 if (is_null($value) or $value === '') {
1222 return $value;
1224 } else if (is_string($value)) {
1225 if ((string)(int)$value === $value) {
1226 // Shortcut.
1227 return $value;
1229 // No null bytes expected in our data, so let's remove it.
1230 $value = str_replace("\0", '', $value);
1232 // Lower error reporting because glibc throws bogus notices.
1233 $olderror = error_reporting();
1234 if ($olderror & E_NOTICE) {
1235 error_reporting($olderror ^ E_NOTICE);
1238 // Note: this duplicates min_fix_utf8() intentionally.
1239 static $buggyiconv = null;
1240 if ($buggyiconv === null) {
1241 $buggyiconv = (!function_exists('iconv') or iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1244 if ($buggyiconv) {
1245 if (function_exists('mb_convert_encoding')) {
1246 $subst = mb_substitute_character();
1247 mb_substitute_character('');
1248 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1249 mb_substitute_character($subst);
1251 } else {
1252 // Warn admins on admin/index.php page.
1253 $result = $value;
1256 } else {
1257 $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
1260 if ($olderror & E_NOTICE) {
1261 error_reporting($olderror);
1264 return $result;
1266 } else if (is_array($value)) {
1267 foreach ($value as $k => $v) {
1268 $value[$k] = fix_utf8($v);
1270 return $value;
1272 } else if (is_object($value)) {
1273 // Do not modify original.
1274 $value = clone($value);
1275 foreach ($value as $k => $v) {
1276 $value->$k = fix_utf8($v);
1278 return $value;
1280 } else {
1281 // This is some other type, no utf-8 here.
1282 return $value;
1287 * Return true if given value is integer or string with integer value
1289 * @param mixed $value String or Int
1290 * @return bool true if number, false if not
1292 function is_number($value) {
1293 if (is_int($value)) {
1294 return true;
1295 } else if (is_string($value)) {
1296 return ((string)(int)$value) === $value;
1297 } else {
1298 return false;
1303 * Returns host part from url.
1305 * @param string $url full url
1306 * @return string host, null if not found
1308 function get_host_from_url($url) {
1309 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1310 if ($matches) {
1311 return $matches[1];
1313 return null;
1317 * Tests whether anything was returned by text editor
1319 * This function is useful for testing whether something you got back from
1320 * the HTML editor actually contains anything. Sometimes the HTML editor
1321 * appear to be empty, but actually you get back a <br> tag or something.
1323 * @param string $string a string containing HTML.
1324 * @return boolean does the string contain any actual content - that is text,
1325 * images, objects, etc.
1327 function html_is_blank($string) {
1328 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1332 * Set a key in global configuration
1334 * Set a key/value pair in both this session's {@link $CFG} global variable
1335 * and in the 'config' database table for future sessions.
1337 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1338 * In that case it doesn't affect $CFG.
1340 * A NULL value will delete the entry.
1342 * @param string $name the key to set
1343 * @param string $value the value to set (without magic quotes)
1344 * @param string $plugin (optional) the plugin scope, default null
1345 * @return bool true or exception
1347 function set_config($name, $value, $plugin=null) {
1348 global $CFG, $DB;
1350 if (empty($plugin)) {
1351 if (!array_key_exists($name, $CFG->config_php_settings)) {
1352 // So it's defined for this invocation at least.
1353 if (is_null($value)) {
1354 unset($CFG->$name);
1355 } else {
1356 // Settings from db are always strings.
1357 $CFG->$name = (string)$value;
1361 if ($DB->get_field('config', 'name', array('name' => $name))) {
1362 if ($value === null) {
1363 $DB->delete_records('config', array('name' => $name));
1364 } else {
1365 $DB->set_field('config', 'value', $value, array('name' => $name));
1367 } else {
1368 if ($value !== null) {
1369 $config = new stdClass();
1370 $config->name = $name;
1371 $config->value = $value;
1372 $DB->insert_record('config', $config, false);
1375 if ($name === 'siteidentifier') {
1376 cache_helper::update_site_identifier($value);
1378 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1379 } else {
1380 // Plugin scope.
1381 if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1382 if ($value===null) {
1383 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1384 } else {
1385 $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1387 } else {
1388 if ($value !== null) {
1389 $config = new stdClass();
1390 $config->plugin = $plugin;
1391 $config->name = $name;
1392 $config->value = $value;
1393 $DB->insert_record('config_plugins', $config, false);
1396 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1399 return true;
1403 * Get configuration values from the global config table
1404 * or the config_plugins table.
1406 * If called with one parameter, it will load all the config
1407 * variables for one plugin, and return them as an object.
1409 * If called with 2 parameters it will return a string single
1410 * value or false if the value is not found.
1412 * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1413 * that we need only fetch it once per request.
1414 * @param string $plugin full component name
1415 * @param string $name default null
1416 * @return mixed hash-like object or single value, return false no config found
1417 * @throws dml_exception
1419 function get_config($plugin, $name = null) {
1420 global $CFG, $DB;
1422 static $siteidentifier = null;
1424 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1425 $forced =& $CFG->config_php_settings;
1426 $iscore = true;
1427 $plugin = 'core';
1428 } else {
1429 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1430 $forced =& $CFG->forced_plugin_settings[$plugin];
1431 } else {
1432 $forced = array();
1434 $iscore = false;
1437 if ($siteidentifier === null) {
1438 try {
1439 // This may fail during installation.
1440 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1441 // install the database.
1442 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1443 } catch (dml_exception $ex) {
1444 // Set siteidentifier to false. We don't want to trip this continually.
1445 $siteidentifier = false;
1446 throw $ex;
1450 if (!empty($name)) {
1451 if (array_key_exists($name, $forced)) {
1452 return (string)$forced[$name];
1453 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1454 return $siteidentifier;
1458 $cache = cache::make('core', 'config');
1459 $result = $cache->get($plugin);
1460 if ($result === false) {
1461 // The user is after a recordset.
1462 if (!$iscore) {
1463 $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1464 } else {
1465 // This part is not really used any more, but anyway...
1466 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1468 $cache->set($plugin, $result);
1471 if (!empty($name)) {
1472 if (array_key_exists($name, $result)) {
1473 return $result[$name];
1475 return false;
1478 if ($plugin === 'core') {
1479 $result['siteidentifier'] = $siteidentifier;
1482 foreach ($forced as $key => $value) {
1483 if (is_null($value) or is_array($value) or is_object($value)) {
1484 // We do not want any extra mess here, just real settings that could be saved in db.
1485 unset($result[$key]);
1486 } else {
1487 // Convert to string as if it went through the DB.
1488 $result[$key] = (string)$value;
1492 return (object)$result;
1496 * Removes a key from global configuration.
1498 * @param string $name the key to set
1499 * @param string $plugin (optional) the plugin scope
1500 * @return boolean whether the operation succeeded.
1502 function unset_config($name, $plugin=null) {
1503 global $CFG, $DB;
1505 if (empty($plugin)) {
1506 unset($CFG->$name);
1507 $DB->delete_records('config', array('name' => $name));
1508 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1509 } else {
1510 $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1511 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1514 return true;
1518 * Remove all the config variables for a given plugin.
1520 * NOTE: this function is called from lib/db/upgrade.php
1522 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1523 * @return boolean whether the operation succeeded.
1525 function unset_all_config_for_plugin($plugin) {
1526 global $DB;
1527 // Delete from the obvious config_plugins first.
1528 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1529 // Next delete any suspect settings from config.
1530 $like = $DB->sql_like('name', '?', true, true, false, '|');
1531 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1532 $DB->delete_records_select('config', $like, $params);
1533 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1534 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1536 return true;
1540 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1542 * All users are verified if they still have the necessary capability.
1544 * @param string $value the value of the config setting.
1545 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1546 * @param bool $includeadmins include administrators.
1547 * @return array of user objects.
1549 function get_users_from_config($value, $capability, $includeadmins = true) {
1550 if (empty($value) or $value === '$@NONE@$') {
1551 return array();
1554 // We have to make sure that users still have the necessary capability,
1555 // it should be faster to fetch them all first and then test if they are present
1556 // instead of validating them one-by-one.
1557 $users = get_users_by_capability(context_system::instance(), $capability);
1558 if ($includeadmins) {
1559 $admins = get_admins();
1560 foreach ($admins as $admin) {
1561 $users[$admin->id] = $admin;
1565 if ($value === '$@ALL@$') {
1566 return $users;
1569 $result = array(); // Result in correct order.
1570 $allowed = explode(',', $value);
1571 foreach ($allowed as $uid) {
1572 if (isset($users[$uid])) {
1573 $user = $users[$uid];
1574 $result[$user->id] = $user;
1578 return $result;
1583 * Invalidates browser caches and cached data in temp.
1585 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1586 * {@link phpunit_util::reset_dataroot()}
1588 * @return void
1590 function purge_all_caches() {
1591 global $CFG, $DB;
1593 reset_text_filters_cache();
1594 js_reset_all_caches();
1595 theme_reset_all_caches();
1596 get_string_manager()->reset_caches();
1597 core_text::reset_caches();
1598 if (class_exists('core_plugin_manager')) {
1599 core_plugin_manager::reset_caches();
1602 // Bump up cacherev field for all courses.
1603 try {
1604 increment_revision_number('course', 'cacherev', '');
1605 } catch (moodle_exception $e) {
1606 // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1609 $DB->reset_caches();
1610 cache_helper::purge_all();
1612 // Purge all other caches: rss, simplepie, etc.
1613 remove_dir($CFG->cachedir.'', true);
1615 // Make sure cache dir is writable, throws exception if not.
1616 make_cache_directory('');
1618 // This is the only place where we purge local caches, we are only adding files there.
1619 // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1620 remove_dir($CFG->localcachedir, true);
1621 set_config('localcachedirpurged', time());
1622 make_localcache_directory('', true);
1626 * Get volatile flags
1628 * @param string $type
1629 * @param int $changedsince default null
1630 * @return array records array
1632 function get_cache_flags($type, $changedsince = null) {
1633 global $DB;
1635 $params = array('type' => $type, 'expiry' => time());
1636 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1637 if ($changedsince !== null) {
1638 $params['changedsince'] = $changedsince;
1639 $sqlwhere .= " AND timemodified > :changedsince";
1641 $cf = array();
1642 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1643 foreach ($flags as $flag) {
1644 $cf[$flag->name] = $flag->value;
1647 return $cf;
1651 * Get volatile flags
1653 * @param string $type
1654 * @param string $name
1655 * @param int $changedsince default null
1656 * @return string|false The cache flag value or false
1658 function get_cache_flag($type, $name, $changedsince=null) {
1659 global $DB;
1661 $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1663 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1664 if ($changedsince !== null) {
1665 $params['changedsince'] = $changedsince;
1666 $sqlwhere .= " AND timemodified > :changedsince";
1669 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1673 * Set a volatile flag
1675 * @param string $type the "type" namespace for the key
1676 * @param string $name the key to set
1677 * @param string $value the value to set (without magic quotes) - null will remove the flag
1678 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1679 * @return bool Always returns true
1681 function set_cache_flag($type, $name, $value, $expiry = null) {
1682 global $DB;
1684 $timemodified = time();
1685 if ($expiry === null || $expiry < $timemodified) {
1686 $expiry = $timemodified + 24 * 60 * 60;
1687 } else {
1688 $expiry = (int)$expiry;
1691 if ($value === null) {
1692 unset_cache_flag($type, $name);
1693 return true;
1696 if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1697 // This is a potential problem in DEBUG_DEVELOPER.
1698 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1699 return true; // No need to update.
1701 $f->value = $value;
1702 $f->expiry = $expiry;
1703 $f->timemodified = $timemodified;
1704 $DB->update_record('cache_flags', $f);
1705 } else {
1706 $f = new stdClass();
1707 $f->flagtype = $type;
1708 $f->name = $name;
1709 $f->value = $value;
1710 $f->expiry = $expiry;
1711 $f->timemodified = $timemodified;
1712 $DB->insert_record('cache_flags', $f);
1714 return true;
1718 * Removes a single volatile flag
1720 * @param string $type the "type" namespace for the key
1721 * @param string $name the key to set
1722 * @return bool
1724 function unset_cache_flag($type, $name) {
1725 global $DB;
1726 $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1727 return true;
1731 * Garbage-collect volatile flags
1733 * @return bool Always returns true
1735 function gc_cache_flags() {
1736 global $DB;
1737 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1738 return true;
1741 // USER PREFERENCE API.
1744 * Refresh user preference cache. This is used most often for $USER
1745 * object that is stored in session, but it also helps with performance in cron script.
1747 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1749 * @package core
1750 * @category preference
1751 * @access public
1752 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1753 * @param int $cachelifetime Cache life time on the current page (in seconds)
1754 * @throws coding_exception
1755 * @return null
1757 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1758 global $DB;
1759 // Static cache, we need to check on each page load, not only every 2 minutes.
1760 static $loadedusers = array();
1762 if (!isset($user->id)) {
1763 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1766 if (empty($user->id) or isguestuser($user->id)) {
1767 // No permanent storage for not-logged-in users and guest.
1768 if (!isset($user->preference)) {
1769 $user->preference = array();
1771 return;
1774 $timenow = time();
1776 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1777 // Already loaded at least once on this page. Are we up to date?
1778 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1779 // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1780 return;
1782 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1783 // No change since the lastcheck on this page.
1784 $user->preference['_lastloaded'] = $timenow;
1785 return;
1789 // OK, so we have to reload all preferences.
1790 $loadedusers[$user->id] = true;
1791 $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1792 $user->preference['_lastloaded'] = $timenow;
1796 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1798 * NOTE: internal function, do not call from other code.
1800 * @package core
1801 * @access private
1802 * @param integer $userid the user whose prefs were changed.
1804 function mark_user_preferences_changed($userid) {
1805 global $CFG;
1807 if (empty($userid) or isguestuser($userid)) {
1808 // No cache flags for guest and not-logged-in users.
1809 return;
1812 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1816 * Sets a preference for the specified user.
1818 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1820 * @package core
1821 * @category preference
1822 * @access public
1823 * @param string $name The key to set as preference for the specified user
1824 * @param string $value The value to set for the $name key in the specified user's
1825 * record, null means delete current value.
1826 * @param stdClass|int|null $user A moodle user object or id, null means current user
1827 * @throws coding_exception
1828 * @return bool Always true or exception
1830 function set_user_preference($name, $value, $user = null) {
1831 global $USER, $DB;
1833 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1834 throw new coding_exception('Invalid preference name in set_user_preference() call');
1837 if (is_null($value)) {
1838 // Null means delete current.
1839 return unset_user_preference($name, $user);
1840 } else if (is_object($value)) {
1841 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1842 } else if (is_array($value)) {
1843 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1845 // Value column maximum length is 1333 characters.
1846 $value = (string)$value;
1847 if (core_text::strlen($value) > 1333) {
1848 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1851 if (is_null($user)) {
1852 $user = $USER;
1853 } else if (isset($user->id)) {
1854 // It is a valid object.
1855 } else if (is_numeric($user)) {
1856 $user = (object)array('id' => (int)$user);
1857 } else {
1858 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1861 check_user_preferences_loaded($user);
1863 if (empty($user->id) or isguestuser($user->id)) {
1864 // No permanent storage for not-logged-in users and guest.
1865 $user->preference[$name] = $value;
1866 return true;
1869 if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1870 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1871 // Preference already set to this value.
1872 return true;
1874 $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1876 } else {
1877 $preference = new stdClass();
1878 $preference->userid = $user->id;
1879 $preference->name = $name;
1880 $preference->value = $value;
1881 $DB->insert_record('user_preferences', $preference);
1884 // Update value in cache.
1885 $user->preference[$name] = $value;
1887 // Set reload flag for other sessions.
1888 mark_user_preferences_changed($user->id);
1890 return true;
1894 * Sets a whole array of preferences for the current user
1896 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1898 * @package core
1899 * @category preference
1900 * @access public
1901 * @param array $prefarray An array of key/value pairs to be set
1902 * @param stdClass|int|null $user A moodle user object or id, null means current user
1903 * @return bool Always true or exception
1905 function set_user_preferences(array $prefarray, $user = null) {
1906 foreach ($prefarray as $name => $value) {
1907 set_user_preference($name, $value, $user);
1909 return true;
1913 * Unsets a preference completely by deleting it from the database
1915 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1917 * @package core
1918 * @category preference
1919 * @access public
1920 * @param string $name The key to unset as preference for the specified user
1921 * @param stdClass|int|null $user A moodle user object or id, null means current user
1922 * @throws coding_exception
1923 * @return bool Always true or exception
1925 function unset_user_preference($name, $user = null) {
1926 global $USER, $DB;
1928 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1929 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1932 if (is_null($user)) {
1933 $user = $USER;
1934 } else if (isset($user->id)) {
1935 // It is a valid object.
1936 } else if (is_numeric($user)) {
1937 $user = (object)array('id' => (int)$user);
1938 } else {
1939 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1942 check_user_preferences_loaded($user);
1944 if (empty($user->id) or isguestuser($user->id)) {
1945 // No permanent storage for not-logged-in user and guest.
1946 unset($user->preference[$name]);
1947 return true;
1950 // Delete from DB.
1951 $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1953 // Delete the preference from cache.
1954 unset($user->preference[$name]);
1956 // Set reload flag for other sessions.
1957 mark_user_preferences_changed($user->id);
1959 return true;
1963 * Used to fetch user preference(s)
1965 * If no arguments are supplied this function will return
1966 * all of the current user preferences as an array.
1968 * If a name is specified then this function
1969 * attempts to return that particular preference value. If
1970 * none is found, then the optional value $default is returned,
1971 * otherwise null.
1973 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1975 * @package core
1976 * @category preference
1977 * @access public
1978 * @param string $name Name of the key to use in finding a preference value
1979 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1980 * @param stdClass|int|null $user A moodle user object or id, null means current user
1981 * @throws coding_exception
1982 * @return string|mixed|null A string containing the value of a single preference. An
1983 * array with all of the preferences or null
1985 function get_user_preferences($name = null, $default = null, $user = null) {
1986 global $USER;
1988 if (is_null($name)) {
1989 // All prefs.
1990 } else if (is_numeric($name) or $name === '_lastloaded') {
1991 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1994 if (is_null($user)) {
1995 $user = $USER;
1996 } else if (isset($user->id)) {
1997 // Is a valid object.
1998 } else if (is_numeric($user)) {
1999 $user = (object)array('id' => (int)$user);
2000 } else {
2001 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2004 check_user_preferences_loaded($user);
2006 if (empty($name)) {
2007 // All values.
2008 return $user->preference;
2009 } else if (isset($user->preference[$name])) {
2010 // The single string value.
2011 return $user->preference[$name];
2012 } else {
2013 // Default value (null if not specified).
2014 return $default;
2018 // FUNCTIONS FOR HANDLING TIME.
2021 * Given date parts in user time produce a GMT timestamp.
2023 * @package core
2024 * @category time
2025 * @param int $year The year part to create timestamp of
2026 * @param int $month The month part to create timestamp of
2027 * @param int $day The day part to create timestamp of
2028 * @param int $hour The hour part to create timestamp of
2029 * @param int $minute The minute part to create timestamp of
2030 * @param int $second The second part to create timestamp of
2031 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2032 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2033 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2034 * applied only if timezone is 99 or string.
2035 * @return int GMT timestamp
2037 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2039 // Save input timezone, required for dst offset check.
2040 $passedtimezone = $timezone;
2042 $timezone = get_user_timezone_offset($timezone);
2044 if (abs($timezone) > 13) {
2045 // Server time.
2046 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2047 } else {
2048 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
2049 $time = usertime($time, $timezone);
2051 // Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
2052 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
2053 $time -= dst_offset_on($time, $passedtimezone);
2057 return $time;
2062 * Format a date/time (seconds) as weeks, days, hours etc as needed
2064 * Given an amount of time in seconds, returns string
2065 * formatted nicely as weeks, days, hours etc as needed
2067 * @package core
2068 * @category time
2069 * @uses MINSECS
2070 * @uses HOURSECS
2071 * @uses DAYSECS
2072 * @uses YEARSECS
2073 * @param int $totalsecs Time in seconds
2074 * @param stdClass $str Should be a time object
2075 * @return string A nicely formatted date/time string
2077 function format_time($totalsecs, $str = null) {
2079 $totalsecs = abs($totalsecs);
2081 if (!$str) {
2082 // Create the str structure the slow way.
2083 $str = new stdClass();
2084 $str->day = get_string('day');
2085 $str->days = get_string('days');
2086 $str->hour = get_string('hour');
2087 $str->hours = get_string('hours');
2088 $str->min = get_string('min');
2089 $str->mins = get_string('mins');
2090 $str->sec = get_string('sec');
2091 $str->secs = get_string('secs');
2092 $str->year = get_string('year');
2093 $str->years = get_string('years');
2096 $years = floor($totalsecs/YEARSECS);
2097 $remainder = $totalsecs - ($years*YEARSECS);
2098 $days = floor($remainder/DAYSECS);
2099 $remainder = $totalsecs - ($days*DAYSECS);
2100 $hours = floor($remainder/HOURSECS);
2101 $remainder = $remainder - ($hours*HOURSECS);
2102 $mins = floor($remainder/MINSECS);
2103 $secs = $remainder - ($mins*MINSECS);
2105 $ss = ($secs == 1) ? $str->sec : $str->secs;
2106 $sm = ($mins == 1) ? $str->min : $str->mins;
2107 $sh = ($hours == 1) ? $str->hour : $str->hours;
2108 $sd = ($days == 1) ? $str->day : $str->days;
2109 $sy = ($years == 1) ? $str->year : $str->years;
2111 $oyears = '';
2112 $odays = '';
2113 $ohours = '';
2114 $omins = '';
2115 $osecs = '';
2117 if ($years) {
2118 $oyears = $years .' '. $sy;
2120 if ($days) {
2121 $odays = $days .' '. $sd;
2123 if ($hours) {
2124 $ohours = $hours .' '. $sh;
2126 if ($mins) {
2127 $omins = $mins .' '. $sm;
2129 if ($secs) {
2130 $osecs = $secs .' '. $ss;
2133 if ($years) {
2134 return trim($oyears .' '. $odays);
2136 if ($days) {
2137 return trim($odays .' '. $ohours);
2139 if ($hours) {
2140 return trim($ohours .' '. $omins);
2142 if ($mins) {
2143 return trim($omins .' '. $osecs);
2145 if ($secs) {
2146 return $osecs;
2148 return get_string('now');
2152 * Returns a formatted string that represents a date in user time.
2154 * @package core
2155 * @category time
2156 * @param int $date the timestamp in UTC, as obtained from the database.
2157 * @param string $format strftime format. You should probably get this using
2158 * get_string('strftime...', 'langconfig');
2159 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2160 * not 99 then daylight saving will not be added.
2161 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2162 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2163 * If false then the leading zero is maintained.
2164 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2165 * @return string the formatted date/time.
2167 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2168 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2169 return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2173 * Returns a formatted date ensuring it is UTF-8.
2175 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2176 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2178 * This function does not do any calculation regarding the user preferences and should
2179 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2180 * to differentiate the use of server time or not (strftime() against gmstrftime()).
2182 * @param int $date the timestamp.
2183 * @param string $format strftime format.
2184 * @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2185 * @return string the formatted date/time.
2186 * @since 2.3.3
2188 function date_format_string($date, $format, $tz = 99) {
2189 global $CFG;
2190 if (abs($tz) > 13) {
2191 if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
2192 $format = core_text::convert($format, 'utf-8', $localewincharset);
2193 $datestring = strftime($format, $date);
2194 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2195 } else {
2196 $datestring = strftime($format, $date);
2198 } else {
2199 if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
2200 $format = core_text::convert($format, 'utf-8', $localewincharset);
2201 $datestring = gmstrftime($format, $date);
2202 $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2203 } else {
2204 $datestring = gmstrftime($format, $date);
2207 return $datestring;
2211 * Given a $time timestamp in GMT (seconds since epoch),
2212 * returns an array that represents the date in user time
2214 * @package core
2215 * @category time
2216 * @uses HOURSECS
2217 * @param int $time Timestamp in GMT
2218 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2219 * dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
2220 * @return array An array that represents the date in user time
2222 function usergetdate($time, $timezone=99) {
2224 // Save input timezone, required for dst offset check.
2225 $passedtimezone = $timezone;
2227 $timezone = get_user_timezone_offset($timezone);
2229 if (abs($timezone) > 13) {
2230 // Server time.
2231 return getdate($time);
2234 // Add daylight saving offset for string timezones only, as we can't get dst for
2235 // float values. if timezone is 99 (user default timezone), then try update dst.
2236 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2237 $time += dst_offset_on($time, $passedtimezone);
2240 $time += intval((float)$timezone * HOURSECS);
2242 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2244 // Be careful to ensure the returned array matches that produced by getdate() above.
2245 list(
2246 $getdate['month'],
2247 $getdate['weekday'],
2248 $getdate['yday'],
2249 $getdate['year'],
2250 $getdate['mon'],
2251 $getdate['wday'],
2252 $getdate['mday'],
2253 $getdate['hours'],
2254 $getdate['minutes'],
2255 $getdate['seconds']
2256 ) = explode('_', $datestring);
2258 // Set correct datatype to match with getdate().
2259 $getdate['seconds'] = (int)$getdate['seconds'];
2260 $getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
2261 $getdate['year'] = (int)$getdate['year'];
2262 $getdate['mon'] = (int)$getdate['mon'];
2263 $getdate['wday'] = (int)$getdate['wday'];
2264 $getdate['mday'] = (int)$getdate['mday'];
2265 $getdate['hours'] = (int)$getdate['hours'];
2266 $getdate['minutes'] = (int)$getdate['minutes'];
2267 return $getdate;
2271 * Given a GMT timestamp (seconds since epoch), offsets it by
2272 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2274 * @package core
2275 * @category time
2276 * @uses HOURSECS
2277 * @param int $date Timestamp in GMT
2278 * @param float|int|string $timezone timezone to calculate GMT time offset before
2279 * calculating user time, 99 is default user timezone
2280 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2281 * @return int
2283 function usertime($date, $timezone=99) {
2285 $timezone = get_user_timezone_offset($timezone);
2287 if (abs($timezone) > 13) {
2288 return $date;
2290 return $date - (int)($timezone * HOURSECS);
2294 * Given a time, return the GMT timestamp of the most recent midnight
2295 * for the current user.
2297 * @package core
2298 * @category time
2299 * @param int $date Timestamp in GMT
2300 * @param float|int|string $timezone timezone to calculate GMT time offset before
2301 * calculating user midnight time, 99 is default user timezone
2302 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2303 * @return int Returns a GMT timestamp
2305 function usergetmidnight($date, $timezone=99) {
2307 $userdate = usergetdate($date, $timezone);
2309 // Time of midnight of this user's day, in GMT.
2310 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2315 * Returns a string that prints the user's timezone
2317 * @package core
2318 * @category time
2319 * @param float|int|string $timezone timezone to calculate GMT time offset before
2320 * calculating user timezone, 99 is default user timezone
2321 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2322 * @return string
2324 function usertimezone($timezone=99) {
2326 $tz = get_user_timezone($timezone);
2328 if (!is_float($tz)) {
2329 return $tz;
2332 if (abs($tz) > 13) {
2333 // Server time.
2334 return get_string('serverlocaltime');
2337 if ($tz == intval($tz)) {
2338 // Don't show .0 for whole hours.
2339 $tz = intval($tz);
2342 if ($tz == 0) {
2343 return 'UTC';
2344 } else if ($tz > 0) {
2345 return 'UTC+'.$tz;
2346 } else {
2347 return 'UTC'.$tz;
2353 * Returns a float which represents the user's timezone difference from GMT in hours
2354 * Checks various settings and picks the most dominant of those which have a value
2356 * @package core
2357 * @category time
2358 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2359 * 99 is default user timezone
2360 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2361 * @return float
2363 function get_user_timezone_offset($tz = 99) {
2364 $tz = get_user_timezone($tz);
2366 if (is_float($tz)) {
2367 return $tz;
2368 } else {
2369 $tzrecord = get_timezone_record($tz);
2370 if (empty($tzrecord)) {
2371 return 99.0;
2373 return (float)$tzrecord->gmtoff / HOURMINS;
2378 * Returns an int which represents the systems's timezone difference from GMT in seconds
2380 * @package core
2381 * @category time
2382 * @param float|int|string $tz timezone for which offset is required.
2383 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2384 * @return int|bool if found, false is timezone 99 or error
2386 function get_timezone_offset($tz) {
2387 if ($tz == 99) {
2388 return false;
2391 if (is_numeric($tz)) {
2392 return intval($tz * 60*60);
2395 if (!$tzrecord = get_timezone_record($tz)) {
2396 return false;
2398 return intval($tzrecord->gmtoff * 60);
2402 * Returns a float or a string which denotes the user's timezone
2403 * 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)
2404 * means that for this timezone there are also DST rules to be taken into account
2405 * Checks various settings and picks the most dominant of those which have a value
2407 * @package core
2408 * @category time
2409 * @param float|int|string $tz timezone to calculate GMT time offset before
2410 * calculating user timezone, 99 is default user timezone
2411 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2412 * @return float|string
2414 function get_user_timezone($tz = 99) {
2415 global $USER, $CFG;
2417 $timezones = array(
2418 $tz,
2419 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2420 isset($USER->timezone) ? $USER->timezone : 99,
2421 isset($CFG->timezone) ? $CFG->timezone : 99,
2424 $tz = 99;
2426 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2427 while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2428 $tz = $next['value'];
2430 return is_numeric($tz) ? (float) $tz : $tz;
2434 * Returns cached timezone record for given $timezonename
2436 * @package core
2437 * @param string $timezonename name of the timezone
2438 * @return stdClass|bool timezonerecord or false
2440 function get_timezone_record($timezonename) {
2441 global $DB;
2442 static $cache = null;
2444 if ($cache === null) {
2445 $cache = array();
2448 if (isset($cache[$timezonename])) {
2449 return $cache[$timezonename];
2452 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2453 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2457 * Build and store the users Daylight Saving Time (DST) table
2459 * @package core
2460 * @param int $fromyear Start year for the table, defaults to 1971
2461 * @param int $toyear End year for the table, defaults to 2035
2462 * @param int|float|string $strtimezone timezone to check if dst should be applied.
2463 * @return bool
2465 function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
2466 global $SESSION, $DB;
2468 $usertz = get_user_timezone($strtimezone);
2470 if (is_float($usertz)) {
2471 // Trivial timezone, no DST.
2472 return false;
2475 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2476 // We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
2477 unset($SESSION->dst_offsets);
2478 unset($SESSION->dst_range);
2481 if (!empty($SESSION->dst_offsets) && empty($fromyear) && empty($toyear)) {
2482 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
2483 // This will be the return path most of the time, pretty light computationally.
2484 return true;
2487 // Reaching here means we either need to extend our table or create it from scratch.
2489 // Remember which TZ we calculated these changes for.
2490 $SESSION->dst_offsettz = $usertz;
2492 if (empty($SESSION->dst_offsets)) {
2493 // If we 're creating from scratch, put the two guard elements in there.
2494 $SESSION->dst_offsets = array(1 => null, 0 => null);
2496 if (empty($SESSION->dst_range)) {
2497 // If creating from scratch.
2498 $from = max((empty($fromyear) ? intval(date('Y')) - 3 : $fromyear), 1971);
2499 $to = min((empty($toyear) ? intval(date('Y')) + 3 : $toyear), 2035);
2501 // Fill in the array with the extra years we need to process.
2502 $yearstoprocess = array();
2503 for ($i = $from; $i <= $to; ++$i) {
2504 $yearstoprocess[] = $i;
2507 // Take note of which years we have processed for future calls.
2508 $SESSION->dst_range = array($from, $to);
2509 } else {
2510 // If needing to extend the table, do the same.
2511 $yearstoprocess = array();
2513 $from = max((empty($fromyear) ? $SESSION->dst_range[0] : $fromyear), 1971);
2514 $to = min((empty($toyear) ? $SESSION->dst_range[1] : $toyear), 2035);
2516 if ($from < $SESSION->dst_range[0]) {
2517 // Take note of which years we need to process and then note that we have processed them for future calls.
2518 for ($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2519 $yearstoprocess[] = $i;
2521 $SESSION->dst_range[0] = $from;
2523 if ($to > $SESSION->dst_range[1]) {
2524 // Take note of which years we need to process and then note that we have processed them for future calls.
2525 for ($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2526 $yearstoprocess[] = $i;
2528 $SESSION->dst_range[1] = $to;
2532 if (empty($yearstoprocess)) {
2533 // This means that there was a call requesting a SMALLER range than we have already calculated.
2534 return true;
2537 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2538 // Also, the array is sorted in descending timestamp order!
2540 // Get DB data.
2542 static $presetscache = array();
2543 if (!isset($presetscache[$usertz])) {
2544 $presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
2545 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
2546 'std_startday, std_weekday, std_skipweeks, std_time');
2548 if (empty($presetscache[$usertz])) {
2549 return false;
2552 // Remove ending guard (first element of the array).
2553 reset($SESSION->dst_offsets);
2554 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2556 // Add all required change timestamps.
2557 foreach ($yearstoprocess as $y) {
2558 // Find the record which is in effect for the year $y.
2559 foreach ($presetscache[$usertz] as $year => $preset) {
2560 if ($year <= $y) {
2561 break;
2565 $changes = dst_changes_for_year($y, $preset);
2567 if ($changes === null) {
2568 continue;
2570 if ($changes['dst'] != 0) {
2571 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2573 if ($changes['std'] != 0) {
2574 $SESSION->dst_offsets[$changes['std']] = 0;
2578 // Put in a guard element at the top.
2579 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2580 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = null; // DAYSECS is arbitrary, any "small" number will do.
2582 // Sort again.
2583 krsort($SESSION->dst_offsets);
2585 return true;
2589 * Calculates the required DST change and returns a Timestamp Array
2591 * @package core
2592 * @category time
2593 * @uses HOURSECS
2594 * @uses MINSECS
2595 * @param int|string $year Int or String Year to focus on
2596 * @param object $timezone Instatiated Timezone object
2597 * @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
2599 function dst_changes_for_year($year, $timezone) {
2601 if ($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 &&
2602 $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2603 return null;
2606 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2607 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2609 list($dsthour, $dstmin) = explode(':', $timezone->dst_time);
2610 list($stdhour, $stdmin) = explode(':', $timezone->std_time);
2612 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2613 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2615 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2616 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2617 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2619 $timedst += $dsthour * HOURSECS + $dstmin * MINSECS;
2620 $timestd += $stdhour * HOURSECS + $stdmin * MINSECS;
2622 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2626 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2627 * - Note: Daylight saving only works for string timezones and not for float.
2629 * @package core
2630 * @category time
2631 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2632 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2633 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2634 * @return int
2636 function dst_offset_on($time, $strtimezone = null) {
2637 global $SESSION;
2639 if (!calculate_user_dst_table(null, null, $strtimezone) || empty($SESSION->dst_offsets)) {
2640 return 0;
2643 reset($SESSION->dst_offsets);
2644 while (list($from, $offset) = each($SESSION->dst_offsets)) {
2645 if ($from <= $time) {
2646 break;
2650 // This is the normal return path.
2651 if ($offset !== null) {
2652 return $offset;
2655 // Reaching this point means we haven't calculated far enough, do it now:
2656 // Calculate extra DST changes if needed and recurse. The recursion always
2657 // moves toward the stopping condition, so will always end.
2659 if ($from == 0) {
2660 // We need a year smaller than $SESSION->dst_range[0].
2661 if ($SESSION->dst_range[0] == 1971) {
2662 return 0;
2664 calculate_user_dst_table($SESSION->dst_range[0] - 5, null, $strtimezone);
2665 return dst_offset_on($time, $strtimezone);
2666 } else {
2667 // We need a year larger than $SESSION->dst_range[1].
2668 if ($SESSION->dst_range[1] == 2035) {
2669 return 0;
2671 calculate_user_dst_table(null, $SESSION->dst_range[1] + 5, $strtimezone);
2672 return dst_offset_on($time, $strtimezone);
2677 * Calculates when the day appears in specific month
2679 * @package core
2680 * @category time
2681 * @param int $startday starting day of the month
2682 * @param int $weekday The day when week starts (normally taken from user preferences)
2683 * @param int $month The month whose day is sought
2684 * @param int $year The year of the month whose day is sought
2685 * @return int
2687 function find_day_in_month($startday, $weekday, $month, $year) {
2688 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2690 $daysinmonth = days_in_month($month, $year);
2691 $daysinweek = count($calendartype->get_weekdays());
2693 if ($weekday == -1) {
2694 // Don't care about weekday, so return:
2695 // abs($startday) if $startday != -1
2696 // $daysinmonth otherwise.
2697 return ($startday == -1) ? $daysinmonth : abs($startday);
2700 // From now on we 're looking for a specific weekday.
2701 // Give "end of month" its actual value, since we know it.
2702 if ($startday == -1) {
2703 $startday = -1 * $daysinmonth;
2706 // Starting from day $startday, the sign is the direction.
2707 if ($startday < 1) {
2708 $startday = abs($startday);
2709 $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2711 // This is the last such weekday of the month.
2712 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2713 if ($lastinmonth > $daysinmonth) {
2714 $lastinmonth -= $daysinweek;
2717 // Find the first such weekday <= $startday.
2718 while ($lastinmonth > $startday) {
2719 $lastinmonth -= $daysinweek;
2722 return $lastinmonth;
2723 } else {
2724 $indexweekday = dayofweek($startday, $month, $year);
2726 $diff = $weekday - $indexweekday;
2727 if ($diff < 0) {
2728 $diff += $daysinweek;
2731 // This is the first such weekday of the month equal to or after $startday.
2732 $firstfromindex = $startday + $diff;
2734 return $firstfromindex;
2739 * Calculate the number of days in a given month
2741 * @package core
2742 * @category time
2743 * @param int $month The month whose day count is sought
2744 * @param int $year The year of the month whose day count is sought
2745 * @return int
2747 function days_in_month($month, $year) {
2748 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2749 return $calendartype->get_num_days_in_month($year, $month);
2753 * Calculate the position in the week of a specific calendar day
2755 * @package core
2756 * @category time
2757 * @param int $day The day of the date whose position in the week is sought
2758 * @param int $month The month of the date whose position in the week is sought
2759 * @param int $year The year of the date whose position in the week is sought
2760 * @return int
2762 function dayofweek($day, $month, $year) {
2763 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2764 return $calendartype->get_weekday($year, $month, $day);
2767 // USER AUTHENTICATION AND LOGIN.
2770 * Returns full login url.
2772 * @return string login url
2774 function get_login_url() {
2775 global $CFG;
2777 $url = "$CFG->wwwroot/login/index.php";
2779 if (!empty($CFG->loginhttps)) {
2780 $url = str_replace('http:', 'https:', $url);
2783 return $url;
2787 * This function checks that the current user is logged in and has the
2788 * required privileges
2790 * This function checks that the current user is logged in, and optionally
2791 * whether they are allowed to be in a particular course and view a particular
2792 * course module.
2793 * If they are not logged in, then it redirects them to the site login unless
2794 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2795 * case they are automatically logged in as guests.
2796 * If $courseid is given and the user is not enrolled in that course then the
2797 * user is redirected to the course enrolment page.
2798 * If $cm is given and the course module is hidden and the user is not a teacher
2799 * in the course then the user is redirected to the course home page.
2801 * When $cm parameter specified, this function sets page layout to 'module'.
2802 * You need to change it manually later if some other layout needed.
2804 * @package core_access
2805 * @category access
2807 * @param mixed $courseorid id of the course or course object
2808 * @param bool $autologinguest default true
2809 * @param object $cm course module object
2810 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2811 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2812 * in order to keep redirects working properly. MDL-14495
2813 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2814 * @return mixed Void, exit, and die depending on path
2815 * @throws coding_exception
2816 * @throws require_login_exception
2818 function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2819 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2821 // Must not redirect when byteserving already started.
2822 if (!empty($_SERVER['HTTP_RANGE'])) {
2823 $preventredirect = true;
2826 // Setup global $COURSE, themes, language and locale.
2827 if (!empty($courseorid)) {
2828 if (is_object($courseorid)) {
2829 $course = $courseorid;
2830 } else if ($courseorid == SITEID) {
2831 $course = clone($SITE);
2832 } else {
2833 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2835 if ($cm) {
2836 if ($cm->course != $course->id) {
2837 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2839 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2840 if (!($cm instanceof cm_info)) {
2841 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2842 // db queries so this is not really a performance concern, however it is obviously
2843 // better if you use get_fast_modinfo to get the cm before calling this.
2844 $modinfo = get_fast_modinfo($course);
2845 $cm = $modinfo->get_cm($cm->id);
2847 $PAGE->set_cm($cm, $course); // Set's up global $COURSE.
2848 $PAGE->set_pagelayout('incourse');
2849 } else {
2850 $PAGE->set_course($course); // Set's up global $COURSE.
2852 } else {
2853 // Do not touch global $COURSE via $PAGE->set_course(),
2854 // the reasons is we need to be able to call require_login() at any time!!
2855 $course = $SITE;
2856 if ($cm) {
2857 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2861 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2862 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2863 // risk leading the user back to the AJAX request URL.
2864 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2865 $setwantsurltome = false;
2868 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2869 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
2870 if ($setwantsurltome) {
2871 $SESSION->wantsurl = qualified_me();
2873 redirect(get_login_url());
2876 // If the user is not even logged in yet then make sure they are.
2877 if (!isloggedin()) {
2878 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2879 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2880 // Misconfigured site guest, just redirect to login page.
2881 redirect(get_login_url());
2882 exit; // Never reached.
2884 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2885 complete_user_login($guest);
2886 $USER->autologinguest = true;
2887 $SESSION->lang = $lang;
2888 } else {
2889 // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2890 if ($preventredirect) {
2891 throw new require_login_exception('You are not logged in');
2894 if ($setwantsurltome) {
2895 $SESSION->wantsurl = qualified_me();
2897 if (!empty($_SERVER['HTTP_REFERER'])) {
2898 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2900 redirect(get_login_url());
2901 exit; // Never reached.
2905 // Loginas as redirection if needed.
2906 if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2907 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2908 if ($USER->loginascontext->instanceid != $course->id) {
2909 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2914 // Check whether the user should be changing password (but only if it is REALLY them).
2915 if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2916 $userauth = get_auth_plugin($USER->auth);
2917 if ($userauth->can_change_password() and !$preventredirect) {
2918 if ($setwantsurltome) {
2919 $SESSION->wantsurl = qualified_me();
2921 if ($changeurl = $userauth->change_password_url()) {
2922 // Use plugin custom url.
2923 redirect($changeurl);
2924 } else {
2925 // Use moodle internal method.
2926 if (empty($CFG->loginhttps)) {
2927 redirect($CFG->wwwroot .'/login/change_password.php');
2928 } else {
2929 $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
2930 redirect($wwwroot .'/login/change_password.php');
2933 } else {
2934 print_error('nopasswordchangeforced', 'auth');
2938 // Check that the user account is properly set up.
2939 if (user_not_fully_set_up($USER)) {
2940 if ($preventredirect) {
2941 throw new require_login_exception('User not fully set-up');
2943 if ($setwantsurltome) {
2944 $SESSION->wantsurl = qualified_me();
2946 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2949 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2950 sesskey();
2952 // Do not bother admins with any formalities.
2953 if (is_siteadmin()) {
2954 // Set accesstime or the user will appear offline which messes up messaging.
2955 user_accesstime_log($course->id);
2956 return;
2959 // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2960 if (!$USER->policyagreed and !is_siteadmin()) {
2961 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2962 if ($preventredirect) {
2963 throw new require_login_exception('Policy not agreed');
2965 if ($setwantsurltome) {
2966 $SESSION->wantsurl = qualified_me();
2968 redirect($CFG->wwwroot .'/user/policy.php');
2969 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2970 if ($preventredirect) {
2971 throw new require_login_exception('Policy not agreed');
2973 if ($setwantsurltome) {
2974 $SESSION->wantsurl = qualified_me();
2976 redirect($CFG->wwwroot .'/user/policy.php');
2980 // Fetch the system context, the course context, and prefetch its child contexts.
2981 $sysctx = context_system::instance();
2982 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2983 if ($cm) {
2984 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2985 } else {
2986 $cmcontext = null;
2989 // If the site is currently under maintenance, then print a message.
2990 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2991 if ($preventredirect) {
2992 throw new require_login_exception('Maintenance in progress');
2995 print_maintenance_message();
2998 // Make sure the course itself is not hidden.
2999 if ($course->id == SITEID) {
3000 // Frontpage can not be hidden.
3001 } else {
3002 if (is_role_switched($course->id)) {
3003 // When switching roles ignore the hidden flag - user had to be in course to do the switch.
3004 } else {
3005 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3006 // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
3007 // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
3008 if ($preventredirect) {
3009 throw new require_login_exception('Course is hidden');
3011 // We need to override the navigation URL as the course won't have been added to the navigation and thus
3012 // the navigation will mess up when trying to find it.
3013 navigation_node::override_active_url(new moodle_url('/'));
3014 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3019 // Is the user enrolled?
3020 if ($course->id == SITEID) {
3021 // Everybody is enrolled on the frontpage.
3022 } else {
3023 if (\core\session\manager::is_loggedinas()) {
3024 // Make sure the REAL person can access this course first.
3025 $realuser = \core\session\manager::get_realuser();
3026 if (!is_enrolled($coursecontext, $realuser->id, '', true) and
3027 !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
3028 if ($preventredirect) {
3029 throw new require_login_exception('Invalid course login-as access');
3031 echo $OUTPUT->header();
3032 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
3036 $access = false;
3038 if (is_role_switched($course->id)) {
3039 // Ok, user had to be inside this course before the switch.
3040 $access = true;
3042 } else if (is_viewing($coursecontext, $USER)) {
3043 // Ok, no need to mess with enrol.
3044 $access = true;
3046 } else {
3047 if (isset($USER->enrol['enrolled'][$course->id])) {
3048 if ($USER->enrol['enrolled'][$course->id] > time()) {
3049 $access = true;
3050 if (isset($USER->enrol['tempguest'][$course->id])) {
3051 unset($USER->enrol['tempguest'][$course->id]);
3052 remove_temp_course_roles($coursecontext);
3054 } else {
3055 // Expired.
3056 unset($USER->enrol['enrolled'][$course->id]);
3059 if (isset($USER->enrol['tempguest'][$course->id])) {
3060 if ($USER->enrol['tempguest'][$course->id] == 0) {
3061 $access = true;
3062 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3063 $access = true;
3064 } else {
3065 // Expired.
3066 unset($USER->enrol['tempguest'][$course->id]);
3067 remove_temp_course_roles($coursecontext);
3071 if (!$access) {
3072 // Cache not ok.
3073 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3074 if ($until !== false) {
3075 // Active participants may always access, a timestamp in the future, 0 (always) or false.
3076 if ($until == 0) {
3077 $until = ENROL_MAX_TIMESTAMP;
3079 $USER->enrol['enrolled'][$course->id] = $until;
3080 $access = true;
3082 } else {
3083 $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
3084 $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
3085 $enrols = enrol_get_plugins(true);
3086 // First ask all enabled enrol instances in course if they want to auto enrol user.
3087 foreach ($instances as $instance) {
3088 if (!isset($enrols[$instance->enrol])) {
3089 continue;
3091 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3092 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3093 if ($until !== false) {
3094 if ($until == 0) {
3095 $until = ENROL_MAX_TIMESTAMP;
3097 $USER->enrol['enrolled'][$course->id] = $until;
3098 $access = true;
3099 break;
3102 // If not enrolled yet try to gain temporary guest access.
3103 if (!$access) {
3104 foreach ($instances as $instance) {
3105 if (!isset($enrols[$instance->enrol])) {
3106 continue;
3108 // Get a duration for the guest access, a timestamp in the future or false.
3109 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3110 if ($until !== false and $until > time()) {
3111 $USER->enrol['tempguest'][$course->id] = $until;
3112 $access = true;
3113 break;
3121 if (!$access) {
3122 if ($preventredirect) {
3123 throw new require_login_exception('Not enrolled');
3125 if ($setwantsurltome) {
3126 $SESSION->wantsurl = qualified_me();
3128 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3132 // Check visibility of activity to current user; includes visible flag, groupmembersonly, conditional availability, etc.
3133 if ($cm && !$cm->uservisible) {
3134 if ($preventredirect) {
3135 throw new require_login_exception('Activity is hidden');
3137 if ($course->id != SITEID) {
3138 $url = new moodle_url('/course/view.php', array('id' => $course->id));
3139 } else {
3140 $url = new moodle_url('/');
3142 redirect($url, get_string('activityiscurrentlyhidden'));
3145 // Finally access granted, update lastaccess times.
3146 user_accesstime_log($course->id);
3151 * This function just makes sure a user is logged out.
3153 * @package core_access
3154 * @category access
3156 function require_logout() {
3157 global $USER, $DB;
3159 if (!isloggedin()) {
3160 // This should not happen often, no need for hooks or events here.
3161 \core\session\manager::terminate_current();
3162 return;
3165 // Execute hooks before action.
3166 $authsequence = get_enabled_auth_plugins();
3167 foreach ($authsequence as $authname) {
3168 $authplugin = get_auth_plugin($authname);
3169 $authplugin->prelogout_hook();
3172 // Store info that gets removed during logout.
3173 $sid = session_id();
3174 $event = \core\event\user_loggedout::create(
3175 array(
3176 'userid' => $USER->id,
3177 'objectid' => $USER->id,
3178 'other' => array('sessionid' => $sid),
3181 if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3182 $event->add_record_snapshot('sessions', $session);
3185 // Delete session record and drop $_SESSION content.
3186 \core\session\manager::terminate_current();
3188 // Trigger event AFTER action.
3189 $event->trigger();
3193 * Weaker version of require_login()
3195 * This is a weaker version of {@link require_login()} which only requires login
3196 * when called from within a course rather than the site page, unless
3197 * the forcelogin option is turned on.
3198 * @see require_login()
3200 * @package core_access
3201 * @category access
3203 * @param mixed $courseorid The course object or id in question
3204 * @param bool $autologinguest Allow autologin guests if that is wanted
3205 * @param object $cm Course activity module if known
3206 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3207 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3208 * in order to keep redirects working properly. MDL-14495
3209 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3210 * @return void
3211 * @throws coding_exception
3213 function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3214 global $CFG, $PAGE, $SITE;
3215 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
3216 or (!is_object($courseorid) and $courseorid == SITEID);
3217 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3218 // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3219 // db queries so this is not really a performance concern, however it is obviously
3220 // better if you use get_fast_modinfo to get the cm before calling this.
3221 if (is_object($courseorid)) {
3222 $course = $courseorid;
3223 } else {
3224 $course = clone($SITE);
3226 $modinfo = get_fast_modinfo($course);
3227 $cm = $modinfo->get_cm($cm->id);
3229 if (!empty($CFG->forcelogin)) {
3230 // Login required for both SITE and courses.
3231 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3233 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3234 // Always login for hidden activities.
3235 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3237 } else if ($issite) {
3238 // Login for SITE not required.
3239 if ($cm and empty($cm->visible)) {
3240 // Hidden activities are not accessible without login.
3241 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3242 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3243 // Not-logged-in users do not have any group membership.
3244 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3245 } else {
3246 // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3247 if (!empty($courseorid)) {
3248 if (is_object($courseorid)) {
3249 $course = $courseorid;
3250 } else {
3251 $course = clone($SITE);
3253 if ($cm) {
3254 if ($cm->course != $course->id) {
3255 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3257 $PAGE->set_cm($cm, $course);
3258 $PAGE->set_pagelayout('incourse');
3259 } else {
3260 $PAGE->set_course($course);
3262 } else {
3263 // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3264 $PAGE->set_course($PAGE->course);
3266 // TODO: verify conditional activities here.
3267 user_accesstime_log(SITEID);
3268 return;
3271 } else {
3272 // Course login always required.
3273 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3278 * Require key login. Function terminates with error if key not found or incorrect.
3280 * @uses NO_MOODLE_COOKIES
3281 * @uses PARAM_ALPHANUM
3282 * @param string $script unique script identifier
3283 * @param int $instance optional instance id
3284 * @return int Instance ID
3286 function require_user_key_login($script, $instance=null) {
3287 global $DB;
3289 if (!NO_MOODLE_COOKIES) {
3290 print_error('sessioncookiesdisable');
3293 // Extra safety.
3294 \core\session\manager::write_close();
3296 $keyvalue = required_param('key', PARAM_ALPHANUM);
3298 if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3299 print_error('invalidkey');
3302 if (!empty($key->validuntil) and $key->validuntil < time()) {
3303 print_error('expiredkey');
3306 if ($key->iprestriction) {
3307 $remoteaddr = getremoteaddr(null);
3308 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3309 print_error('ipmismatch');
3313 if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3314 print_error('invaliduserid');
3317 // Emulate normal session.
3318 enrol_check_plugins($user);
3319 \core\session\manager::set_user($user);
3321 // Note we are not using normal login.
3322 if (!defined('USER_KEY_LOGIN')) {
3323 define('USER_KEY_LOGIN', true);
3326 // Return instance id - it might be empty.
3327 return $key->instance;
3331 * Creates a new private user access key.
3333 * @param string $script unique target identifier
3334 * @param int $userid
3335 * @param int $instance optional instance id
3336 * @param string $iprestriction optional ip restricted access
3337 * @param timestamp $validuntil key valid only until given data
3338 * @return string access key value
3340 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3341 global $DB;
3343 $key = new stdClass();
3344 $key->script = $script;
3345 $key->userid = $userid;
3346 $key->instance = $instance;
3347 $key->iprestriction = $iprestriction;
3348 $key->validuntil = $validuntil;
3349 $key->timecreated = time();
3351 // Something long and unique.
3352 $key->value = md5($userid.'_'.time().random_string(40));
3353 while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3354 // Must be unique.
3355 $key->value = md5($userid.'_'.time().random_string(40));
3357 $DB->insert_record('user_private_key', $key);
3358 return $key->value;
3362 * Delete the user's new private user access keys for a particular script.
3364 * @param string $script unique target identifier
3365 * @param int $userid
3366 * @return void
3368 function delete_user_key($script, $userid) {
3369 global $DB;
3370 $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3374 * Gets a private user access key (and creates one if one doesn't exist).
3376 * @param string $script unique target identifier
3377 * @param int $userid
3378 * @param int $instance optional instance id
3379 * @param string $iprestriction optional ip restricted access
3380 * @param timestamp $validuntil key valid only until given data
3381 * @return string access key value
3383 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3384 global $DB;
3386 if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3387 'instance' => $instance, 'iprestriction' => $iprestriction,
3388 'validuntil' => $validuntil))) {
3389 return $key->value;
3390 } else {
3391 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3397 * Modify the user table by setting the currently logged in user's last login to now.
3399 * @return bool Always returns true
3401 function update_user_login_times() {
3402 global $USER, $DB, $CFG;
3404 require_once($CFG->dirroot.'/user/lib.php');
3406 if (isguestuser()) {
3407 // Do not update guest access times/ips for performance.
3408 return true;
3411 $now = time();
3413 $user = new stdClass();
3414 $user->id = $USER->id;
3416 // Make sure all users that logged in have some firstaccess.
3417 if ($USER->firstaccess == 0) {
3418 $USER->firstaccess = $user->firstaccess = $now;
3421 // Store the previous current as lastlogin.
3422 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3424 $USER->currentlogin = $user->currentlogin = $now;
3426 // Function user_accesstime_log() may not update immediately, better do it here.
3427 $USER->lastaccess = $user->lastaccess = $now;
3428 $USER->lastip = $user->lastip = getremoteaddr();
3430 user_update_user($user, false);
3431 return true;
3435 * Determines if a user has completed setting up their account.
3437 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3438 * @return bool
3440 function user_not_fully_set_up($user) {
3441 if (isguestuser($user)) {
3442 return false;
3444 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3448 * Check whether the user has exceeded the bounce threshold
3450 * @param stdClass $user A {@link $USER} object
3451 * @return bool true => User has exceeded bounce threshold
3453 function over_bounce_threshold($user) {
3454 global $CFG, $DB;
3456 if (empty($CFG->handlebounces)) {
3457 return false;
3460 if (empty($user->id)) {
3461 // No real (DB) user, nothing to do here.
3462 return false;
3465 // Set sensible defaults.
3466 if (empty($CFG->minbounces)) {
3467 $CFG->minbounces = 10;
3469 if (empty($CFG->bounceratio)) {
3470 $CFG->bounceratio = .20;
3472 $bouncecount = 0;
3473 $sendcount = 0;
3474 if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3475 $bouncecount = $bounce->value;
3477 if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3478 $sendcount = $send->value;
3480 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3484 * Used to increment or reset email sent count
3486 * @param stdClass $user object containing an id
3487 * @param bool $reset will reset the count to 0
3488 * @return void
3490 function set_send_count($user, $reset=false) {
3491 global $DB;
3493 if (empty($user->id)) {
3494 // No real (DB) user, nothing to do here.
3495 return;
3498 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3499 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3500 $DB->update_record('user_preferences', $pref);
3501 } else if (!empty($reset)) {
3502 // If it's not there and we're resetting, don't bother. Make a new one.
3503 $pref = new stdClass();
3504 $pref->name = 'email_send_count';
3505 $pref->value = 1;
3506 $pref->userid = $user->id;
3507 $DB->insert_record('user_preferences', $pref, false);
3512 * Increment or reset user's email bounce count
3514 * @param stdClass $user object containing an id
3515 * @param bool $reset will reset the count to 0
3517 function set_bounce_count($user, $reset=false) {
3518 global $DB;
3520 if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3521 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3522 $DB->update_record('user_preferences', $pref);
3523 } else if (!empty($reset)) {
3524 // If it's not there and we're resetting, don't bother. Make a new one.
3525 $pref = new stdClass();
3526 $pref->name = 'email_bounce_count';
3527 $pref->value = 1;
3528 $pref->userid = $user->id;
3529 $DB->insert_record('user_preferences', $pref, false);
3534 * Determines if the logged in user is currently moving an activity
3536 * @param int $courseid The id of the course being tested
3537 * @return bool
3539 function ismoving($courseid) {
3540 global $USER;
3542 if (!empty($USER->activitycopy)) {
3543 return ($USER->activitycopycourse == $courseid);
3545 return false;
3549 * Returns a persons full name
3551 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3552 * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
3553 * specify one.
3555 * @param stdClass $user A {@link $USER} object to get full name of.
3556 * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
3557 * @return string
3559 function fullname($user, $override=false) {
3560 global $CFG, $SESSION;
3562 // Get all of the name fields.
3563 $allnames = get_all_user_name_fields();
3564 if ($CFG->debugdeveloper) {
3565 foreach ($allnames as $allname) {
3566 if (!array_key_exists($allname, $user)) {
3567 // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3568 debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3569 // Message has been sent, no point in sending the message multiple times.
3570 break;
3575 if (!isset($user->firstname) and !isset($user->lastname)) {
3576 return '';
3579 if (!$override) {
3580 if (!empty($CFG->forcefirstname)) {
3581 $user->firstname = $CFG->forcefirstname;
3583 if (!empty($CFG->forcelastname)) {
3584 $user->lastname = $CFG->forcelastname;
3588 if (!empty($SESSION->fullnamedisplay)) {
3589 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3592 $template = null;
3593 // If the fullnamedisplay setting is available, set the template to that.
3594 if (isset($CFG->fullnamedisplay)) {
3595 $template = $CFG->fullnamedisplay;
3597 // If the template is empty, or set to language, or $override is set, return the language string.
3598 if (empty($template) || $template == 'language' || $override) {
3599 return get_string('fullnamedisplay', null, $user);
3602 $requirednames = array();
3603 // With each name, see if it is in the display name template, and add it to the required names array if it is.
3604 foreach ($allnames as $allname) {
3605 if (strpos($template, $allname) !== false) {
3606 $requirednames[] = $allname;
3610 $displayname = $template;
3611 // Switch in the actual data into the template.
3612 foreach ($requirednames as $altname) {
3613 if (isset($user->$altname)) {
3614 // Using empty() on the below if statement causes breakages.
3615 if ((string)$user->$altname == '') {
3616 $displayname = str_replace($altname, 'EMPTY', $displayname);
3617 } else {
3618 $displayname = str_replace($altname, $user->$altname, $displayname);
3620 } else {
3621 $displayname = str_replace($altname, 'EMPTY', $displayname);
3624 // Tidy up any misc. characters (Not perfect, but gets most characters).
3625 // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3626 // katakana and parenthesis.
3627 $patterns = array();
3628 // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3629 // filled in by a user.
3630 // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3631 $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3632 // This regular expression is to remove any double spaces in the display name.
3633 $patterns[] = '/\s{2,}/';
3634 foreach ($patterns as $pattern) {
3635 $displayname = preg_replace($pattern, ' ', $displayname);
3638 // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3639 $displayname = trim($displayname);
3640 if (empty($displayname)) {
3641 // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3642 // people in general feel is a good setting to fall back on.
3643 $displayname = $user->firstname;
3645 return $displayname;
3649 * A centralised location for the all name fields. Returns an array / sql string snippet.
3651 * @param bool $returnsql True for an sql select field snippet.
3652 * @param string $alias table alias to use in front of each field.
3653 * @return array|string All name fields.
3655 function get_all_user_name_fields($returnsql = false, $alias = null) {
3656 $alternatenames = array('firstnamephonetic',
3657 'lastnamephonetic',
3658 'middlename',
3659 'alternatename',
3660 'firstname',
3661 'lastname');
3662 if ($returnsql) {
3663 if ($alias) {
3664 foreach ($alternatenames as $key => $altname) {
3665 $alternatenames[$key] = "$alias.$altname";
3668 $alternatenames = implode(',', $alternatenames);
3670 return $alternatenames;
3674 * Returns an array of values in order of occurance in a provided string.
3675 * The key in the result is the character postion in the string.
3677 * @param array $values Values to be found in the string format
3678 * @param string $stringformat The string which may contain values being searched for.
3679 * @return array An array of values in order according to placement in the string format.
3681 function order_in_string($values, $stringformat) {
3682 $valuearray = array();
3683 foreach ($values as $value) {
3684 $pattern = "/$value\b/";
3685 // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3686 if (preg_match($pattern, $stringformat)) {
3687 $replacement = "thing";
3688 // Replace the value with something more unique to ensure we get the right position when using strpos().
3689 $newformat = preg_replace($pattern, $replacement, $stringformat);
3690 $position = strpos($newformat, $replacement);
3691 $valuearray[$position] = $value;
3694 ksort($valuearray);
3695 return $valuearray;
3699 * Checks if current user is shown any extra fields when listing users.
3701 * @param object $context Context
3702 * @param array $already Array of fields that we're going to show anyway
3703 * so don't bother listing them
3704 * @return array Array of field names from user table, not including anything
3705 * listed in $already
3707 function get_extra_user_fields($context, $already = array()) {
3708 global $CFG;
3710 // Only users with permission get the extra fields.
3711 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3712 return array();
3715 // Split showuseridentity on comma.
3716 if (empty($CFG->showuseridentity)) {
3717 // Explode gives wrong result with empty string.
3718 $extra = array();
3719 } else {
3720 $extra = explode(',', $CFG->showuseridentity);
3722 $renumber = false;
3723 foreach ($extra as $key => $field) {
3724 if (in_array($field, $already)) {
3725 unset($extra[$key]);
3726 $renumber = true;
3729 if ($renumber) {
3730 // For consistency, if entries are removed from array, renumber it
3731 // so they are numbered as you would expect.
3732 $extra = array_merge($extra);
3734 return $extra;
3738 * If the current user is to be shown extra user fields when listing or
3739 * selecting users, returns a string suitable for including in an SQL select
3740 * clause to retrieve those fields.
3742 * @param context $context Context
3743 * @param string $alias Alias of user table, e.g. 'u' (default none)
3744 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3745 * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
3746 * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
3748 function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
3749 $fields = get_extra_user_fields($context, $already);
3750 $result = '';
3751 // Add punctuation for alias.
3752 if ($alias !== '') {
3753 $alias .= '.';
3755 foreach ($fields as $field) {
3756 $result .= ', ' . $alias . $field;
3757 if ($prefix) {
3758 $result .= ' AS ' . $prefix . $field;
3761 return $result;
3765 * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
3766 * @param string $field Field name, e.g. 'phone1'
3767 * @return string Text description taken from language file, e.g. 'Phone number'
3769 function get_user_field_name($field) {
3770 // Some fields have language strings which are not the same as field name.
3771 switch ($field) {
3772 case 'phone1' : {
3773 return get_string('phone');
3775 case 'url' : {
3776 return get_string('webpage');
3778 case 'icq' : {
3779 return get_string('icqnumber');
3781 case 'skype' : {
3782 return get_string('skypeid');
3784 case 'aim' : {
3785 return get_string('aimid');
3787 case 'yahoo' : {
3788 return get_string('yahooid');
3790 case 'msn' : {
3791 return get_string('msnid');
3794 // Otherwise just use the same lang string.
3795 return get_string($field);
3799 * Returns whether a given authentication plugin exists.
3801 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3802 * @return boolean Whether the plugin is available.
3804 function exists_auth_plugin($auth) {
3805 global $CFG;
3807 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3808 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3810 return false;
3814 * Checks if a given plugin is in the list of enabled authentication plugins.
3816 * @param string $auth Authentication plugin.
3817 * @return boolean Whether the plugin is enabled.
3819 function is_enabled_auth($auth) {
3820 if (empty($auth)) {
3821 return false;
3824 $enabled = get_enabled_auth_plugins();
3826 return in_array($auth, $enabled);
3830 * Returns an authentication plugin instance.
3832 * @param string $auth name of authentication plugin
3833 * @return auth_plugin_base An instance of the required authentication plugin.
3835 function get_auth_plugin($auth) {
3836 global $CFG;
3838 // Check the plugin exists first.
3839 if (! exists_auth_plugin($auth)) {
3840 print_error('authpluginnotfound', 'debug', '', $auth);
3843 // Return auth plugin instance.
3844 require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3845 $class = "auth_plugin_$auth";
3846 return new $class;
3850 * Returns array of active auth plugins.
3852 * @param bool $fix fix $CFG->auth if needed
3853 * @return array
3855 function get_enabled_auth_plugins($fix=false) {
3856 global $CFG;
3858 $default = array('manual', 'nologin');
3860 if (empty($CFG->auth)) {
3861 $auths = array();
3862 } else {
3863 $auths = explode(',', $CFG->auth);
3866 if ($fix) {
3867 $auths = array_unique($auths);
3868 foreach ($auths as $k => $authname) {
3869 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3870 unset($auths[$k]);
3873 $newconfig = implode(',', $auths);
3874 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3875 set_config('auth', $newconfig);
3879 return (array_merge($default, $auths));
3883 * Returns true if an internal authentication method is being used.
3884 * if method not specified then, global default is assumed
3886 * @param string $auth Form of authentication required
3887 * @return bool
3889 function is_internal_auth($auth) {
3890 // Throws error if bad $auth.
3891 $authplugin = get_auth_plugin($auth);
3892 return $authplugin->is_internal();
3896 * Returns true if the user is a 'restored' one.
3898 * Used in the login process to inform the user and allow him/her to reset the password
3900 * @param string $username username to be checked
3901 * @return bool
3903 function is_restored_user($username) {
3904 global $CFG, $DB;
3906 return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3910 * Returns an array of user fields
3912 * @return array User field/column names
3914 function get_user_fieldnames() {
3915 global $DB;
3917 $fieldarray = $DB->get_columns('user');
3918 unset($fieldarray['id']);
3919 $fieldarray = array_keys($fieldarray);
3921 return $fieldarray;
3925 * Creates a bare-bones user record
3927 * @todo Outline auth types and provide code example
3929 * @param string $username New user's username to add to record
3930 * @param string $password New user's password to add to record
3931 * @param string $auth Form of authentication required
3932 * @return stdClass A complete user object
3934 function create_user_record($username, $password, $auth = 'manual') {
3935 global $CFG, $DB;
3936 require_once($CFG->dirroot.'/user/profile/lib.php');
3937 require_once($CFG->dirroot.'/user/lib.php');
3939 // Just in case check text case.
3940 $username = trim(core_text::strtolower($username));
3942 $authplugin = get_auth_plugin($auth);
3943 $customfields = $authplugin->get_custom_user_profile_fields();
3944 $newuser = new stdClass();
3945 if ($newinfo = $authplugin->get_userinfo($username)) {
3946 $newinfo = truncate_userinfo($newinfo);
3947 foreach ($newinfo as $key => $value) {
3948 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3949 $newuser->$key = $value;
3954 if (!empty($newuser->email)) {
3955 if (email_is_not_allowed($newuser->email)) {
3956 unset($newuser->email);
3960 if (!isset($newuser->city)) {
3961 $newuser->city = '';
3964 $newuser->auth = $auth;
3965 $newuser->username = $username;
3967 // Fix for MDL-8480
3968 // user CFG lang for user if $newuser->lang is empty
3969 // or $user->lang is not an installed language.
3970 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3971 $newuser->lang = $CFG->lang;
3973 $newuser->confirmed = 1;
3974 $newuser->lastip = getremoteaddr();
3975 $newuser->timecreated = time();
3976 $newuser->timemodified = $newuser->timecreated;
3977 $newuser->mnethostid = $CFG->mnet_localhost_id;
3979 $newuser->id = user_create_user($newuser, false);
3981 // Save user profile data.
3982 profile_save_data($newuser);
3984 $user = get_complete_user_data('id', $newuser->id);
3985 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3986 set_user_preference('auth_forcepasswordchange', 1, $user);
3988 // Set the password.
3989 update_internal_user_password($user, $password);
3991 return $user;
3995 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3997 * @param string $username user's username to update the record
3998 * @return stdClass A complete user object
4000 function update_user_record($username) {
4001 global $DB, $CFG;
4002 require_once($CFG->dirroot."/user/profile/lib.php");
4003 require_once($CFG->dirroot.'/user/lib.php');
4004 // Just in case check text case.
4005 $username = trim(core_text::strtolower($username));
4007 $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
4008 $newuser = array();
4009 $userauth = get_auth_plugin($oldinfo->auth);
4011 if ($newinfo = $userauth->get_userinfo($username)) {
4012 $newinfo = truncate_userinfo($newinfo);
4013 $customfields = $userauth->get_custom_user_profile_fields();
4015 foreach ($newinfo as $key => $value) {
4016 $key = strtolower($key);
4017 $iscustom = in_array($key, $customfields);
4018 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
4019 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
4020 // Unknown or must not be changed.
4021 continue;
4023 $confval = $userauth->config->{'field_updatelocal_' . $key};
4024 $lockval = $userauth->config->{'field_lock_' . $key};
4025 if (empty($confval) || empty($lockval)) {
4026 continue;
4028 if ($confval === 'onlogin') {
4029 // MDL-4207 Don't overwrite modified user profile values with
4030 // empty LDAP values when 'unlocked if empty' is set. The purpose
4031 // of the setting 'unlocked if empty' is to allow the user to fill
4032 // in a value for the selected field _if LDAP is giving
4033 // nothing_ for this field. Thus it makes sense to let this value
4034 // stand in until LDAP is giving a value for this field.
4035 if (!(empty($value) && $lockval === 'unlockedifempty')) {
4036 if ($iscustom || (in_array($key, $userauth->userfields) &&
4037 ((string)$oldinfo->$key !== (string)$value))) {
4038 $newuser[$key] = (string)$value;
4043 if ($newuser) {
4044 $newuser['id'] = $oldinfo->id;
4045 $newuser['timemodified'] = time();
4046 user_update_user((object) $newuser, false);
4048 // Save user profile data.
4049 profile_save_data((object) $newuser);
4053 return get_complete_user_data('id', $oldinfo->id);
4057 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4059 * @param array $info Array of user properties to truncate if needed
4060 * @return array The now truncated information that was passed in
4062 function truncate_userinfo(array $info) {
4063 // Define the limits.
4064 $limit = array(
4065 'username' => 100,
4066 'idnumber' => 255,
4067 'firstname' => 100,
4068 'lastname' => 100,
4069 'email' => 100,
4070 'icq' => 15,
4071 'phone1' => 20,
4072 'phone2' => 20,
4073 'institution' => 40,
4074 'department' => 30,
4075 'address' => 70,
4076 'city' => 120,
4077 'country' => 2,
4078 'url' => 255,
4081 // Apply where needed.
4082 foreach (array_keys($info) as $key) {
4083 if (!empty($limit[$key])) {
4084 $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4088 return $info;
4092 * Marks user deleted in internal user database and notifies the auth plugin.
4093 * Also unenrols user from all roles and does other cleanup.
4095 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4097 * @param stdClass $user full user object before delete
4098 * @return boolean success
4099 * @throws coding_exception if invalid $user parameter detected
4101 function delete_user(stdClass $user) {
4102 global $CFG, $DB;
4103 require_once($CFG->libdir.'/grouplib.php');
4104 require_once($CFG->libdir.'/gradelib.php');
4105 require_once($CFG->dirroot.'/message/lib.php');
4106 require_once($CFG->dirroot.'/tag/lib.php');
4107 require_once($CFG->dirroot.'/user/lib.php');
4109 // Make sure nobody sends bogus record type as parameter.
4110 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4111 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4114 // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4115 if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4116 debugging('Attempt to delete unknown user account.');
4117 return false;
4120 // There must be always exactly one guest record, originally the guest account was identified by username only,
4121 // now we use $CFG->siteguest for performance reasons.
4122 if ($user->username === 'guest' or isguestuser($user)) {
4123 debugging('Guest user account can not be deleted.');
4124 return false;
4127 // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4128 // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4129 if ($user->auth === 'manual' and is_siteadmin($user)) {
4130 debugging('Local administrator accounts can not be deleted.');
4131 return false;
4134 // Keep user record before updating it, as we have to pass this to user_deleted event.
4135 $olduser = clone $user;
4137 // Keep a copy of user context, we need it for event.
4138 $usercontext = context_user::instance($user->id);
4140 // Delete all grades - backup is kept in grade_grades_history table.
4141 grade_user_delete($user->id);
4143 // Move unread messages from this user to read.
4144 message_move_userfrom_unread2read($user->id);
4146 // TODO: remove from cohorts using standard API here.
4148 // Remove user tags.
4149 tag_set('user', $user->id, array());
4151 // Unconditionally unenrol from all courses.
4152 enrol_user_delete($user);
4154 // Unenrol from all roles in all contexts.
4155 // This might be slow but it is really needed - modules might do some extra cleanup!
4156 role_unassign_all(array('userid' => $user->id));
4158 // Now do a brute force cleanup.
4160 // Remove from all cohorts.
4161 $DB->delete_records('cohort_members', array('userid' => $user->id));
4163 // Remove from all groups.
4164 $DB->delete_records('groups_members', array('userid' => $user->id));
4166 // Brute force unenrol from all courses.
4167 $DB->delete_records('user_enrolments', array('userid' => $user->id));
4169 // Purge user preferences.
4170 $DB->delete_records('user_preferences', array('userid' => $user->id));
4172 // Purge user extra profile info.
4173 $DB->delete_records('user_info_data', array('userid' => $user->id));
4175 // Last course access not necessary either.
4176 $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4177 // Remove all user tokens.
4178 $DB->delete_records('external_tokens', array('userid' => $user->id));
4180 // Unauthorise the user for all services.
4181 $DB->delete_records('external_services_users', array('userid' => $user->id));
4183 // Remove users private keys.
4184 $DB->delete_records('user_private_key', array('userid' => $user->id));
4186 // Force logout - may fail if file based sessions used, sorry.
4187 \core\session\manager::kill_user_sessions($user->id);
4189 // Workaround for bulk deletes of users with the same email address.
4190 $delname = "$user->email.".time();
4191 while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4192 $delname++;
4195 // Mark internal user record as "deleted".
4196 $updateuser = new stdClass();
4197 $updateuser->id = $user->id;
4198 $updateuser->deleted = 1;
4199 $updateuser->username = $delname; // Remember it just in case.
4200 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
4201 $updateuser->idnumber = ''; // Clear this field to free it up.
4202 $updateuser->picture = 0;
4203 $updateuser->timemodified = time();
4205 user_update_user($updateuser, false);
4207 // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
4208 context_helper::delete_instance(CONTEXT_USER, $user->id);
4210 // Any plugin that needs to cleanup should register this event.
4211 // Trigger event.
4212 $event = \core\event\user_deleted::create(
4213 array(
4214 'objectid' => $user->id,
4215 'context' => $usercontext,
4216 'other' => array(
4217 'username' => $user->username,
4218 'email' => $user->email,
4219 'idnumber' => $user->idnumber,
4220 'picture' => $user->picture,
4221 'mnethostid' => $user->mnethostid
4225 $event->add_record_snapshot('user', $olduser);
4226 $event->trigger();
4228 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4229 // should know about this updated property persisted to the user's table.
4230 $user->timemodified = $updateuser->timemodified;
4232 // Notify auth plugin - do not block the delete even when plugin fails.
4233 $authplugin = get_auth_plugin($user->auth);
4234 $authplugin->user_delete($user);
4236 return true;
4240 * Retrieve the guest user object.
4242 * @return stdClass A {@link $USER} object
4244 function guest_user() {
4245 global $CFG, $DB;
4247 if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4248 $newuser->confirmed = 1;
4249 $newuser->lang = $CFG->lang;
4250 $newuser->lastip = getremoteaddr();
4253 return $newuser;
4257 * Authenticates a user against the chosen authentication mechanism
4259 * Given a username and password, this function looks them
4260 * up using the currently selected authentication mechanism,
4261 * and if the authentication is successful, it returns a
4262 * valid $user object from the 'user' table.
4264 * Uses auth_ functions from the currently active auth module
4266 * After authenticate_user_login() returns success, you will need to
4267 * log that the user has logged in, and call complete_user_login() to set
4268 * the session up.
4270 * Note: this function works only with non-mnet accounts!
4272 * @param string $username User's username
4273 * @param string $password User's password
4274 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4275 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4276 * @return stdClass|false A {@link $USER} object or false if error
4278 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4279 global $CFG, $DB;
4280 require_once("$CFG->libdir/authlib.php");
4282 $authsenabled = get_enabled_auth_plugins();
4284 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4285 // Use manual if auth not set.
4286 $auth = empty($user->auth) ? 'manual' : $user->auth;
4287 if (!empty($user->suspended)) {
4288 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4289 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4290 $failurereason = AUTH_LOGIN_SUSPENDED;
4291 return false;
4293 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4294 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4295 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4296 // Legacy way to suspend user.
4297 $failurereason = AUTH_LOGIN_SUSPENDED;
4298 return false;
4300 $auths = array($auth);
4302 } else {
4303 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4304 if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
4305 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4306 $failurereason = AUTH_LOGIN_NOUSER;
4307 return false;
4310 // Do not try to authenticate non-existent accounts when user creation is not disabled.
4311 if (!empty($CFG->authpreventaccountcreation)) {
4312 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4313 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".$_SERVER['HTTP_USER_AGENT']);
4314 $failurereason = AUTH_LOGIN_NOUSER;
4315 return false;
4318 // User does not exist.
4319 $auths = $authsenabled;
4320 $user = new stdClass();
4321 $user->id = 0;
4324 if ($ignorelockout) {
4325 // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4326 // or this function is called from a SSO script.
4327 } else if ($user->id) {
4328 // Verify login lockout after other ways that may prevent user login.
4329 if (login_is_lockedout($user)) {
4330 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4331 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4332 $failurereason = AUTH_LOGIN_LOCKOUT;
4333 return false;
4335 } else {
4336 // We can not lockout non-existing accounts.
4339 foreach ($auths as $auth) {
4340 $authplugin = get_auth_plugin($auth);
4342 // On auth fail fall through to the next plugin.
4343 if (!$authplugin->user_login($username, $password)) {
4344 continue;
4347 // Successful authentication.
4348 if ($user->id) {
4349 // User already exists in database.
4350 if (empty($user->auth)) {
4351 // For some reason auth isn't set yet.
4352 $DB->set_field('user', 'auth', $auth, array('username' => $username));
4353 $user->auth = $auth;
4356 // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4357 // the current hash algorithm while we have access to the user's password.
4358 update_internal_user_password($user, $password);
4360 if ($authplugin->is_synchronised_with_external()) {
4361 // Update user record from external DB.
4362 $user = update_user_record($username);
4364 } else {
4365 // Create account, we verified above that user creation is allowed.
4366 $user = create_user_record($username, $password, $auth);
4369 $authplugin->sync_roles($user);
4371 foreach ($authsenabled as $hau) {
4372 $hauth = get_auth_plugin($hau);
4373 $hauth->user_authenticated_hook($user, $username, $password);
4376 if (empty($user->id)) {
4377 $failurereason = AUTH_LOGIN_NOUSER;
4378 return false;
4381 if (!empty($user->suspended)) {
4382 // Just in case some auth plugin suspended account.
4383 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4384 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4385 $failurereason = AUTH_LOGIN_SUSPENDED;
4386 return false;
4389 login_attempt_valid($user);
4390 $failurereason = AUTH_LOGIN_OK;
4391 return $user;
4394 // Failed if all the plugins have failed.
4395 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4396 if (debugging('', DEBUG_ALL)) {
4397 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4400 if ($user->id) {
4401 login_attempt_failed($user);
4402 $failurereason = AUTH_LOGIN_FAILED;
4403 } else {
4404 $failurereason = AUTH_LOGIN_NOUSER;
4407 return false;
4411 * Call to complete the user login process after authenticate_user_login()
4412 * has succeeded. It will setup the $USER variable and other required bits
4413 * and pieces.
4415 * NOTE:
4416 * - It will NOT log anything -- up to the caller to decide what to log.
4417 * - this function does not set any cookies any more!
4419 * @param stdClass $user
4420 * @return stdClass A {@link $USER} object - BC only, do not use
4422 function complete_user_login($user) {
4423 global $CFG, $USER;
4425 \core\session\manager::login_user($user);
4427 // Reload preferences from DB.
4428 unset($USER->preference);
4429 check_user_preferences_loaded($USER);
4431 // Update login times.
4432 update_user_login_times();
4434 // Extra session prefs init.
4435 set_login_session_preferences();
4437 // Trigger login event.
4438 $event = \core\event\user_loggedin::create(
4439 array(
4440 'userid' => $USER->id,
4441 'objectid' => $USER->id,
4442 'other' => array('username' => $USER->username),
4445 $event->add_record_snapshot('user', $user);
4446 $event->trigger();
4448 if (isguestuser()) {
4449 // No need to continue when user is THE guest.
4450 return $USER;
4453 if (CLI_SCRIPT) {
4454 // We can redirect to password change URL only in browser.
4455 return $USER;
4458 // Select password change url.
4459 $userauth = get_auth_plugin($USER->auth);
4461 // Check whether the user should be changing password.
4462 if (get_user_preferences('auth_forcepasswordchange', false)) {
4463 if ($userauth->can_change_password()) {
4464 if ($changeurl = $userauth->change_password_url()) {
4465 redirect($changeurl);
4466 } else {
4467 redirect($CFG->httpswwwroot.'/login/change_password.php');
4469 } else {
4470 print_error('nopasswordchangeforced', 'auth');
4473 return $USER;
4477 * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4479 * @param string $password String to check.
4480 * @return boolean True if the $password matches the format of an md5 sum.
4482 function password_is_legacy_hash($password) {
4483 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4487 * Checks whether the password compatibility library will work with the current
4488 * version of PHP. This cannot be done using PHP version numbers since the fix
4489 * has been backported to earlier versions in some distributions.
4491 * See https://github.com/ircmaxell/password_compat/issues/10 for more details.
4493 * @return bool True if the library is NOT supported.
4495 function password_compat_not_supported() {
4497 $hash = '$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG';
4499 // Create a one off application cache to store bcrypt support status as
4500 // the support status doesn't change and crypt() is slow.
4501 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'password_compat');
4503 if (!$bcryptsupport = $cache->get('bcryptsupport')) {
4504 $test = crypt('password', $hash);
4505 // Cache string instead of boolean to avoid MDL-37472.
4506 if ($test == $hash) {
4507 $bcryptsupport = 'supported';
4508 } else {
4509 $bcryptsupport = 'not supported';
4511 $cache->set('bcryptsupport', $bcryptsupport);
4514 // Return true if bcrypt *not* supported.
4515 return ($bcryptsupport !== 'supported');
4519 * Compare password against hash stored in user object to determine if it is valid.
4521 * If necessary it also updates the stored hash to the current format.
4523 * @param stdClass $user (Password property may be updated).
4524 * @param string $password Plain text password.
4525 * @return bool True if password is valid.
4527 function validate_internal_user_password($user, $password) {
4528 global $CFG;
4529 require_once($CFG->libdir.'/password_compat/lib/password.php');
4531 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4532 // Internal password is not used at all, it can not validate.
4533 return false;
4536 // If hash isn't a legacy (md5) hash, validate using the library function.
4537 if (!password_is_legacy_hash($user->password)) {
4538 return password_verify($password, $user->password);
4541 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4542 // is valid we can then update it to the new algorithm.
4544 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4545 $validated = false;
4547 if ($user->password === md5($password.$sitesalt)
4548 or $user->password === md5($password)
4549 or $user->password === md5(addslashes($password).$sitesalt)
4550 or $user->password === md5(addslashes($password))) {
4551 // Note: we are intentionally using the addslashes() here because we
4552 // need to accept old password hashes of passwords with magic quotes.
4553 $validated = true;
4555 } else {
4556 for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4557 $alt = 'passwordsaltalt'.$i;
4558 if (!empty($CFG->$alt)) {
4559 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4560 $validated = true;
4561 break;
4567 if ($validated) {
4568 // If the password matches the existing md5 hash, update to the
4569 // current hash algorithm while we have access to the user's password.
4570 update_internal_user_password($user, $password);
4573 return $validated;
4577 * Calculate hash for a plain text password.
4579 * @param string $password Plain text password to be hashed.
4580 * @param bool $fasthash If true, use a low cost factor when generating the hash
4581 * This is much faster to generate but makes the hash
4582 * less secure. It is used when lots of hashes need to
4583 * be generated quickly.
4584 * @return string The hashed password.
4586 * @throws moodle_exception If a problem occurs while generating the hash.
4588 function hash_internal_user_password($password, $fasthash = false) {
4589 global $CFG;
4590 require_once($CFG->libdir.'/password_compat/lib/password.php');
4592 // Use the legacy hashing algorithm (md5) if PHP is not new enough to support bcrypt properly.
4593 if (password_compat_not_supported()) {
4594 if (isset($CFG->passwordsaltmain)) {
4595 return md5($password.$CFG->passwordsaltmain);
4596 } else {
4597 return md5($password);
4601 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4602 $options = ($fasthash) ? array('cost' => 4) : array();
4604 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4606 if ($generatedhash === false || $generatedhash === null) {
4607 throw new moodle_exception('Failed to generate password hash.');
4610 return $generatedhash;
4614 * Update password hash in user object (if necessary).
4616 * The password is updated if:
4617 * 1. The password has changed (the hash of $user->password is different
4618 * to the hash of $password).
4619 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4620 * md5 algorithm).
4622 * Updating the password will modify the $user object and the database
4623 * record to use the current hashing algorithm.
4625 * @param stdClass $user User object (password property may be updated).
4626 * @param string $password Plain text password.
4627 * @return bool Always returns true.
4629 function update_internal_user_password($user, $password) {
4630 global $CFG, $DB;
4631 require_once($CFG->libdir.'/password_compat/lib/password.php');
4633 // Use the legacy hashing algorithm (md5) if PHP doesn't support bcrypt properly.
4634 $legacyhash = password_compat_not_supported();
4636 // Figure out what the hashed password should be.
4637 $authplugin = get_auth_plugin($user->auth);
4638 if ($authplugin->prevent_local_passwords()) {
4639 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4640 } else {
4641 $hashedpassword = hash_internal_user_password($password);
4644 if ($legacyhash) {
4645 $passwordchanged = ($user->password !== $hashedpassword);
4646 $algorithmchanged = false;
4647 } else {
4648 // If verification fails then it means the password has changed.
4649 $passwordchanged = !password_verify($password, $user->password);
4650 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4653 if ($passwordchanged || $algorithmchanged) {
4654 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
4655 $user->password = $hashedpassword;
4657 // Trigger event.
4658 $event = \core\event\user_updated::create(array(
4659 'objectid' => $user->id,
4660 'context' => context_user::instance($user->id)
4662 $event->add_record_snapshot('user', $user);
4663 $event->trigger();
4666 return true;
4670 * Get a complete user record, which includes all the info in the user record.
4672 * Intended for setting as $USER session variable
4674 * @param string $field The user field to be checked for a given value.
4675 * @param string $value The value to match for $field.
4676 * @param int $mnethostid
4677 * @return mixed False, or A {@link $USER} object.
4679 function get_complete_user_data($field, $value, $mnethostid = null) {
4680 global $CFG, $DB;
4682 if (!$field || !$value) {
4683 return false;
4686 // Build the WHERE clause for an SQL query.
4687 $params = array('fieldval' => $value);
4688 $constraints = "$field = :fieldval AND deleted <> 1";
4690 // If we are loading user data based on anything other than id,
4691 // we must also restrict our search based on mnet host.
4692 if ($field != 'id') {
4693 if (empty($mnethostid)) {
4694 // If empty, we restrict to local users.
4695 $mnethostid = $CFG->mnet_localhost_id;
4698 if (!empty($mnethostid)) {
4699 $params['mnethostid'] = $mnethostid;
4700 $constraints .= " AND mnethostid = :mnethostid";
4703 // Get all the basic user data.
4704 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4705 return false;
4708 // Get various settings and preferences.
4710 // Preload preference cache.
4711 check_user_preferences_loaded($user);
4713 // Load course enrolment related stuff.
4714 $user->lastcourseaccess = array(); // During last session.
4715 $user->currentcourseaccess = array(); // During current session.
4716 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4717 foreach ($lastaccesses as $lastaccess) {
4718 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4722 $sql = "SELECT g.id, g.courseid
4723 FROM {groups} g, {groups_members} gm
4724 WHERE gm.groupid=g.id AND gm.userid=?";
4726 // This is a special hack to speedup calendar display.
4727 $user->groupmember = array();
4728 if (!isguestuser($user)) {
4729 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4730 foreach ($groups as $group) {
4731 if (!array_key_exists($group->courseid, $user->groupmember)) {
4732 $user->groupmember[$group->courseid] = array();
4734 $user->groupmember[$group->courseid][$group->id] = $group->id;
4739 // Add the custom profile fields to the user record.
4740 $user->profile = array();
4741 if (!isguestuser($user)) {
4742 require_once($CFG->dirroot.'/user/profile/lib.php');
4743 profile_load_custom_fields($user);
4746 // Rewrite some variables if necessary.
4747 if (!empty($user->description)) {
4748 // No need to cart all of it around.
4749 $user->description = true;
4751 if (isguestuser($user)) {
4752 // Guest language always same as site.
4753 $user->lang = $CFG->lang;
4754 // Name always in current language.
4755 $user->firstname = get_string('guestuser');
4756 $user->lastname = ' ';
4759 return $user;
4763 * Validate a password against the configured password policy
4765 * @param string $password the password to be checked against the password policy
4766 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4767 * @return bool true if the password is valid according to the policy. false otherwise.
4769 function check_password_policy($password, &$errmsg) {
4770 global $CFG;
4772 if (empty($CFG->passwordpolicy)) {
4773 return true;
4776 $errmsg = '';
4777 if (core_text::strlen($password) < $CFG->minpasswordlength) {
4778 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4781 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4782 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4785 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4786 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4789 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4790 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4793 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4794 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4796 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4797 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4800 if ($errmsg == '') {
4801 return true;
4802 } else {
4803 return false;
4809 * When logging in, this function is run to set certain preferences for the current SESSION.
4811 function set_login_session_preferences() {
4812 global $SESSION;
4814 $SESSION->justloggedin = true;
4816 unset($SESSION->lang);
4817 unset($SESSION->load_navigation_admin);
4822 * Delete a course, including all related data from the database, and any associated files.
4824 * @param mixed $courseorid The id of the course or course object to delete.
4825 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4826 * @return bool true if all the removals succeeded. false if there were any failures. If this
4827 * method returns false, some of the removals will probably have succeeded, and others
4828 * failed, but you have no way of knowing which.
4830 function delete_course($courseorid, $showfeedback = true) {
4831 global $DB;
4833 if (is_object($courseorid)) {
4834 $courseid = $courseorid->id;
4835 $course = $courseorid;
4836 } else {
4837 $courseid = $courseorid;
4838 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4839 return false;
4842 $context = context_course::instance($courseid);
4844 // Frontpage course can not be deleted!!
4845 if ($courseid == SITEID) {
4846 return false;
4849 // Make the course completely empty.
4850 remove_course_contents($courseid, $showfeedback);
4852 // Delete the course and related context instance.
4853 context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4855 $DB->delete_records("course", array("id" => $courseid));
4856 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4858 // Trigger a course deleted event.
4859 $event = \core\event\course_deleted::create(array(
4860 'objectid' => $course->id,
4861 'context' => $context,
4862 'other' => array(
4863 'shortname' => $course->shortname,
4864 'fullname' => $course->fullname,
4865 'idnumber' => $course->idnumber
4868 $event->add_record_snapshot('course', $course);
4869 $event->trigger();
4871 return true;
4875 * Clear a course out completely, deleting all content but don't delete the course itself.
4877 * This function does not verify any permissions.
4879 * Please note this function also deletes all user enrolments,
4880 * enrolment instances and role assignments by default.
4882 * $options:
4883 * - 'keep_roles_and_enrolments' - false by default
4884 * - 'keep_groups_and_groupings' - false by default
4886 * @param int $courseid The id of the course that is being deleted
4887 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4888 * @param array $options extra options
4889 * @return bool true if all the removals succeeded. false if there were any failures. If this
4890 * method returns false, some of the removals will probably have succeeded, and others
4891 * failed, but you have no way of knowing which.
4893 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4894 global $CFG, $DB, $OUTPUT;
4896 require_once($CFG->libdir.'/badgeslib.php');
4897 require_once($CFG->libdir.'/completionlib.php');
4898 require_once($CFG->libdir.'/questionlib.php');
4899 require_once($CFG->libdir.'/gradelib.php');
4900 require_once($CFG->dirroot.'/group/lib.php');
4901 require_once($CFG->dirroot.'/tag/coursetagslib.php');
4902 require_once($CFG->dirroot.'/comment/lib.php');
4903 require_once($CFG->dirroot.'/rating/lib.php');
4905 // Handle course badges.
4906 badges_handle_course_deletion($courseid);
4908 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4909 $strdeleted = get_string('deleted').' - ';
4911 // Some crazy wishlist of stuff we should skip during purging of course content.
4912 $options = (array)$options;
4914 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4915 $coursecontext = context_course::instance($courseid);
4916 $fs = get_file_storage();
4918 // Delete course completion information, this has to be done before grades and enrols.
4919 $cc = new completion_info($course);
4920 $cc->clear_criteria();
4921 if ($showfeedback) {
4922 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4925 // Remove all data from gradebook - this needs to be done before course modules
4926 // because while deleting this information, the system may need to reference
4927 // the course modules that own the grades.
4928 remove_course_grades($courseid, $showfeedback);
4929 remove_grade_letters($coursecontext, $showfeedback);
4931 // Delete course blocks in any all child contexts,
4932 // they may depend on modules so delete them first.
4933 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4934 foreach ($childcontexts as $childcontext) {
4935 blocks_delete_all_for_context($childcontext->id);
4937 unset($childcontexts);
4938 blocks_delete_all_for_context($coursecontext->id);
4939 if ($showfeedback) {
4940 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4943 // Delete every instance of every module,
4944 // this has to be done before deleting of course level stuff.
4945 $locations = core_component::get_plugin_list('mod');
4946 foreach ($locations as $modname => $moddir) {
4947 if ($modname === 'NEWMODULE') {
4948 continue;
4950 if ($module = $DB->get_record('modules', array('name' => $modname))) {
4951 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
4952 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
4953 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
4955 if ($instances = $DB->get_records($modname, array('course' => $course->id))) {
4956 foreach ($instances as $instance) {
4957 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
4958 // Delete activity context questions and question categories.
4959 question_delete_activity($cm, $showfeedback);
4961 if (function_exists($moddelete)) {
4962 // This purges all module data in related tables, extra user prefs, settings, etc.
4963 $moddelete($instance->id);
4964 } else {
4965 // NOTE: we should not allow installation of modules with missing delete support!
4966 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4967 $DB->delete_records($modname, array('id' => $instance->id));
4970 if ($cm) {
4971 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
4972 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4973 $DB->delete_records('course_modules', array('id' => $cm->id));
4977 if (function_exists($moddeletecourse)) {
4978 // Execute ptional course cleanup callback.
4979 $moddeletecourse($course, $showfeedback);
4981 if ($instances and $showfeedback) {
4982 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4984 } else {
4985 // Ooops, this module is not properly installed, force-delete it in the next block.
4989 // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
4991 // Remove all data from availability and completion tables that is associated
4992 // with course-modules belonging to this course. Note this is done even if the
4993 // features are not enabled now, in case they were enabled previously.
4994 $DB->delete_records_select('course_modules_completion',
4995 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4996 array($courseid));
4997 $DB->delete_records_select('course_modules_availability',
4998 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4999 array($courseid));
5000 $DB->delete_records_select('course_modules_avail_fields',
5001 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
5002 array($courseid));
5004 // Remove course-module data.
5005 $cms = $DB->get_records('course_modules', array('course' => $course->id));
5006 foreach ($cms as $cm) {
5007 if ($module = $DB->get_record('modules', array('id' => $cm->module))) {
5008 try {
5009 $DB->delete_records($module->name, array('id' => $cm->instance));
5010 } catch (Exception $e) {
5011 // Ignore weird or missing table problems.
5014 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5015 $DB->delete_records('course_modules', array('id' => $cm->id));
5018 if ($showfeedback) {
5019 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5022 // Cleanup the rest of plugins.
5023 $cleanuplugintypes = array('report', 'coursereport', 'format');
5024 foreach ($cleanuplugintypes as $type) {
5025 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
5026 foreach ($plugins as $plugin => $pluginfunction) {
5027 $pluginfunction($course->id, $showfeedback);
5029 if ($showfeedback) {
5030 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
5034 // Delete questions and question categories.
5035 question_delete_course($course, $showfeedback);
5036 if ($showfeedback) {
5037 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5040 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5041 $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5042 foreach ($childcontexts as $childcontext) {
5043 $childcontext->delete();
5045 unset($childcontexts);
5047 // Remove all roles and enrolments by default.
5048 if (empty($options['keep_roles_and_enrolments'])) {
5049 // This hack is used in restore when deleting contents of existing course.
5050 role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5051 enrol_course_delete($course);
5052 if ($showfeedback) {
5053 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5057 // Delete any groups, removing members and grouping/course links first.
5058 if (empty($options['keep_groups_and_groupings'])) {
5059 groups_delete_groupings($course->id, $showfeedback);
5060 groups_delete_groups($course->id, $showfeedback);
5063 // Filters be gone!
5064 filter_delete_all_for_context($coursecontext->id);
5066 // Die comments!
5067 comment::delete_comments($coursecontext->id);
5069 // Ratings are history too.
5070 $delopt = new stdclass();
5071 $delopt->contextid = $coursecontext->id;
5072 $rm = new rating_manager();
5073 $rm->delete_ratings($delopt);
5075 // Delete course tags.
5076 coursetag_delete_course_tags($course->id, $showfeedback);
5078 // Delete calendar events.
5079 $DB->delete_records('event', array('courseid' => $course->id));
5080 $fs->delete_area_files($coursecontext->id, 'calendar');
5082 // Delete all related records in other core tables that may have a courseid
5083 // This array stores the tables that need to be cleared, as
5084 // table_name => column_name that contains the course id.
5085 $tablestoclear = array(
5086 'log' => 'course', // Course logs (NOTE: this might be changed in the future).
5087 'backup_courses' => 'courseid', // Scheduled backup stuff.
5088 'user_lastaccess' => 'courseid', // User access info.
5090 foreach ($tablestoclear as $table => $col) {
5091 $DB->delete_records($table, array($col => $course->id));
5094 // Delete all course backup files.
5095 $fs->delete_area_files($coursecontext->id, 'backup');
5097 // Cleanup course record - remove links to deleted stuff.
5098 $oldcourse = new stdClass();
5099 $oldcourse->id = $course->id;
5100 $oldcourse->summary = '';
5101 $oldcourse->cacherev = 0;
5102 $oldcourse->legacyfiles = 0;
5103 $oldcourse->enablecompletion = 0;
5104 if (!empty($options['keep_groups_and_groupings'])) {
5105 $oldcourse->defaultgroupingid = 0;
5107 $DB->update_record('course', $oldcourse);
5109 // Delete course sections and availability options.
5110 $DB->delete_records_select('course_sections_availability',
5111 'coursesectionid IN (SELECT id from {course_sections} WHERE course=?)',
5112 array($course->id));
5113 $DB->delete_records_select('course_sections_avail_fields',
5114 'coursesectionid IN (SELECT id from {course_sections} WHERE course=?)',
5115 array($course->id));
5116 $DB->delete_records('course_sections', array('course' => $course->id));
5118 // Delete legacy, section and any other course files.
5119 $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5121 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5122 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5123 // Easy, do not delete the context itself...
5124 $coursecontext->delete_content();
5125 } else {
5126 // Hack alert!!!!
5127 // We can not drop all context stuff because it would bork enrolments and roles,
5128 // there might be also files used by enrol plugins...
5131 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5132 // also some non-standard unsupported plugins may try to store something there.
5133 fulldelete($CFG->dataroot.'/'.$course->id);
5135 // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5136 $cachemodinfo = cache::make('core', 'coursemodinfo');
5137 $cachemodinfo->delete($courseid);
5139 // Trigger a course content deleted event.
5140 $event = \core\event\course_content_deleted::create(array(
5141 'objectid' => $course->id,
5142 'context' => $coursecontext,
5143 'other' => array('shortname' => $course->shortname,
5144 'fullname' => $course->fullname,
5145 'options' => $options) // Passing this for legacy reasons.
5147 $event->add_record_snapshot('course', $course);
5148 $event->trigger();
5150 return true;
5154 * Change dates in module - used from course reset.
5156 * @param string $modname forum, assignment, etc
5157 * @param array $fields array of date fields from mod table
5158 * @param int $timeshift time difference
5159 * @param int $courseid
5160 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5161 * @return bool success
5163 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5164 global $CFG, $DB;
5165 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5167 $return = true;
5168 $params = array($timeshift, $courseid);
5169 foreach ($fields as $field) {
5170 $updatesql = "UPDATE {".$modname."}
5171 SET $field = $field + ?
5172 WHERE course=? AND $field<>0";
5173 if ($modid) {
5174 $updatesql .= ' AND id=?';
5175 $params[] = $modid;
5177 $return = $DB->execute($updatesql, $params) && $return;
5180 $refreshfunction = $modname.'_refresh_events';
5181 if (function_exists($refreshfunction)) {
5182 $refreshfunction($courseid);
5185 return $return;
5189 * This function will empty a course of user data.
5190 * It will retain the activities and the structure of the course.
5192 * @param object $data an object containing all the settings including courseid (without magic quotes)
5193 * @return array status array of array component, item, error
5195 function reset_course_userdata($data) {
5196 global $CFG, $DB;
5197 require_once($CFG->libdir.'/gradelib.php');
5198 require_once($CFG->libdir.'/completionlib.php');
5199 require_once($CFG->dirroot.'/group/lib.php');
5201 $data->courseid = $data->id;
5202 $context = context_course::instance($data->courseid);
5204 $eventparams = array(
5205 'context' => $context,
5206 'courseid' => $data->id,
5207 'other' => array(
5208 'reset_options' => (array) $data
5211 $event = \core\event\course_reset_started::create($eventparams);
5212 $event->trigger();
5214 // Calculate the time shift of dates.
5215 if (!empty($data->reset_start_date)) {
5216 // Time part of course startdate should be zero.
5217 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5218 } else {
5219 $data->timeshift = 0;
5222 // Result array: component, item, error.
5223 $status = array();
5225 // Start the resetting.
5226 $componentstr = get_string('general');
5228 // Move the course start time.
5229 if (!empty($data->reset_start_date) and $data->timeshift) {
5230 // Change course start data.
5231 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5232 // Update all course and group events - do not move activity events.
5233 $updatesql = "UPDATE {event}
5234 SET timestart = timestart + ?
5235 WHERE courseid=? AND instance=0";
5236 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5238 $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5241 if (!empty($data->reset_logs)) {
5242 $DB->delete_records('log', array('course' => $data->courseid));
5243 $status[] = array('component' => $componentstr, 'item' => get_string('deletelogs'), 'error' => false);
5246 if (!empty($data->reset_events)) {
5247 $DB->delete_records('event', array('courseid' => $data->courseid));
5248 $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5251 if (!empty($data->reset_notes)) {
5252 require_once($CFG->dirroot.'/notes/lib.php');
5253 note_delete_all($data->courseid);
5254 $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5257 if (!empty($data->delete_blog_associations)) {
5258 require_once($CFG->dirroot.'/blog/lib.php');
5259 blog_remove_associations_for_course($data->courseid);
5260 $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5263 if (!empty($data->reset_completion)) {
5264 // Delete course and activity completion information.
5265 $course = $DB->get_record('course', array('id' => $data->courseid));
5266 $cc = new completion_info($course);
5267 $cc->delete_all_completion_data();
5268 $status[] = array('component' => $componentstr,
5269 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5272 $componentstr = get_string('roles');
5274 if (!empty($data->reset_roles_overrides)) {
5275 $children = $context->get_child_contexts();
5276 foreach ($children as $child) {
5277 $DB->delete_records('role_capabilities', array('contextid' => $child->id));
5279 $DB->delete_records('role_capabilities', array('contextid' => $context->id));
5280 // Force refresh for logged in users.
5281 $context->mark_dirty();
5282 $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5285 if (!empty($data->reset_roles_local)) {
5286 $children = $context->get_child_contexts();
5287 foreach ($children as $child) {
5288 role_unassign_all(array('contextid' => $child->id));
5290 // Force refresh for logged in users.
5291 $context->mark_dirty();
5292 $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5295 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5296 $data->unenrolled = array();
5297 if (!empty($data->unenrol_users)) {
5298 $plugins = enrol_get_plugins(true);
5299 $instances = enrol_get_instances($data->courseid, true);
5300 foreach ($instances as $key => $instance) {
5301 if (!isset($plugins[$instance->enrol])) {
5302 unset($instances[$key]);
5303 continue;
5307 foreach ($data->unenrol_users as $withroleid) {
5308 if ($withroleid) {
5309 $sql = "SELECT ue.*
5310 FROM {user_enrolments} ue
5311 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5312 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5313 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5314 $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5316 } else {
5317 // Without any role assigned at course context.
5318 $sql = "SELECT ue.*
5319 FROM {user_enrolments} ue
5320 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5321 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5322 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5323 WHERE ra.id IS null";
5324 $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5327 $rs = $DB->get_recordset_sql($sql, $params);
5328 foreach ($rs as $ue) {
5329 if (!isset($instances[$ue->enrolid])) {
5330 continue;
5332 $instance = $instances[$ue->enrolid];
5333 $plugin = $plugins[$instance->enrol];
5334 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5335 continue;
5338 $plugin->unenrol_user($instance, $ue->userid);
5339 $data->unenrolled[$ue->userid] = $ue->userid;
5341 $rs->close();
5344 if (!empty($data->unenrolled)) {
5345 $status[] = array(
5346 'component' => $componentstr,
5347 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5348 'error' => false
5352 $componentstr = get_string('groups');
5354 // Remove all group members.
5355 if (!empty($data->reset_groups_members)) {
5356 groups_delete_group_members($data->courseid);
5357 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5360 // Remove all groups.
5361 if (!empty($data->reset_groups_remove)) {
5362 groups_delete_groups($data->courseid, false);
5363 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5366 // Remove all grouping members.
5367 if (!empty($data->reset_groupings_members)) {
5368 groups_delete_groupings_groups($data->courseid, false);
5369 $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5372 // Remove all groupings.
5373 if (!empty($data->reset_groupings_remove)) {
5374 groups_delete_groupings($data->courseid, false);
5375 $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5378 // Look in every instance of every module for data to delete.
5379 $unsupportedmods = array();
5380 if ($allmods = $DB->get_records('modules') ) {
5381 foreach ($allmods as $mod) {
5382 $modname = $mod->name;
5383 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5384 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
5385 if (file_exists($modfile)) {
5386 if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5387 continue; // Skip mods with no instances.
5389 include_once($modfile);
5390 if (function_exists($moddeleteuserdata)) {
5391 $modstatus = $moddeleteuserdata($data);
5392 if (is_array($modstatus)) {
5393 $status = array_merge($status, $modstatus);
5394 } else {
5395 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5397 } else {
5398 $unsupportedmods[] = $mod;
5400 } else {
5401 debugging('Missing lib.php in '.$modname.' module!');
5406 // Mention unsupported mods.
5407 if (!empty($unsupportedmods)) {
5408 foreach ($unsupportedmods as $mod) {
5409 $status[] = array(
5410 'component' => get_string('modulenameplural', $mod->name),
5411 'item' => '',
5412 'error' => get_string('resetnotimplemented')
5417 $componentstr = get_string('gradebook', 'grades');
5418 // Reset gradebook,.
5419 if (!empty($data->reset_gradebook_items)) {
5420 remove_course_grades($data->courseid, false);
5421 grade_grab_course_grades($data->courseid);
5422 grade_regrade_final_grades($data->courseid);
5423 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5425 } else if (!empty($data->reset_gradebook_grades)) {
5426 grade_course_reset($data->courseid);
5427 $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5429 // Reset comments.
5430 if (!empty($data->reset_comments)) {
5431 require_once($CFG->dirroot.'/comment/lib.php');
5432 comment::reset_course_page_comments($context);
5435 $event = \core\event\course_reset_ended::create($eventparams);
5436 $event->trigger();
5438 return $status;
5442 * Generate an email processing address.
5444 * @param int $modid
5445 * @param string $modargs
5446 * @return string Returns email processing address
5448 function generate_email_processing_address($modid, $modargs) {
5449 global $CFG;
5451 $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5452 return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5458 * @todo Finish documenting this function
5460 * @param string $modargs
5461 * @param string $body Currently unused
5463 function moodle_process_email($modargs, $body) {
5464 global $DB;
5466 // The first char should be an unencoded letter. We'll take this as an action.
5467 switch ($modargs{0}) {
5468 case 'B': { // Bounce.
5469 list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5470 if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5471 // Check the half md5 of their email.
5472 $md5check = substr(md5($user->email), 0, 16);
5473 if ($md5check == substr($modargs, -16)) {
5474 set_bounce_count($user);
5476 // Else maybe they've already changed it?
5479 break;
5480 // Maybe more later?
5484 // CORRESPONDENCE.
5487 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5489 * @param string $action 'get', 'buffer', 'close' or 'flush'
5490 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5492 function get_mailer($action='get') {
5493 global $CFG;
5495 /** @var moodle_phpmailer $mailer */
5496 static $mailer = null;
5497 static $counter = 0;
5499 if (!isset($CFG->smtpmaxbulk)) {
5500 $CFG->smtpmaxbulk = 1;
5503 if ($action == 'get') {
5504 $prevkeepalive = false;
5506 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5507 if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5508 $counter++;
5509 // Reset the mailer.
5510 $mailer->Priority = 3;
5511 $mailer->CharSet = 'UTF-8'; // Our default.
5512 $mailer->ContentType = "text/plain";
5513 $mailer->Encoding = "8bit";
5514 $mailer->From = "root@localhost";
5515 $mailer->FromName = "Root User";
5516 $mailer->Sender = "";
5517 $mailer->Subject = "";
5518 $mailer->Body = "";
5519 $mailer->AltBody = "";
5520 $mailer->ConfirmReadingTo = "";
5522 $mailer->clearAllRecipients();
5523 $mailer->clearReplyTos();
5524 $mailer->clearAttachments();
5525 $mailer->clearCustomHeaders();
5526 return $mailer;
5529 $prevkeepalive = $mailer->SMTPKeepAlive;
5530 get_mailer('flush');
5533 require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5534 $mailer = new moodle_phpmailer();
5536 $counter = 1;
5538 if ($CFG->smtphosts == 'qmail') {
5539 // Use Qmail system.
5540 $mailer->isQmail();
5542 } else if (empty($CFG->smtphosts)) {
5543 // Use PHP mail() = sendmail.
5544 $mailer->isMail();
5546 } else {
5547 // Use SMTP directly.
5548 $mailer->isSMTP();
5549 if (!empty($CFG->debugsmtp)) {
5550 $mailer->SMTPDebug = true;
5552 // Specify main and backup servers.
5553 $mailer->Host = $CFG->smtphosts;
5554 // Specify secure connection protocol.
5555 $mailer->SMTPSecure = $CFG->smtpsecure;
5556 // Use previous keepalive.
5557 $mailer->SMTPKeepAlive = $prevkeepalive;
5559 if ($CFG->smtpuser) {
5560 // Use SMTP authentication.
5561 $mailer->SMTPAuth = true;
5562 $mailer->Username = $CFG->smtpuser;
5563 $mailer->Password = $CFG->smtppass;
5567 return $mailer;
5570 $nothing = null;
5572 // Keep smtp session open after sending.
5573 if ($action == 'buffer') {
5574 if (!empty($CFG->smtpmaxbulk)) {
5575 get_mailer('flush');
5576 $m = get_mailer();
5577 if ($m->Mailer == 'smtp') {
5578 $m->SMTPKeepAlive = true;
5581 return $nothing;
5584 // Close smtp session, but continue buffering.
5585 if ($action == 'flush') {
5586 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5587 if (!empty($mailer->SMTPDebug)) {
5588 echo '<pre>'."\n";
5590 $mailer->SmtpClose();
5591 if (!empty($mailer->SMTPDebug)) {
5592 echo '</pre>';
5595 return $nothing;
5598 // Close smtp session, do not buffer anymore.
5599 if ($action == 'close') {
5600 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5601 get_mailer('flush');
5602 $mailer->SMTPKeepAlive = false;
5604 $mailer = null; // Better force new instance.
5605 return $nothing;
5610 * Send an email to a specified user
5612 * @param stdClass $user A {@link $USER} object
5613 * @param stdClass $from A {@link $USER} object
5614 * @param string $subject plain text subject line of the email
5615 * @param string $messagetext plain text version of the message
5616 * @param string $messagehtml complete html version of the message (optional)
5617 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
5618 * @param string $attachname the name of the file (extension indicates MIME)
5619 * @param bool $usetrueaddress determines whether $from email address should
5620 * be sent out. Will be overruled by user profile setting for maildisplay
5621 * @param string $replyto Email address to reply to
5622 * @param string $replytoname Name of reply to recipient
5623 * @param int $wordwrapwidth custom word wrap width, default 79
5624 * @return bool Returns true if mail was sent OK and false if there was an error.
5626 function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5627 $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5629 global $CFG;
5631 if (empty($user) or empty($user->id)) {
5632 debugging('Can not send email to null user', DEBUG_DEVELOPER);
5633 return false;
5636 if (empty($user->email)) {
5637 debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5638 return false;
5641 if (!empty($user->deleted)) {
5642 debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5643 return false;
5646 if (!empty($CFG->noemailever)) {
5647 // Hidden setting for development sites, set in config.php if needed.
5648 debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5649 return true;
5652 if (!empty($CFG->divertallemailsto)) {
5653 $subject = "[DIVERTED {$user->email}] $subject";
5654 $user = clone($user);
5655 $user->email = $CFG->divertallemailsto;
5658 // Skip mail to suspended users.
5659 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5660 return true;
5663 if (!validate_email($user->email)) {
5664 // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5665 $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
5666 error_log($invalidemail);
5667 if (CLI_SCRIPT) {
5668 mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
5670 return false;
5673 if (over_bounce_threshold($user)) {
5674 $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
5675 error_log($bouncemsg);
5676 if (CLI_SCRIPT) {
5677 mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
5679 return false;
5682 // If the user is a remote mnet user, parse the email text for URL to the
5683 // wwwroot and modify the url to direct the user's browser to login at their
5684 // home site (identity provider - idp) before hitting the link itself.
5685 if (is_mnet_remote_user($user)) {
5686 require_once($CFG->dirroot.'/mnet/lib.php');
5688 $jumpurl = mnet_get_idp_jump_url($user);
5689 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5691 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5692 $callback,
5693 $messagetext);
5694 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5695 $callback,
5696 $messagehtml);
5698 $mail = get_mailer();
5700 if (!empty($mail->SMTPDebug)) {
5701 echo '<pre>' . "\n";
5704 $temprecipients = array();
5705 $tempreplyto = array();
5707 $supportuser = core_user::get_support_user();
5709 // Make up an email address for handling bounces.
5710 if (!empty($CFG->handlebounces)) {
5711 $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5712 $mail->Sender = generate_email_processing_address(0, $modargs);
5713 } else {
5714 $mail->Sender = $supportuser->email;
5717 if (is_string($from)) { // So we can pass whatever we want if there is need.
5718 $mail->From = $CFG->noreplyaddress;
5719 $mail->FromName = $from;
5720 } else if ($usetrueaddress and $from->maildisplay) {
5721 $mail->From = $from->email;
5722 $mail->FromName = fullname($from);
5723 } else {
5724 $mail->From = $CFG->noreplyaddress;
5725 $mail->FromName = fullname($from);
5726 if (empty($replyto)) {
5727 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5731 if (!empty($replyto)) {
5732 $tempreplyto[] = array($replyto, $replytoname);
5735 $mail->Subject = substr($subject, 0, 900);
5737 $temprecipients[] = array($user->email, fullname($user));
5739 // Set word wrap.
5740 $mail->WordWrap = $wordwrapwidth;
5742 if (!empty($from->customheaders)) {
5743 // Add custom headers.
5744 if (is_array($from->customheaders)) {
5745 foreach ($from->customheaders as $customheader) {
5746 $mail->addCustomHeader($customheader);
5748 } else {
5749 $mail->addCustomHeader($from->customheaders);
5753 if (!empty($from->priority)) {
5754 $mail->Priority = $from->priority;
5757 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5758 // Don't ever send HTML to users who don't want it.
5759 $mail->isHTML(true);
5760 $mail->Encoding = 'quoted-printable';
5761 $mail->Body = $messagehtml;
5762 $mail->AltBody = "\n$messagetext\n";
5763 } else {
5764 $mail->IsHTML(false);
5765 $mail->Body = "\n$messagetext\n";
5768 if ($attachment && $attachname) {
5769 if (preg_match( "~\\.\\.~" , $attachment )) {
5770 // Security check for ".." in dir path.
5771 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5772 $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5773 } else {
5774 require_once($CFG->libdir.'/filelib.php');
5775 $mimetype = mimeinfo('type', $attachname);
5776 $mail->addAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
5780 // Check if the email should be sent in an other charset then the default UTF-8.
5781 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5783 // Use the defined site mail charset or eventually the one preferred by the recipient.
5784 $charset = $CFG->sitemailcharset;
5785 if (!empty($CFG->allowusermailcharset)) {
5786 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5787 $charset = $useremailcharset;
5791 // Convert all the necessary strings if the charset is supported.
5792 $charsets = get_list_of_charsets();
5793 unset($charsets['UTF-8']);
5794 if (in_array($charset, $charsets)) {
5795 $mail->CharSet = $charset;
5796 $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5797 $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5798 $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5799 $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5801 foreach ($temprecipients as $key => $values) {
5802 $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5804 foreach ($tempreplyto as $key => $values) {
5805 $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5810 foreach ($temprecipients as $values) {
5811 $mail->addAddress($values[0], $values[1]);
5813 foreach ($tempreplyto as $values) {
5814 $mail->addReplyTo($values[0], $values[1]);
5817 if ($mail->send()) {
5818 set_send_count($user);
5819 if (!empty($mail->SMTPDebug)) {
5820 echo '</pre>';
5822 return true;
5823 } else {
5824 add_to_log(SITEID, 'library', 'mailer', qualified_me(), 'ERROR: '. $mail->ErrorInfo);
5825 if (CLI_SCRIPT) {
5826 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5828 if (!empty($mail->SMTPDebug)) {
5829 echo '</pre>';
5831 return false;
5836 * Generate a signoff for emails based on support settings
5838 * @return string
5840 function generate_email_signoff() {
5841 global $CFG;
5843 $signoff = "\n";
5844 if (!empty($CFG->supportname)) {
5845 $signoff .= $CFG->supportname."\n";
5847 if (!empty($CFG->supportemail)) {
5848 $signoff .= $CFG->supportemail."\n";
5850 if (!empty($CFG->supportpage)) {
5851 $signoff .= $CFG->supportpage."\n";
5853 return $signoff;
5857 * Sets specified user's password and send the new password to the user via email.
5859 * @param stdClass $user A {@link $USER} object
5860 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
5861 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
5863 function setnew_password_and_mail($user, $fasthash = false) {
5864 global $CFG, $DB;
5866 // We try to send the mail in language the user understands,
5867 // unfortunately the filter_string() does not support alternative langs yet
5868 // so multilang will not work properly for site->fullname.
5869 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
5871 $site = get_site();
5873 $supportuser = core_user::get_support_user();
5875 $newpassword = generate_password();
5877 $hashedpassword = hash_internal_user_password($newpassword, $fasthash);
5878 $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
5879 $user->password = $hashedpassword;
5881 // Trigger event.
5882 $event = \core\event\user_updated::create(array(
5883 'objectid' => $user->id,
5884 'context' => context_user::instance($user->id)
5886 $event->add_record_snapshot('user', $user);
5887 $event->trigger();
5889 $a = new stdClass();
5890 $a->firstname = fullname($user, true);
5891 $a->sitename = format_string($site->fullname);
5892 $a->username = $user->username;
5893 $a->newpassword = $newpassword;
5894 $a->link = $CFG->wwwroot .'/login/';
5895 $a->signoff = generate_email_signoff();
5897 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
5899 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
5901 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5902 return email_to_user($user, $supportuser, $subject, $message);
5907 * Resets specified user's password and send the new password to the user via email.
5909 * @param stdClass $user A {@link $USER} object
5910 * @return bool Returns true if mail was sent OK and false if there was an error.
5912 function reset_password_and_mail($user) {
5913 global $CFG;
5915 $site = get_site();
5916 $supportuser = core_user::get_support_user();
5918 $userauth = get_auth_plugin($user->auth);
5919 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
5920 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
5921 return false;
5924 $newpassword = generate_password();
5926 if (!$userauth->user_update_password($user, $newpassword)) {
5927 print_error("cannotsetpassword");
5930 $a = new stdClass();
5931 $a->firstname = $user->firstname;
5932 $a->lastname = $user->lastname;
5933 $a->sitename = format_string($site->fullname);
5934 $a->username = $user->username;
5935 $a->newpassword = $newpassword;
5936 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
5937 $a->signoff = generate_email_signoff();
5939 $message = get_string('newpasswordtext', '', $a);
5941 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
5943 unset_user_preference('create_password', $user); // Prevent cron from generating the password.
5945 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5946 return email_to_user($user, $supportuser, $subject, $message);
5950 * Send email to specified user with confirmation text and activation link.
5952 * @param stdClass $user A {@link $USER} object
5953 * @return bool Returns true if mail was sent OK and false if there was an error.
5955 function send_confirmation_email($user) {
5956 global $CFG;
5958 $site = get_site();
5959 $supportuser = core_user::get_support_user();
5961 $data = new stdClass();
5962 $data->firstname = fullname($user);
5963 $data->sitename = format_string($site->fullname);
5964 $data->admin = generate_email_signoff();
5966 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
5968 $username = urlencode($user->username);
5969 $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
5970 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
5971 $message = get_string('emailconfirmation', '', $data);
5972 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
5974 $user->mailformat = 1; // Always send HTML version as well.
5976 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
5977 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
5981 * Sends a password change confirmation email.
5983 * @param stdClass $user A {@link $USER} object
5984 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
5985 * @return bool Returns true if mail was sent OK and false if there was an error.
5987 function send_password_change_confirmation_email($user, $resetrecord) {
5988 global $CFG;
5990 $site = get_site();
5991 $supportuser = core_user::get_support_user();
5992 $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
5994 $data = new stdClass();
5995 $data->firstname = $user->firstname;
5996 $data->lastname = $user->lastname;
5997 $data->username = $user->username;
5998 $data->sitename = format_string($site->fullname);
5999 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6000 $data->admin = generate_email_signoff();
6001 $data->resetminutes = $pwresetmins;
6003 $message = get_string('emailresetconfirmation', '', $data);
6004 $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6006 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6007 return email_to_user($user, $supportuser, $subject, $message);
6012 * Sends an email containinginformation on how to change your password.
6014 * @param stdClass $user A {@link $USER} object
6015 * @return bool Returns true if mail was sent OK and false if there was an error.
6017 function send_password_change_info($user) {
6018 global $CFG;
6020 $site = get_site();
6021 $supportuser = core_user::get_support_user();
6022 $systemcontext = context_system::instance();
6024 $data = new stdClass();
6025 $data->firstname = $user->firstname;
6026 $data->lastname = $user->lastname;
6027 $data->sitename = format_string($site->fullname);
6028 $data->admin = generate_email_signoff();
6030 $userauth = get_auth_plugin($user->auth);
6032 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
6033 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6034 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6035 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6036 return email_to_user($user, $supportuser, $subject, $message);
6039 if ($userauth->can_change_password() and $userauth->change_password_url()) {
6040 // We have some external url for password changing.
6041 $data->link .= $userauth->change_password_url();
6043 } else {
6044 // No way to change password, sorry.
6045 $data->link = '';
6048 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
6049 $message = get_string('emailpasswordchangeinfo', '', $data);
6050 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6051 } else {
6052 $message = get_string('emailpasswordchangeinfofail', '', $data);
6053 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6056 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6057 return email_to_user($user, $supportuser, $subject, $message);
6062 * Check that an email is allowed. It returns an error message if there was a problem.
6064 * @param string $email Content of email
6065 * @return string|false
6067 function email_is_not_allowed($email) {
6068 global $CFG;
6070 if (!empty($CFG->allowemailaddresses)) {
6071 $allowed = explode(' ', $CFG->allowemailaddresses);
6072 foreach ($allowed as $allowedpattern) {
6073 $allowedpattern = trim($allowedpattern);
6074 if (!$allowedpattern) {
6075 continue;
6077 if (strpos($allowedpattern, '.') === 0) {
6078 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6079 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6080 return false;
6083 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6084 return false;
6087 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6089 } else if (!empty($CFG->denyemailaddresses)) {
6090 $denied = explode(' ', $CFG->denyemailaddresses);
6091 foreach ($denied as $deniedpattern) {
6092 $deniedpattern = trim($deniedpattern);
6093 if (!$deniedpattern) {
6094 continue;
6096 if (strpos($deniedpattern, '.') === 0) {
6097 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6098 // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6099 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6102 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6103 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6108 return false;
6111 // FILE HANDLING.
6114 * Returns local file storage instance
6116 * @return file_storage
6118 function get_file_storage() {
6119 global $CFG;
6121 static $fs = null;
6123 if ($fs) {
6124 return $fs;
6127 require_once("$CFG->libdir/filelib.php");
6129 if (isset($CFG->filedir)) {
6130 $filedir = $CFG->filedir;
6131 } else {
6132 $filedir = $CFG->dataroot.'/filedir';
6135 if (isset($CFG->trashdir)) {
6136 $trashdirdir = $CFG->trashdir;
6137 } else {
6138 $trashdirdir = $CFG->dataroot.'/trashdir';
6141 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6143 return $fs;
6147 * Returns local file storage instance
6149 * @return file_browser
6151 function get_file_browser() {
6152 global $CFG;
6154 static $fb = null;
6156 if ($fb) {
6157 return $fb;
6160 require_once("$CFG->libdir/filelib.php");
6162 $fb = new file_browser();
6164 return $fb;
6168 * Returns file packer
6170 * @param string $mimetype default application/zip
6171 * @return file_packer
6173 function get_file_packer($mimetype='application/zip') {
6174 global $CFG;
6176 static $fp = array();
6178 if (isset($fp[$mimetype])) {
6179 return $fp[$mimetype];
6182 switch ($mimetype) {
6183 case 'application/zip':
6184 case 'application/vnd.moodle.profiling':
6185 $classname = 'zip_packer';
6186 break;
6188 case 'application/x-gzip' :
6189 $classname = 'tgz_packer';
6190 break;
6192 case 'application/vnd.moodle.backup':
6193 $classname = 'mbz_packer';
6194 break;
6196 default:
6197 return false;
6200 require_once("$CFG->libdir/filestorage/$classname.php");
6201 $fp[$mimetype] = new $classname();
6203 return $fp[$mimetype];
6207 * Returns current name of file on disk if it exists.
6209 * @param string $newfile File to be verified
6210 * @return string Current name of file on disk if true
6212 function valid_uploaded_file($newfile) {
6213 if (empty($newfile)) {
6214 return '';
6216 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6217 return $newfile['tmp_name'];
6218 } else {
6219 return '';
6224 * Returns the maximum size for uploading files.
6226 * There are seven possible upload limits:
6227 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6228 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6229 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6230 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6231 * 5. by the Moodle admin in $CFG->maxbytes
6232 * 6. by the teacher in the current course $course->maxbytes
6233 * 7. by the teacher for the current module, eg $assignment->maxbytes
6235 * These last two are passed to this function as arguments (in bytes).
6236 * Anything defined as 0 is ignored.
6237 * The smallest of all the non-zero numbers is returned.
6239 * @todo Finish documenting this function
6241 * @param int $sitebytes Set maximum size
6242 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6243 * @param int $modulebytes Current module ->maxbytes (in bytes)
6244 * @return int The maximum size for uploading files.
6246 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6248 if (! $filesize = ini_get('upload_max_filesize')) {
6249 $filesize = '5M';
6251 $minimumsize = get_real_size($filesize);
6253 if ($postsize = ini_get('post_max_size')) {
6254 $postsize = get_real_size($postsize);
6255 if ($postsize < $minimumsize) {
6256 $minimumsize = $postsize;
6260 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6261 $minimumsize = $sitebytes;
6264 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6265 $minimumsize = $coursebytes;
6268 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6269 $minimumsize = $modulebytes;
6272 return $minimumsize;
6276 * Returns the maximum size for uploading files for the current user
6278 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6280 * @param context $context The context in which to check user capabilities
6281 * @param int $sitebytes Set maximum size
6282 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6283 * @param int $modulebytes Current module ->maxbytes (in bytes)
6284 * @param stdClass $user The user
6285 * @return int The maximum size for uploading files.
6287 function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
6288 global $USER;
6290 if (empty($user)) {
6291 $user = $USER;
6294 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6295 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6298 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6302 * Returns an array of possible sizes in local language
6304 * Related to {@link get_max_upload_file_size()} - this function returns an
6305 * array of possible sizes in an array, translated to the
6306 * local language.
6308 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6310 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6311 * with the value set to 0. This option will be the first in the list.
6313 * @uses SORT_NUMERIC
6314 * @param int $sitebytes Set maximum size
6315 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6316 * @param int $modulebytes Current module ->maxbytes (in bytes)
6317 * @param int|array $custombytes custom upload size/s which will be added to list,
6318 * Only value/s smaller then maxsize will be added to list.
6319 * @return array
6321 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6322 global $CFG;
6324 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6325 return array();
6328 if ($sitebytes == 0) {
6329 // Will get the minimum of upload_max_filesize or post_max_size.
6330 $sitebytes = get_max_upload_file_size();
6333 $filesize = array();
6334 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6335 5242880, 10485760, 20971520, 52428800, 104857600);
6337 // If custombytes is given and is valid then add it to the list.
6338 if (is_number($custombytes) and $custombytes > 0) {
6339 $custombytes = (int)$custombytes;
6340 if (!in_array($custombytes, $sizelist)) {
6341 $sizelist[] = $custombytes;
6343 } else if (is_array($custombytes)) {
6344 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6347 // Allow maxbytes to be selected if it falls outside the above boundaries.
6348 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6349 // Note: get_real_size() is used in order to prevent problems with invalid values.
6350 $sizelist[] = get_real_size($CFG->maxbytes);
6353 foreach ($sizelist as $sizebytes) {
6354 if ($sizebytes < $maxsize && $sizebytes > 0) {
6355 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6359 $limitlevel = '';
6360 $displaysize = '';
6361 if ($modulebytes &&
6362 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6363 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6364 $limitlevel = get_string('activity', 'core');
6365 $displaysize = display_size($modulebytes);
6366 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6368 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6369 $limitlevel = get_string('course', 'core');
6370 $displaysize = display_size($coursebytes);
6371 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6373 } else if ($sitebytes) {
6374 $limitlevel = get_string('site', 'core');
6375 $displaysize = display_size($sitebytes);
6376 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6379 krsort($filesize, SORT_NUMERIC);
6380 if ($limitlevel) {
6381 $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6382 $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6385 return $filesize;
6389 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6391 * If excludefiles is defined, then that file/directory is ignored
6392 * If getdirs is true, then (sub)directories are included in the output
6393 * If getfiles is true, then files are included in the output
6394 * (at least one of these must be true!)
6396 * @todo Finish documenting this function. Add examples of $excludefile usage.
6398 * @param string $rootdir A given root directory to start from
6399 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6400 * @param bool $descend If true then subdirectories are recursed as well
6401 * @param bool $getdirs If true then (sub)directories are included in the output
6402 * @param bool $getfiles If true then files are included in the output
6403 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6405 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6407 $dirs = array();
6409 if (!$getdirs and !$getfiles) { // Nothing to show.
6410 return $dirs;
6413 if (!is_dir($rootdir)) { // Must be a directory.
6414 return $dirs;
6417 if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
6418 return $dirs;
6421 if (!is_array($excludefiles)) {
6422 $excludefiles = array($excludefiles);
6425 while (false !== ($file = readdir($dir))) {
6426 $firstchar = substr($file, 0, 1);
6427 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6428 continue;
6430 $fullfile = $rootdir .'/'. $file;
6431 if (filetype($fullfile) == 'dir') {
6432 if ($getdirs) {
6433 $dirs[] = $file;
6435 if ($descend) {
6436 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6437 foreach ($subdirs as $subdir) {
6438 $dirs[] = $file .'/'. $subdir;
6441 } else if ($getfiles) {
6442 $dirs[] = $file;
6445 closedir($dir);
6447 asort($dirs);
6449 return $dirs;
6454 * Adds up all the files in a directory and works out the size.
6456 * @param string $rootdir The directory to start from
6457 * @param string $excludefile A file to exclude when summing directory size
6458 * @return int The summed size of all files and subfiles within the root directory
6460 function get_directory_size($rootdir, $excludefile='') {
6461 global $CFG;
6463 // Do it this way if we can, it's much faster.
6464 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6465 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6466 $output = null;
6467 $return = null;
6468 exec($command, $output, $return);
6469 if (is_array($output)) {
6470 // We told it to return k.
6471 return get_real_size(intval($output[0]).'k');
6475 if (!is_dir($rootdir)) {
6476 // Must be a directory.
6477 return 0;
6480 if (!$dir = @opendir($rootdir)) {
6481 // Can't open it for some reason.
6482 return 0;
6485 $size = 0;
6487 while (false !== ($file = readdir($dir))) {
6488 $firstchar = substr($file, 0, 1);
6489 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6490 continue;
6492 $fullfile = $rootdir .'/'. $file;
6493 if (filetype($fullfile) == 'dir') {
6494 $size += get_directory_size($fullfile, $excludefile);
6495 } else {
6496 $size += filesize($fullfile);
6499 closedir($dir);
6501 return $size;
6505 * Converts bytes into display form
6507 * @static string $gb Localized string for size in gigabytes
6508 * @static string $mb Localized string for size in megabytes
6509 * @static string $kb Localized string for size in kilobytes
6510 * @static string $b Localized string for size in bytes
6511 * @param int $size The size to convert to human readable form
6512 * @return string
6514 function display_size($size) {
6516 static $gb, $mb, $kb, $b;
6518 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6519 return get_string('unlimited');
6522 if (empty($gb)) {
6523 $gb = get_string('sizegb');
6524 $mb = get_string('sizemb');
6525 $kb = get_string('sizekb');
6526 $b = get_string('sizeb');
6529 if ($size >= 1073741824) {
6530 $size = round($size / 1073741824 * 10) / 10 . $gb;
6531 } else if ($size >= 1048576) {
6532 $size = round($size / 1048576 * 10) / 10 . $mb;
6533 } else if ($size >= 1024) {
6534 $size = round($size / 1024 * 10) / 10 . $kb;
6535 } else {
6536 $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
6538 return $size;
6542 * Cleans a given filename by removing suspicious or troublesome characters
6544 * @see clean_param()
6545 * @param string $string file name
6546 * @return string cleaned file name
6548 function clean_filename($string) {
6549 return clean_param($string, PARAM_FILE);
6553 // STRING TRANSLATION.
6556 * Returns the code for the current language
6558 * @category string
6559 * @return string
6561 function current_language() {
6562 global $CFG, $USER, $SESSION, $COURSE;
6564 if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
6565 // Course language can override all other settings for this page.
6566 $return = $COURSE->lang;
6568 } else if (!empty($SESSION->lang)) {
6569 // Session language can override other settings.
6570 $return = $SESSION->lang;
6572 } else if (!empty($USER->lang)) {
6573 $return = $USER->lang;
6575 } else if (isset($CFG->lang)) {
6576 $return = $CFG->lang;
6578 } else {
6579 $return = 'en';
6582 // Just in case this slipped in from somewhere by accident.
6583 $return = str_replace('_utf8', '', $return);
6585 return $return;
6589 * Returns parent language of current active language if defined
6591 * @category string
6592 * @param string $lang null means current language
6593 * @return string
6595 function get_parent_language($lang=null) {
6596 global $COURSE, $SESSION;
6598 // Let's hack around the current language.
6599 if (!empty($lang)) {
6600 $oldcourselang = empty($COURSE->lang) ? '' : $COURSE->lang;
6601 $oldsessionlang = empty($SESSION->lang) ? '' : $SESSION->lang;
6602 $COURSE->lang = '';
6603 $SESSION->lang = $lang;
6606 $parentlang = get_string('parentlanguage', 'langconfig');
6607 if ($parentlang === 'en') {
6608 $parentlang = '';
6611 // Let's hack around the current language.
6612 if (!empty($lang)) {
6613 $COURSE->lang = $oldcourselang;
6614 $SESSION->lang = $oldsessionlang;
6617 return $parentlang;
6621 * Returns current string_manager instance.
6623 * The param $forcereload is needed for CLI installer only where the string_manager instance
6624 * must be replaced during the install.php script life time.
6626 * @category string
6627 * @param bool $forcereload shall the singleton be released and new instance created instead?
6628 * @return core_string_manager
6630 function get_string_manager($forcereload=false) {
6631 global $CFG;
6633 static $singleton = null;
6635 if ($forcereload) {
6636 $singleton = null;
6638 if ($singleton === null) {
6639 if (empty($CFG->early_install_lang)) {
6641 if (empty($CFG->langlist)) {
6642 $translist = array();
6643 } else {
6644 $translist = explode(',', $CFG->langlist);
6647 $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
6649 } else {
6650 $singleton = new core_string_manager_install();
6654 return $singleton;
6658 * Returns a localized string.
6660 * Returns the translated string specified by $identifier as
6661 * for $module. Uses the same format files as STphp.
6662 * $a is an object, string or number that can be used
6663 * within translation strings
6665 * eg 'hello {$a->firstname} {$a->lastname}'
6666 * or 'hello {$a}'
6668 * If you would like to directly echo the localized string use
6669 * the function {@link print_string()}
6671 * Example usage of this function involves finding the string you would
6672 * like a local equivalent of and using its identifier and module information
6673 * to retrieve it.<br/>
6674 * If you open moodle/lang/en/moodle.php and look near line 278
6675 * you will find a string to prompt a user for their word for 'course'
6676 * <code>
6677 * $string['course'] = 'Course';
6678 * </code>
6679 * So if you want to display the string 'Course'
6680 * in any language that supports it on your site
6681 * you just need to use the identifier 'course'
6682 * <code>
6683 * $mystring = '<strong>'. get_string('course') .'</strong>';
6684 * or
6685 * </code>
6686 * If the string you want is in another file you'd take a slightly
6687 * different approach. Looking in moodle/lang/en/calendar.php you find
6688 * around line 75:
6689 * <code>
6690 * $string['typecourse'] = 'Course event';
6691 * </code>
6692 * If you want to display the string "Course event" in any language
6693 * supported you would use the identifier 'typecourse' and the module 'calendar'
6694 * (because it is in the file calendar.php):
6695 * <code>
6696 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6697 * </code>
6699 * As a last resort, should the identifier fail to map to a string
6700 * the returned string will be [[ $identifier ]]
6702 * In Moodle 2.3 there is a new argument to this function $lazyload.
6703 * Setting $lazyload to true causes get_string to return a lang_string object
6704 * rather than the string itself. The fetching of the string is then put off until
6705 * the string object is first used. The object can be used by calling it's out
6706 * method or by casting the object to a string, either directly e.g.
6707 * (string)$stringobject
6708 * or indirectly by using the string within another string or echoing it out e.g.
6709 * echo $stringobject
6710 * return "<p>{$stringobject}</p>";
6711 * It is worth noting that using $lazyload and attempting to use the string as an
6712 * array key will cause a fatal error as objects cannot be used as array keys.
6713 * But you should never do that anyway!
6714 * For more information {@link lang_string}
6716 * @category string
6717 * @param string $identifier The key identifier for the localized string
6718 * @param string $component The module where the key identifier is stored,
6719 * usually expressed as the filename in the language pack without the
6720 * .php on the end but can also be written as mod/forum or grade/export/xls.
6721 * If none is specified then moodle.php is used.
6722 * @param string|object|array $a An object, string or number that can be used
6723 * within translation strings
6724 * @param bool $lazyload If set to true a string object is returned instead of
6725 * the string itself. The string then isn't calculated until it is first used.
6726 * @return string The localized string.
6727 * @throws coding_exception
6729 function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6730 global $CFG;
6732 // If the lazy load argument has been supplied return a lang_string object
6733 // instead.
6734 // We need to make sure it is true (and a bool) as you will see below there
6735 // used to be a forth argument at one point.
6736 if ($lazyload === true) {
6737 return new lang_string($identifier, $component, $a);
6740 if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6741 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6744 // There is now a forth argument again, this time it is a boolean however so
6745 // we can still check for the old extralocations parameter.
6746 if (!is_bool($lazyload) && !empty($lazyload)) {
6747 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
6750 if (strpos($component, '/') !== false) {
6751 debugging('The module name you passed to get_string is the deprecated format ' .
6752 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
6753 $componentpath = explode('/', $component);
6755 switch ($componentpath[0]) {
6756 case 'mod':
6757 $component = $componentpath[1];
6758 break;
6759 case 'blocks':
6760 case 'block':
6761 $component = 'block_'.$componentpath[1];
6762 break;
6763 case 'enrol':
6764 $component = 'enrol_'.$componentpath[1];
6765 break;
6766 case 'format':
6767 $component = 'format_'.$componentpath[1];
6768 break;
6769 case 'grade':
6770 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
6771 break;
6775 $result = get_string_manager()->get_string($identifier, $component, $a);
6777 // Debugging feature lets you display string identifier and component.
6778 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
6779 $result .= ' {' . $identifier . '/' . $component . '}';
6781 return $result;
6785 * Converts an array of strings to their localized value.
6787 * @param array $array An array of strings
6788 * @param string $component The language module that these strings can be found in.
6789 * @return stdClass translated strings.
6791 function get_strings($array, $component = '') {
6792 $string = new stdClass;
6793 foreach ($array as $item) {
6794 $string->$item = get_string($item, $component);
6796 return $string;
6800 * Prints out a translated string.
6802 * Prints out a translated string using the return value from the {@link get_string()} function.
6804 * Example usage of this function when the string is in the moodle.php file:<br/>
6805 * <code>
6806 * echo '<strong>';
6807 * print_string('course');
6808 * echo '</strong>';
6809 * </code>
6811 * Example usage of this function when the string is not in the moodle.php file:<br/>
6812 * <code>
6813 * echo '<h1>';
6814 * print_string('typecourse', 'calendar');
6815 * echo '</h1>';
6816 * </code>
6818 * @category string
6819 * @param string $identifier The key identifier for the localized string
6820 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
6821 * @param string|object|array $a An object, string or number that can be used within translation strings
6823 function print_string($identifier, $component = '', $a = null) {
6824 echo get_string($identifier, $component, $a);
6828 * Returns a list of charset codes
6830 * Returns a list of charset codes. It's hardcoded, so they should be added manually
6831 * (checking that such charset is supported by the texlib library!)
6833 * @return array And associative array with contents in the form of charset => charset
6835 function get_list_of_charsets() {
6837 $charsets = array(
6838 'EUC-JP' => 'EUC-JP',
6839 'ISO-2022-JP'=> 'ISO-2022-JP',
6840 'ISO-8859-1' => 'ISO-8859-1',
6841 'SHIFT-JIS' => 'SHIFT-JIS',
6842 'GB2312' => 'GB2312',
6843 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
6844 'UTF-8' => 'UTF-8');
6846 asort($charsets);
6848 return $charsets;
6852 * Returns a list of valid and compatible themes
6854 * @return array
6856 function get_list_of_themes() {
6857 global $CFG;
6859 $themes = array();
6861 if (!empty($CFG->themelist)) { // Use admin's list of themes.
6862 $themelist = explode(',', $CFG->themelist);
6863 } else {
6864 $themelist = array_keys(core_component::get_plugin_list("theme"));
6867 foreach ($themelist as $key => $themename) {
6868 $theme = theme_config::load($themename);
6869 $themes[$themename] = $theme;
6872 core_collator::asort_objects_by_method($themes, 'get_theme_name');
6874 return $themes;
6878 * Returns a list of timezones in the current language
6880 * @return array
6882 function get_list_of_timezones() {
6883 global $DB;
6885 static $timezones;
6887 if (!empty($timezones)) { // This function has been called recently.
6888 return $timezones;
6891 $timezones = array();
6893 if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
6894 foreach ($rawtimezones as $timezone) {
6895 if (!empty($timezone->name)) {
6896 if (get_string_manager()->string_exists(strtolower($timezone->name), 'timezones')) {
6897 $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
6898 } else {
6899 $timezones[$timezone->name] = $timezone->name;
6901 if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found.
6902 $timezones[$timezone->name] = $timezone->name;
6908 asort($timezones);
6910 for ($i = -13; $i <= 13; $i += .5) {
6911 $tzstring = 'UTC';
6912 if ($i < 0) {
6913 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
6914 } else if ($i > 0) {
6915 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
6916 } else {
6917 $timezones[sprintf("%.1f", $i)] = $tzstring;
6921 return $timezones;
6925 * Factory function for emoticon_manager
6927 * @return emoticon_manager singleton
6929 function get_emoticon_manager() {
6930 static $singleton = null;
6932 if (is_null($singleton)) {
6933 $singleton = new emoticon_manager();
6936 return $singleton;
6940 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
6942 * Whenever this manager mentiones 'emoticon object', the following data
6943 * structure is expected: stdClass with properties text, imagename, imagecomponent,
6944 * altidentifier and altcomponent
6946 * @see admin_setting_emoticons
6948 * @copyright 2010 David Mudrak
6949 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6951 class emoticon_manager {
6954 * Returns the currently enabled emoticons
6956 * @return array of emoticon objects
6958 public function get_emoticons() {
6959 global $CFG;
6961 if (empty($CFG->emoticons)) {
6962 return array();
6965 $emoticons = $this->decode_stored_config($CFG->emoticons);
6967 if (!is_array($emoticons)) {
6968 // Something is wrong with the format of stored setting.
6969 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
6970 return array();
6973 return $emoticons;
6977 * Converts emoticon object into renderable pix_emoticon object
6979 * @param stdClass $emoticon emoticon object
6980 * @param array $attributes explicit HTML attributes to set
6981 * @return pix_emoticon
6983 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
6984 $stringmanager = get_string_manager();
6985 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
6986 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
6987 } else {
6988 $alt = s($emoticon->text);
6990 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
6994 * Encodes the array of emoticon objects into a string storable in config table
6996 * @see self::decode_stored_config()
6997 * @param array $emoticons array of emtocion objects
6998 * @return string
7000 public function encode_stored_config(array $emoticons) {
7001 return json_encode($emoticons);
7005 * Decodes the string into an array of emoticon objects
7007 * @see self::encode_stored_config()
7008 * @param string $encoded
7009 * @return string|null
7011 public function decode_stored_config($encoded) {
7012 $decoded = json_decode($encoded);
7013 if (!is_array($decoded)) {
7014 return null;
7016 return $decoded;
7020 * Returns default set of emoticons supported by Moodle
7022 * @return array of sdtClasses
7024 public function default_emoticons() {
7025 return array(
7026 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7027 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7028 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7029 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7030 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7031 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7032 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7033 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7034 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7035 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7036 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7037 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7038 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7039 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7040 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7041 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7042 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7043 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7044 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7045 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7046 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7047 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7048 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7049 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7050 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7051 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7052 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7053 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7054 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7055 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7060 * Helper method preparing the stdClass with the emoticon properties
7062 * @param string|array $text or array of strings
7063 * @param string $imagename to be used by {@link pix_emoticon}
7064 * @param string $altidentifier alternative string identifier, null for no alt
7065 * @param string $altcomponent where the alternative string is defined
7066 * @param string $imagecomponent to be used by {@link pix_emoticon}
7067 * @return stdClass
7069 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7070 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7071 return (object)array(
7072 'text' => $text,
7073 'imagename' => $imagename,
7074 'imagecomponent' => $imagecomponent,
7075 'altidentifier' => $altidentifier,
7076 'altcomponent' => $altcomponent,
7081 // ENCRYPTION.
7084 * rc4encrypt
7086 * @param string $data Data to encrypt.
7087 * @return string The now encrypted data.
7089 function rc4encrypt($data) {
7090 return endecrypt(get_site_identifier(), $data, '');
7094 * rc4decrypt
7096 * @param string $data Data to decrypt.
7097 * @return string The now decrypted data.
7099 function rc4decrypt($data) {
7100 return endecrypt(get_site_identifier(), $data, 'de');
7104 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7106 * @todo Finish documenting this function
7108 * @param string $pwd The password to use when encrypting or decrypting
7109 * @param string $data The data to be decrypted/encrypted
7110 * @param string $case Either 'de' for decrypt or '' for encrypt
7111 * @return string
7113 function endecrypt ($pwd, $data, $case) {
7115 if ($case == 'de') {
7116 $data = urldecode($data);
7119 $key[] = '';
7120 $box[] = '';
7121 $pwdlength = strlen($pwd);
7123 for ($i = 0; $i <= 255; $i++) {
7124 $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7125 $box[$i] = $i;
7128 $x = 0;
7130 for ($i = 0; $i <= 255; $i++) {
7131 $x = ($x + $box[$i] + $key[$i]) % 256;
7132 $tempswap = $box[$i];
7133 $box[$i] = $box[$x];
7134 $box[$x] = $tempswap;
7137 $cipher = '';
7139 $a = 0;
7140 $j = 0;
7142 for ($i = 0; $i < strlen($data); $i++) {
7143 $a = ($a + 1) % 256;
7144 $j = ($j + $box[$a]) % 256;
7145 $temp = $box[$a];
7146 $box[$a] = $box[$j];
7147 $box[$j] = $temp;
7148 $k = $box[(($box[$a] + $box[$j]) % 256)];
7149 $cipherby = ord(substr($data, $i, 1)) ^ $k;
7150 $cipher .= chr($cipherby);
7153 if ($case == 'de') {
7154 $cipher = urldecode(urlencode($cipher));
7155 } else {
7156 $cipher = urlencode($cipher);
7159 return $cipher;
7162 // ENVIRONMENT CHECKING.
7165 * This method validates a plug name. It is much faster than calling clean_param.
7167 * @param string $name a string that might be a plugin name.
7168 * @return bool if this string is a valid plugin name.
7170 function is_valid_plugin_name($name) {
7171 // This does not work for 'mod', bad luck, use any other type.
7172 return core_component::is_valid_plugin_name('tool', $name);
7176 * Get a list of all the plugins of a given type that define a certain API function
7177 * in a certain file. The plugin component names and function names are returned.
7179 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7180 * @param string $function the part of the name of the function after the
7181 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7182 * names like report_courselist_hook.
7183 * @param string $file the name of file within the plugin that defines the
7184 * function. Defaults to lib.php.
7185 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7186 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7188 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7189 $pluginfunctions = array();
7190 $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, $file, true);
7191 foreach ($pluginswithfile as $plugin => $notused) {
7192 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7194 if (function_exists($fullfunction)) {
7195 // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7196 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
7198 } else if ($plugintype === 'mod') {
7199 // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7200 $shortfunction = $plugin . '_' . $function;
7201 if (function_exists($shortfunction)) {
7202 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
7206 return $pluginfunctions;
7210 * Lists plugin-like directories within specified directory
7212 * This function was originally used for standard Moodle plugins, please use
7213 * new core_component::get_plugin_list() now.
7215 * This function is used for general directory listing and backwards compatility.
7217 * @param string $directory relative directory from root
7218 * @param string $exclude dir name to exclude from the list (defaults to none)
7219 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7220 * @return array Sorted array of directory names found under the requested parameters
7222 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7223 global $CFG;
7225 $plugins = array();
7227 if (empty($basedir)) {
7228 $basedir = $CFG->dirroot .'/'. $directory;
7230 } else {
7231 $basedir = $basedir .'/'. $directory;
7234 if ($CFG->debugdeveloper and empty($exclude)) {
7235 // Make sure devs do not use this to list normal plugins,
7236 // this is intended for general directories that are not plugins!
7238 $subtypes = core_component::get_plugin_types();
7239 if (in_array($basedir, $subtypes)) {
7240 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7242 unset($subtypes);
7245 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7246 if (!$dirhandle = opendir($basedir)) {
7247 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7248 return array();
7250 while (false !== ($dir = readdir($dirhandle))) {
7251 // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7252 if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7253 $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7254 continue;
7256 if (filetype($basedir .'/'. $dir) != 'dir') {
7257 continue;
7259 $plugins[] = $dir;
7261 closedir($dirhandle);
7263 if ($plugins) {
7264 asort($plugins);
7266 return $plugins;
7270 * Invoke plugin's callback functions
7272 * @param string $type plugin type e.g. 'mod'
7273 * @param string $name plugin name
7274 * @param string $feature feature name
7275 * @param string $action feature's action
7276 * @param array $params parameters of callback function, should be an array
7277 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7278 * @return mixed
7280 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7282 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7283 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7287 * Invoke component's callback functions
7289 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7290 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7291 * @param array $params parameters of callback function
7292 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7293 * @return mixed
7295 function component_callback($component, $function, array $params = array(), $default = null) {
7297 $functionname = component_callback_exists($component, $function);
7299 if ($functionname) {
7300 // Function exists, so just return function result.
7301 $ret = call_user_func_array($functionname, $params);
7302 if (is_null($ret)) {
7303 return $default;
7304 } else {
7305 return $ret;
7308 return $default;
7312 * Determine if a component callback exists and return the function name to call. Note that this
7313 * function will include the required library files so that the functioname returned can be
7314 * called directly.
7316 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7317 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7318 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7319 * @throws coding_exception if invalid component specfied
7321 function component_callback_exists($component, $function) {
7322 global $CFG; // This is needed for the inclusions.
7324 $cleancomponent = clean_param($component, PARAM_COMPONENT);
7325 if (empty($cleancomponent)) {
7326 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7328 $component = $cleancomponent;
7330 list($type, $name) = core_component::normalize_component($component);
7331 $component = $type . '_' . $name;
7333 $oldfunction = $name.'_'.$function;
7334 $function = $component.'_'.$function;
7336 $dir = core_component::get_component_directory($component);
7337 if (empty($dir)) {
7338 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7341 // Load library and look for function.
7342 if (file_exists($dir.'/lib.php')) {
7343 require_once($dir.'/lib.php');
7346 if (!function_exists($function) and function_exists($oldfunction)) {
7347 if ($type !== 'mod' and $type !== 'core') {
7348 debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7350 $function = $oldfunction;
7353 if (function_exists($function)) {
7354 return $function;
7356 return false;
7360 * Checks whether a plugin supports a specified feature.
7362 * @param string $type Plugin type e.g. 'mod'
7363 * @param string $name Plugin name e.g. 'forum'
7364 * @param string $feature Feature code (FEATURE_xx constant)
7365 * @param mixed $default default value if feature support unknown
7366 * @return mixed Feature result (false if not supported, null if feature is unknown,
7367 * otherwise usually true but may have other feature-specific value such as array)
7368 * @throws coding_exception
7370 function plugin_supports($type, $name, $feature, $default = null) {
7371 global $CFG;
7373 if ($type === 'mod' and $name === 'NEWMODULE') {
7374 // Somebody forgot to rename the module template.
7375 return false;
7378 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7379 if (empty($component)) {
7380 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7383 $function = null;
7385 if ($type === 'mod') {
7386 // We need this special case because we support subplugins in modules,
7387 // otherwise it would end up in infinite loop.
7388 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7389 include_once("$CFG->dirroot/mod/$name/lib.php");
7390 $function = $component.'_supports';
7391 if (!function_exists($function)) {
7392 // Legacy non-frankenstyle function name.
7393 $function = $name.'_supports';
7397 } else {
7398 if (!$path = core_component::get_plugin_directory($type, $name)) {
7399 // Non existent plugin type.
7400 return false;
7402 if (file_exists("$path/lib.php")) {
7403 include_once("$path/lib.php");
7404 $function = $component.'_supports';
7408 if ($function and function_exists($function)) {
7409 $supports = $function($feature);
7410 if (is_null($supports)) {
7411 // Plugin does not know - use default.
7412 return $default;
7413 } else {
7414 return $supports;
7418 // Plugin does not care, so use default.
7419 return $default;
7423 * Returns true if the current version of PHP is greater that the specified one.
7425 * @todo Check PHP version being required here is it too low?
7427 * @param string $version The version of php being tested.
7428 * @return bool
7430 function check_php_version($version='5.2.4') {
7431 return (version_compare(phpversion(), $version) >= 0);
7435 * Determine if moodle installation requires update.
7437 * Checks version numbers of main code and all plugins to see
7438 * if there are any mismatches.
7440 * @return bool
7442 function moodle_needs_upgrading() {
7443 global $CFG;
7445 if (empty($CFG->version)) {
7446 return true;
7449 // There is no need to purge plugininfo caches here because
7450 // these caches are not used during upgrade and they are purged after
7451 // every upgrade.
7453 if (empty($CFG->allversionshash)) {
7454 return true;
7457 $hash = core_component::get_all_versions_hash();
7459 return ($hash !== $CFG->allversionshash);
7463 * Returns the major version of this site
7465 * Moodle version numbers consist of three numbers separated by a dot, for
7466 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7467 * called major version. This function extracts the major version from either
7468 * $CFG->release (default) or eventually from the $release variable defined in
7469 * the main version.php.
7471 * @param bool $fromdisk should the version if source code files be used
7472 * @return string|false the major version like '2.3', false if could not be determined
7474 function moodle_major_version($fromdisk = false) {
7475 global $CFG;
7477 if ($fromdisk) {
7478 $release = null;
7479 require($CFG->dirroot.'/version.php');
7480 if (empty($release)) {
7481 return false;
7484 } else {
7485 if (empty($CFG->release)) {
7486 return false;
7488 $release = $CFG->release;
7491 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7492 return $matches[0];
7493 } else {
7494 return false;
7498 // MISCELLANEOUS.
7501 * Sets the system locale
7503 * @category string
7504 * @param string $locale Can be used to force a locale
7506 function moodle_setlocale($locale='') {
7507 global $CFG;
7509 static $currentlocale = ''; // Last locale caching.
7511 $oldlocale = $currentlocale;
7513 // Fetch the correct locale based on ostype.
7514 if ($CFG->ostype == 'WINDOWS') {
7515 $stringtofetch = 'localewin';
7516 } else {
7517 $stringtofetch = 'locale';
7520 // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
7521 if (!empty($locale)) {
7522 $currentlocale = $locale;
7523 } else if (!empty($CFG->locale)) { // Override locale for all language packs.
7524 $currentlocale = $CFG->locale;
7525 } else {
7526 $currentlocale = get_string($stringtofetch, 'langconfig');
7529 // Do nothing if locale already set up.
7530 if ($oldlocale == $currentlocale) {
7531 return;
7534 // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
7535 // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
7536 // Some day, numeric, monetary and other categories should be set too, I think. :-/.
7538 // Get current values.
7539 $monetary= setlocale (LC_MONETARY, 0);
7540 $numeric = setlocale (LC_NUMERIC, 0);
7541 $ctype = setlocale (LC_CTYPE, 0);
7542 if ($CFG->ostype != 'WINDOWS') {
7543 $messages= setlocale (LC_MESSAGES, 0);
7545 // Set locale to all.
7546 setlocale (LC_ALL, $currentlocale);
7547 // Set old values.
7548 setlocale (LC_MONETARY, $monetary);
7549 setlocale (LC_NUMERIC, $numeric);
7550 if ($CFG->ostype != 'WINDOWS') {
7551 setlocale (LC_MESSAGES, $messages);
7553 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
7554 // To workaround a well-known PHP problem with Turkish letter Ii.
7555 setlocale (LC_CTYPE, $ctype);
7560 * Count words in a string.
7562 * Words are defined as things between whitespace.
7564 * @category string
7565 * @param string $string The text to be searched for words.
7566 * @return int The count of words in the specified string
7568 function count_words($string) {
7569 $string = strip_tags($string);
7570 return count(preg_split("/\w\b/", $string)) - 1;
7574 * Count letters in a string.
7576 * Letters are defined as chars not in tags and different from whitespace.
7578 * @category string
7579 * @param string $string The text to be searched for letters.
7580 * @return int The count of letters in the specified text.
7582 function count_letters($string) {
7583 $string = strip_tags($string); // Tags are out now.
7584 $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
7586 return core_text::strlen($string);
7590 * Generate and return a random string of the specified length.
7592 * @param int $length The length of the string to be created.
7593 * @return string
7595 function random_string ($length=15) {
7596 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
7597 $pool .= 'abcdefghijklmnopqrstuvwxyz';
7598 $pool .= '0123456789';
7599 $poollen = strlen($pool);
7600 mt_srand ((double) microtime() * 1000000);
7601 $string = '';
7602 for ($i = 0; $i < $length; $i++) {
7603 $string .= substr($pool, (mt_rand()%($poollen)), 1);
7605 return $string;
7609 * Generate a complex random string (useful for md5 salts)
7611 * This function is based on the above {@link random_string()} however it uses a
7612 * larger pool of characters and generates a string between 24 and 32 characters
7614 * @param int $length Optional if set generates a string to exactly this length
7615 * @return string
7617 function complex_random_string($length=null) {
7618 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7619 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
7620 $poollen = strlen($pool);
7621 mt_srand ((double) microtime() * 1000000);
7622 if ($length===null) {
7623 $length = floor(rand(24, 32));
7625 $string = '';
7626 for ($i = 0; $i < $length; $i++) {
7627 $string .= $pool[(mt_rand()%$poollen)];
7629 return $string;
7633 * Given some text (which may contain HTML) and an ideal length,
7634 * this function truncates the text neatly on a word boundary if possible
7636 * @category string
7637 * @param string $text text to be shortened
7638 * @param int $ideal ideal string length
7639 * @param boolean $exact if false, $text will not be cut mid-word
7640 * @param string $ending The string to append if the passed string is truncated
7641 * @return string $truncate shortened string
7643 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
7644 // If the plain text is shorter than the maximum length, return the whole text.
7645 if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
7646 return $text;
7649 // Splits on HTML tags. Each open/close/empty tag will be the first thing
7650 // and only tag in its 'line'.
7651 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
7653 $totallength = core_text::strlen($ending);
7654 $truncate = '';
7656 // This array stores information about open and close tags and their position
7657 // in the truncated string. Each item in the array is an object with fields
7658 // ->open (true if open), ->tag (tag name in lower case), and ->pos
7659 // (byte position in truncated text).
7660 $tagdetails = array();
7662 foreach ($lines as $linematchings) {
7663 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
7664 if (!empty($linematchings[1])) {
7665 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
7666 if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
7667 if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
7668 // Record closing tag.
7669 $tagdetails[] = (object) array(
7670 'open' => false,
7671 'tag' => core_text::strtolower($tagmatchings[1]),
7672 'pos' => core_text::strlen($truncate),
7675 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
7676 // Record opening tag.
7677 $tagdetails[] = (object) array(
7678 'open' => true,
7679 'tag' => core_text::strtolower($tagmatchings[1]),
7680 'pos' => core_text::strlen($truncate),
7684 // Add html-tag to $truncate'd text.
7685 $truncate .= $linematchings[1];
7688 // Calculate the length of the plain text part of the line; handle entities as one character.
7689 $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
7690 if ($totallength + $contentlength > $ideal) {
7691 // The number of characters which are left.
7692 $left = $ideal - $totallength;
7693 $entitieslength = 0;
7694 // Search for html entities.
7695 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)) {
7696 // Calculate the real length of all entities in the legal range.
7697 foreach ($entities[0] as $entity) {
7698 if ($entity[1]+1-$entitieslength <= $left) {
7699 $left--;
7700 $entitieslength += core_text::strlen($entity[0]);
7701 } else {
7702 // No more characters left.
7703 break;
7707 $breakpos = $left + $entitieslength;
7709 // If the words shouldn't be cut in the middle...
7710 if (!$exact) {
7711 // Search the last occurence of a space.
7712 for (; $breakpos > 0; $breakpos--) {
7713 if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
7714 if ($char === '.' or $char === ' ') {
7715 $breakpos += 1;
7716 break;
7717 } else if (strlen($char) > 2) {
7718 // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
7719 $breakpos += 1;
7720 break;
7725 if ($breakpos == 0) {
7726 // This deals with the test_shorten_text_no_spaces case.
7727 $breakpos = $left + $entitieslength;
7728 } else if ($breakpos > $left + $entitieslength) {
7729 // This deals with the previous for loop breaking on the first char.
7730 $breakpos = $left + $entitieslength;
7733 $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
7734 // Maximum length is reached, so get off the loop.
7735 break;
7736 } else {
7737 $truncate .= $linematchings[2];
7738 $totallength += $contentlength;
7741 // If the maximum length is reached, get off the loop.
7742 if ($totallength >= $ideal) {
7743 break;
7747 // Add the defined ending to the text.
7748 $truncate .= $ending;
7750 // Now calculate the list of open html tags based on the truncate position.
7751 $opentags = array();
7752 foreach ($tagdetails as $taginfo) {
7753 if ($taginfo->open) {
7754 // Add tag to the beginning of $opentags list.
7755 array_unshift($opentags, $taginfo->tag);
7756 } else {
7757 // Can have multiple exact same open tags, close the last one.
7758 $pos = array_search($taginfo->tag, array_reverse($opentags, true));
7759 if ($pos !== false) {
7760 unset($opentags[$pos]);
7765 // Close all unclosed html-tags.
7766 foreach ($opentags as $tag) {
7767 $truncate .= '</' . $tag . '>';
7770 return $truncate;
7775 * Given dates in seconds, how many weeks is the date from startdate
7776 * The first week is 1, the second 2 etc ...
7778 * @param int $startdate Timestamp for the start date
7779 * @param int $thedate Timestamp for the end date
7780 * @return string
7782 function getweek ($startdate, $thedate) {
7783 if ($thedate < $startdate) {
7784 return 0;
7787 return floor(($thedate - $startdate) / WEEKSECS) + 1;
7791 * Returns a randomly generated password of length $maxlen. inspired by
7793 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
7794 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
7796 * @param int $maxlen The maximum size of the password being generated.
7797 * @return string
7799 function generate_password($maxlen=10) {
7800 global $CFG;
7802 if (empty($CFG->passwordpolicy)) {
7803 $fillers = PASSWORD_DIGITS;
7804 $wordlist = file($CFG->wordlist);
7805 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7806 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
7807 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
7808 $password = $word1 . $filler1 . $word2;
7809 } else {
7810 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
7811 $digits = $CFG->minpassworddigits;
7812 $lower = $CFG->minpasswordlower;
7813 $upper = $CFG->minpasswordupper;
7814 $nonalphanum = $CFG->minpasswordnonalphanum;
7815 $total = $lower + $upper + $digits + $nonalphanum;
7816 // Var minlength should be the greater one of the two ( $minlen and $total ).
7817 $minlen = $minlen < $total ? $total : $minlen;
7818 // Var maxlen can never be smaller than minlen.
7819 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
7820 $additional = $maxlen - $total;
7822 // Make sure we have enough characters to fulfill
7823 // complexity requirements.
7824 $passworddigits = PASSWORD_DIGITS;
7825 while ($digits > strlen($passworddigits)) {
7826 $passworddigits .= PASSWORD_DIGITS;
7828 $passwordlower = PASSWORD_LOWER;
7829 while ($lower > strlen($passwordlower)) {
7830 $passwordlower .= PASSWORD_LOWER;
7832 $passwordupper = PASSWORD_UPPER;
7833 while ($upper > strlen($passwordupper)) {
7834 $passwordupper .= PASSWORD_UPPER;
7836 $passwordnonalphanum = PASSWORD_NONALPHANUM;
7837 while ($nonalphanum > strlen($passwordnonalphanum)) {
7838 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
7841 // Now mix and shuffle it all.
7842 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
7843 substr(str_shuffle ($passwordupper), 0, $upper) .
7844 substr(str_shuffle ($passworddigits), 0, $digits) .
7845 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
7846 substr(str_shuffle ($passwordlower .
7847 $passwordupper .
7848 $passworddigits .
7849 $passwordnonalphanum), 0 , $additional));
7852 return substr ($password, 0, $maxlen);
7856 * Given a float, prints it nicely.
7857 * Localized floats must not be used in calculations!
7859 * The stripzeros feature is intended for making numbers look nicer in small
7860 * areas where it is not necessary to indicate the degree of accuracy by showing
7861 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
7862 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
7864 * @param float $float The float to print
7865 * @param int $decimalpoints The number of decimal places to print.
7866 * @param bool $localized use localized decimal separator
7867 * @param bool $stripzeros If true, removes final zeros after decimal point
7868 * @return string locale float
7870 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
7871 if (is_null($float)) {
7872 return '';
7874 if ($localized) {
7875 $separator = get_string('decsep', 'langconfig');
7876 } else {
7877 $separator = '.';
7879 $result = number_format($float, $decimalpoints, $separator, '');
7880 if ($stripzeros) {
7881 // Remove zeros and final dot if not needed.
7882 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
7884 return $result;
7888 * Converts locale specific floating point/comma number back to standard PHP float value
7889 * Do NOT try to do any math operations before this conversion on any user submitted floats!
7891 * @param string $localefloat locale aware float representation
7892 * @param bool $strict If true, then check the input and return false if it is not a valid number.
7893 * @return mixed float|bool - false or the parsed float.
7895 function unformat_float($localefloat, $strict = false) {
7896 $localefloat = trim($localefloat);
7898 if ($localefloat == '') {
7899 return null;
7902 $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
7903 $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
7905 if ($strict && !is_numeric($localefloat)) {
7906 return false;
7909 return (float)$localefloat;
7913 * Given a simple array, this shuffles it up just like shuffle()
7914 * Unlike PHP's shuffle() this function works on any machine.
7916 * @param array $array The array to be rearranged
7917 * @return array
7919 function swapshuffle($array) {
7921 srand ((double) microtime() * 10000000);
7922 $last = count($array) - 1;
7923 for ($i = 0; $i <= $last; $i++) {
7924 $from = rand(0, $last);
7925 $curr = $array[$i];
7926 $array[$i] = $array[$from];
7927 $array[$from] = $curr;
7929 return $array;
7933 * Like {@link swapshuffle()}, but works on associative arrays
7935 * @param array $array The associative array to be rearranged
7936 * @return array
7938 function swapshuffle_assoc($array) {
7940 $newarray = array();
7941 $newkeys = swapshuffle(array_keys($array));
7943 foreach ($newkeys as $newkey) {
7944 $newarray[$newkey] = $array[$newkey];
7946 return $newarray;
7950 * Given an arbitrary array, and a number of draws,
7951 * this function returns an array with that amount
7952 * of items. The indexes are retained.
7954 * @todo Finish documenting this function
7956 * @param array $array
7957 * @param int $draws
7958 * @return array
7960 function draw_rand_array($array, $draws) {
7961 srand ((double) microtime() * 10000000);
7963 $return = array();
7965 $last = count($array);
7967 if ($draws > $last) {
7968 $draws = $last;
7971 while ($draws > 0) {
7972 $last--;
7974 $keys = array_keys($array);
7975 $rand = rand(0, $last);
7977 $return[$keys[$rand]] = $array[$keys[$rand]];
7978 unset($array[$keys[$rand]]);
7980 $draws--;
7983 return $return;
7987 * Calculate the difference between two microtimes
7989 * @param string $a The first Microtime
7990 * @param string $b The second Microtime
7991 * @return string
7993 function microtime_diff($a, $b) {
7994 list($adec, $asec) = explode(' ', $a);
7995 list($bdec, $bsec) = explode(' ', $b);
7996 return $bsec - $asec + $bdec - $adec;
8000 * Given a list (eg a,b,c,d,e) this function returns
8001 * an array of 1->a, 2->b, 3->c etc
8003 * @param string $list The string to explode into array bits
8004 * @param string $separator The separator used within the list string
8005 * @return array The now assembled array
8007 function make_menu_from_list($list, $separator=',') {
8009 $array = array_reverse(explode($separator, $list), true);
8010 foreach ($array as $key => $item) {
8011 $outarray[$key+1] = trim($item);
8013 return $outarray;
8017 * Creates an array that represents all the current grades that
8018 * can be chosen using the given grading type.
8020 * Negative numbers
8021 * are scales, zero is no grade, and positive numbers are maximum
8022 * grades.
8024 * @todo Finish documenting this function or better deprecated this completely!
8026 * @param int $gradingtype
8027 * @return array
8029 function make_grades_menu($gradingtype) {
8030 global $DB;
8032 $grades = array();
8033 if ($gradingtype < 0) {
8034 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8035 return make_menu_from_list($scale->scale);
8037 } else if ($gradingtype > 0) {
8038 for ($i=$gradingtype; $i>=0; $i--) {
8039 $grades[$i] = $i .' / '. $gradingtype;
8041 return $grades;
8043 return $grades;
8047 * This function returns the number of activities using the given scale in the given course.
8049 * @param int $courseid The course ID to check.
8050 * @param int $scaleid The scale ID to check
8051 * @return int
8053 function course_scale_used($courseid, $scaleid) {
8054 global $CFG, $DB;
8056 $return = 0;
8058 if (!empty($scaleid)) {
8059 if ($cms = get_course_mods($courseid)) {
8060 foreach ($cms as $cm) {
8061 // Check cm->name/lib.php exists.
8062 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
8063 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
8064 $functionname = $cm->modname.'_scale_used';
8065 if (function_exists($functionname)) {
8066 if ($functionname($cm->instance, $scaleid)) {
8067 $return++;
8074 // Check if any course grade item makes use of the scale.
8075 $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
8077 // Check if any outcome in the course makes use of the scale.
8078 $return += $DB->count_records_sql("SELECT COUNT('x')
8079 FROM {grade_outcomes_courses} goc,
8080 {grade_outcomes} go
8081 WHERE go.id = goc.outcomeid
8082 AND go.scaleid = ? AND goc.courseid = ?",
8083 array($scaleid, $courseid));
8085 return $return;
8089 * This function returns the number of activities using scaleid in the entire site
8091 * @param int $scaleid
8092 * @param array $courses
8093 * @return int
8095 function site_scale_used($scaleid, &$courses) {
8096 $return = 0;
8098 if (!is_array($courses) || count($courses) == 0) {
8099 $courses = get_courses("all", false, "c.id, c.shortname");
8102 if (!empty($scaleid)) {
8103 if (is_array($courses) && count($courses) > 0) {
8104 foreach ($courses as $course) {
8105 $return += course_scale_used($course->id, $scaleid);
8109 return $return;
8113 * make_unique_id_code
8115 * @todo Finish documenting this function
8117 * @uses $_SERVER
8118 * @param string $extra Extra string to append to the end of the code
8119 * @return string
8121 function make_unique_id_code($extra = '') {
8123 $hostname = 'unknownhost';
8124 if (!empty($_SERVER['HTTP_HOST'])) {
8125 $hostname = $_SERVER['HTTP_HOST'];
8126 } else if (!empty($_ENV['HTTP_HOST'])) {
8127 $hostname = $_ENV['HTTP_HOST'];
8128 } else if (!empty($_SERVER['SERVER_NAME'])) {
8129 $hostname = $_SERVER['SERVER_NAME'];
8130 } else if (!empty($_ENV['SERVER_NAME'])) {
8131 $hostname = $_ENV['SERVER_NAME'];
8134 $date = gmdate("ymdHis");
8136 $random = random_string(6);
8138 if ($extra) {
8139 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8140 } else {
8141 return $hostname .'+'. $date .'+'. $random;
8147 * Function to check the passed address is within the passed subnet
8149 * The parameter is a comma separated string of subnet definitions.
8150 * Subnet strings can be in one of three formats:
8151 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
8152 * 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)
8153 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
8154 * Code for type 1 modified from user posted comments by mediator at
8155 * {@link http://au.php.net/manual/en/function.ip2long.php}
8157 * @param string $addr The address you are checking
8158 * @param string $subnetstr The string of subnet addresses
8159 * @return bool
8161 function address_in_subnet($addr, $subnetstr) {
8163 if ($addr == '0.0.0.0') {
8164 return false;
8166 $subnets = explode(',', $subnetstr);
8167 $found = false;
8168 $addr = trim($addr);
8169 $addr = cleanremoteaddr($addr, false); // Normalise.
8170 if ($addr === null) {
8171 return false;
8173 $addrparts = explode(':', $addr);
8175 $ipv6 = strpos($addr, ':');
8177 foreach ($subnets as $subnet) {
8178 $subnet = trim($subnet);
8179 if ($subnet === '') {
8180 continue;
8183 if (strpos($subnet, '/') !== false) {
8184 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8185 list($ip, $mask) = explode('/', $subnet);
8186 $mask = trim($mask);
8187 if (!is_number($mask)) {
8188 continue; // Incorect mask number, eh?
8190 $ip = cleanremoteaddr($ip, false); // Normalise.
8191 if ($ip === null) {
8192 continue;
8194 if (strpos($ip, ':') !== false) {
8195 // IPv6.
8196 if (!$ipv6) {
8197 continue;
8199 if ($mask > 128 or $mask < 0) {
8200 continue; // Nonsense.
8202 if ($mask == 0) {
8203 return true; // Any address.
8205 if ($mask == 128) {
8206 if ($ip === $addr) {
8207 return true;
8209 continue;
8211 $ipparts = explode(':', $ip);
8212 $modulo = $mask % 16;
8213 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
8214 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8215 if (implode(':', $ipnet) === implode(':', $addrnet)) {
8216 if ($modulo == 0) {
8217 return true;
8219 $pos = ($mask-$modulo)/16;
8220 $ipnet = hexdec($ipparts[$pos]);
8221 $addrnet = hexdec($addrparts[$pos]);
8222 $mask = 0xffff << (16 - $modulo);
8223 if (($addrnet & $mask) == ($ipnet & $mask)) {
8224 return true;
8228 } else {
8229 // IPv4.
8230 if ($ipv6) {
8231 continue;
8233 if ($mask > 32 or $mask < 0) {
8234 continue; // Nonsense.
8236 if ($mask == 0) {
8237 return true;
8239 if ($mask == 32) {
8240 if ($ip === $addr) {
8241 return true;
8243 continue;
8245 $mask = 0xffffffff << (32 - $mask);
8246 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8247 return true;
8251 } else if (strpos($subnet, '-') !== false) {
8252 // 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.
8253 $parts = explode('-', $subnet);
8254 if (count($parts) != 2) {
8255 continue;
8258 if (strpos($subnet, ':') !== false) {
8259 // IPv6.
8260 if (!$ipv6) {
8261 continue;
8263 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8264 if ($ipstart === null) {
8265 continue;
8267 $ipparts = explode(':', $ipstart);
8268 $start = hexdec(array_pop($ipparts));
8269 $ipparts[] = trim($parts[1]);
8270 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8271 if ($ipend === null) {
8272 continue;
8274 $ipparts[7] = '';
8275 $ipnet = implode(':', $ipparts);
8276 if (strpos($addr, $ipnet) !== 0) {
8277 continue;
8279 $ipparts = explode(':', $ipend);
8280 $end = hexdec($ipparts[7]);
8282 $addrend = hexdec($addrparts[7]);
8284 if (($addrend >= $start) and ($addrend <= $end)) {
8285 return true;
8288 } else {
8289 // IPv4.
8290 if ($ipv6) {
8291 continue;
8293 $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8294 if ($ipstart === null) {
8295 continue;
8297 $ipparts = explode('.', $ipstart);
8298 $ipparts[3] = trim($parts[1]);
8299 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8300 if ($ipend === null) {
8301 continue;
8304 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8305 return true;
8309 } else {
8310 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8311 if (strpos($subnet, ':') !== false) {
8312 // IPv6.
8313 if (!$ipv6) {
8314 continue;
8316 $parts = explode(':', $subnet);
8317 $count = count($parts);
8318 if ($parts[$count-1] === '') {
8319 unset($parts[$count-1]); // Trim trailing :'s.
8320 $count--;
8321 $subnet = implode('.', $parts);
8323 $isip = cleanremoteaddr($subnet, false); // Normalise.
8324 if ($isip !== null) {
8325 if ($isip === $addr) {
8326 return true;
8328 continue;
8329 } else if ($count > 8) {
8330 continue;
8332 $zeros = array_fill(0, 8-$count, '0');
8333 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8334 if (address_in_subnet($addr, $subnet)) {
8335 return true;
8338 } else {
8339 // IPv4.
8340 if ($ipv6) {
8341 continue;
8343 $parts = explode('.', $subnet);
8344 $count = count($parts);
8345 if ($parts[$count-1] === '') {
8346 unset($parts[$count-1]); // Trim trailing .
8347 $count--;
8348 $subnet = implode('.', $parts);
8350 if ($count == 4) {
8351 $subnet = cleanremoteaddr($subnet, false); // Normalise.
8352 if ($subnet === $addr) {
8353 return true;
8355 continue;
8356 } else if ($count > 4) {
8357 continue;
8359 $zeros = array_fill(0, 4-$count, '0');
8360 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8361 if (address_in_subnet($addr, $subnet)) {
8362 return true;
8368 return false;
8372 * For outputting debugging info
8374 * @param string $string The string to write
8375 * @param string $eol The end of line char(s) to use
8376 * @param string $sleep Period to make the application sleep
8377 * This ensures any messages have time to display before redirect
8379 function mtrace($string, $eol="\n", $sleep=0) {
8381 if (defined('STDOUT') and !PHPUNIT_TEST) {
8382 fwrite(STDOUT, $string.$eol);
8383 } else {
8384 echo $string . $eol;
8387 flush();
8389 // Delay to keep message on user's screen in case of subsequent redirect.
8390 if ($sleep) {
8391 sleep($sleep);
8396 * Replace 1 or more slashes or backslashes to 1 slash
8398 * @param string $path The path to strip
8399 * @return string the path with double slashes removed
8401 function cleardoubleslashes ($path) {
8402 return preg_replace('/(\/|\\\){1,}/', '/', $path);
8406 * Is current ip in give list?
8408 * @param string $list
8409 * @return bool
8411 function remoteip_in_list($list) {
8412 $inlist = false;
8413 $clientip = getremoteaddr(null);
8415 if (!$clientip) {
8416 // Ensure access on cli.
8417 return true;
8420 $list = explode("\n", $list);
8421 foreach ($list as $subnet) {
8422 $subnet = trim($subnet);
8423 if (address_in_subnet($clientip, $subnet)) {
8424 $inlist = true;
8425 break;
8428 return $inlist;
8432 * Returns most reliable client address
8434 * @param string $default If an address can't be determined, then return this
8435 * @return string The remote IP address
8437 function getremoteaddr($default='0.0.0.0') {
8438 global $CFG;
8440 if (empty($CFG->getremoteaddrconf)) {
8441 // This will happen, for example, before just after the upgrade, as the
8442 // user is redirected to the admin screen.
8443 $variablestoskip = 0;
8444 } else {
8445 $variablestoskip = $CFG->getremoteaddrconf;
8447 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
8448 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
8449 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
8450 return $address ? $address : $default;
8453 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
8454 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
8455 $address = cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
8456 return $address ? $address : $default;
8459 if (!empty($_SERVER['REMOTE_ADDR'])) {
8460 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
8461 return $address ? $address : $default;
8462 } else {
8463 return $default;
8468 * Cleans an ip address. Internal addresses are now allowed.
8469 * (Originally local addresses were not allowed.)
8471 * @param string $addr IPv4 or IPv6 address
8472 * @param bool $compress use IPv6 address compression
8473 * @return string normalised ip address string, null if error
8475 function cleanremoteaddr($addr, $compress=false) {
8476 $addr = trim($addr);
8478 // TODO: maybe add a separate function is_addr_public() or something like this.
8480 if (strpos($addr, ':') !== false) {
8481 // Can be only IPv6.
8482 $parts = explode(':', $addr);
8483 $count = count($parts);
8485 if (strpos($parts[$count-1], '.') !== false) {
8486 // Legacy ipv4 notation.
8487 $last = array_pop($parts);
8488 $ipv4 = cleanremoteaddr($last, true);
8489 if ($ipv4 === null) {
8490 return null;
8492 $bits = explode('.', $ipv4);
8493 $parts[] = dechex($bits[0]).dechex($bits[1]);
8494 $parts[] = dechex($bits[2]).dechex($bits[3]);
8495 $count = count($parts);
8496 $addr = implode(':', $parts);
8499 if ($count < 3 or $count > 8) {
8500 return null; // Severly malformed.
8503 if ($count != 8) {
8504 if (strpos($addr, '::') === false) {
8505 return null; // Malformed.
8507 // Uncompress.
8508 $insertat = array_search('', $parts, true);
8509 $missing = array_fill(0, 1 + 8 - $count, '0');
8510 array_splice($parts, $insertat, 1, $missing);
8511 foreach ($parts as $key => $part) {
8512 if ($part === '') {
8513 $parts[$key] = '0';
8518 $adr = implode(':', $parts);
8519 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
8520 return null; // Incorrect format - sorry.
8523 // Normalise 0s and case.
8524 $parts = array_map('hexdec', $parts);
8525 $parts = array_map('dechex', $parts);
8527 $result = implode(':', $parts);
8529 if (!$compress) {
8530 return $result;
8533 if ($result === '0:0:0:0:0:0:0:0') {
8534 return '::'; // All addresses.
8537 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
8538 if ($compressed !== $result) {
8539 return $compressed;
8542 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
8543 if ($compressed !== $result) {
8544 return $compressed;
8547 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
8548 if ($compressed !== $result) {
8549 return $compressed;
8552 return $result;
8555 // First get all things that look like IPv4 addresses.
8556 $parts = array();
8557 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
8558 return null;
8560 unset($parts[0]);
8562 foreach ($parts as $key => $match) {
8563 if ($match > 255) {
8564 return null;
8566 $parts[$key] = (int)$match; // Normalise 0s.
8569 return implode('.', $parts);
8573 * This function will make a complete copy of anything it's given,
8574 * regardless of whether it's an object or not.
8576 * @param mixed $thing Something you want cloned
8577 * @return mixed What ever it is you passed it
8579 function fullclone($thing) {
8580 return unserialize(serialize($thing));
8584 * If new messages are waiting for the current user, then insert
8585 * JavaScript to pop up the messaging window into the page
8587 * @return void
8589 function message_popup_window() {
8590 global $USER, $DB, $PAGE, $CFG;
8592 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
8593 return;
8596 if (!isloggedin() || isguestuser()) {
8597 return;
8600 if (!isset($USER->message_lastpopup)) {
8601 $USER->message_lastpopup = 0;
8602 } else if ($USER->message_lastpopup > (time()-120)) {
8603 // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
8604 return;
8607 // A quick query to check whether the user has new messages.
8608 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
8609 if ($messagecount<1) {
8610 return;
8613 // Got unread messages so now do another query that joins with the user table.
8614 $messagesql = "SELECT m.id, m.smallmessage, m.fullmessageformat, m.notification, u.firstname, u.lastname
8615 FROM {message} m
8616 JOIN {message_working} mw ON m.id=mw.unreadmessageid
8617 JOIN {message_processors} p ON mw.processorid=p.id
8618 JOIN {user} u ON m.useridfrom=u.id
8619 WHERE m.useridto = :userid
8620 AND p.name='popup'";
8622 // If the user was last notified over an hour ago we can re-notify them of old messages
8623 // so don't worry about when the new message was sent.
8624 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
8625 if (!$lastnotifiedlongago) {
8626 $messagesql .= 'AND m.timecreated > :lastpopuptime';
8629 $messageusers = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
8631 // If we have new messages to notify the user about.
8632 if (!empty($messageusers)) {
8634 $strmessages = '';
8635 if (count($messageusers)>1) {
8636 $strmessages = get_string('unreadnewmessages', 'message', count($messageusers));
8637 } else {
8638 $messageusers = reset($messageusers);
8640 // Show who the message is from if its not a notification.
8641 if (!$messageusers->notification) {
8642 $strmessages = get_string('unreadnewmessage', 'message', fullname($messageusers) );
8645 // Try to display the small version of the message.
8646 $smallmessage = null;
8647 if (!empty($messageusers->smallmessage)) {
8648 // Display the first 200 chars of the message in the popup.
8649 $smallmessage = null;
8650 if (core_text::strlen($messageusers->smallmessage) > 200) {
8651 $smallmessage = core_text::substr($messageusers->smallmessage, 0, 200).'...';
8652 } else {
8653 $smallmessage = $messageusers->smallmessage;
8656 // Prevent html symbols being displayed.
8657 if ($messageusers->fullmessageformat == FORMAT_HTML) {
8658 $smallmessage = html_to_text($smallmessage);
8659 } else {
8660 $smallmessage = s($smallmessage);
8662 } else if ($messageusers->notification) {
8663 // Its a notification with no smallmessage so just say they have a notification.
8664 $smallmessage = get_string('unreadnewnotification', 'message');
8666 if (!empty($smallmessage)) {
8667 $strmessages .= '<div id="usermessage">'.s($smallmessage).'</div>';
8671 $strgomessage = get_string('gotomessages', 'message');
8672 $strstaymessage = get_string('ignore', 'admin');
8674 $notificationsound = null;
8675 $beep = get_user_preferences('message_beepnewmessage', '');
8676 if (!empty($beep)) {
8677 // Browsers will work down this list until they find something they support.
8678 $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
8679 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
8680 $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
8681 $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
8683 $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
8686 $url = $CFG->wwwroot.'/message/index.php';
8687 $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
8688 html_writer::start_tag('div', array('id' => 'newmessagetext')).
8689 $strmessages.
8690 html_writer::end_tag('div').
8692 $notificationsound.
8693 html_writer::start_tag('div', array('id' => 'newmessagelinks')).
8694 html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
8695 html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
8696 html_writer::end_tag('div');
8697 html_writer::end_tag('div');
8699 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
8701 $USER->message_lastpopup = time();
8706 * Used to make sure that $min <= $value <= $max
8708 * Make sure that value is between min, and max
8710 * @param int $min The minimum value
8711 * @param int $value The value to check
8712 * @param int $max The maximum value
8713 * @return int
8715 function bounded_number($min, $value, $max) {
8716 if ($value < $min) {
8717 return $min;
8719 if ($value > $max) {
8720 return $max;
8722 return $value;
8726 * Check if there is a nested array within the passed array
8728 * @param array $array
8729 * @return bool true if there is a nested array false otherwise
8731 function array_is_nested($array) {
8732 foreach ($array as $value) {
8733 if (is_array($value)) {
8734 return true;
8737 return false;
8741 * get_performance_info() pairs up with init_performance_info()
8742 * loaded in setup.php. Returns an array with 'html' and 'txt'
8743 * values ready for use, and each of the individual stats provided
8744 * separately as well.
8746 * @return array
8748 function get_performance_info() {
8749 global $CFG, $PERF, $DB, $PAGE;
8751 $info = array();
8752 $info['html'] = ''; // Holds userfriendly HTML representation.
8753 $info['txt'] = me() . ' '; // Holds log-friendly representation.
8755 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
8757 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
8758 $info['txt'] .= 'time: '.$info['realtime'].'s ';
8760 if (function_exists('memory_get_usage')) {
8761 $info['memory_total'] = memory_get_usage();
8762 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
8763 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
8764 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
8765 $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
8768 if (function_exists('memory_get_peak_usage')) {
8769 $info['memory_peak'] = memory_get_peak_usage();
8770 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
8771 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
8774 $inc = get_included_files();
8775 $info['includecount'] = count($inc);
8776 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
8777 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
8779 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
8780 // We can not track more performance before installation or before PAGE init, sorry.
8781 return $info;
8784 $filtermanager = filter_manager::instance();
8785 if (method_exists($filtermanager, 'get_performance_summary')) {
8786 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
8787 $info = array_merge($filterinfo, $info);
8788 foreach ($filterinfo as $key => $value) {
8789 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8790 $info['txt'] .= "$key: $value ";
8794 $stringmanager = get_string_manager();
8795 if (method_exists($stringmanager, 'get_performance_summary')) {
8796 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
8797 $info = array_merge($filterinfo, $info);
8798 foreach ($filterinfo as $key => $value) {
8799 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
8800 $info['txt'] .= "$key: $value ";
8804 $jsmodules = $PAGE->requires->get_loaded_modules();
8805 if ($jsmodules) {
8806 $yuicount = 0;
8807 $othercount = 0;
8808 $details = '';
8809 foreach ($jsmodules as $module => $backtraces) {
8810 if (strpos($module, 'yui') === 0) {
8811 $yuicount += 1;
8812 } else {
8813 $othercount += 1;
8815 if (!empty($CFG->yuimoduledebug)) {
8816 // Hidden feature for developers working on YUI module infrastructure.
8817 $details .= "<div class='yui-module'><p>$module</p>";
8818 foreach ($backtraces as $backtrace) {
8819 $details .= "<div class='backtrace'>$backtrace</div>";
8821 $details .= '</div>';
8824 $info['html'] .= "<span class='includedyuimodules'>Included YUI modules: $yuicount</span> ";
8825 $info['txt'] .= "includedyuimodules: $yuicount ";
8826 $info['html'] .= "<span class='includedjsmodules'>Other JavaScript modules: $othercount</span> ";
8827 $info['txt'] .= "includedjsmodules: $othercount ";
8828 if ($details) {
8829 $info['html'] .= '<div id="yui-module-debug" class="notifytiny">'.$details.'</div>';
8833 if (!empty($PERF->logwrites)) {
8834 $info['logwrites'] = $PERF->logwrites;
8835 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
8836 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
8839 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
8840 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
8841 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
8843 if (function_exists('posix_times')) {
8844 $ptimes = posix_times();
8845 if (is_array($ptimes)) {
8846 foreach ($ptimes as $key => $val) {
8847 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
8849 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
8850 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
8854 // Grab the load average for the last minute.
8855 // /proc will only work under some linux configurations
8856 // while uptime is there under MacOSX/Darwin and other unices.
8857 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
8858 list($serverload) = explode(' ', $loadavg[0]);
8859 unset($loadavg);
8860 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
8861 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
8862 $serverload = $matches[1];
8863 } else {
8864 trigger_error('Could not parse uptime output!');
8867 if (!empty($serverload)) {
8868 $info['serverload'] = $serverload;
8869 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
8870 $info['txt'] .= "serverload: {$info['serverload']} ";
8873 // Display size of session if session started.
8874 if ($si = \core\session\manager::get_performance_info()) {
8875 $info['sessionsize'] = $si['size'];
8876 $info['html'] .= $si['html'];
8877 $info['txt'] .= $si['txt'];
8880 if ($stats = cache_helper::get_stats()) {
8881 $html = '<span class="cachesused">';
8882 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
8883 $text = 'Caches used (hits/misses/sets): ';
8884 $hits = 0;
8885 $misses = 0;
8886 $sets = 0;
8887 foreach ($stats as $definition => $stores) {
8888 $html .= '<span class="cache-definition-stats">';
8889 $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
8890 $text .= "$definition {";
8891 foreach ($stores as $store => $data) {
8892 $hits += $data['hits'];
8893 $misses += $data['misses'];
8894 $sets += $data['sets'];
8895 if ($data['hits'] == 0 and $data['misses'] > 0) {
8896 $cachestoreclass = 'nohits';
8897 } else if ($data['hits'] < $data['misses']) {
8898 $cachestoreclass = 'lowhits';
8899 } else {
8900 $cachestoreclass = 'hihits';
8902 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
8903 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
8905 $html .= '</span>';
8906 $text .= '} ';
8908 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
8909 $html .= '</span> ';
8910 $info['cachesused'] = "$hits / $misses / $sets";
8911 $info['html'] .= $html;
8912 $info['txt'] .= $text.'. ';
8913 } else {
8914 $info['cachesused'] = '0 / 0 / 0';
8915 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
8916 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
8919 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
8920 return $info;
8924 * Legacy function.
8926 * @todo Document this function linux people
8928 function apd_get_profiling() {
8929 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
8933 * Delete directory or only its content
8935 * @param string $dir directory path
8936 * @param bool $contentonly
8937 * @return bool success, true also if dir does not exist
8939 function remove_dir($dir, $contentonly=false) {
8940 if (!file_exists($dir)) {
8941 // Nothing to do.
8942 return true;
8944 if (!$handle = opendir($dir)) {
8945 return false;
8947 $result = true;
8948 while (false!==($item = readdir($handle))) {
8949 if ($item != '.' && $item != '..') {
8950 if (is_dir($dir.'/'.$item)) {
8951 $result = remove_dir($dir.'/'.$item) && $result;
8952 } else {
8953 $result = unlink($dir.'/'.$item) && $result;
8957 closedir($handle);
8958 if ($contentonly) {
8959 clearstatcache(); // Make sure file stat cache is properly invalidated.
8960 return $result;
8962 $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
8963 clearstatcache(); // Make sure file stat cache is properly invalidated.
8964 return $result;
8968 * Detect if an object or a class contains a given property
8969 * will take an actual object or the name of a class
8971 * @param mix $obj Name of class or real object to test
8972 * @param string $property name of property to find
8973 * @return bool true if property exists
8975 function object_property_exists( $obj, $property ) {
8976 if (is_string( $obj )) {
8977 $properties = get_class_vars( $obj );
8978 } else {
8979 $properties = get_object_vars( $obj );
8981 return array_key_exists( $property, $properties );
8985 * Converts an object into an associative array
8987 * This function converts an object into an associative array by iterating
8988 * over its public properties. Because this function uses the foreach
8989 * construct, Iterators are respected. It works recursively on arrays of objects.
8990 * Arrays and simple values are returned as is.
8992 * If class has magic properties, it can implement IteratorAggregate
8993 * and return all available properties in getIterator()
8995 * @param mixed $var
8996 * @return array
8998 function convert_to_array($var) {
8999 $result = array();
9001 // Loop over elements/properties.
9002 foreach ($var as $key => $value) {
9003 // Recursively convert objects.
9004 if (is_object($value) || is_array($value)) {
9005 $result[$key] = convert_to_array($value);
9006 } else {
9007 // Simple values are untouched.
9008 $result[$key] = $value;
9011 return $result;
9015 * Detect a custom script replacement in the data directory that will
9016 * replace an existing moodle script
9018 * @return string|bool full path name if a custom script exists, false if no custom script exists
9020 function custom_script_path() {
9021 global $CFG, $SCRIPT;
9023 if ($SCRIPT === null) {
9024 // Probably some weird external script.
9025 return false;
9028 $scriptpath = $CFG->customscripts . $SCRIPT;
9030 // Check the custom script exists.
9031 if (file_exists($scriptpath) and is_file($scriptpath)) {
9032 return $scriptpath;
9033 } else {
9034 return false;
9039 * Returns whether or not the user object is a remote MNET user. This function
9040 * is in moodlelib because it does not rely on loading any of the MNET code.
9042 * @param object $user A valid user object
9043 * @return bool True if the user is from a remote Moodle.
9045 function is_mnet_remote_user($user) {
9046 global $CFG;
9048 if (!isset($CFG->mnet_localhost_id)) {
9049 include_once($CFG->dirroot . '/mnet/lib.php');
9050 $env = new mnet_environment();
9051 $env->init();
9052 unset($env);
9055 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9059 * This function will search for browser prefereed languages, setting Moodle
9060 * to use the best one available if $SESSION->lang is undefined
9062 function setup_lang_from_browser() {
9063 global $CFG, $SESSION, $USER;
9065 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9066 // Lang is defined in session or user profile, nothing to do.
9067 return;
9070 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9071 return;
9074 // Extract and clean langs from headers.
9075 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9076 $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
9077 $rawlangs = explode(',', $rawlangs); // Convert to array.
9078 $langs = array();
9080 $order = 1.0;
9081 foreach ($rawlangs as $lang) {
9082 if (strpos($lang, ';') === false) {
9083 $langs[(string)$order] = $lang;
9084 $order = $order-0.01;
9085 } else {
9086 $parts = explode(';', $lang);
9087 $pos = strpos($parts[1], '=');
9088 $langs[substr($parts[1], $pos+1)] = $parts[0];
9091 krsort($langs, SORT_NUMERIC);
9093 // Look for such langs under standard locations.
9094 foreach ($langs as $lang) {
9095 // Clean it properly for include.
9096 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9097 if (get_string_manager()->translation_exists($lang, false)) {
9098 // Lang exists, set it in session.
9099 $SESSION->lang = $lang;
9100 // We have finished. Go out.
9101 break;
9104 return;
9108 * Check if $url matches anything in proxybypass list
9110 * Any errors just result in the proxy being used (least bad)
9112 * @param string $url url to check
9113 * @return boolean true if we should bypass the proxy
9115 function is_proxybypass( $url ) {
9116 global $CFG;
9118 // Sanity check.
9119 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9120 return false;
9123 // Get the host part out of the url.
9124 if (!$host = parse_url( $url, PHP_URL_HOST )) {
9125 return false;
9128 // Get the possible bypass hosts into an array.
9129 $matches = explode( ',', $CFG->proxybypass );
9131 // Check for a match.
9132 // (IPs need to match the left hand side and hosts the right of the url,
9133 // but we can recklessly check both as there can't be a false +ve).
9134 foreach ($matches as $match) {
9135 $match = trim($match);
9137 // Try for IP match (Left side).
9138 $lhs = substr($host, 0, strlen($match));
9139 if (strcasecmp($match, $lhs)==0) {
9140 return true;
9143 // Try for host match (Right side).
9144 $rhs = substr($host, -strlen($match));
9145 if (strcasecmp($match, $rhs)==0) {
9146 return true;
9150 // Nothing matched.
9151 return false;
9155 * Check if the passed navigation is of the new style
9157 * @param mixed $navigation
9158 * @return bool true for yes false for no
9160 function is_newnav($navigation) {
9161 if (is_array($navigation) && !empty($navigation['newnav'])) {
9162 return true;
9163 } else {
9164 return false;
9169 * Checks whether the given variable name is defined as a variable within the given object.
9171 * This will NOT work with stdClass objects, which have no class variables.
9173 * @param string $var The variable name
9174 * @param object $object The object to check
9175 * @return boolean
9177 function in_object_vars($var, $object) {
9178 $classvars = get_class_vars(get_class($object));
9179 $classvars = array_keys($classvars);
9180 return in_array($var, $classvars);
9184 * Returns an array without repeated objects.
9185 * This function is similar to array_unique, but for arrays that have objects as values
9187 * @param array $array
9188 * @param bool $keepkeyassoc
9189 * @return array
9191 function object_array_unique($array, $keepkeyassoc = true) {
9192 $duplicatekeys = array();
9193 $tmp = array();
9195 foreach ($array as $key => $val) {
9196 // Convert objects to arrays, in_array() does not support objects.
9197 if (is_object($val)) {
9198 $val = (array)$val;
9201 if (!in_array($val, $tmp)) {
9202 $tmp[] = $val;
9203 } else {
9204 $duplicatekeys[] = $key;
9208 foreach ($duplicatekeys as $key) {
9209 unset($array[$key]);
9212 return $keepkeyassoc ? $array : array_values($array);
9216 * Is a userid the primary administrator?
9218 * @param int $userid int id of user to check
9219 * @return boolean
9221 function is_primary_admin($userid) {
9222 $primaryadmin = get_admin();
9224 if ($userid == $primaryadmin->id) {
9225 return true;
9226 } else {
9227 return false;
9232 * Returns the site identifier
9234 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9236 function get_site_identifier() {
9237 global $CFG;
9238 // Check to see if it is missing. If so, initialise it.
9239 if (empty($CFG->siteidentifier)) {
9240 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9242 // Return it.
9243 return $CFG->siteidentifier;
9247 * Check whether the given password has no more than the specified
9248 * number of consecutive identical characters.
9250 * @param string $password password to be checked against the password policy
9251 * @param integer $maxchars maximum number of consecutive identical characters
9252 * @return bool
9254 function check_consecutive_identical_characters($password, $maxchars) {
9256 if ($maxchars < 1) {
9257 return true; // Zero 0 is to disable this check.
9259 if (strlen($password) <= $maxchars) {
9260 return true; // Too short to fail this test.
9263 $previouschar = '';
9264 $consecutivecount = 1;
9265 foreach (str_split($password) as $char) {
9266 if ($char != $previouschar) {
9267 $consecutivecount = 1;
9268 } else {
9269 $consecutivecount++;
9270 if ($consecutivecount > $maxchars) {
9271 return false; // Check failed already.
9275 $previouschar = $char;
9278 return true;
9282 * Helper function to do partial function binding.
9283 * so we can use it for preg_replace_callback, for example
9284 * this works with php functions, user functions, static methods and class methods
9285 * it returns you a callback that you can pass on like so:
9287 * $callback = partial('somefunction', $arg1, $arg2);
9288 * or
9289 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
9290 * or even
9291 * $obj = new someclass();
9292 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
9294 * and then the arguments that are passed through at calltime are appended to the argument list.
9296 * @param mixed $function a php callback
9297 * @param mixed $arg1,... $argv arguments to partially bind with
9298 * @return array Array callback
9300 function partial() {
9301 if (!class_exists('partial')) {
9303 * Used to manage function binding.
9304 * @copyright 2009 Penny Leach
9305 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9307 class partial{
9308 /** @var array */
9309 public $values = array();
9310 /** @var string The function to call as a callback. */
9311 public $func;
9313 * Constructor
9314 * @param string $func
9315 * @param array $args
9317 public function __construct($func, $args) {
9318 $this->values = $args;
9319 $this->func = $func;
9322 * Calls the callback function.
9323 * @return mixed
9325 public function method() {
9326 $args = func_get_args();
9327 return call_user_func_array($this->func, array_merge($this->values, $args));
9331 $args = func_get_args();
9332 $func = array_shift($args);
9333 $p = new partial($func, $args);
9334 return array($p, 'method');
9338 * helper function to load up and initialise the mnet environment
9339 * this must be called before you use mnet functions.
9341 * @return mnet_environment the equivalent of old $MNET global
9343 function get_mnet_environment() {
9344 global $CFG;
9345 require_once($CFG->dirroot . '/mnet/lib.php');
9346 static $instance = null;
9347 if (empty($instance)) {
9348 $instance = new mnet_environment();
9349 $instance->init();
9351 return $instance;
9355 * during xmlrpc server code execution, any code wishing to access
9356 * information about the remote peer must use this to get it.
9358 * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
9360 function get_mnet_remote_client() {
9361 if (!defined('MNET_SERVER')) {
9362 debugging(get_string('notinxmlrpcserver', 'mnet'));
9363 return false;
9365 global $MNET_REMOTE_CLIENT;
9366 if (isset($MNET_REMOTE_CLIENT)) {
9367 return $MNET_REMOTE_CLIENT;
9369 return false;
9373 * during the xmlrpc server code execution, this will be called
9374 * to setup the object returned by {@link get_mnet_remote_client}
9376 * @param mnet_remote_client $client the client to set up
9377 * @throws moodle_exception
9379 function set_mnet_remote_client($client) {
9380 if (!defined('MNET_SERVER')) {
9381 throw new moodle_exception('notinxmlrpcserver', 'mnet');
9383 global $MNET_REMOTE_CLIENT;
9384 $MNET_REMOTE_CLIENT = $client;
9388 * return the jump url for a given remote user
9389 * this is used for rewriting forum post links in emails, etc
9391 * @param stdclass $user the user to get the idp url for
9393 function mnet_get_idp_jump_url($user) {
9394 global $CFG;
9396 static $mnetjumps = array();
9397 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
9398 $idp = mnet_get_peer_host($user->mnethostid);
9399 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
9400 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
9402 return $mnetjumps[$user->mnethostid];
9406 * Gets the homepage to use for the current user
9408 * @return int One of HOMEPAGE_*
9410 function get_home_page() {
9411 global $CFG;
9413 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
9414 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
9415 return HOMEPAGE_MY;
9416 } else {
9417 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
9420 return HOMEPAGE_SITE;
9424 * Gets the name of a course to be displayed when showing a list of courses.
9425 * By default this is just $course->fullname but user can configure it. The
9426 * result of this function should be passed through print_string.
9427 * @param stdClass|course_in_list $course Moodle course object
9428 * @return string Display name of course (either fullname or short + fullname)
9430 function get_course_display_name_for_list($course) {
9431 global $CFG;
9432 if (!empty($CFG->courselistshortnames)) {
9433 if (!($course instanceof stdClass)) {
9434 $course = (object)convert_to_array($course);
9436 return get_string('courseextendednamedisplay', '', $course);
9437 } else {
9438 return $course->fullname;
9443 * The lang_string class
9445 * This special class is used to create an object representation of a string request.
9446 * It is special because processing doesn't occur until the object is first used.
9447 * The class was created especially to aid performance in areas where strings were
9448 * required to be generated but were not necessarily used.
9449 * As an example the admin tree when generated uses over 1500 strings, of which
9450 * normally only 1/3 are ever actually printed at any time.
9451 * The performance advantage is achieved by not actually processing strings that
9452 * arn't being used, as such reducing the processing required for the page.
9454 * How to use the lang_string class?
9455 * There are two methods of using the lang_string class, first through the
9456 * forth argument of the get_string function, and secondly directly.
9457 * The following are examples of both.
9458 * 1. Through get_string calls e.g.
9459 * $string = get_string($identifier, $component, $a, true);
9460 * $string = get_string('yes', 'moodle', null, true);
9461 * 2. Direct instantiation
9462 * $string = new lang_string($identifier, $component, $a, $lang);
9463 * $string = new lang_string('yes');
9465 * How do I use a lang_string object?
9466 * The lang_string object makes use of a magic __toString method so that you
9467 * are able to use the object exactly as you would use a string in most cases.
9468 * This means you are able to collect it into a variable and then directly
9469 * echo it, or concatenate it into another string, or similar.
9470 * The other thing you can do is manually get the string by calling the
9471 * lang_strings out method e.g.
9472 * $string = new lang_string('yes');
9473 * $string->out();
9474 * Also worth noting is that the out method can take one argument, $lang which
9475 * allows the developer to change the language on the fly.
9477 * When should I use a lang_string object?
9478 * The lang_string object is designed to be used in any situation where a
9479 * string may not be needed, but needs to be generated.
9480 * The admin tree is a good example of where lang_string objects should be
9481 * used.
9482 * A more practical example would be any class that requries strings that may
9483 * not be printed (after all classes get renderer by renderers and who knows
9484 * what they will do ;))
9486 * When should I not use a lang_string object?
9487 * Don't use lang_strings when you are going to use a string immediately.
9488 * There is no need as it will be processed immediately and there will be no
9489 * advantage, and in fact perhaps a negative hit as a class has to be
9490 * instantiated for a lang_string object, however get_string won't require
9491 * that.
9493 * Limitations:
9494 * 1. You cannot use a lang_string object as an array offset. Doing so will
9495 * result in PHP throwing an error. (You can use it as an object property!)
9497 * @package core
9498 * @category string
9499 * @copyright 2011 Sam Hemelryk
9500 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9502 class lang_string {
9504 /** @var string The strings identifier */
9505 protected $identifier;
9506 /** @var string The strings component. Default '' */
9507 protected $component = '';
9508 /** @var array|stdClass Any arguments required for the string. Default null */
9509 protected $a = null;
9510 /** @var string The language to use when processing the string. Default null */
9511 protected $lang = null;
9513 /** @var string The processed string (once processed) */
9514 protected $string = null;
9517 * A special boolean. If set to true then the object has been woken up and
9518 * cannot be regenerated. If this is set then $this->string MUST be used.
9519 * @var bool
9521 protected $forcedstring = false;
9524 * Constructs a lang_string object
9526 * This function should do as little processing as possible to ensure the best
9527 * performance for strings that won't be used.
9529 * @param string $identifier The strings identifier
9530 * @param string $component The strings component
9531 * @param stdClass|array $a Any arguments the string requires
9532 * @param string $lang The language to use when processing the string.
9533 * @throws coding_exception
9535 public function __construct($identifier, $component = '', $a = null, $lang = null) {
9536 if (empty($component)) {
9537 $component = 'moodle';
9540 $this->identifier = $identifier;
9541 $this->component = $component;
9542 $this->lang = $lang;
9544 // We MUST duplicate $a to ensure that it if it changes by reference those
9545 // changes are not carried across.
9546 // To do this we always ensure $a or its properties/values are strings
9547 // and that any properties/values that arn't convertable are forgotten.
9548 if (!empty($a)) {
9549 if (is_scalar($a)) {
9550 $this->a = $a;
9551 } else if ($a instanceof lang_string) {
9552 $this->a = $a->out();
9553 } else if (is_object($a) or is_array($a)) {
9554 $a = (array)$a;
9555 $this->a = array();
9556 foreach ($a as $key => $value) {
9557 // Make sure conversion errors don't get displayed (results in '').
9558 if (is_array($value)) {
9559 $this->a[$key] = '';
9560 } else if (is_object($value)) {
9561 if (method_exists($value, '__toString')) {
9562 $this->a[$key] = $value->__toString();
9563 } else {
9564 $this->a[$key] = '';
9566 } else {
9567 $this->a[$key] = (string)$value;
9573 if (debugging(false, DEBUG_DEVELOPER)) {
9574 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
9575 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
9577 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
9578 throw new coding_exception('Invalid string compontent. Please check your string definition');
9580 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
9581 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
9587 * Processes the string.
9589 * This function actually processes the string, stores it in the string property
9590 * and then returns it.
9591 * You will notice that this function is VERY similar to the get_string method.
9592 * That is because it is pretty much doing the same thing.
9593 * However as this function is an upgrade it isn't as tolerant to backwards
9594 * compatibility.
9596 * @return string
9597 * @throws coding_exception
9599 protected function get_string() {
9600 global $CFG;
9602 // Check if we need to process the string.
9603 if ($this->string === null) {
9604 // Check the quality of the identifier.
9605 if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
9606 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);
9609 // Process the string.
9610 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
9611 // Debugging feature lets you display string identifier and component.
9612 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
9613 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
9616 // Return the string.
9617 return $this->string;
9621 * Returns the string
9623 * @param string $lang The langauge to use when processing the string
9624 * @return string
9626 public function out($lang = null) {
9627 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
9628 if ($this->forcedstring) {
9629 debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
9630 return $this->get_string();
9632 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
9633 return $translatedstring->out();
9635 return $this->get_string();
9639 * Magic __toString method for printing a string
9641 * @return string
9643 public function __toString() {
9644 return $this->get_string();
9648 * Magic __set_state method used for var_export
9650 * @return string
9652 public function __set_state() {
9653 return $this->get_string();
9657 * Prepares the lang_string for sleep and stores only the forcedstring and
9658 * string properties... the string cannot be regenerated so we need to ensure
9659 * it is generated for this.
9661 * @return string
9663 public function __sleep() {
9664 $this->get_string();
9665 $this->forcedstring = true;
9666 return array('forcedstring', 'string', 'lang');