3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * moodlelib.php - Moodle main library
21 * Main library file of miscellaneous general-purpose Moodle functions.
22 * Other main libraries:
23 * - weblib.php - functions that produce web output
24 * - datalib.php - functions that access the database
28 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32 defined('MOODLE_INTERNAL') ||
die();
34 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
36 /// Date and time constants ///
38 * Time constant - the number of seconds in a year
40 define('YEARSECS', 31536000);
43 * Time constant - the number of seconds in a week
45 define('WEEKSECS', 604800);
48 * Time constant - the number of seconds in a day
50 define('DAYSECS', 86400);
53 * Time constant - the number of seconds in an hour
55 define('HOURSECS', 3600);
58 * Time constant - the number of seconds in a minute
60 define('MINSECS', 60);
63 * Time constant - the number of minutes in a day
65 define('DAYMINS', 1440);
68 * Time constant - the number of minutes in an hour
70 define('HOURMINS', 60);
72 /// Parameter constants - every call to optional_param(), required_param() ///
73 /// or clean_param() should have a specified type of parameter. //////////////
78 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
80 define('PARAM_ALPHA', 'alpha');
83 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
84 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
86 define('PARAM_ALPHAEXT', 'alphaext');
89 * PARAM_ALPHANUM - expected numbers and letters only.
91 define('PARAM_ALPHANUM', 'alphanum');
94 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
96 define('PARAM_ALPHANUMEXT', 'alphanumext');
99 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
101 define('PARAM_AUTH', 'auth');
104 * PARAM_BASE64 - Base 64 encoded format
106 define('PARAM_BASE64', 'base64');
109 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
111 define('PARAM_BOOL', 'bool');
114 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
115 * checked against the list of capabilities in the database.
117 define('PARAM_CAPABILITY', 'capability');
120 * PARAM_CLEANHTML - cleans submitted HTML code. use only for text in HTML format. This cleaning may fix xhtml strictness too.
122 define('PARAM_CLEANHTML', 'cleanhtml');
125 * PARAM_EMAIL - an email address following the RFC
127 define('PARAM_EMAIL', 'email');
130 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
132 define('PARAM_FILE', 'file');
135 * PARAM_FLOAT - a real/floating point number.
137 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
138 * It does not work for languages that use , as a decimal separator.
139 * Instead, do something like
140 * $rawvalue = required_param('name', PARAM_RAW);
141 * // ... other code including require_login, which sets current lang ...
142 * $realvalue = unformat_float($rawvalue);
143 * // ... then use $realvalue
145 define('PARAM_FLOAT', 'float');
148 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
150 define('PARAM_HOST', 'host');
153 * PARAM_INT - integers only, use when expecting only numbers.
155 define('PARAM_INT', 'int');
158 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
160 define('PARAM_LANG', 'lang');
163 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
165 define('PARAM_LOCALURL', 'localurl');
168 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
170 define('PARAM_NOTAGS', 'notags');
173 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
174 * note: the leading slash is not removed, window drive letter is not allowed
176 define('PARAM_PATH', 'path');
179 * PARAM_PEM - Privacy Enhanced Mail format
181 define('PARAM_PEM', 'pem');
184 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
186 define('PARAM_PERMISSION', 'permission');
189 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
191 define('PARAM_RAW', 'raw');
194 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
196 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
199 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
201 define('PARAM_SAFEDIR', 'safedir');
204 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
206 define('PARAM_SAFEPATH', 'safepath');
209 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
211 define('PARAM_SEQUENCE', 'sequence');
214 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
216 define('PARAM_TAG', 'tag');
219 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
221 define('PARAM_TAGLIST', 'taglist');
224 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
226 define('PARAM_TEXT', 'text');
229 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
231 define('PARAM_THEME', 'theme');
234 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
236 define('PARAM_URL', 'url');
239 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user accounts, do NOT use when syncing with external systems!!
241 define('PARAM_USERNAME', 'username');
244 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
246 define('PARAM_STRINGID', 'stringid');
248 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
250 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
251 * It was one of the first types, that is why it is abused so much ;-)
252 * @deprecated since 2.0
254 define('PARAM_CLEAN', 'clean');
257 * PARAM_INTEGER - deprecated alias for PARAM_INT
259 define('PARAM_INTEGER', 'int');
262 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
264 define('PARAM_NUMBER', 'float');
267 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
268 * NOTE: originally alias for PARAM_APLHA
270 define('PARAM_ACTION', 'alphanumext');
273 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
274 * NOTE: originally alias for PARAM_APLHA
276 define('PARAM_FORMAT', 'alphanumext');
279 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
281 define('PARAM_MULTILANG', 'text');
284 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
285 * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
286 * America/Port-au-Prince)
288 define('PARAM_TIMEZONE', 'timezone');
291 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
293 define('PARAM_CLEANFILE', 'file');
296 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
297 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
298 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
299 * NOTE: numbers and underscores are strongly discouraged in plugin names!
301 define('PARAM_COMPONENT', 'component');
304 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
305 * It is usually used together with context id and component.
306 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
308 define('PARAM_AREA', 'area');
311 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
312 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
313 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
315 define('PARAM_PLUGIN', 'plugin');
321 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
323 define('VALUE_REQUIRED', 1);
326 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
328 define('VALUE_OPTIONAL', 2);
331 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
333 define('VALUE_DEFAULT', 0);
336 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
338 define('NULL_NOT_ALLOWED', false);
341 * NULL_ALLOWED - the parameter can be set to null in the database
343 define('NULL_ALLOWED', true);
347 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
349 define('PAGE_COURSE_VIEW', 'course-view');
351 /** Get remote addr constant */
352 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
353 /** Get remote addr constant */
354 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
356 /// Blog access level constant declaration ///
357 define ('BLOG_USER_LEVEL', 1);
358 define ('BLOG_GROUP_LEVEL', 2);
359 define ('BLOG_COURSE_LEVEL', 3);
360 define ('BLOG_SITE_LEVEL', 4);
361 define ('BLOG_GLOBAL_LEVEL', 5);
366 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
367 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
368 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
370 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
372 define('TAG_MAX_LENGTH', 50);
374 /// Password policy constants ///
375 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
376 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
377 define ('PASSWORD_DIGITS', '0123456789');
378 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
380 /// Feature constants ///
381 // Used for plugin_supports() to report features that are, or are not, supported by a module.
383 /** True if module can provide a grade */
384 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
385 /** True if module supports outcomes */
386 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
387 /** True if module supports advanced grading methods */
388 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
390 /** True if module has code to track whether somebody viewed it */
391 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
392 /** True if module has custom completion rules */
393 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
395 /** True if module has no 'view' page (like label) */
396 define('FEATURE_NO_VIEW_LINK', 'viewlink');
397 /** True if module supports outcomes */
398 define('FEATURE_IDNUMBER', 'idnumber');
399 /** True if module supports groups */
400 define('FEATURE_GROUPS', 'groups');
401 /** True if module supports groupings */
402 define('FEATURE_GROUPINGS', 'groupings');
403 /** True if module supports groupmembersonly */
404 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
406 /** Type of module */
407 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
408 /** True if module supports intro editor */
409 define('FEATURE_MOD_INTRO', 'mod_intro');
410 /** True if module has default completion */
411 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
413 define('FEATURE_COMMENT', 'comment');
415 define('FEATURE_RATE', 'rate');
416 /** True if module supports backup/restore of moodle2 format */
417 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
419 /** True if module can show description on course main page */
420 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
422 /** Unspecified module archetype */
423 define('MOD_ARCHETYPE_OTHER', 0);
424 /** Resource-like type module */
425 define('MOD_ARCHETYPE_RESOURCE', 1);
426 /** Assignment module archetype */
427 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
430 * Security token used for allowing access
431 * from external application such as web services.
432 * Scripts do not use any session, performance is relatively
433 * low because we need to load access info in each request.
434 * Scripts are executed in parallel.
436 define('EXTERNAL_TOKEN_PERMANENT', 0);
439 * Security token used for allowing access
440 * of embedded applications, the code is executed in the
441 * active user session. Token is invalidated after user logs out.
442 * Scripts are executed serially - normal session locking is used.
444 define('EXTERNAL_TOKEN_EMBEDDED', 1);
447 * The home page should be the site home
449 define('HOMEPAGE_SITE', 0);
451 * The home page should be the users my page
453 define('HOMEPAGE_MY', 1);
455 * The home page can be chosen by the user
457 define('HOMEPAGE_USER', 2);
460 * Hub directory url (should be moodle.org)
462 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
466 * Moodle.org url (should be moodle.org)
468 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
471 * Moodle mobile app service name
473 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
475 /// PARAMETER HANDLING ////////////////////////////////////////////////////
478 * Returns a particular value for the named variable, taken from
479 * POST or GET. If the parameter doesn't exist then an error is
480 * thrown because we require this variable.
482 * This function should be used to initialise all required values
483 * in a script that are based on parameters. Usually it will be
485 * $id = required_param('id', PARAM_INT);
487 * Please note the $type parameter is now required and the value can not be array.
489 * @param string $parname the name of the page parameter we want
490 * @param string $type expected type of parameter
493 function required_param($parname, $type) {
494 if (func_num_args() != 2 or empty($parname) or empty($type)) {
495 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
497 if (isset($_POST[$parname])) { // POST has precedence
498 $param = $_POST[$parname];
499 } else if (isset($_GET[$parname])) {
500 $param = $_GET[$parname];
502 print_error('missingparam', '', '', $parname);
505 if (is_array($param)) {
506 debugging('Invalid array parameter detected in required_param(): '.$parname);
507 // TODO: switch to fatal error in Moodle 2.3
508 //print_error('missingparam', '', '', $parname);
509 return required_param_array($parname, $type);
512 return clean_param($param, $type);
516 * Returns a particular array value for the named variable, taken from
517 * POST or GET. If the parameter doesn't exist then an error is
518 * thrown because we require this variable.
520 * This function should be used to initialise all required values
521 * in a script that are based on parameters. Usually it will be
523 * $ids = required_param_array('ids', PARAM_INT);
525 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
527 * @param string $parname the name of the page parameter we want
528 * @param string $type expected type of parameter
531 function required_param_array($parname, $type) {
532 if (func_num_args() != 2 or empty($parname) or empty($type)) {
533 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
535 if (isset($_POST[$parname])) { // POST has precedence
536 $param = $_POST[$parname];
537 } else if (isset($_GET[$parname])) {
538 $param = $_GET[$parname];
540 print_error('missingparam', '', '', $parname);
542 if (!is_array($param)) {
543 print_error('missingparam', '', '', $parname);
547 foreach($param as $key=>$value) {
548 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
549 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
552 $result[$key] = clean_param($value, $type);
559 * Returns a particular value for the named variable, taken from
560 * POST or GET, otherwise returning a given default.
562 * This function should be used to initialise all optional values
563 * in a script that are based on parameters. Usually it will be
565 * $name = optional_param('name', 'Fred', PARAM_TEXT);
567 * Please note the $type parameter is now required and the value can not be array.
569 * @param string $parname the name of the page parameter we want
570 * @param mixed $default the default value to return if nothing is found
571 * @param string $type expected type of parameter
574 function optional_param($parname, $default, $type) {
575 if (func_num_args() != 3 or empty($parname) or empty($type)) {
576 throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
578 if (!isset($default)) {
582 if (isset($_POST[$parname])) { // POST has precedence
583 $param = $_POST[$parname];
584 } else if (isset($_GET[$parname])) {
585 $param = $_GET[$parname];
590 if (is_array($param)) {
591 debugging('Invalid array parameter detected in required_param(): '.$parname);
592 // TODO: switch to $default in Moodle 2.3
594 return optional_param_array($parname, $default, $type);
597 return clean_param($param, $type);
601 * Returns a particular array value for the named variable, taken from
602 * POST or GET, otherwise returning a given default.
604 * This function should be used to initialise all optional values
605 * in a script that are based on parameters. Usually it will be
607 * $ids = optional_param('id', array(), PARAM_INT);
609 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
611 * @param string $parname the name of the page parameter we want
612 * @param mixed $default the default value to return if nothing is found
613 * @param string $type expected type of parameter
616 function optional_param_array($parname, $default, $type) {
617 if (func_num_args() != 3 or empty($parname) or empty($type)) {
618 throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
621 if (isset($_POST[$parname])) { // POST has precedence
622 $param = $_POST[$parname];
623 } else if (isset($_GET[$parname])) {
624 $param = $_GET[$parname];
628 if (!is_array($param)) {
629 debugging('optional_param_array() expects array parameters only: '.$parname);
634 foreach($param as $key=>$value) {
635 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
636 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
639 $result[$key] = clean_param($value, $type);
646 * Strict validation of parameter values, the values are only converted
647 * to requested PHP type. Internally it is using clean_param, the values
648 * before and after cleaning must be equal - otherwise
649 * an invalid_parameter_exception is thrown.
650 * Objects and classes are not accepted.
652 * @param mixed $param
653 * @param string $type PARAM_ constant
654 * @param bool $allownull are nulls valid value?
655 * @param string $debuginfo optional debug information
656 * @return mixed the $param value converted to PHP type or invalid_parameter_exception
658 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED
, $debuginfo='') {
659 if (is_null($param)) {
660 if ($allownull == NULL_ALLOWED
) {
663 throw new invalid_parameter_exception($debuginfo);
666 if (is_array($param) or is_object($param)) {
667 throw new invalid_parameter_exception($debuginfo);
670 $cleaned = clean_param($param, $type);
671 if ((string)$param !== (string)$cleaned) {
672 // conversion to string is usually lossless
673 throw new invalid_parameter_exception($debuginfo);
680 * Makes sure array contains only the allowed types,
681 * this function does not validate array key names!
683 * $options = clean_param($options, PARAM_INT);
686 * @param array $param the variable array we are cleaning
687 * @param string $type expected format of param after cleaning.
688 * @param bool $recursive clean recursive arrays
691 function clean_param_array(array $param = null, $type, $recursive = false) {
692 $param = (array)$param; // convert null to empty array
693 foreach ($param as $key => $value) {
694 if (is_array($value)) {
696 $param[$key] = clean_param_array($value, $type, true);
698 throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.');
701 $param[$key] = clean_param($value, $type);
708 * Used by {@link optional_param()} and {@link required_param()} to
709 * clean the variables and/or cast to specific types, based on
712 * $course->format = clean_param($course->format, PARAM_ALPHA);
713 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
716 * @param mixed $param the variable we are cleaning
717 * @param string $type expected format of param after cleaning.
720 function clean_param($param, $type) {
724 if (is_array($param)) {
725 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
726 } else if (is_object($param)) {
727 if (method_exists($param, '__toString')) {
728 $param = $param->__toString();
730 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
735 case PARAM_RAW
: // no cleaning at all
736 $param = fix_utf8($param);
739 case PARAM_RAW_TRIMMED
: // no cleaning, but strip leading and trailing whitespace.
740 $param = fix_utf8($param);
743 case PARAM_CLEAN
: // General HTML cleaning, try to use more specific type if possible
744 // this is deprecated!, please use more specific type instead
745 if (is_numeric($param)) {
748 $param = fix_utf8($param);
749 return clean_text($param); // Sweep for scripts, etc
751 case PARAM_CLEANHTML
: // clean html fragment
752 $param = fix_utf8($param);
753 $param = clean_text($param, FORMAT_HTML
); // Sweep for scripts, etc
757 return (int)$param; // Convert to integer
761 return (float)$param; // Convert to float
763 case PARAM_ALPHA
: // Remove everything not a-z
764 return preg_replace('/[^a-zA-Z]/i', '', $param);
766 case PARAM_ALPHAEXT
: // Remove everything not a-zA-Z_- (originally allowed "/" too)
767 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
769 case PARAM_ALPHANUM
: // Remove everything not a-zA-Z0-9
770 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
772 case PARAM_ALPHANUMEXT
: // Remove everything not a-zA-Z0-9_-
773 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
775 case PARAM_SEQUENCE
: // Remove everything not 0-9,
776 return preg_replace('/[^0-9,]/i', '', $param);
778 case PARAM_BOOL
: // Convert to 1 or 0
779 $tempstr = strtolower($param);
780 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
782 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
785 $param = empty($param) ?
0 : 1;
789 case PARAM_NOTAGS
: // Strip all tags
790 $param = fix_utf8($param);
791 return strip_tags($param);
793 case PARAM_TEXT
: // leave only tags needed for multilang
794 $param = fix_utf8($param);
795 // if the multilang syntax is not correct we strip all tags
796 // because it would break xhtml strict which is required for accessibility standards
797 // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
799 if (strpos($param, '</lang>') !== false) {
800 // old and future mutilang syntax
801 $param = strip_tags($param, '<lang>');
802 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
806 foreach ($matches[0] as $match) {
807 if ($match === '</lang>') {
815 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
826 } else if (strpos($param, '</span>') !== false) {
827 // current problematic multilang syntax
828 $param = strip_tags($param, '<span>');
829 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
833 foreach ($matches[0] as $match) {
834 if ($match === '</span>') {
842 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
854 // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
855 return strip_tags($param);
857 case PARAM_COMPONENT
:
858 // we do not want any guessing here, either the name is correct or not
859 // please note only normalised component names are accepted
860 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
863 if (strpos($param, '__') !== false) {
866 if (strpos($param, 'mod_') === 0) {
867 // module names must not contain underscores because we need to differentiate them from invalid plugin types
868 if (substr_count($param, '_') != 1) {
876 // we do not want any guessing here, either the name is correct or not
877 if (!preg_match('/^[a-z][a-z0-9_]*[a-z0-9]$/', $param)) {
880 if (strpos($param, '__') !== false) {
885 case PARAM_SAFEDIR
: // Remove everything not a-zA-Z0-9_-
886 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
888 case PARAM_SAFEPATH
: // Remove everything not a-zA-Z0-9/_-
889 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
891 case PARAM_FILE
: // Strip all suspicious characters from filename
892 $param = fix_utf8($param);
893 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
894 $param = preg_replace('~\.\.+~', '', $param);
895 if ($param === '.') {
900 case PARAM_PATH
: // Strip all suspicious characters from file path
901 $param = fix_utf8($param);
902 $param = str_replace('\\', '/', $param);
903 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
904 $param = preg_replace('~\.\.+~', '', $param);
905 $param = preg_replace('~//+~', '/', $param);
906 return preg_replace('~/(\./)+~', '/', $param);
908 case PARAM_HOST
: // allow FQDN or IPv4 dotted quad
909 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
910 // match ipv4 dotted quad
911 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
912 // confirm values are ok
916 ||
$match[4] > 255 ) {
917 // hmmm, what kind of dotted quad is this?
920 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
921 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
922 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
924 // all is ok - $param is respected
931 case PARAM_URL
: // allow safe ftp, http, mailto urls
932 $param = fix_utf8($param);
933 include_once($CFG->dirroot
. '/lib/validateurlsyntax.php');
934 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
935 // all is ok, param is respected
937 $param =''; // not really ok
941 case PARAM_LOCALURL
: // allow http absolute, root relative and relative URLs within wwwroot
942 $param = clean_param($param, PARAM_URL
);
943 if (!empty($param)) {
944 if (preg_match(':^/:', $param)) {
945 // root-relative, ok!
946 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot
, '/').'/i',$param)) {
947 // absolute, and matches our wwwroot
949 // relative - let's make sure there are no tricks
950 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
960 $param = trim($param);
961 // PEM formatted strings may contain letters/numbers and the symbols
965 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
966 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
967 list($wholething, $body) = $matches;
968 unset($wholething, $matches);
969 $b64 = clean_param($body, PARAM_BASE64
);
971 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
979 if (!empty($param)) {
980 // PEM formatted strings may contain letters/numbers and the symbols
984 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
987 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY
);
988 // Each line of base64 encoded data must be 64 characters in
989 // length, except for the last line which may be less than (or
990 // equal to) 64 characters long.
991 for ($i=0, $j=count($lines); $i < $j; $i++
) {
993 if (64 < strlen($lines[$i])) {
999 if (64 != strlen($lines[$i])) {
1003 return implode("\n",$lines);
1009 $param = fix_utf8($param);
1010 // Please note it is not safe to use the tag name directly anywhere,
1011 // it must be processed with s(), urlencode() before embedding anywhere.
1012 // remove some nasties
1013 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1014 //convert many whitespace chars into one
1015 $param = preg_replace('/\s+/', ' ', $param);
1016 $textlib = textlib_get_instance();
1017 $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH
);
1021 $param = fix_utf8($param);
1022 $tags = explode(',', $param);
1024 foreach ($tags as $tag) {
1025 $res = clean_param($tag, PARAM_TAG
);
1031 return implode(',', $result);
1036 case PARAM_CAPABILITY
:
1037 if (get_capability_info($param)) {
1043 case PARAM_PERMISSION
:
1044 $param = (int)$param;
1045 if (in_array($param, array(CAP_INHERIT
, CAP_ALLOW
, CAP_PREVENT
, CAP_PROHIBIT
))) {
1052 $param = clean_param($param, PARAM_PLUGIN
);
1053 if (empty($param)) {
1055 } else if (exists_auth_plugin($param)) {
1062 $param = clean_param($param, PARAM_SAFEDIR
);
1063 if (get_string_manager()->translation_exists($param)) {
1066 return ''; // Specified language is not installed or param malformed
1070 $param = clean_param($param, PARAM_PLUGIN
);
1071 if (empty($param)) {
1073 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1075 } else if (!empty($CFG->themedir
) and file_exists("$CFG->themedir/$param/config.php")) {
1078 return ''; // Specified theme is not installed
1081 case PARAM_USERNAME
:
1082 $param = fix_utf8($param);
1083 $param = str_replace(" " , "", $param);
1084 $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919
1085 if (empty($CFG->extendedusernamechars
)) {
1086 // regular expression, eliminate all chars EXCEPT:
1087 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1088 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1093 $param = fix_utf8($param);
1094 if (validate_email($param)) {
1100 case PARAM_STRINGID
:
1101 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1107 case PARAM_TIMEZONE
: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
1108 $param = fix_utf8($param);
1109 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1110 if (preg_match($timezonepattern, $param)) {
1116 default: // throw error, switched parameters in optional_param or another serious problem
1117 print_error("unknownparamtype", '', '', $type);
1122 * Makes sure the data is using valid utf8, invalid characters are discarded.
1124 * Note: this function is not intended for full objects with methods and private properties.
1126 * @param mixed $value
1127 * @return mixed with proper utf-8 encoding
1129 function fix_utf8($value) {
1130 if (is_null($value) or $value === '') {
1133 } else if (is_string($value)) {
1134 if ((string)(int)$value === $value) {
1139 // Note: This is a partial backport of MDL-32586 and MDL-33007 to stable branches.
1140 // Lower error reporting because glibc throws bogus notices.
1141 $olderror = error_reporting();
1142 if ($olderror & E_NOTICE
) {
1143 error_reporting($olderror ^ E_NOTICE
);
1146 // Detect buggy iconv implementations borking results.
1147 static $buggyiconv = null;
1148 if ($buggyiconv === null) {
1149 $buggyiconv = (!function_exists('iconv') or iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1153 if (function_exists('mb_convert_encoding')) {
1154 // Fallback to mbstring if available.
1155 $subst = mb_substitute_character();
1156 mb_substitute_character('');
1157 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1158 mb_substitute_character($subst);
1161 // Return unmodified text, mbstring not available.
1166 // Working iconv, use it normally (with PHP notices disabled)
1167 $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
1170 // Back to original reporting level
1171 if ($olderror & E_NOTICE
) {
1172 error_reporting($olderror);
1177 } else if (is_array($value)) {
1178 foreach ($value as $k=>$v) {
1179 $value[$k] = fix_utf8($v);
1183 } else if (is_object($value)) {
1184 $value = clone($value); // do not modify original
1185 foreach ($value as $k=>$v) {
1186 $value->$k = fix_utf8($v);
1191 // this is some other type, no utf-8 here
1197 * Return true if given value is integer or string with integer value
1199 * @param mixed $value String or Int
1200 * @return bool true if number, false if not
1202 function is_number($value) {
1203 if (is_int($value)) {
1205 } else if (is_string($value)) {
1206 return ((string)(int)$value) === $value;
1213 * Returns host part from url
1214 * @param string $url full url
1215 * @return string host, null if not found
1217 function get_host_from_url($url) {
1218 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1226 * Tests whether anything was returned by text editor
1228 * This function is useful for testing whether something you got back from
1229 * the HTML editor actually contains anything. Sometimes the HTML editor
1230 * appear to be empty, but actually you get back a <br> tag or something.
1232 * @param string $string a string containing HTML.
1233 * @return boolean does the string contain any actual content - that is text,
1234 * images, objects, etc.
1236 function html_is_blank($string) {
1237 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1241 * Set a key in global configuration
1243 * Set a key/value pair in both this session's {@link $CFG} global variable
1244 * and in the 'config' database table for future sessions.
1246 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1247 * In that case it doesn't affect $CFG.
1249 * A NULL value will delete the entry.
1253 * @param string $name the key to set
1254 * @param string $value the value to set (without magic quotes)
1255 * @param string $plugin (optional) the plugin scope, default NULL
1256 * @return bool true or exception
1258 function set_config($name, $value, $plugin=NULL) {
1261 if (empty($plugin)) {
1262 if (!array_key_exists($name, $CFG->config_php_settings
)) {
1263 // So it's defined for this invocation at least
1264 if (is_null($value)) {
1267 $CFG->$name = (string)$value; // settings from db are always strings
1271 if ($DB->get_field('config', 'name', array('name'=>$name))) {
1272 if ($value === null) {
1273 $DB->delete_records('config', array('name'=>$name));
1275 $DB->set_field('config', 'value', $value, array('name'=>$name));
1278 if ($value !== null) {
1279 $config = new stdClass();
1280 $config->name
= $name;
1281 $config->value
= $value;
1282 $DB->insert_record('config', $config, false);
1286 } else { // plugin scope
1287 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1288 if ($value===null) {
1289 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1291 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1294 if ($value !== null) {
1295 $config = new stdClass();
1296 $config->plugin
= $plugin;
1297 $config->name
= $name;
1298 $config->value
= $value;
1299 $DB->insert_record('config_plugins', $config, false);
1308 * Get configuration values from the global config table
1309 * or the config_plugins table.
1311 * If called with one parameter, it will load all the config
1312 * variables for one plugin, and return them as an object.
1314 * If called with 2 parameters it will return a string single
1315 * value or false if the value is not found.
1317 * @param string $plugin full component name
1318 * @param string $name default NULL
1319 * @return mixed hash-like object or single value, return false no config found
1321 function get_config($plugin, $name = NULL) {
1324 // normalise component name
1325 if ($plugin === 'moodle' or $plugin === 'core') {
1329 if (!empty($name)) { // the user is asking for a specific value
1330 if (!empty($plugin)) {
1331 if (isset($CFG->forced_plugin_settings
[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings
[$plugin])) {
1332 // setting forced in config file
1333 return $CFG->forced_plugin_settings
[$plugin][$name];
1335 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1338 if (array_key_exists($name, $CFG->config_php_settings
)) {
1339 // setting force in config file
1340 return $CFG->config_php_settings
[$name];
1342 return $DB->get_field('config', 'value', array('name'=>$name));
1347 // the user is after a recordset
1349 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1350 if (isset($CFG->forced_plugin_settings
[$plugin])) {
1351 foreach($CFG->forced_plugin_settings
[$plugin] as $n=>$v) {
1352 if (is_null($v) or is_array($v) or is_object($v)) {
1353 // we do not want any extra mess here, just real settings that could be saved in db
1354 unset($localcfg[$n]);
1356 //convert to string as if it went through the DB
1357 $localcfg[$n] = (string)$v;
1362 return (object)$localcfg;
1364 return new stdClass();
1368 // this part is not really used any more, but anyway...
1369 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1370 foreach($CFG->config_php_settings
as $n=>$v) {
1371 if (is_null($v) or is_array($v) or is_object($v)) {
1372 // we do not want any extra mess here, just real settings that could be saved in db
1373 unset($localcfg[$n]);
1375 //convert to string as if it went through the DB
1376 $localcfg[$n] = (string)$v;
1379 return (object)$localcfg;
1384 * Removes a key from global configuration
1386 * @param string $name the key to set
1387 * @param string $plugin (optional) the plugin scope
1389 * @return boolean whether the operation succeeded.
1391 function unset_config($name, $plugin=NULL) {
1394 if (empty($plugin)) {
1396 $DB->delete_records('config', array('name'=>$name));
1398 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1405 * Remove all the config variables for a given plugin.
1407 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1408 * @return boolean whether the operation succeeded.
1410 function unset_all_config_for_plugin($plugin) {
1412 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1413 $like = $DB->sql_like('name', '?', true, true, false, '|');
1414 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1415 $DB->delete_records_select('config', $like, $params);
1420 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1422 * All users are verified if they still have the necessary capability.
1424 * @param string $value the value of the config setting.
1425 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1426 * @param bool $include admins, include administrators
1427 * @return array of user objects.
1429 function get_users_from_config($value, $capability, $includeadmins = true) {
1432 if (empty($value) or $value === '$@NONE@$') {
1436 // we have to make sure that users still have the necessary capability,
1437 // it should be faster to fetch them all first and then test if they are present
1438 // instead of validating them one-by-one
1439 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM
), $capability);
1440 if ($includeadmins) {
1441 $admins = get_admins();
1442 foreach ($admins as $admin) {
1443 $users[$admin->id
] = $admin;
1447 if ($value === '$@ALL@$') {
1451 $result = array(); // result in correct order
1452 $allowed = explode(',', $value);
1453 foreach ($allowed as $uid) {
1454 if (isset($users[$uid])) {
1455 $user = $users[$uid];
1456 $result[$user->id
] = $user;
1465 * Invalidates browser caches and cached data in temp
1468 function purge_all_caches() {
1471 reset_text_filters_cache();
1472 js_reset_all_caches();
1473 theme_reset_all_caches();
1474 get_string_manager()->reset_caches();
1476 // purge all other caches: rss, simplepie, etc.
1477 remove_dir($CFG->cachedir
.'', true);
1479 // make sure cache dir is writable, throws exception if not
1480 make_cache_directory('');
1482 // hack: this script may get called after the purifier was initialised,
1483 // but we do not want to verify repeatedly this exists in each call
1484 make_cache_directory('htmlpurifier');
1488 * Get volatile flags
1490 * @param string $type
1491 * @param int $changedsince default null
1492 * @return records array
1494 function get_cache_flags($type, $changedsince=NULL) {
1497 $params = array('type'=>$type, 'expiry'=>time());
1498 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1499 if ($changedsince !== NULL) {
1500 $params['changedsince'] = $changedsince;
1501 $sqlwhere .= " AND timemodified > :changedsince";
1505 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1506 foreach ($flags as $flag) {
1507 $cf[$flag->name
] = $flag->value
;
1514 * Get volatile flags
1516 * @param string $type
1517 * @param string $name
1518 * @param int $changedsince default null
1519 * @return records array
1521 function get_cache_flag($type, $name, $changedsince=NULL) {
1524 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1526 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1527 if ($changedsince !== NULL) {
1528 $params['changedsince'] = $changedsince;
1529 $sqlwhere .= " AND timemodified > :changedsince";
1532 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1536 * Set a volatile flag
1538 * @param string $type the "type" namespace for the key
1539 * @param string $name the key to set
1540 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1541 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1542 * @return bool Always returns true
1544 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1547 $timemodified = time();
1548 if ($expiry===NULL ||
$expiry < $timemodified) {
1549 $expiry = $timemodified +
24 * 60 * 60;
1551 $expiry = (int)$expiry;
1554 if ($value === NULL) {
1555 unset_cache_flag($type,$name);
1559 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE
)) { // this is a potential problem in DEBUG_DEVELOPER
1560 if ($f->value
== $value and $f->expiry
== $expiry and $f->timemodified
== $timemodified) {
1561 return true; //no need to update; helps rcache too
1564 $f->expiry
= $expiry;
1565 $f->timemodified
= $timemodified;
1566 $DB->update_record('cache_flags', $f);
1568 $f = new stdClass();
1569 $f->flagtype
= $type;
1572 $f->expiry
= $expiry;
1573 $f->timemodified
= $timemodified;
1574 $DB->insert_record('cache_flags', $f);
1580 * Removes a single volatile flag
1583 * @param string $type the "type" namespace for the key
1584 * @param string $name the key to set
1587 function unset_cache_flag($type, $name) {
1589 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1594 * Garbage-collect volatile flags
1596 * @return bool Always returns true
1598 function gc_cache_flags() {
1600 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1604 /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
1607 * Refresh user preference cache. This is used most often for $USER
1608 * object that is stored in session, but it also helps with performance in cron script.
1610 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1612 * @param stdClass $user user object, preferences are preloaded into ->preference property
1613 * @param int $cachelifetime cache life time on the current page (ins seconds)
1616 function check_user_preferences_loaded(stdClass
$user, $cachelifetime = 120) {
1618 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1620 if (!isset($user->id
)) {
1621 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1624 if (empty($user->id
) or isguestuser($user->id
)) {
1625 // No permanent storage for not-logged-in users and guest
1626 if (!isset($user->preference
)) {
1627 $user->preference
= array();
1634 if (isset($loadedusers[$user->id
]) and isset($user->preference
) and isset($user->preference
['_lastloaded'])) {
1635 // Already loaded at least once on this page. Are we up to date?
1636 if ($user->preference
['_lastloaded'] +
$cachelifetime > $timenow) {
1637 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1640 } else if (!get_cache_flag('userpreferenceschanged', $user->id
, $user->preference
['_lastloaded'])) {
1641 // no change since the lastcheck on this page
1642 $user->preference
['_lastloaded'] = $timenow;
1647 // OK, so we have to reload all preferences
1648 $loadedusers[$user->id
] = true;
1649 $user->preference
= $DB->get_records_menu('user_preferences', array('userid'=>$user->id
), '', 'name,value'); // All values
1650 $user->preference
['_lastloaded'] = $timenow;
1654 * Called from set/delete_user_preferences, so that the prefs can
1655 * be correctly reloaded in different sessions.
1657 * NOTE: internal function, do not call from other code.
1659 * @param integer $userid the user whose prefs were changed.
1662 function mark_user_preferences_changed($userid) {
1665 if (empty($userid) or isguestuser($userid)) {
1666 // no cache flags for guest and not-logged-in users
1670 set_cache_flag('userpreferenceschanged', $userid, 1, time() +
$CFG->sessiontimeout
);
1674 * Sets a preference for the specified user.
1676 * If user object submitted, 'preference' property contains the preferences cache.
1678 * @param string $name The key to set as preference for the specified user
1679 * @param string $value The value to set for the $name key in the specified user's record,
1680 * null means delete current value
1681 * @param stdClass|int $user A moodle user object or id, null means current user
1682 * @return bool always true or exception
1684 function set_user_preference($name, $value, $user = null) {
1687 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1688 throw new coding_exception('Invalid preference name in set_user_preference() call');
1691 if (is_null($value)) {
1692 // null means delete current
1693 return unset_user_preference($name, $user);
1694 } else if (is_object($value)) {
1695 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1696 } else if (is_array($value)) {
1697 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1699 $value = (string)$value;
1700 if (textlib
::strlen($value) > 1333) { //value column maximum length is 1333 characters
1701 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1704 if (is_null($user)) {
1706 } else if (isset($user->id
)) {
1707 // $user is valid object
1708 } else if (is_numeric($user)) {
1709 $user = (object)array('id'=>(int)$user);
1711 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1714 check_user_preferences_loaded($user);
1716 if (empty($user->id
) or isguestuser($user->id
)) {
1717 // no permanent storage for not-logged-in users and guest
1718 $user->preference
[$name] = $value;
1722 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id
, 'name'=>$name))) {
1723 if ($preference->value
=== $value and isset($user->preference
[$name]) and $user->preference
[$name] === $value) {
1724 // preference already set to this value
1727 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id
));
1730 $preference = new stdClass();
1731 $preference->userid
= $user->id
;
1732 $preference->name
= $name;
1733 $preference->value
= $value;
1734 $DB->insert_record('user_preferences', $preference);
1737 // update value in cache
1738 $user->preference
[$name] = $value;
1740 // set reload flag for other sessions
1741 mark_user_preferences_changed($user->id
);
1747 * Sets a whole array of preferences for the current user
1749 * If user object submitted, 'preference' property contains the preferences cache.
1751 * @param array $prefarray An array of key/value pairs to be set
1752 * @param stdClass|int $user A moodle user object or id, null means current user
1753 * @return bool always true or exception
1755 function set_user_preferences(array $prefarray, $user = null) {
1756 foreach ($prefarray as $name => $value) {
1757 set_user_preference($name, $value, $user);
1763 * Unsets a preference completely by deleting it from the database
1765 * If user object submitted, 'preference' property contains the preferences cache.
1767 * @param string $name The key to unset as preference for the specified user
1768 * @param stdClass|int $user A moodle user object or id, null means current user
1769 * @return bool always true or exception
1771 function unset_user_preference($name, $user = null) {
1774 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1775 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1778 if (is_null($user)) {
1780 } else if (isset($user->id
)) {
1781 // $user is valid object
1782 } else if (is_numeric($user)) {
1783 $user = (object)array('id'=>(int)$user);
1785 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1788 check_user_preferences_loaded($user);
1790 if (empty($user->id
) or isguestuser($user->id
)) {
1791 // no permanent storage for not-logged-in user and guest
1792 unset($user->preference
[$name]);
1797 $DB->delete_records('user_preferences', array('userid'=>$user->id
, 'name'=>$name));
1799 // delete the preference from cache
1800 unset($user->preference
[$name]);
1802 // set reload flag for other sessions
1803 mark_user_preferences_changed($user->id
);
1809 * Used to fetch user preference(s)
1811 * If no arguments are supplied this function will return
1812 * all of the current user preferences as an array.
1814 * If a name is specified then this function
1815 * attempts to return that particular preference value. If
1816 * none is found, then the optional value $default is returned,
1819 * If user object submitted, 'preference' property contains the preferences cache.
1821 * @param string $name Name of the key to use in finding a preference value
1822 * @param mixed $default Value to be returned if the $name key is not set in the user preferences
1823 * @param stdClass|int $user A moodle user object or id, null means current user
1824 * @return mixed string value or default
1826 function get_user_preferences($name = null, $default = null, $user = null) {
1829 if (is_null($name)) {
1831 } else if (is_numeric($name) or $name === '_lastloaded') {
1832 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1835 if (is_null($user)) {
1837 } else if (isset($user->id
)) {
1838 // $user is valid object
1839 } else if (is_numeric($user)) {
1840 $user = (object)array('id'=>(int)$user);
1842 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1845 check_user_preferences_loaded($user);
1848 return $user->preference
; // All values
1849 } else if (isset($user->preference
[$name])) {
1850 return $user->preference
[$name]; // The single string value
1852 return $default; // Default value (null if not specified)
1856 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1859 * Given date parts in user time produce a GMT timestamp.
1861 * @todo Finish documenting this function
1862 * @param int $year The year part to create timestamp of
1863 * @param int $month The month part to create timestamp of
1864 * @param int $day The day part to create timestamp of
1865 * @param int $hour The hour part to create timestamp of
1866 * @param int $minute The minute part to create timestamp of
1867 * @param int $second The second part to create timestamp of
1868 * @param mixed $timezone Timezone modifier, if 99 then use default user's timezone
1869 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1870 * applied only if timezone is 99 or string.
1871 * @return int timestamp
1873 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1875 //save input timezone, required for dst offset check.
1876 $passedtimezone = $timezone;
1878 $timezone = get_user_timezone_offset($timezone);
1880 if (abs($timezone) > 13) { //server time
1881 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1883 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1884 $time = usertime($time, $timezone);
1886 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1887 if ($applydst && ((99 == $passedtimezone) ||
!is_numeric($passedtimezone))) {
1888 $time -= dst_offset_on($time, $passedtimezone);
1897 * Format a date/time (seconds) as weeks, days, hours etc as needed
1899 * Given an amount of time in seconds, returns string
1900 * formatted nicely as weeks, days, hours etc as needed
1906 * @param int $totalsecs Time in seconds
1907 * @param object $str Should be a time object
1908 * @return string A nicely formatted date/time string
1910 function format_time($totalsecs, $str=NULL) {
1912 $totalsecs = abs($totalsecs);
1914 if (!$str) { // Create the str structure the slow way
1915 $str = new stdClass();
1916 $str->day
= get_string('day');
1917 $str->days
= get_string('days');
1918 $str->hour
= get_string('hour');
1919 $str->hours
= get_string('hours');
1920 $str->min
= get_string('min');
1921 $str->mins
= get_string('mins');
1922 $str->sec
= get_string('sec');
1923 $str->secs
= get_string('secs');
1924 $str->year
= get_string('year');
1925 $str->years
= get_string('years');
1929 $years = floor($totalsecs/YEARSECS
);
1930 $remainder = $totalsecs - ($years*YEARSECS
);
1931 $days = floor($remainder/DAYSECS
);
1932 $remainder = $totalsecs - ($days*DAYSECS
);
1933 $hours = floor($remainder/HOURSECS
);
1934 $remainder = $remainder - ($hours*HOURSECS
);
1935 $mins = floor($remainder/MINSECS
);
1936 $secs = $remainder - ($mins*MINSECS
);
1938 $ss = ($secs == 1) ?
$str->sec
: $str->secs
;
1939 $sm = ($mins == 1) ?
$str->min
: $str->mins
;
1940 $sh = ($hours == 1) ?
$str->hour
: $str->hours
;
1941 $sd = ($days == 1) ?
$str->day
: $str->days
;
1942 $sy = ($years == 1) ?
$str->year
: $str->years
;
1950 if ($years) $oyears = $years .' '. $sy;
1951 if ($days) $odays = $days .' '. $sd;
1952 if ($hours) $ohours = $hours .' '. $sh;
1953 if ($mins) $omins = $mins .' '. $sm;
1954 if ($secs) $osecs = $secs .' '. $ss;
1956 if ($years) return trim($oyears .' '. $odays);
1957 if ($days) return trim($odays .' '. $ohours);
1958 if ($hours) return trim($ohours .' '. $omins);
1959 if ($mins) return trim($omins .' '. $osecs);
1960 if ($secs) return $osecs;
1961 return get_string('now');
1965 * Returns a formatted string that represents a date in user time
1967 * Returns a formatted string that represents a date in user time
1968 * <b>WARNING: note that the format is for strftime(), not date().</b>
1969 * Because of a bug in most Windows time libraries, we can't use
1970 * the nicer %e, so we have to use %d which has leading zeroes.
1971 * A lot of the fuss in the function is just getting rid of these leading
1972 * zeroes as efficiently as possible.
1974 * If parameter fixday = true (default), then take off leading
1975 * zero from %d, else maintain it.
1977 * @param int $date the timestamp in UTC, as obtained from the database.
1978 * @param string $format strftime format. You should probably get this using
1979 * get_string('strftime...', 'langconfig');
1980 * @param mixed $timezone by default, uses the user's time zone. if numeric and
1981 * not 99 then daylight saving will not be added.
1982 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1983 * If false then the leading zero is maintained.
1984 * @return string the formatted date/time.
1986 function userdate($date, $format = '', $timezone = 99, $fixday = true) {
1990 if (empty($format)) {
1991 $format = get_string('strftimedaydatetime', 'langconfig');
1994 if (!empty($CFG->nofixday
)) { // Config.php can force %d not to be fixed.
1996 } else if ($fixday) {
1997 $formatnoday = str_replace('%d', 'DD', $format);
1998 $fixday = ($formatnoday != $format);
2001 //add daylight saving offset for string timezones only, as we can't get dst for
2002 //float values. if timezone is 99 (user default timezone), then try update dst.
2003 if ((99 == $timezone) ||
!is_numeric($timezone)) {
2004 $date +
= dst_offset_on($date, $timezone);
2007 $timezone = get_user_timezone_offset($timezone);
2009 if (abs($timezone) > 13) { /// Server time
2011 $datestring = strftime($formatnoday, $date);
2012 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
2013 $datestring = str_replace('DD', $daystring, $datestring);
2015 $datestring = strftime($format, $date);
2018 $date +
= (int)($timezone * 3600);
2020 $datestring = gmstrftime($formatnoday, $date);
2021 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
2022 $datestring = str_replace('DD', $daystring, $datestring);
2024 $datestring = gmstrftime($format, $date);
2028 /// If we are running under Windows convert from windows encoding to UTF-8
2029 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
2031 if ($CFG->ostype
== 'WINDOWS') {
2032 if ($localewincharset = get_string('localewincharset', 'langconfig')) {
2033 $textlib = textlib_get_instance();
2034 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
2042 * Given a $time timestamp in GMT (seconds since epoch),
2043 * returns an array that represents the date in user time
2045 * @todo Finish documenting this function
2047 * @param int $time Timestamp in GMT
2048 * @param mixed $timezone offset time with timezone, if float and not 99, then no
2049 * dst offset is applyed
2050 * @return array An array that represents the date in user time
2052 function usergetdate($time, $timezone=99) {
2054 //save input timezone, required for dst offset check.
2055 $passedtimezone = $timezone;
2057 $timezone = get_user_timezone_offset($timezone);
2059 if (abs($timezone) > 13) { // Server time
2060 return getdate($time);
2063 //add daylight saving offset for string timezones only, as we can't get dst for
2064 //float values. if timezone is 99 (user default timezone), then try update dst.
2065 if ($passedtimezone == 99 ||
!is_numeric($passedtimezone)) {
2066 $time +
= dst_offset_on($time, $passedtimezone);
2069 $time +
= intval((float)$timezone * HOURSECS
);
2071 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2073 //be careful to ensure the returned array matches that produced by getdate() above
2076 $getdate['weekday'],
2083 $getdate['minutes'],
2085 ) = explode('_', $datestring);
2087 // set correct datatype to match with getdate()
2088 $getdate['seconds'] = (int)$getdate['seconds'];
2089 $getdate['yday'] = (int)$getdate['yday'] - 1; // gettime returns 0 through 365
2090 $getdate['year'] = (int)$getdate['year'];
2091 $getdate['mon'] = (int)$getdate['mon'];
2092 $getdate['wday'] = (int)$getdate['wday'];
2093 $getdate['mday'] = (int)$getdate['mday'];
2094 $getdate['hours'] = (int)$getdate['hours'];
2095 $getdate['minutes'] = (int)$getdate['minutes'];
2100 * Given a GMT timestamp (seconds since epoch), offsets it by
2101 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2104 * @param int $date Timestamp in GMT
2105 * @param float $timezone
2108 function usertime($date, $timezone=99) {
2110 $timezone = get_user_timezone_offset($timezone);
2112 if (abs($timezone) > 13) {
2115 return $date - (int)($timezone * HOURSECS
);
2119 * Given a time, return the GMT timestamp of the most recent midnight
2120 * for the current user.
2122 * @param int $date Timestamp in GMT
2123 * @param float $timezone Defaults to user's timezone
2124 * @return int Returns a GMT timestamp
2126 function usergetmidnight($date, $timezone=99) {
2128 $userdate = usergetdate($date, $timezone);
2130 // Time of midnight of this user's day, in GMT
2131 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2136 * Returns a string that prints the user's timezone
2138 * @param float $timezone The user's timezone
2141 function usertimezone($timezone=99) {
2143 $tz = get_user_timezone($timezone);
2145 if (!is_float($tz)) {
2149 if(abs($tz) > 13) { // Server time
2150 return get_string('serverlocaltime');
2153 if($tz == intval($tz)) {
2154 // Don't show .0 for whole hours
2171 * Returns a float which represents the user's timezone difference from GMT in hours
2172 * Checks various settings and picks the most dominant of those which have a value
2176 * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
2179 function get_user_timezone_offset($tz = 99) {
2183 $tz = get_user_timezone($tz);
2185 if (is_float($tz)) {
2188 $tzrecord = get_timezone_record($tz);
2189 if (empty($tzrecord)) {
2192 return (float)$tzrecord->gmtoff
/ HOURMINS
;
2197 * Returns an int which represents the systems's timezone difference from GMT in seconds
2200 * @param mixed $tz timezone
2201 * @return int if found, false is timezone 99 or error
2203 function get_timezone_offset($tz) {
2210 if (is_numeric($tz)) {
2211 return intval($tz * 60*60);
2214 if (!$tzrecord = get_timezone_record($tz)) {
2217 return intval($tzrecord->gmtoff
* 60);
2221 * Returns a float or a string which denotes the user's timezone
2222 * 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)
2223 * means that for this timezone there are also DST rules to be taken into account
2224 * Checks various settings and picks the most dominant of those which have a value
2228 * @param mixed $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
2231 function get_user_timezone($tz = 99) {
2236 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
2237 isset($USER->timezone
) ?
$USER->timezone
: 99,
2238 isset($CFG->timezone
) ?
$CFG->timezone
: 99,
2243 while(($tz == '' ||
$tz == 99 ||
$tz == NULL) && $next = each($timezones)) {
2244 $tz = $next['value'];
2247 return is_numeric($tz) ?
(float) $tz : $tz;
2251 * Returns cached timezone record for given $timezonename
2255 * @param string $timezonename
2256 * @return mixed timezonerecord object or false
2258 function get_timezone_record($timezonename) {
2260 static $cache = NULL;
2262 if ($cache === NULL) {
2266 if (isset($cache[$timezonename])) {
2267 return $cache[$timezonename];
2270 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2271 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE
);
2275 * Build and store the users Daylight Saving Time (DST) table
2280 * @param mixed $from_year Start year for the table, defaults to 1971
2281 * @param mixed $to_year End year for the table, defaults to 2035
2282 * @param mixed $strtimezone, if null or 99 then user's default timezone is used
2285 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2286 global $CFG, $SESSION, $DB;
2288 $usertz = get_user_timezone($strtimezone);
2290 if (is_float($usertz)) {
2291 // Trivial timezone, no DST
2295 if (!empty($SESSION->dst_offsettz
) && $SESSION->dst_offsettz
!= $usertz) {
2296 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2297 unset($SESSION->dst_offsets
);
2298 unset($SESSION->dst_range
);
2301 if (!empty($SESSION->dst_offsets
) && empty($from_year) && empty($to_year)) {
2302 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2303 // This will be the return path most of the time, pretty light computationally
2307 // Reaching here means we either need to extend our table or create it from scratch
2309 // Remember which TZ we calculated these changes for
2310 $SESSION->dst_offsettz
= $usertz;
2312 if(empty($SESSION->dst_offsets
)) {
2313 // If we 're creating from scratch, put the two guard elements in there
2314 $SESSION->dst_offsets
= array(1 => NULL, 0 => NULL);
2316 if(empty($SESSION->dst_range
)) {
2317 // If creating from scratch
2318 $from = max((empty($from_year) ?
intval(date('Y')) - 3 : $from_year), 1971);
2319 $to = min((empty($to_year) ?
intval(date('Y')) +
3 : $to_year), 2035);
2321 // Fill in the array with the extra years we need to process
2322 $yearstoprocess = array();
2323 for($i = $from; $i <= $to; ++
$i) {
2324 $yearstoprocess[] = $i;
2327 // Take note of which years we have processed for future calls
2328 $SESSION->dst_range
= array($from, $to);
2331 // If needing to extend the table, do the same
2332 $yearstoprocess = array();
2334 $from = max((empty($from_year) ?
$SESSION->dst_range
[0] : $from_year), 1971);
2335 $to = min((empty($to_year) ?
$SESSION->dst_range
[1] : $to_year), 2035);
2337 if($from < $SESSION->dst_range
[0]) {
2338 // Take note of which years we need to process and then note that we have processed them for future calls
2339 for($i = $from; $i < $SESSION->dst_range
[0]; ++
$i) {
2340 $yearstoprocess[] = $i;
2342 $SESSION->dst_range
[0] = $from;
2344 if($to > $SESSION->dst_range
[1]) {
2345 // Take note of which years we need to process and then note that we have processed them for future calls
2346 for($i = $SESSION->dst_range
[1] +
1; $i <= $to; ++
$i) {
2347 $yearstoprocess[] = $i;
2349 $SESSION->dst_range
[1] = $to;
2353 if(empty($yearstoprocess)) {
2354 // This means that there was a call requesting a SMALLER range than we have already calculated
2358 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2359 // Also, the array is sorted in descending timestamp order!
2363 static $presets_cache = array();
2364 if (!isset($presets_cache[$usertz])) {
2365 $presets_cache[$usertz] = $DB->get_records('timezone', array('name'=>$usertz), 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, std_startday, std_weekday, std_skipweeks, std_time');
2367 if(empty($presets_cache[$usertz])) {
2371 // Remove ending guard (first element of the array)
2372 reset($SESSION->dst_offsets
);
2373 unset($SESSION->dst_offsets
[key($SESSION->dst_offsets
)]);
2375 // Add all required change timestamps
2376 foreach($yearstoprocess as $y) {
2377 // Find the record which is in effect for the year $y
2378 foreach($presets_cache[$usertz] as $year => $preset) {
2384 $changes = dst_changes_for_year($y, $preset);
2386 if($changes === NULL) {
2389 if($changes['dst'] != 0) {
2390 $SESSION->dst_offsets
[$changes['dst']] = $preset->dstoff
* MINSECS
;
2392 if($changes['std'] != 0) {
2393 $SESSION->dst_offsets
[$changes['std']] = 0;
2397 // Put in a guard element at the top
2398 $maxtimestamp = max(array_keys($SESSION->dst_offsets
));
2399 $SESSION->dst_offsets
[($maxtimestamp + DAYSECS
)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2402 krsort($SESSION->dst_offsets
);
2408 * Calculates the required DST change and returns a Timestamp Array
2412 * @param mixed $year Int or String Year to focus on
2413 * @param object $timezone Instatiated Timezone object
2414 * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy
2416 function dst_changes_for_year($year, $timezone) {
2418 if($timezone->dst_startday
== 0 && $timezone->dst_weekday
== 0 && $timezone->std_startday
== 0 && $timezone->std_weekday
== 0) {
2422 $monthdaydst = find_day_in_month($timezone->dst_startday
, $timezone->dst_weekday
, $timezone->dst_month
, $year);
2423 $monthdaystd = find_day_in_month($timezone->std_startday
, $timezone->std_weekday
, $timezone->std_month
, $year);
2425 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time
);
2426 list($std_hour, $std_min) = explode(':', $timezone->std_time
);
2428 $timedst = make_timestamp($year, $timezone->dst_month
, $monthdaydst, 0, 0, 0, 99, false);
2429 $timestd = make_timestamp($year, $timezone->std_month
, $monthdaystd, 0, 0, 0, 99, false);
2431 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2432 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2433 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2435 $timedst +
= $dst_hour * HOURSECS +
$dst_min * MINSECS
;
2436 $timestd +
= $std_hour * HOURSECS +
$std_min * MINSECS
;
2438 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2442 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2443 * - Note: Daylight saving only works for string timezones and not for float.
2446 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2447 * @param mixed $strtimezone timezone for which offset is expected, if 99 or null
2448 * then user's default timezone is used.
2451 function dst_offset_on($time, $strtimezone = NULL) {
2454 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) ||
empty($SESSION->dst_offsets
)) {
2458 reset($SESSION->dst_offsets
);
2459 while(list($from, $offset) = each($SESSION->dst_offsets
)) {
2460 if($from <= $time) {
2465 // This is the normal return path
2466 if($offset !== NULL) {
2470 // Reaching this point means we haven't calculated far enough, do it now:
2471 // Calculate extra DST changes if needed and recurse. The recursion always
2472 // moves toward the stopping condition, so will always end.
2475 // We need a year smaller than $SESSION->dst_range[0]
2476 if($SESSION->dst_range
[0] == 1971) {
2479 calculate_user_dst_table($SESSION->dst_range
[0] - 5, NULL, $strtimezone);
2480 return dst_offset_on($time, $strtimezone);
2483 // We need a year larger than $SESSION->dst_range[1]
2484 if($SESSION->dst_range
[1] == 2035) {
2487 calculate_user_dst_table(NULL, $SESSION->dst_range
[1] +
5, $strtimezone);
2488 return dst_offset_on($time, $strtimezone);
2495 * @todo Document what this function does
2496 * @param int $startday
2497 * @param int $weekday
2502 function find_day_in_month($startday, $weekday, $month, $year) {
2504 $daysinmonth = days_in_month($month, $year);
2506 if($weekday == -1) {
2507 // Don't care about weekday, so return:
2508 // abs($startday) if $startday != -1
2509 // $daysinmonth otherwise
2510 return ($startday == -1) ?
$daysinmonth : abs($startday);
2513 // From now on we 're looking for a specific weekday
2515 // Give "end of month" its actual value, since we know it
2516 if($startday == -1) {
2517 $startday = -1 * $daysinmonth;
2520 // Starting from day $startday, the sign is the direction
2524 $startday = abs($startday);
2525 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2527 // This is the last such weekday of the month
2528 $lastinmonth = $daysinmonth +
$weekday - $lastmonthweekday;
2529 if($lastinmonth > $daysinmonth) {
2533 // Find the first such weekday <= $startday
2534 while($lastinmonth > $startday) {
2538 return $lastinmonth;
2543 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2545 $diff = $weekday - $indexweekday;
2550 // This is the first such weekday of the month equal to or after $startday
2551 $firstfromindex = $startday +
$diff;
2553 return $firstfromindex;
2559 * Calculate the number of days in a given month
2561 * @param int $month The month whose day count is sought
2562 * @param int $year The year of the month whose day count is sought
2565 function days_in_month($month, $year) {
2566 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2570 * Calculate the position in the week of a specific calendar day
2572 * @param int $day The day of the date whose position in the week is sought
2573 * @param int $month The month of the date whose position in the week is sought
2574 * @param int $year The year of the date whose position in the week is sought
2577 function dayofweek($day, $month, $year) {
2578 // I wonder if this is any different from
2579 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2580 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2583 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2586 * Returns full login url.
2588 * @return string login url
2590 function get_login_url() {
2593 $url = "$CFG->wwwroot/login/index.php";
2595 if (!empty($CFG->loginhttps
)) {
2596 $url = str_replace('http:', 'https:', $url);
2603 * This function checks that the current user is logged in and has the
2604 * required privileges
2606 * This function checks that the current user is logged in, and optionally
2607 * whether they are allowed to be in a particular course and view a particular
2609 * If they are not logged in, then it redirects them to the site login unless
2610 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2611 * case they are automatically logged in as guests.
2612 * If $courseid is given and the user is not enrolled in that course then the
2613 * user is redirected to the course enrolment page.
2614 * If $cm is given and the course module is hidden and the user is not a teacher
2615 * in the course then the user is redirected to the course home page.
2617 * When $cm parameter specified, this function sets page layout to 'module'.
2618 * You need to change it manually later if some other layout needed.
2620 * @param mixed $courseorid id of the course or course object
2621 * @param bool $autologinguest default true
2622 * @param object $cm course module object
2623 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2624 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2625 * in order to keep redirects working properly. MDL-14495
2626 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2627 * @return mixed Void, exit, and die depending on path
2629 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2630 global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT;
2632 // setup global $COURSE, themes, language and locale
2633 if (!empty($courseorid)) {
2634 if (is_object($courseorid)) {
2635 $course = $courseorid;
2636 } else if ($courseorid == SITEID
) {
2637 $course = clone($SITE);
2639 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST
);
2642 if ($cm->course
!= $course->id
) {
2643 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2645 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2646 if (!($cm instanceof cm_info
)) {
2647 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2648 // db queries so this is not really a performance concern, however it is obviously
2649 // better if you use get_fast_modinfo to get the cm before calling this.
2650 $modinfo = get_fast_modinfo($course);
2651 $cm = $modinfo->get_cm($cm->id
);
2653 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2654 $PAGE->set_pagelayout('incourse');
2656 $PAGE->set_course($course); // set's up global $COURSE
2659 // do not touch global $COURSE via $PAGE->set_course(),
2660 // the reasons is we need to be able to call require_login() at any time!!
2663 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2667 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2668 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2669 // risk leading the user back to the AJAX request URL.
2670 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT
) {
2671 $setwantsurltome = false;
2674 // If the user is not even logged in yet then make sure they are
2675 if (!isloggedin()) {
2676 if ($autologinguest and !empty($CFG->guestloginbutton
) and !empty($CFG->autologinguests
)) {
2677 if (!$guest = get_complete_user_data('id', $CFG->siteguest
)) {
2678 // misconfigured site guest, just redirect to login page
2679 redirect(get_login_url());
2680 exit; // never reached
2682 $lang = isset($SESSION->lang
) ?
$SESSION->lang
: $CFG->lang
;
2683 complete_user_login($guest);
2684 $USER->autologinguest
= true;
2685 $SESSION->lang
= $lang;
2687 //NOTE: $USER->site check was obsoleted by session test cookie,
2688 // $USER->confirmed test is in login/index.php
2689 if ($preventredirect) {
2690 throw new require_login_exception('You are not logged in');
2693 if ($setwantsurltome) {
2694 // TODO: switch to PAGE->url
2695 $SESSION->wantsurl
= $FULLME;
2697 if (!empty($_SERVER['HTTP_REFERER'])) {
2698 $SESSION->fromurl
= $_SERVER['HTTP_REFERER'];
2700 redirect(get_login_url());
2701 exit; // never reached
2705 // loginas as redirection if needed
2706 if ($course->id
!= SITEID
and session_is_loggedinas()) {
2707 if ($USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
2708 if ($USER->loginascontext
->instanceid
!= $course->id
) {
2709 print_error('loginasonecourse', '', $CFG->wwwroot
.'/course/view.php?id='.$USER->loginascontext
->instanceid
);
2714 // check whether the user should be changing password (but only if it is REALLY them)
2715 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2716 $userauth = get_auth_plugin($USER->auth
);
2717 if ($userauth->can_change_password() and !$preventredirect) {
2718 if ($setwantsurltome) {
2719 $SESSION->wantsurl
= $FULLME;
2721 if ($changeurl = $userauth->change_password_url()) {
2722 //use plugin custom url
2723 redirect($changeurl);
2725 //use moodle internal method
2726 if (empty($CFG->loginhttps
)) {
2727 redirect($CFG->wwwroot
.'/login/change_password.php');
2729 $wwwroot = str_replace('http:','https:', $CFG->wwwroot
);
2730 redirect($wwwroot .'/login/change_password.php');
2734 print_error('nopasswordchangeforced', 'auth');
2738 // Check that the user account is properly set up
2739 if (user_not_fully_set_up($USER)) {
2740 if ($preventredirect) {
2741 throw new require_login_exception('User not fully set-up');
2743 if ($setwantsurltome) {
2744 $SESSION->wantsurl
= $FULLME;
2746 redirect($CFG->wwwroot
.'/user/edit.php?id='. $USER->id
.'&course='. SITEID
);
2749 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2752 // Do not bother admins with any formalities
2753 if (is_siteadmin()) {
2754 //set accesstime or the user will appear offline which messes up messaging
2755 user_accesstime_log($course->id
);
2759 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2760 if (!$USER->policyagreed
and !is_siteadmin()) {
2761 if (!empty($CFG->sitepolicy
) and !isguestuser()) {
2762 if ($preventredirect) {
2763 throw new require_login_exception('Policy not agreed');
2765 if ($setwantsurltome) {
2766 $SESSION->wantsurl
= $FULLME;
2768 redirect($CFG->wwwroot
.'/user/policy.php');
2769 } else if (!empty($CFG->sitepolicyguest
) and isguestuser()) {
2770 if ($preventredirect) {
2771 throw new require_login_exception('Policy not agreed');
2773 if ($setwantsurltome) {
2774 $SESSION->wantsurl
= $FULLME;
2776 redirect($CFG->wwwroot
.'/user/policy.php');
2780 // Fetch the system context, the course context, and prefetch its child contexts
2781 $sysctx = get_context_instance(CONTEXT_SYSTEM
);
2782 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
, MUST_EXIST
);
2784 $cmcontext = get_context_instance(CONTEXT_MODULE
, $cm->id
, MUST_EXIST
);
2789 // If the site is currently under maintenance, then print a message
2790 if (!empty($CFG->maintenance_enabled
) and !has_capability('moodle/site:config', $sysctx)) {
2791 if ($preventredirect) {
2792 throw new require_login_exception('Maintenance in progress');
2795 print_maintenance_message();
2798 // make sure the course itself is not hidden
2799 if ($course->id
== SITEID
) {
2800 // frontpage can not be hidden
2802 if (is_role_switched($course->id
)) {
2803 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2805 if (!$course->visible
and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2806 // originally there was also test of parent category visibility,
2807 // BUT is was very slow in complex queries involving "my courses"
2808 // now it is also possible to simply hide all courses user is not enrolled in :-)
2809 if ($preventredirect) {
2810 throw new require_login_exception('Course is hidden');
2812 // We need to override the navigation URL as the course won't have
2813 // been added to the navigation and thus the navigation will mess up
2814 // when trying to find it.
2815 navigation_node
::override_active_url(new moodle_url('/'));
2816 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
2821 // is the user enrolled?
2822 if ($course->id
== SITEID
) {
2823 // everybody is enrolled on the frontpage
2826 if (session_is_loggedinas()) {
2827 // Make sure the REAL person can access this course first
2828 $realuser = session_get_realuser();
2829 if (!is_enrolled($coursecontext, $realuser->id
, '', true) and !is_viewing($coursecontext, $realuser->id
) and !is_siteadmin($realuser->id
)) {
2830 if ($preventredirect) {
2831 throw new require_login_exception('Invalid course login-as access');
2833 echo $OUTPUT->header();
2834 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot
.'/');
2840 if (is_role_switched($course->id
)) {
2841 // ok, user had to be inside this course before the switch
2844 } else if (is_viewing($coursecontext, $USER)) {
2845 // ok, no need to mess with enrol
2849 if (isset($USER->enrol
['enrolled'][$course->id
])) {
2850 if ($USER->enrol
['enrolled'][$course->id
] > time()) {
2852 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2853 unset($USER->enrol
['tempguest'][$course->id
]);
2854 remove_temp_course_roles($coursecontext);
2858 unset($USER->enrol
['enrolled'][$course->id
]);
2861 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2862 if ($USER->enrol
['tempguest'][$course->id
] == 0) {
2864 } else if ($USER->enrol
['tempguest'][$course->id
] > time()) {
2868 unset($USER->enrol
['tempguest'][$course->id
]);
2869 remove_temp_course_roles($coursecontext);
2876 $until = enrol_get_enrolment_end($coursecontext->instanceid
, $USER->id
);
2877 if ($until !== false) {
2878 // active participants may always access, a timestamp in the future, 0 (always) or false.
2880 $until = ENROL_MAX_TIMESTAMP
;
2882 $USER->enrol
['enrolled'][$course->id
] = $until;
2886 $instances = $DB->get_records('enrol', array('courseid'=>$course->id
, 'status'=>ENROL_INSTANCE_ENABLED
), 'sortorder, id ASC');
2887 $enrols = enrol_get_plugins(true);
2888 // first ask all enabled enrol instances in course if they want to auto enrol user
2889 foreach($instances as $instance) {
2890 if (!isset($enrols[$instance->enrol
])) {
2893 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2894 $until = $enrols[$instance->enrol
]->try_autoenrol($instance);
2895 if ($until !== false) {
2897 $until = ENROL_MAX_TIMESTAMP
;
2899 $USER->enrol
['enrolled'][$course->id
] = $until;
2904 // if not enrolled yet try to gain temporary guest access
2906 foreach($instances as $instance) {
2907 if (!isset($enrols[$instance->enrol
])) {
2910 // Get a duration for the guest access, a timestamp in the future or false.
2911 $until = $enrols[$instance->enrol
]->try_guestaccess($instance);
2912 if ($until !== false and $until > time()) {
2913 $USER->enrol
['tempguest'][$course->id
] = $until;
2924 if ($preventredirect) {
2925 throw new require_login_exception('Not enrolled');
2927 if ($setwantsurltome) {
2928 $SESSION->wantsurl
= $FULLME;
2930 redirect($CFG->wwwroot
.'/enrol/index.php?id='. $course->id
);
2934 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
2935 // conditional availability, etc
2936 if ($cm && !$cm->uservisible
) {
2937 if ($preventredirect) {
2938 throw new require_login_exception('Activity is hidden');
2940 redirect($CFG->wwwroot
, get_string('activityiscurrentlyhidden'));
2943 // Finally access granted, update lastaccess times
2944 user_accesstime_log($course->id
);
2949 * This function just makes sure a user is logged out.
2953 function require_logout() {
2959 add_to_log(SITEID
, "user", "logout", "view.php?id=$USER->id&course=".SITEID
, $USER->id
, 0, $USER->id
);
2961 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2962 foreach($authsequence as $authname) {
2963 $authplugin = get_auth_plugin($authname);
2964 $authplugin->prelogout_hook();
2968 events_trigger('user_logout', $params);
2969 session_get_instance()->terminate_current();
2974 * Weaker version of require_login()
2976 * This is a weaker version of {@link require_login()} which only requires login
2977 * when called from within a course rather than the site page, unless
2978 * the forcelogin option is turned on.
2979 * @see require_login()
2982 * @param mixed $courseorid The course object or id in question
2983 * @param bool $autologinguest Allow autologin guests if that is wanted
2984 * @param object $cm Course activity module if known
2985 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2986 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2987 * in order to keep redirects working properly. MDL-14495
2988 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2991 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2992 global $CFG, $PAGE, $SITE;
2993 $issite = (is_object($courseorid) and $courseorid->id
== SITEID
)
2994 or (!is_object($courseorid) and $courseorid == SITEID
);
2995 if ($issite && !empty($cm) && !($cm instanceof cm_info
)) {
2996 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2997 // db queries so this is not really a performance concern, however it is obviously
2998 // better if you use get_fast_modinfo to get the cm before calling this.
2999 if (is_object($courseorid)) {
3000 $course = $courseorid;
3002 $course = clone($SITE);
3004 $modinfo = get_fast_modinfo($course);
3005 $cm = $modinfo->get_cm($cm->id
);
3007 if (!empty($CFG->forcelogin
)) {
3008 // login required for both SITE and courses
3009 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3011 } else if ($issite && !empty($cm) and !$cm->uservisible
) {
3012 // always login for hidden activities
3013 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3015 } else if ($issite) {
3016 //login for SITE not required
3017 if ($cm and empty($cm->visible
)) {
3018 // hidden activities are not accessible without login
3019 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3020 } else if ($cm and !empty($CFG->enablegroupmembersonly
) and $cm->groupmembersonly
) {
3021 // not-logged-in users do not have any group membership
3022 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3024 // We still need to instatiate PAGE vars properly so that things
3025 // that rely on it like navigation function correctly.
3026 if (!empty($courseorid)) {
3027 if (is_object($courseorid)) {
3028 $course = $courseorid;
3030 $course = clone($SITE);
3033 if ($cm->course
!= $course->id
) {
3034 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3036 $PAGE->set_cm($cm, $course);
3037 $PAGE->set_pagelayout('incourse');
3039 $PAGE->set_course($course);
3042 // If $PAGE->course, and hence $PAGE->context, have not already been set
3043 // up properly, set them up now.
3044 $PAGE->set_course($PAGE->course
);
3046 //TODO: verify conditional activities here
3047 user_accesstime_log(SITEID
);
3052 // course login always required
3053 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3058 * Require key login. Function terminates with error if key not found or incorrect.
3064 * @uses NO_MOODLE_COOKIES
3065 * @uses PARAM_ALPHANUM
3066 * @param string $script unique script identifier
3067 * @param int $instance optional instance id
3068 * @return int Instance ID
3070 function require_user_key_login($script, $instance=null) {
3071 global $USER, $SESSION, $CFG, $DB;
3073 if (!NO_MOODLE_COOKIES
) {
3074 print_error('sessioncookiesdisable');
3078 @session_write_close
();
3080 $keyvalue = required_param('key', PARAM_ALPHANUM
);
3082 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
3083 print_error('invalidkey');
3086 if (!empty($key->validuntil
) and $key->validuntil
< time()) {
3087 print_error('expiredkey');
3090 if ($key->iprestriction
) {
3091 $remoteaddr = getremoteaddr(null);
3092 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction
)) {
3093 print_error('ipmismatch');
3097 if (!$user = $DB->get_record('user', array('id'=>$key->userid
))) {
3098 print_error('invaliduserid');
3101 /// emulate normal session
3102 enrol_check_plugins($user);
3103 session_set_user($user);
3105 /// note we are not using normal login
3106 if (!defined('USER_KEY_LOGIN')) {
3107 define('USER_KEY_LOGIN', true);
3110 /// return instance id - it might be empty
3111 return $key->instance
;
3115 * Creates a new private user access key.
3118 * @param string $script unique target identifier
3119 * @param int $userid
3120 * @param int $instance optional instance id
3121 * @param string $iprestriction optional ip restricted access
3122 * @param timestamp $validuntil key valid only until given data
3123 * @return string access key value
3125 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3128 $key = new stdClass();
3129 $key->script
= $script;
3130 $key->userid
= $userid;
3131 $key->instance
= $instance;
3132 $key->iprestriction
= $iprestriction;
3133 $key->validuntil
= $validuntil;
3134 $key->timecreated
= time();
3136 $key->value
= md5($userid.'_'.time().random_string(40)); // something long and unique
3137 while ($DB->record_exists('user_private_key', array('value'=>$key->value
))) {
3139 $key->value
= md5($userid.'_'.time().random_string(40));
3141 $DB->insert_record('user_private_key', $key);
3146 * Delete the user's new private user access keys for a particular script.
3149 * @param string $script unique target identifier
3150 * @param int $userid
3153 function delete_user_key($script,$userid) {
3155 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3159 * Gets a private user access key (and creates one if one doesn't exist).
3162 * @param string $script unique target identifier
3163 * @param int $userid
3164 * @param int $instance optional instance id
3165 * @param string $iprestriction optional ip restricted access
3166 * @param timestamp $validuntil key valid only until given data
3167 * @return string access key value
3169 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3172 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3173 'instance'=>$instance, 'iprestriction'=>$iprestriction,
3174 'validuntil'=>$validuntil))) {
3177 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3183 * Modify the user table by setting the currently logged in user's
3184 * last login to now.
3188 * @return bool Always returns true
3190 function update_user_login_times() {
3193 $user = new stdClass();
3194 $USER->lastlogin
= $user->lastlogin
= $USER->currentlogin
;
3195 $USER->currentlogin
= $user->lastaccess
= $user->currentlogin
= time();
3197 $user->id
= $USER->id
;
3199 $DB->update_record('user', $user);
3204 * Determines if a user has completed setting up their account.
3206 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3209 function user_not_fully_set_up($user) {
3210 if (isguestuser($user)) {
3213 return (empty($user->firstname
) or empty($user->lastname
) or empty($user->email
) or over_bounce_threshold($user));
3217 * Check whether the user has exceeded the bounce threshold
3221 * @param user $user A {@link $USER} object
3222 * @return bool true=>User has exceeded bounce threshold
3224 function over_bounce_threshold($user) {
3227 if (empty($CFG->handlebounces
)) {
3231 if (empty($user->id
)) { /// No real (DB) user, nothing to do here.
3235 // set sensible defaults
3236 if (empty($CFG->minbounces
)) {
3237 $CFG->minbounces
= 10;
3239 if (empty($CFG->bounceratio
)) {
3240 $CFG->bounceratio
= .20;
3244 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id
, 'name'=>'email_bounce_count'))) {
3245 $bouncecount = $bounce->value
;
3247 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id
, 'name'=>'email_send_count'))) {
3248 $sendcount = $send->value
;
3250 return ($bouncecount >= $CFG->minbounces
&& $bouncecount/$sendcount >= $CFG->bounceratio
);
3254 * Used to increment or reset email sent count
3257 * @param user $user object containing an id
3258 * @param bool $reset will reset the count to 0
3261 function set_send_count($user,$reset=false) {
3264 if (empty($user->id
)) { /// No real (DB) user, nothing to do here.
3268 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id
, 'name'=>'email_send_count'))) {
3269 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3270 $DB->update_record('user_preferences', $pref);
3272 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3274 $pref = new stdClass();
3275 $pref->name
= 'email_send_count';
3277 $pref->userid
= $user->id
;
3278 $DB->insert_record('user_preferences', $pref, false);
3283 * Increment or reset user's email bounce count
3286 * @param user $user object containing an id
3287 * @param bool $reset will reset the count to 0
3289 function set_bounce_count($user,$reset=false) {
3292 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id
, 'name'=>'email_bounce_count'))) {
3293 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
3294 $DB->update_record('user_preferences', $pref);
3296 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3298 $pref = new stdClass();
3299 $pref->name
= 'email_bounce_count';
3301 $pref->userid
= $user->id
;
3302 $DB->insert_record('user_preferences', $pref, false);
3307 * Keeps track of login attempts
3311 function update_login_count() {
3316 if (empty($SESSION->logincount
)) {
3317 $SESSION->logincount
= 1;
3319 $SESSION->logincount++
;
3322 if ($SESSION->logincount
> $max_logins) {
3323 unset($SESSION->wantsurl
);
3324 print_error('errortoomanylogins');
3329 * Resets login attempts
3333 function reset_login_count() {
3336 $SESSION->logincount
= 0;
3340 * Determines if the currently logged in user is in editing mode.
3341 * Note: originally this function had $userid parameter - it was not usable anyway
3343 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3344 * @todo Deprecated function remove when ready
3347 * @uses DEBUG_DEVELOPER
3350 function isediting() {
3352 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER
);
3353 return $PAGE->user_is_editing();
3357 * Determines if the logged in user is currently moving an activity
3360 * @param int $courseid The id of the course being tested
3363 function ismoving($courseid) {
3366 if (!empty($USER->activitycopy
)) {
3367 return ($USER->activitycopycourse
== $courseid);
3373 * Returns a persons full name
3375 * Given an object containing firstname and lastname
3376 * values, this function returns a string with the
3377 * full name of the person.
3378 * The result may depend on system settings
3379 * or language. 'override' will force both names
3380 * to be used even if system settings specify one.
3384 * @param object $user A {@link $USER} object to get full name of
3385 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3388 function fullname($user, $override=false) {
3389 global $CFG, $SESSION;
3391 if (!isset($user->firstname
) and !isset($user->lastname
)) {
3396 if (!empty($CFG->forcefirstname
)) {
3397 $user->firstname
= $CFG->forcefirstname
;
3399 if (!empty($CFG->forcelastname
)) {
3400 $user->lastname
= $CFG->forcelastname
;
3404 if (!empty($SESSION->fullnamedisplay
)) {
3405 $CFG->fullnamedisplay
= $SESSION->fullnamedisplay
;
3408 if (!isset($CFG->fullnamedisplay
) or $CFG->fullnamedisplay
=== 'firstname lastname') {
3409 return $user->firstname
.' '. $user->lastname
;
3411 } else if ($CFG->fullnamedisplay
== 'lastname firstname') {
3412 return $user->lastname
.' '. $user->firstname
;
3414 } else if ($CFG->fullnamedisplay
== 'firstname') {
3416 return get_string('fullnamedisplay', '', $user);
3418 return $user->firstname
;
3422 return get_string('fullnamedisplay', '', $user);
3426 * Checks if current user is shown any extra fields when listing users.
3427 * @param object $context Context
3428 * @param array $already Array of fields that we're going to show anyway
3429 * so don't bother listing them
3430 * @return array Array of field names from user table, not including anything
3431 * listed in $already
3433 function get_extra_user_fields($context, $already = array()) {
3436 // Only users with permission get the extra fields
3437 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3441 // Split showuseridentity on comma
3442 if (empty($CFG->showuseridentity
)) {
3443 // Explode gives wrong result with empty string
3446 $extra = explode(',', $CFG->showuseridentity
);
3449 foreach ($extra as $key => $field) {
3450 if (in_array($field, $already)) {
3451 unset($extra[$key]);
3456 // For consistency, if entries are removed from array, renumber it
3457 // so they are numbered as you would expect
3458 $extra = array_merge($extra);
3464 * If the current user is to be shown extra user fields when listing or
3465 * selecting users, returns a string suitable for including in an SQL select
3466 * clause to retrieve those fields.
3467 * @param object $context Context
3468 * @param string $alias Alias of user table, e.g. 'u' (default none)
3469 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3470 * @param array $already Array of fields that we're going to include anyway
3471 * so don't list them (default none)
3472 * @return string Partial SQL select clause, beginning with comma, for example
3473 * ',u.idnumber,u.department' unless it is blank
3475 function get_extra_user_fields_sql($context, $alias='', $prefix='',
3476 $already = array()) {
3477 $fields = get_extra_user_fields($context, $already);
3479 // Add punctuation for alias
3480 if ($alias !== '') {
3483 foreach ($fields as $field) {
3484 $result .= ', ' . $alias . $field;
3486 $result .= ' AS ' . $prefix . $field;
3493 * Returns the display name of a field in the user table. Works for most fields
3494 * that are commonly displayed to users.
3495 * @param string $field Field name, e.g. 'phone1'
3496 * @return string Text description taken from language file, e.g. 'Phone number'
3498 function get_user_field_name($field) {
3499 // Some fields have language strings which are not the same as field name
3501 case 'phone1' : return get_string('phone');
3503 // Otherwise just use the same lang string
3504 return get_string($field);
3508 * Returns whether a given authentication plugin exists.
3511 * @param string $auth Form of authentication to check for. Defaults to the
3512 * global setting in {@link $CFG}.
3513 * @return boolean Whether the plugin is available.
3515 function exists_auth_plugin($auth) {
3518 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3519 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3525 * Checks if a given plugin is in the list of enabled authentication plugins.
3527 * @param string $auth Authentication plugin.
3528 * @return boolean Whether the plugin is enabled.
3530 function is_enabled_auth($auth) {
3535 $enabled = get_enabled_auth_plugins();
3537 return in_array($auth, $enabled);
3541 * Returns an authentication plugin instance.
3544 * @param string $auth name of authentication plugin
3545 * @return auth_plugin_base An instance of the required authentication plugin.
3547 function get_auth_plugin($auth) {
3550 // check the plugin exists first
3551 if (! exists_auth_plugin($auth)) {
3552 print_error('authpluginnotfound', 'debug', '', $auth);
3555 // return auth plugin instance
3556 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3557 $class = "auth_plugin_$auth";
3562 * Returns array of active auth plugins.
3564 * @param bool $fix fix $CFG->auth if needed
3567 function get_enabled_auth_plugins($fix=false) {
3570 $default = array('manual', 'nologin');
3572 if (empty($CFG->auth
)) {
3575 $auths = explode(',', $CFG->auth
);
3579 $auths = array_unique($auths);
3580 foreach($auths as $k=>$authname) {
3581 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3585 $newconfig = implode(',', $auths);
3586 if (!isset($CFG->auth
) or $newconfig != $CFG->auth
) {
3587 set_config('auth', $newconfig);
3591 return (array_merge($default, $auths));
3595 * Returns true if an internal authentication method is being used.
3596 * if method not specified then, global default is assumed
3598 * @param string $auth Form of authentication required
3601 function is_internal_auth($auth) {
3602 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3603 return $authplugin->is_internal();
3607 * Returns true if the user is a 'restored' one
3609 * Used in the login process to inform the user
3610 * and allow him/her to reset the password
3614 * @param string $username username to be checked
3617 function is_restored_user($username) {
3620 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id
, 'password'=>'restored'));
3624 * Returns an array of user fields
3626 * @return array User field/column names
3628 function get_user_fieldnames() {
3631 $fieldarray = $DB->get_columns('user');
3632 unset($fieldarray['id']);
3633 $fieldarray = array_keys($fieldarray);
3639 * Creates a bare-bones user record
3641 * @todo Outline auth types and provide code example
3643 * @param string $username New user's username to add to record
3644 * @param string $password New user's password to add to record
3645 * @param string $auth Form of authentication required
3646 * @return stdClass A complete user object
3648 function create_user_record($username, $password, $auth = 'manual') {
3651 //just in case check text case
3652 $username = trim(moodle_strtolower($username));
3654 $authplugin = get_auth_plugin($auth);
3656 $newuser = new stdClass();
3658 if ($newinfo = $authplugin->get_userinfo($username)) {
3659 $newinfo = truncate_userinfo($newinfo);
3660 foreach ($newinfo as $key => $value){
3661 $newuser->$key = $value;
3665 if (!empty($newuser->email
)) {
3666 if (email_is_not_allowed($newuser->email
)) {
3667 unset($newuser->email
);
3671 if (!isset($newuser->city
)) {
3672 $newuser->city
= '';
3675 $newuser->auth
= $auth;
3676 $newuser->username
= $username;
3679 // user CFG lang for user if $newuser->lang is empty
3680 // or $user->lang is not an installed language
3681 if (empty($newuser->lang
) ||
!get_string_manager()->translation_exists($newuser->lang
)) {
3682 $newuser->lang
= $CFG->lang
;
3684 $newuser->confirmed
= 1;
3685 $newuser->lastip
= getremoteaddr();
3686 $newuser->timecreated
= time();
3687 $newuser->timemodified
= $newuser->timecreated
;
3688 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
3690 $newuser->id
= $DB->insert_record('user', $newuser);
3691 $user = get_complete_user_data('id', $newuser->id
);
3692 if (!empty($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'})){
3693 set_user_preference('auth_forcepasswordchange', 1, $user);
3695 update_internal_user_password($user, $password);
3697 // fetch full user record for the event, the complete user data contains too much info
3698 // and we want to be consistent with other places that trigger this event
3699 events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id
)));
3705 * Will update a local user record from an external source.
3706 * (MNET users can not be updated using this method!)
3708 * @param string $username user's username to update the record
3709 * @return stdClass A complete user object
3711 function update_user_record($username) {
3714 $username = trim(moodle_strtolower($username)); /// just in case check text case
3716 $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id
), '*', MUST_EXIST
);
3718 $userauth = get_auth_plugin($oldinfo->auth
);
3720 if ($newinfo = $userauth->get_userinfo($username)) {
3721 $newinfo = truncate_userinfo($newinfo);
3722 foreach ($newinfo as $key => $value){
3723 $key = strtolower($key);
3724 if (!property_exists($oldinfo, $key) or $key === 'username' or $key === 'id'
3725 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3726 // unknown or must not be changed
3729 $confval = $userauth->config
->{'field_updatelocal_' . $key};
3730 $lockval = $userauth->config
->{'field_lock_' . $key};
3731 if (empty($confval) ||
empty($lockval)) {
3734 if ($confval === 'onlogin') {
3735 // MDL-4207 Don't overwrite modified user profile values with
3736 // empty LDAP values when 'unlocked if empty' is set. The purpose
3737 // of the setting 'unlocked if empty' is to allow the user to fill
3738 // in a value for the selected field _if LDAP is giving
3739 // nothing_ for this field. Thus it makes sense to let this value
3740 // stand in until LDAP is giving a value for this field.
3741 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3742 if ((string)$oldinfo->$key !== (string)$value) {
3743 $newuser[$key] = (string)$value;
3749 $newuser['id'] = $oldinfo->id
;
3750 $newuser['timemodified'] = time();
3751 $DB->update_record('user', $newuser);
3752 // fetch full user record for the event, the complete user data contains too much info
3753 // and we want to be consistent with other places that trigger this event
3754 events_trigger('user_updated', $DB->get_record('user', array('id'=>$oldinfo->id
)));
3758 return get_complete_user_data('id', $oldinfo->id
);
3762 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3763 * which may have large fields
3765 * @todo Add vartype handling to ensure $info is an array
3767 * @param array $info Array of user properties to truncate if needed
3768 * @return array The now truncated information that was passed in
3770 function truncate_userinfo($info) {
3771 // define the limits
3781 'institution' => 40,
3789 $textlib = textlib_get_instance();
3790 // apply where needed
3791 foreach (array_keys($info) as $key) {
3792 if (!empty($limit[$key])) {
3793 $info[$key] = trim($textlib->substr($info[$key],0, $limit[$key]));
3801 * Marks user deleted in internal user database and notifies the auth plugin.
3802 * Also unenrols user from all roles and does other cleanup.
3804 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3806 * @param stdClass $user full user object before delete
3807 * @return boolean always true
3809 function delete_user($user) {
3811 require_once($CFG->libdir
.'/grouplib.php');
3812 require_once($CFG->libdir
.'/gradelib.php');
3813 require_once($CFG->dirroot
.'/message/lib.php');
3814 require_once($CFG->dirroot
.'/tag/lib.php');
3816 // delete all grades - backup is kept in grade_grades_history table
3817 grade_user_delete($user->id
);
3819 //move unread messages from this user to read
3820 message_move_userfrom_unread2read($user->id
);
3822 // TODO: remove from cohorts using standard API here
3825 tag_set('user', $user->id
, array());
3827 // unconditionally unenrol from all courses
3828 enrol_user_delete($user);
3830 // unenrol from all roles in all contexts
3831 role_unassign_all(array('userid'=>$user->id
)); // this might be slow but it is really needed - modules might do some extra cleanup!
3833 //now do a brute force cleanup
3835 // remove from all cohorts
3836 $DB->delete_records('cohort_members', array('userid'=>$user->id
));
3838 // remove from all groups
3839 $DB->delete_records('groups_members', array('userid'=>$user->id
));
3841 // brute force unenrol from all courses
3842 $DB->delete_records('user_enrolments', array('userid'=>$user->id
));
3844 // purge user preferences
3845 $DB->delete_records('user_preferences', array('userid'=>$user->id
));
3847 // purge user extra profile info
3848 $DB->delete_records('user_info_data', array('userid'=>$user->id
));
3850 // last course access not necessary either
3851 $DB->delete_records('user_lastaccess', array('userid'=>$user->id
));
3853 // remove all user tokens
3854 $DB->delete_records('external_tokens', array('userid'=>$user->id
));
3856 // unauthorise the user for all services
3857 $DB->delete_records('external_services_users', array('userid'=>$user->id
));
3859 // force logout - may fail if file based sessions used, sorry
3860 session_kill_user($user->id
);
3862 // now do a final accesslib cleanup - removes all role assignments in user context and context itself
3863 delete_context(CONTEXT_USER
, $user->id
);
3865 // workaround for bulk deletes of users with the same email address
3866 $delname = "$user->email.".time();
3867 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3871 // mark internal user record as "deleted"
3872 $updateuser = new stdClass();
3873 $updateuser->id
= $user->id
;
3874 $updateuser->deleted
= 1;
3875 $updateuser->username
= $delname; // Remember it just in case
3876 $updateuser->email
= md5($user->username
);// Store hash of username, useful importing/restoring users
3877 $updateuser->idnumber
= ''; // Clear this field to free it up
3878 $updateuser->timemodified
= time();
3880 $DB->update_record('user', $updateuser);
3881 // Add this action to log
3882 add_to_log(SITEID
, 'user', 'delete', "view.php?id=$user->id", $user->firstname
.' '.$user->lastname
);
3885 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
3886 // should know about this updated property persisted to the user's table.
3887 $user->timemodified
= $updateuser->timemodified
;
3889 // notify auth plugin - do not block the delete even when plugin fails
3890 $authplugin = get_auth_plugin($user->auth
);
3891 $authplugin->user_delete($user);
3893 // any plugin that needs to cleanup should register this event
3894 events_trigger('user_deleted', $user);
3900 * Retrieve the guest user object
3904 * @return user A {@link $USER} object
3906 function guest_user() {
3909 if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest
))) {
3910 $newuser->confirmed
= 1;
3911 $newuser->lang
= $CFG->lang
;
3912 $newuser->lastip
= getremoteaddr();
3919 * Authenticates a user against the chosen authentication mechanism
3921 * Given a username and password, this function looks them
3922 * up using the currently selected authentication mechanism,
3923 * and if the authentication is successful, it returns a
3924 * valid $user object from the 'user' table.
3926 * Uses auth_ functions from the currently active auth module
3928 * After authenticate_user_login() returns success, you will need to
3929 * log that the user has logged in, and call complete_user_login() to set
3932 * Note: this function works only with non-mnet accounts!
3934 * @param string $username User's username
3935 * @param string $password User's password
3936 * @return user|flase A {@link $USER} object or false if error
3938 function authenticate_user_login($username, $password) {
3941 $authsenabled = get_enabled_auth_plugins();
3943 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id
)) {
3944 $auth = empty($user->auth
) ?
'manual' : $user->auth
; // use manual if auth not set
3945 if (!empty($user->suspended
)) {
3946 add_to_log(SITEID
, 'login', 'error', 'index.php', $username);
3947 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3950 if ($auth=='nologin' or !is_enabled_auth($auth)) {
3951 add_to_log(SITEID
, 'login', 'error', 'index.php', $username);
3952 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3955 $auths = array($auth);
3958 // check if there's a deleted record (cheaply)
3959 if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
3960 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3964 // User does not exist
3965 $auths = $authsenabled;
3966 $user = new stdClass();
3970 foreach ($auths as $auth) {
3971 $authplugin = get_auth_plugin($auth);
3973 // on auth fail fall through to the next plugin
3974 if (!$authplugin->user_login($username, $password)) {
3978 // successful authentication
3979 if ($user->id
) { // User already exists in database
3980 if (empty($user->auth
)) { // For some reason auth isn't set yet
3981 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
3982 $user->auth
= $auth;
3984 if (empty($user->firstaccess
)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
3985 $DB->set_field('user','firstaccess', $user->timemodified
, array('id' => $user->id
));
3986 $user->firstaccess
= $user->timemodified
;
3989 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3991 if ($authplugin->is_synchronised_with_external()) { // update user record from external DB
3992 $user = update_user_record($username);
3995 // if user not found and user creation is not disabled, create it
3996 if (empty($CFG->authpreventaccountcreation
)) {
3997 $user = create_user_record($username, $password, $auth);
4003 $authplugin->sync_roles($user);
4005 foreach ($authsenabled as $hau) {
4006 $hauth = get_auth_plugin($hau);
4007 $hauth->user_authenticated_hook($user, $username, $password);
4010 if (empty($user->id
)) {
4014 if (!empty($user->suspended
)) {
4015 // just in case some auth plugin suspended account
4016 add_to_log(SITEID
, 'login', 'error', 'index.php', $username);
4017 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4024 // failed if all the plugins have failed
4025 add_to_log(SITEID
, 'login', 'error', 'index.php', $username);
4026 if (debugging('', DEBUG_ALL
)) {
4027 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4033 * Call to complete the user login process after authenticate_user_login()
4034 * has succeeded. It will setup the $USER variable and other required bits
4038 * - It will NOT log anything -- up to the caller to decide what to log.
4039 * - this function does not set any cookies any more!
4041 * @param object $user
4042 * @return object A {@link $USER} object - BC only, do not use
4044 function complete_user_login($user) {
4047 // regenerate session id and delete old session,
4048 // this helps prevent session fixation attacks from the same domain
4049 session_regenerate_id(true);
4051 // let enrol plugins deal with new enrolments if necessary
4052 enrol_check_plugins($user);
4054 // check enrolments, load caps and setup $USER object
4055 session_set_user($user);
4057 // reload preferences from DB
4058 unset($USER->preference
);
4059 check_user_preferences_loaded($USER);
4061 // update login times
4062 update_user_login_times();
4064 // extra session prefs init
4065 set_login_session_preferences();
4067 if (isguestuser()) {
4068 // no need to continue when user is THE guest
4072 /// Select password change url
4073 $userauth = get_auth_plugin($USER->auth
);
4075 /// check whether the user should be changing password
4076 if (get_user_preferences('auth_forcepasswordchange', false)){
4077 if ($userauth->can_change_password()) {
4078 if ($changeurl = $userauth->change_password_url()) {
4079 redirect($changeurl);
4081 redirect($CFG->httpswwwroot
.'/login/change_password.php');
4084 print_error('nopasswordchangeforced', 'auth');
4091 * Compare password against hash stored in internal user table.
4092 * If necessary it also updates the stored hash to new format.
4094 * @param stdClass $user (password property may be updated)
4095 * @param string $password plain text password
4096 * @return bool is password valid?
4098 function validate_internal_user_password($user, $password) {
4101 if (!isset($CFG->passwordsaltmain
)) {
4102 $CFG->passwordsaltmain
= '';
4107 if ($user->password
=== 'not cached') {
4108 // internal password is not used at all, it can not validate
4110 } else if ($user->password
=== md5($password.$CFG->passwordsaltmain
)
4111 or $user->password
=== md5($password)
4112 or $user->password
=== md5(addslashes($password).$CFG->passwordsaltmain
)
4113 or $user->password
=== md5(addslashes($password))) {
4114 // note: we are intentionally using the addslashes() here because we
4115 // need to accept old password hashes of passwords with magic quotes
4119 for ($i=1; $i<=20; $i++
) { //20 alternative salts should be enough, right?
4120 $alt = 'passwordsaltalt'.$i;
4121 if (!empty($CFG->$alt)) {
4122 if ($user->password
=== md5($password.$CFG->$alt) or $user->password
=== md5(addslashes($password).$CFG->$alt)) {
4131 // force update of password hash using latest main password salt and encoding if needed
4132 update_internal_user_password($user, $password);
4139 * Calculate hashed value from password using current hash mechanism.
4141 * @param string $password
4142 * @return string password hash
4144 function hash_internal_user_password($password) {
4147 if (isset($CFG->passwordsaltmain
)) {
4148 return md5($password.$CFG->passwordsaltmain
);
4150 return md5($password);
4155 * Update password hash in user object.
4157 * @param stdClass $user (password property may be updated)
4158 * @param string $password plain text password
4159 * @return bool always returns true
4161 function update_internal_user_password($user, $password) {
4164 $authplugin = get_auth_plugin($user->auth
);
4165 if ($authplugin->prevent_local_passwords()) {
4166 $hashedpassword = 'not cached';
4168 $hashedpassword = hash_internal_user_password($password);
4171 if ($user->password
!== $hashedpassword) {
4172 $DB->set_field('user', 'password', $hashedpassword, array('id'=>$user->id
));
4173 $user->password
= $hashedpassword;
4180 * Get a complete user record, which includes all the info
4181 * in the user record.
4183 * Intended for setting as $USER session variable
4185 * @param string $field The user field to be checked for a given value.
4186 * @param string $value The value to match for $field.
4187 * @param int $mnethostid
4188 * @return mixed False, or A {@link $USER} object.
4190 function get_complete_user_data($field, $value, $mnethostid = null) {
4193 if (!$field ||
!$value) {
4197 /// Build the WHERE clause for an SQL query
4198 $params = array('fieldval'=>$value);
4199 $constraints = "$field = :fieldval AND deleted <> 1";
4201 // If we are loading user data based on anything other than id,
4202 // we must also restrict our search based on mnet host.
4203 if ($field != 'id') {
4204 if (empty($mnethostid)) {
4205 // if empty, we restrict to local users
4206 $mnethostid = $CFG->mnet_localhost_id
;
4209 if (!empty($mnethostid)) {
4210 $params['mnethostid'] = $mnethostid;
4211 $constraints .= " AND mnethostid = :mnethostid";
4214 /// Get all the basic user data
4216 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4220 /// Get various settings and preferences
4222 // preload preference cache
4223 check_user_preferences_loaded($user);
4225 // load course enrolment related stuff
4226 $user->lastcourseaccess
= array(); // during last session
4227 $user->currentcourseaccess
= array(); // during current session
4228 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid'=>$user->id
))) {
4229 foreach ($lastaccesses as $lastaccess) {
4230 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
4234 $sql = "SELECT g.id, g.courseid
4235 FROM {groups} g, {groups_members} gm
4236 WHERE gm.groupid=g.id AND gm.userid=?";
4238 // this is a special hack to speedup calendar display
4239 $user->groupmember
= array();
4240 if (!isguestuser($user)) {
4241 if ($groups = $DB->get_records_sql($sql, array($user->id
))) {
4242 foreach ($groups as $group) {
4243 if (!array_key_exists($group->courseid
, $user->groupmember
)) {
4244 $user->groupmember
[$group->courseid
] = array();
4246 $user->groupmember
[$group->courseid
][$group->id
] = $group->id
;
4251 /// Add the custom profile fields to the user record
4252 $user->profile
= array();
4253 if (!isguestuser($user)) {
4254 require_once($CFG->dirroot
.'/user/profile/lib.php');
4255 profile_load_custom_fields($user);
4258 /// Rewrite some variables if necessary
4259 if (!empty($user->description
)) {
4260 $user->description
= true; // No need to cart all of it around
4262 if (isguestuser($user)) {
4263 $user->lang
= $CFG->lang
; // Guest language always same as site
4264 $user->firstname
= get_string('guestuser'); // Name always in current language
4265 $user->lastname
= ' ';
4272 * Validate a password against the configured password policy
4275 * @param string $password the password to be checked against the password policy
4276 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4277 * @return bool true if the password is valid according to the policy. false otherwise.
4279 function check_password_policy($password, &$errmsg) {
4282 if (empty($CFG->passwordpolicy
)) {
4286 $textlib = textlib_get_instance();
4288 if ($textlib->strlen($password) < $CFG->minpasswordlength
) {
4289 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength
) .'</div>';
4292 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits
) {
4293 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits
) .'</div>';
4296 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower
) {
4297 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower
) .'</div>';
4300 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper
) {
4301 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper
) .'</div>';
4304 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum
) {
4305 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
) .'</div>';
4307 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars
)) {
4308 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars
) .'</div>';
4311 if ($errmsg == '') {
4320 * When logging in, this function is run to set certain preferences
4321 * for the current SESSION
4326 function set_login_session_preferences() {
4327 global $SESSION, $CFG;
4329 $SESSION->justloggedin
= true;
4331 unset($SESSION->lang
);
4336 * Delete a course, including all related data from the database,
4337 * and any associated files.
4341 * @param mixed $courseorid The id of the course or course object to delete.
4342 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4343 * @return bool true if all the removals succeeded. false if there were any failures. If this
4344 * method returns false, some of the removals will probably have succeeded, and others
4345 * failed, but you have no way of knowing which.
4347 function delete_course($courseorid, $showfeedback = true) {
4350 if (is_object($courseorid)) {
4351 $courseid = $courseorid->id
;
4352 $course = $courseorid;
4354 $courseid = $courseorid;
4355 if (!$course = $DB->get_record('course', array('id'=>$courseid))) {
4359 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
4361 // frontpage course can not be deleted!!
4362 if ($courseid == SITEID
) {
4366 // make the course completely empty
4367 remove_course_contents($courseid, $showfeedback);
4369 // delete the course and related context instance
4370 delete_context(CONTEXT_COURSE
, $courseid);
4372 // We will update the course's timemodified, as it will be passed to the course_deleted event,
4373 // which should know about this updated property, as this event is meant to pass the full course record
4374 $course->timemodified
= time();
4376 $DB->delete_records("course", array("id"=>$courseid));
4379 $course->context
= $context; // you can not fetch context in the event because it was already deleted
4380 events_trigger('course_deleted', $course);
4386 * Clear a course out completely, deleting all content
4387 * but don't delete the course itself.
4388 * This function does not verify any permissions.
4390 * Please note this function also deletes all user enrolments,
4391 * enrolment instances and role assignments by default.
4394 * - 'keep_roles_and_enrolments' - false by default
4395 * - 'keep_groups_and_groupings' - false by default
4397 * @param int $courseid The id of the course that is being deleted
4398 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4399 * @param array $options extra options
4400 * @return bool true if all the removals succeeded. false if there were any failures. If this
4401 * method returns false, some of the removals will probably have succeeded, and others
4402 * failed, but you have no way of knowing which.
4404 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4405 global $CFG, $DB, $OUTPUT;
4406 require_once($CFG->libdir
.'/completionlib.php');
4407 require_once($CFG->libdir
.'/questionlib.php');
4408 require_once($CFG->libdir
.'/gradelib.php');
4409 require_once($CFG->dirroot
.'/group/lib.php');
4410 require_once($CFG->dirroot
.'/tag/coursetagslib.php');
4411 require_once($CFG->dirroot
.'/comment/lib.php');
4412 require_once($CFG->dirroot
.'/rating/lib.php');
4414 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4415 $strdeleted = get_string('deleted').' - ';
4417 // Some crazy wishlist of stuff we should skip during purging of course content
4418 $options = (array)$options;
4420 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST
);
4421 $coursecontext = context_course
::instance($courseid);
4422 $fs = get_file_storage();
4424 // Delete course completion information, this has to be done before grades and enrols
4425 $cc = new completion_info($course);
4426 $cc->clear_criteria();
4427 if ($showfeedback) {
4428 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4431 // Remove all data from gradebook - this needs to be done before course modules
4432 // because while deleting this information, the system may need to reference
4433 // the course modules that own the grades.
4434 remove_course_grades($courseid, $showfeedback);
4435 remove_grade_letters($coursecontext, $showfeedback);
4437 // Delete course blocks in any all child contexts,
4438 // they may depend on modules so delete them first
4439 $childcontexts = $coursecontext->get_child_contexts(); // returns all subcontexts since 2.2
4440 foreach ($childcontexts as $childcontext) {
4441 blocks_delete_all_for_context($childcontext->id
);
4443 unset($childcontexts);
4444 blocks_delete_all_for_context($coursecontext->id
);
4445 if ($showfeedback) {
4446 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4449 // Delete every instance of every module,
4450 // this has to be done before deleting of course level stuff
4451 $locations = get_plugin_list('mod');
4452 foreach ($locations as $modname=>$moddir) {
4453 if ($modname === 'NEWMODULE') {
4456 if ($module = $DB->get_record('modules', array('name'=>$modname))) {
4457 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective
4458 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
4459 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
4461 if ($instances = $DB->get_records($modname, array('course'=>$course->id
))) {
4462 foreach ($instances as $instance) {
4463 if ($cm = get_coursemodule_from_instance($modname, $instance->id
, $course->id
)) {
4464 /// Delete activity context questions and question categories
4465 question_delete_activity($cm, $showfeedback);
4467 if (function_exists($moddelete)) {
4468 // This purges all module data in related tables, extra user prefs, settings, etc.
4469 $moddelete($instance->id
);
4471 // NOTE: we should not allow installation of modules with missing delete support!
4472 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4473 $DB->delete_records($modname, array('id'=>$instance->id
));
4477 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition
4478 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
4479 $DB->delete_records('course_modules', array('id'=>$cm->id
));
4483 if (function_exists($moddeletecourse)) {
4484 // Execute ptional course cleanup callback
4485 $moddeletecourse($course, $showfeedback);
4487 if ($instances and $showfeedback) {
4488 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4491 // Ooops, this module is not properly installed, force-delete it in the next block
4495 // We have tried to delete everything the nice way - now let's force-delete any remaining module data
4497 // Remove all data from availability and completion tables that is associated
4498 // with course-modules belonging to this course. Note this is done even if the
4499 // features are not enabled now, in case they were enabled previously.
4500 $DB->delete_records_select('course_modules_completion',
4501 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4503 $DB->delete_records_select('course_modules_availability',
4504 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4507 // Remove course-module data.
4508 $cms = $DB->get_records('course_modules', array('course'=>$course->id
));
4509 foreach ($cms as $cm) {
4510 if ($module = $DB->get_record('modules', array('id'=>$cm->module
))) {
4512 $DB->delete_records($module->name
, array('id'=>$cm->instance
));
4513 } catch (Exception
$e) {
4514 // Ignore weird or missing table problems
4517 context_helper
::delete_instance(CONTEXT_MODULE
, $cm->id
);
4518 $DB->delete_records('course_modules', array('id'=>$cm->id
));
4521 if ($showfeedback) {
4522 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
4525 // Cleanup the rest of plugins
4526 $cleanuplugintypes = array('report', 'coursereport', 'format');
4527 foreach ($cleanuplugintypes as $type) {
4528 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
4529 foreach ($plugins as $plugin=>$pluginfunction) {
4530 $pluginfunction($course->id
, $showfeedback);
4532 if ($showfeedback) {
4533 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
4537 // Delete questions and question categories
4538 question_delete_course($course, $showfeedback);
4539 if ($showfeedback) {
4540 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
4543 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone
4544 $childcontexts = $coursecontext->get_child_contexts(); // returns all subcontexts since 2.2
4545 foreach ($childcontexts as $childcontext) {
4546 $childcontext->delete();
4548 unset($childcontexts);
4550 // Remove all roles and enrolments by default
4551 if (empty($options['keep_roles_and_enrolments'])) {
4552 // this hack is used in restore when deleting contents of existing course
4553 role_unassign_all(array('contextid'=>$coursecontext->id
), true);
4554 enrol_course_delete($course);
4555 if ($showfeedback) {
4556 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
4560 // Delete any groups, removing members and grouping/course links first.
4561 if (empty($options['keep_groups_and_groupings'])) {
4562 groups_delete_groupings($course->id
, $showfeedback);
4563 groups_delete_groups($course->id
, $showfeedback);
4567 filter_delete_all_for_context($coursecontext->id
);
4570 comment
::delete_comments($coursecontext->id
);
4572 // ratings are history too
4573 $delopt = new stdclass();
4574 $delopt->contextid
= $coursecontext->id
;
4575 $rm = new rating_manager();
4576 $rm->delete_ratings($delopt);
4578 // Delete course tags
4579 coursetag_delete_course_tags($course->id
, $showfeedback);
4581 // Delete calendar events
4582 $DB->delete_records('event', array('courseid'=>$course->id
));
4583 $fs->delete_area_files($coursecontext->id
, 'calendar');
4585 // Delete all related records in other core tables that may have a courseid
4586 // This array stores the tables that need to be cleared, as
4587 // table_name => column_name that contains the course id.
4588 $tablestoclear = array(
4589 'log' => 'course', // Course logs (NOTE: this might be changed in the future)
4590 'backup_courses' => 'courseid', // Scheduled backup stuff
4591 'user_lastaccess' => 'courseid', // User access info
4593 foreach ($tablestoclear as $table => $col) {
4594 $DB->delete_records($table, array($col=>$course->id
));
4597 // delete all course backup files
4598 $fs->delete_area_files($coursecontext->id
, 'backup');
4600 // cleanup course record - remove links to deleted stuff
4601 $oldcourse = new stdClass();
4602 $oldcourse->id
= $course->id
;
4603 $oldcourse->summary
= '';
4604 $oldcourse->modinfo
= NULL;
4605 $oldcourse->legacyfiles
= 0;
4606 $oldcourse->enablecompletion
= 0;
4607 if (!empty($options['keep_groups_and_groupings'])) {
4608 $oldcourse->defaultgroupingid
= 0;
4610 $DB->update_record('course', $oldcourse);
4612 // Delete course sections and user selections
4613 $DB->delete_records('course_sections', array('course'=>$course->id
));
4614 $DB->delete_records('course_display', array('course'=>$course->id
));
4616 // delete legacy, section and any other course files
4617 $fs->delete_area_files($coursecontext->id
, 'course'); // files from summary and section
4619 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
4620 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
4621 // Easy, do not delete the context itself...
4622 $coursecontext->delete_content();
4626 // We can not drop all context stuff because it would bork enrolments and roles,
4627 // there might be also files used by enrol plugins...
4630 // Delete legacy files - just in case some files are still left there after conversion to new file api,
4631 // also some non-standard unsupported plugins may try to store something there
4632 fulldelete($CFG->dataroot
.'/'.$course->id
);
4634 // Finally trigger the event
4635 $course->context
= $coursecontext; // you can not access context in cron event later after course is deleted
4636 $course->options
= $options; // not empty if we used any crazy hack
4637 events_trigger('course_content_removed', $course);
4643 * Change dates in module - used from course reset.
4647 * @param string $modname forum, assignment, etc
4648 * @param array $fields array of date fields from mod table
4649 * @param int $timeshift time difference
4650 * @param int $courseid
4651 * @return bool success
4653 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid) {
4655 include_once($CFG->dirroot
.'/mod/'.$modname.'/lib.php');
4658 foreach ($fields as $field) {
4659 $updatesql = "UPDATE {".$modname."}
4660 SET $field = $field + ?
4661 WHERE course=? AND $field<>0 AND $field<>0";
4662 $return = $DB->execute($updatesql, array($timeshift, $courseid)) && $return;
4665 $refreshfunction = $modname.'_refresh_events';
4666 if (function_exists($refreshfunction)) {
4667 $refreshfunction($courseid);
4674 * This function will empty a course of user data.
4675 * It will retain the activities and the structure of the course.
4677 * @param object $data an object containing all the settings including courseid (without magic quotes)
4678 * @return array status array of array component, item, error
4680 function reset_course_userdata($data) {
4681 global $CFG, $USER, $DB;
4682 require_once($CFG->libdir
.'/gradelib.php');
4683 require_once($CFG->libdir
.'/completionlib.php');
4684 require_once($CFG->dirroot
.'/group/lib.php');
4686 $data->courseid
= $data->id
;
4687 $context = get_context_instance(CONTEXT_COURSE
, $data->courseid
);
4689 // calculate the time shift of dates
4690 if (!empty($data->reset_start_date
)) {
4691 // time part of course startdate should be zero
4692 $data->timeshift
= $data->reset_start_date
- usergetmidnight($data->reset_start_date_old
);
4694 $data->timeshift
= 0;
4697 // result array: component, item, error
4700 // start the resetting
4701 $componentstr = get_string('general');
4703 // move the course start time
4704 if (!empty($data->reset_start_date
) and $data->timeshift
) {
4705 // change course start data
4706 $DB->set_field('course', 'startdate', $data->reset_start_date
, array('id'=>$data->courseid
));
4707 // update all course and group events - do not move activity events
4708 $updatesql = "UPDATE {event}
4709 SET timestart = timestart + ?
4710 WHERE courseid=? AND instance=0";
4711 $DB->execute($updatesql, array($data->timeshift
, $data->courseid
));
4713 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
4716 if (!empty($data->reset_logs
)) {
4717 $DB->delete_records('log', array('course'=>$data->courseid
));
4718 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletelogs'), 'error'=>false);
4721 if (!empty($data->reset_events
)) {
4722 $DB->delete_records('event', array('courseid'=>$data->courseid
));
4723 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteevents', 'calendar'), 'error'=>false);
4726 if (!empty($data->reset_notes
)) {
4727 require_once($CFG->dirroot
.'/notes/lib.php');
4728 note_delete_all($data->courseid
);
4729 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotes', 'notes'), 'error'=>false);
4732 if (!empty($data->delete_blog_associations
)) {
4733 require_once($CFG->dirroot
.'/blog/lib.php');
4734 blog_remove_associations_for_course($data->courseid
);
4735 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteblogassociations', 'blog'), 'error'=>false);
4738 if (!empty($data->reset_course_completion
)) {
4739 // Delete course completion information
4740 $course = $DB->get_record('course', array('id'=>$data->courseid
));
4741 $cc = new completion_info($course);
4742 $cc->delete_course_completion_data();
4743 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletecoursecompletiondata', 'completion'), 'error'=>false);
4746 $componentstr = get_string('roles');
4748 if (!empty($data->reset_roles_overrides
)) {
4749 $children = get_child_contexts($context);
4750 foreach ($children as $child) {
4751 $DB->delete_records('role_capabilities', array('contextid'=>$child->id
));
4753 $DB->delete_records('role_capabilities', array('contextid'=>$context->id
));
4754 //force refresh for logged in users
4755 mark_context_dirty($context->path
);
4756 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletecourseoverrides', 'role'), 'error'=>false);
4759 if (!empty($data->reset_roles_local
)) {
4760 $children = get_child_contexts($context);
4761 foreach ($children as $child) {
4762 role_unassign_all(array('contextid'=>$child->id
));
4764 //force refresh for logged in users
4765 mark_context_dirty($context->path
);
4766 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletelocalroles', 'role'), 'error'=>false);
4769 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
4770 $data->unenrolled
= array();
4771 if (!empty($data->unenrol_users
)) {
4772 $plugins = enrol_get_plugins(true);
4773 $instances = enrol_get_instances($data->courseid
, true);
4774 foreach ($instances as $key=>$instance) {
4775 if (!isset($plugins[$instance->enrol
])) {
4776 unset($instances[$key]);
4779 if (!$plugins[$instance->enrol
]->allow_unenrol($instance)) {
4780 unset($instances[$key]);
4784 $sqlempty = $DB->sql_empty();
4785 foreach($data->unenrol_users
as $withroleid) {
4786 $sql = "SELECT DISTINCT ue.userid, ue.enrolid
4787 FROM {user_enrolments} ue
4788 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
4789 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
4790 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
4791 $params = array('courseid'=>$data->courseid
, 'roleid'=>$withroleid, 'courselevel'=>CONTEXT_COURSE
);
4793 $rs = $DB->get_recordset_sql($sql, $params);
4794 foreach ($rs as $ue) {
4795 if (!isset($instances[$ue->enrolid
])) {
4798 $plugins[$instances[$ue->enrolid
]->enrol
]->unenrol_user($instances[$ue->enrolid
], $ue->userid
);
4799 $data->unenrolled
[$ue->userid
] = $ue->userid
;
4803 if (!empty($data->unenrolled
)) {
4804 $status[] = array('component'=>$componentstr, 'item'=>get_string('unenrol', 'enrol').' ('.count($data->unenrolled
).')', 'error'=>false);
4808 $componentstr = get_string('groups');
4810 // remove all group members
4811 if (!empty($data->reset_groups_members
)) {
4812 groups_delete_group_members($data->courseid
);
4813 $status[] = array('component'=>$componentstr, 'item'=>get_string('removegroupsmembers', 'group'), 'error'=>false);
4816 // remove all groups
4817 if (!empty($data->reset_groups_remove
)) {
4818 groups_delete_groups($data->courseid
, false);
4819 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallgroups', 'group'), 'error'=>false);
4822 // remove all grouping members
4823 if (!empty($data->reset_groupings_members
)) {
4824 groups_delete_groupings_groups($data->courseid
, false);
4825 $status[] = array('component'=>$componentstr, 'item'=>get_string('removegroupingsmembers', 'group'), 'error'=>false);
4828 // remove all groupings
4829 if (!empty($data->reset_groupings_remove
)) {
4830 groups_delete_groupings($data->courseid
, false);
4831 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallgroupings', 'group'), 'error'=>false);
4834 // Look in every instance of every module for data to delete
4835 $unsupported_mods = array();
4836 if ($allmods = $DB->get_records('modules') ) {
4837 foreach ($allmods as $mod) {
4838 $modname = $mod->name
;
4839 if (!$DB->count_records($modname, array('course'=>$data->courseid
))) {
4840 continue; // skip mods with no instances
4842 $modfile = $CFG->dirroot
.'/mod/'. $modname.'/lib.php';
4843 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data
4844 if (file_exists($modfile)) {
4845 include_once($modfile);
4846 if (function_exists($moddeleteuserdata)) {
4847 $modstatus = $moddeleteuserdata($data);
4848 if (is_array($modstatus)) {
4849 $status = array_merge($status, $modstatus);
4851 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
4854 $unsupported_mods[] = $mod;
4857 debugging('Missing lib.php in '.$modname.' module!');
4862 // mention unsupported mods
4863 if (!empty($unsupported_mods)) {
4864 foreach($unsupported_mods as $mod) {
4865 $status[] = array('component'=>get_string('modulenameplural', $mod->name
), 'item'=>'', 'error'=>get_string('resetnotimplemented'));
4870 $componentstr = get_string('gradebook', 'grades');
4872 if (!empty($data->reset_gradebook_items
)) {
4873 remove_course_grades($data->courseid
, false);
4874 grade_grab_course_grades($data->courseid
);
4875 grade_regrade_final_grades($data->courseid
);
4876 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeallcourseitems', 'grades'), 'error'=>false);
4878 } else if (!empty($data->reset_gradebook_grades
)) {
4879 grade_course_reset($data->courseid
);
4880 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeallcoursegrades', 'grades'), 'error'=>false);
4883 if (!empty($data->reset_comments
)) {
4884 require_once($CFG->dirroot
.'/comment/lib.php');
4885 comment
::reset_course_page_comments($context);
4892 * Generate an email processing address
4895 * @param string $modargs
4896 * @return string Returns email processing address
4898 function generate_email_processing_address($modid,$modargs) {
4901 $header = $CFG->mailprefix
. substr(base64_encode(pack('C',$modid)),0,2).$modargs;
4902 return $header . substr(md5($header.get_site_identifier()),0,16).'@'.$CFG->maildomain
;
4908 * @todo Finish documenting this function
4911 * @param string $modargs
4912 * @param string $body Currently unused
4914 function moodle_process_email($modargs,$body) {
4917 // the first char should be an unencoded letter. We'll take this as an action
4918 switch ($modargs{0}) {
4919 case 'B': { // bounce
4920 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
4921 if ($user = $DB->get_record("user", array('id'=>$userid), "id,email")) {
4922 // check the half md5 of their email
4923 $md5check = substr(md5($user->email
),0,16);
4924 if ($md5check == substr($modargs, -16)) {
4925 set_bounce_count($user);
4927 // else maybe they've already changed it?
4931 // maybe more later?
4935 /// CORRESPONDENCE ////////////////////////////////////////////////
4938 * Get mailer instance, enable buffering, flush buffer or disable buffering.
4941 * @param string $action 'get', 'buffer', 'close' or 'flush'
4942 * @return object|null mailer instance if 'get' used or nothing
4944 function get_mailer($action='get') {
4947 static $mailer = null;
4948 static $counter = 0;
4950 if (!isset($CFG->smtpmaxbulk
)) {
4951 $CFG->smtpmaxbulk
= 1;
4954 if ($action == 'get') {
4955 $prevkeepalive = false;
4957 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
4958 if ($counter < $CFG->smtpmaxbulk
and !$mailer->IsError()) {
4961 $mailer->Priority
= 3;
4962 $mailer->CharSet
= 'UTF-8'; // our default
4963 $mailer->ContentType
= "text/plain";
4964 $mailer->Encoding
= "8bit";
4965 $mailer->From
= "root@localhost";
4966 $mailer->FromName
= "Root User";
4967 $mailer->Sender
= "";
4968 $mailer->Subject
= "";
4970 $mailer->AltBody
= "";
4971 $mailer->ConfirmReadingTo
= "";
4973 $mailer->ClearAllRecipients();
4974 $mailer->ClearReplyTos();
4975 $mailer->ClearAttachments();
4976 $mailer->ClearCustomHeaders();
4980 $prevkeepalive = $mailer->SMTPKeepAlive
;
4981 get_mailer('flush');
4984 include_once($CFG->libdir
.'/phpmailer/moodle_phpmailer.php');
4985 $mailer = new moodle_phpmailer();
4989 $mailer->Version
= 'Moodle '.$CFG->version
; // mailer version
4990 $mailer->PluginDir
= $CFG->libdir
.'/phpmailer/'; // plugin directory (eg smtp plugin)
4991 $mailer->CharSet
= 'UTF-8';
4993 // some MTAs may do double conversion of LF if CRLF used, CRLF is required line ending in RFC 822bis
4994 if (isset($CFG->mailnewline
) and $CFG->mailnewline
== 'CRLF') {
4995 $mailer->LE
= "\r\n";
5000 if ($CFG->smtphosts
== 'qmail') {
5001 $mailer->IsQmail(); // use Qmail system
5003 } else if (empty($CFG->smtphosts
)) {
5004 $mailer->IsMail(); // use PHP mail() = sendmail
5007 $mailer->IsSMTP(); // use SMTP directly
5008 if (!empty($CFG->debugsmtp
)) {
5009 $mailer->SMTPDebug
= true;
5011 $mailer->Host
= $CFG->smtphosts
; // specify main and backup servers
5012 $mailer->SMTPKeepAlive
= $prevkeepalive; // use previous keepalive
5014 if ($CFG->smtpuser
) { // Use SMTP authentication
5015 $mailer->SMTPAuth
= true;
5016 $mailer->Username
= $CFG->smtpuser
;
5017 $mailer->Password
= $CFG->smtppass
;
5026 // keep smtp session open after sending
5027 if ($action == 'buffer') {
5028 if (!empty($CFG->smtpmaxbulk
)) {
5029 get_mailer('flush');
5031 if ($m->Mailer
== 'smtp') {
5032 $m->SMTPKeepAlive
= true;
5038 // close smtp session, but continue buffering
5039 if ($action == 'flush') {
5040 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5041 if (!empty($mailer->SMTPDebug
)) {
5044 $mailer->SmtpClose();
5045 if (!empty($mailer->SMTPDebug
)) {
5052 // close smtp session, do not buffer anymore
5053 if ($action == 'close') {
5054 if (isset($mailer) and $mailer->Mailer
== 'smtp') {
5055 get_mailer('flush');
5056 $mailer->SMTPKeepAlive
= false;
5058 $mailer = null; // better force new instance
5064 * Send an email to a specified user
5068 * @global string IdentityProvider(IDP) URL user hits to jump to mnet peer.
5070 * @param stdClass $user A {@link $USER} object
5071 * @param stdClass $from A {@link $USER} object
5072 * @param string $subject plain text subject line of the email
5073 * @param string $messagetext plain text version of the message
5074 * @param string $messagehtml complete html version of the message (optional)
5075 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
5076 * @param string $attachname the name of the file (extension indicates MIME)
5077 * @param bool $usetrueaddress determines whether $from email address should
5078 * be sent out. Will be overruled by user profile setting for maildisplay
5079 * @param string $replyto Email address to reply to
5080 * @param string $replytoname Name of reply to recipient
5081 * @param int $wordwrapwidth custom word wrap width, default 79
5082 * @return bool Returns true if mail was sent OK and false if there was an error.
5084 function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='', $wordwrapwidth=79) {
5086 global $CFG, $FULLME;
5088 if (empty($user) ||
empty($user->email
)) {
5089 $nulluser = 'User is null or has no email';
5090 error_log($nulluser);
5092 mtrace('Error: lib/moodlelib.php email_to_user(): '.$nulluser);
5097 if (!empty($user->deleted
)) {
5098 // do not mail deleted users
5099 $userdeleted = 'User is deleted';
5100 error_log($userdeleted);
5102 mtrace('Error: lib/moodlelib.php email_to_user(): '.$userdeleted);
5107 if (!empty($CFG->noemailever
)) {
5108 // hidden setting for development sites, set in config.php if needed
5109 $noemail = 'Not sending email due to noemailever config setting';
5110 error_log($noemail);
5112 mtrace('Error: lib/moodlelib.php email_to_user(): '.$noemail);
5117 if (!empty($CFG->divertallemailsto
)) {
5118 $subject = "[DIVERTED {$user->email}] $subject";
5119 $user = clone($user);
5120 $user->email
= $CFG->divertallemailsto
;
5123 // skip mail to suspended users
5124 if ((isset($user->auth
) && $user->auth
=='nologin') or (isset($user->suspended
) && $user->suspended
)) {
5128 if (!validate_email($user->email
)) {
5129 // we can not send emails to invalid addresses - it might create security issue or confuse the mailer
5130 $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
5131 error_log($invalidemail);
5133 mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
5138 if (over_bounce_threshold($user)) {
5139 $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
5140 error_log($bouncemsg);
5142 mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
5147 // If the user is a remote mnet user, parse the email text for URL to the
5148 // wwwroot and modify the url to direct the user's browser to login at their
5149 // home site (identity provider - idp) before hitting the link itself
5150 if (is_mnet_remote_user($user)) {
5151 require_once($CFG->dirroot
.'/mnet/lib.php');
5153 $jumpurl = mnet_get_idp_jump_url($user);
5154 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5156 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5159 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5163 $mail = get_mailer();
5165 if (!empty($mail->SMTPDebug
)) {
5166 echo '<pre>' . "\n";
5169 $temprecipients = array();
5170 $tempreplyto = array();
5172 $supportuser = generate_email_supportuser();
5174 // make up an email address for handling bounces
5175 if (!empty($CFG->handlebounces
)) {
5176 $modargs = 'B'.base64_encode(pack('V',$user->id
)).substr(md5($user->email
),0,16);
5177 $mail->Sender
= generate_email_processing_address(0,$modargs);
5179 $mail->Sender
= $supportuser->email
;
5182 if (is_string($from)) { // So we can pass whatever we want if there is need
5183 $mail->From
= $CFG->noreplyaddress
;
5184 $mail->FromName
= $from;
5185 } else if ($usetrueaddress and $from->maildisplay
) {
5186 $mail->From
= $from->email
;
5187 $mail->FromName
= fullname($from);
5189 $mail->From
= $CFG->noreplyaddress
;
5190 $mail->FromName
= fullname($from);
5191 if (empty($replyto)) {
5192 $tempreplyto[] = array($CFG->noreplyaddress
, get_string('noreplyname'));
5196 if (!empty($replyto)) {
5197 $tempreplyto[] = array($replyto, $replytoname);
5200 $mail->Subject
= substr($subject, 0, 900);
5202 $temprecipients[] = array($user->email
, fullname($user));
5204 $mail->WordWrap
= $wordwrapwidth; // set word wrap
5206 if (!empty($from->customheaders
)) { // Add custom headers
5207 if (is_array($from->customheaders
)) {
5208 foreach ($from->customheaders
as $customheader) {
5209 $mail->AddCustomHeader($customheader);
5212 $mail->AddCustomHeader($from->customheaders
);
5216 if (!empty($from->priority
)) {
5217 $mail->Priority
= $from->priority
;
5220 if ($messagehtml && !empty($user->mailformat
) && $user->mailformat
== 1) { // Don't ever send HTML to users who don't want it
5221 $mail->IsHTML(true);
5222 $mail->Encoding
= 'quoted-printable'; // Encoding to use
5223 $mail->Body
= $messagehtml;
5224 $mail->AltBody
= "\n$messagetext\n";
5226 $mail->IsHTML(false);
5227 $mail->Body
= "\n$messagetext\n";
5230 if ($attachment && $attachname) {
5231 if (preg_match( "~\\.\\.~" ,$attachment )) { // Security check for ".." in dir path
5232 $temprecipients[] = array($supportuser->email
, fullname($supportuser, true));
5233 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5235 require_once($CFG->libdir
.'/filelib.php');
5236 $mimetype = mimeinfo('type', $attachname);
5237 $mail->AddAttachment($CFG->dataroot
.'/'. $attachment, $attachname, 'base64', $mimetype);
5241 // Check if the email should be sent in an other charset then the default UTF-8
5242 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
5244 // use the defined site mail charset or eventually the one preferred by the recipient
5245 $charset = $CFG->sitemailcharset
;
5246 if (!empty($CFG->allowusermailcharset
)) {
5247 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
5248 $charset = $useremailcharset;
5252 // convert all the necessary strings if the charset is supported
5253 $charsets = get_list_of_charsets();
5254 unset($charsets['UTF-8']);
5255 if (in_array($charset, $charsets)) {
5256 $textlib = textlib_get_instance();
5257 $mail->CharSet
= $charset;
5258 $mail->FromName
= $textlib->convert($mail->FromName
, 'utf-8', strtolower($charset));
5259 $mail->Subject
= $textlib->convert($mail->Subject
, 'utf-8', strtolower($charset));
5260 $mail->Body
= $textlib->convert($mail->Body
, 'utf-8', strtolower($charset));
5261 $mail->AltBody
= $textlib->convert($mail->AltBody
, 'utf-8', strtolower($charset));
5263 foreach ($temprecipients as $key => $values) {
5264 $temprecipients[$key][1] = $textlib->convert($values[1], 'utf-8', strtolower($charset));
5266 foreach ($tempreplyto as $key => $values) {
5267 $tempreplyto[$key][1] = $textlib->convert($values[1], 'utf-8', strtolower($charset));
5272 foreach ($temprecipients as $values) {
5273 $mail->AddAddress($values[0], $values[1]);
5275 foreach ($tempreplyto as $values) {
5276 $mail->AddReplyTo($values[0], $values[1]);
5279 if ($mail->Send()) {
5280 set_send_count($user);
5281 $mail->IsSMTP(); // use SMTP directly
5282 if (!empty($mail->SMTPDebug
)) {
5287 add_to_log(SITEID
, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo
);
5289 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo
);
5291 if (!empty($mail->SMTPDebug
)) {
5299 * Generate a signoff for emails based on support settings
5304 function generate_email_signoff() {
5308 if (!empty($CFG->supportname
)) {
5309 $signoff .= $CFG->supportname
."\n";
5311 if (!empty($CFG->supportemail
)) {
5312 $signoff .= $CFG->supportemail
."\n";
5314 if (!empty($CFG->supportpage
)) {
5315 $signoff .= $CFG->supportpage
."\n";
5321 * Generate a fake user for emails based on support settings
5323 * @return object user info
5325 function generate_email_supportuser() {
5328 static $supportuser;
5330 if (!empty($supportuser)) {
5331 return $supportuser;
5334 $supportuser = new stdClass();
5335 $supportuser->email
= $CFG->supportemail ?
$CFG->supportemail
: $CFG->noreplyaddress
;
5336 $supportuser->firstname
= $CFG->supportname ?
$CFG->supportname
: get_string('noreplyname');
5337 $supportuser->lastname
= '';
5338 $supportuser->maildisplay
= true;
5340 return $supportuser;
5345 * Sets specified user's password and send the new password to the user via email.
5349 * @param user $user A {@link $USER} object
5350 * @return boolean|string Returns "true" if mail was sent OK and "false" if there was an error
5352 function setnew_password_and_mail($user) {
5357 $supportuser = generate_email_supportuser();
5359 $newpassword = generate_password();
5361 $DB->set_field('user', 'password', hash_internal_user_password($newpassword), array('id'=>$user->id
));
5363 $a = new stdClass();
5364 $a->firstname
= fullname($user, true);
5365 $a->sitename
= format_string($site->fullname
);
5366 $a->username
= $user->username
;
5367 $a->newpassword
= $newpassword;
5368 $a->link
= $CFG->wwwroot
.'/login/';
5369 $a->signoff
= generate_email_signoff();
5371 $message = get_string('newusernewpasswordtext', '', $a);
5373 $subject = format_string($site->fullname
) .': '. get_string('newusernewpasswordsubj');
5375 //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
5376 return email_to_user($user, $supportuser, $subject, $message);
5381 * Resets specified user's password and send the new password to the user via email.
5383 * @param stdClass $user A {@link $USER} object
5384 * @return bool Returns true if mail was sent OK and false if there was an error.
5386 function reset_password_and_mail($user) {
5390 $supportuser = generate_email_supportuser();
5392 $userauth = get_auth_plugin($user->auth
);
5393 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth
)) {
5394 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
5398 $newpassword = generate_password();
5400 if (!$userauth->user_update_password($user, $newpassword)) {
5401 print_error("cannotsetpassword");
5404 $a = new stdClass();
5405 $a->firstname
= $user->firstname
;
5406 $a->lastname
= $user->lastname
;
5407 $a->sitename
= format_string($site->fullname
);
5408 $a->username
= $user->username
;
5409 $a->newpassword
= $newpassword;
5410 $a->link
= $CFG->httpswwwroot
.'/login/change_password.php';
5411 $a->signoff
= generate_email_signoff();
5413 $message = get_string('newpasswordtext', '', $a);
5415 $subject = format_string($site->fullname
) .': '. get_string('changedpassword');
5417 unset_user_preference('create_password', $user); // prevent cron from generating the password
5419 //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
5420 return email_to_user($user, $supportuser, $subject, $message);
5425 * Send email to specified user with confirmation text and activation link.
5428 * @param user $user A {@link $USER} object
5429 * @return bool Returns true if mail was sent OK and false if there was an error.
5431 function send_confirmation_email($user) {
5435 $supportuser = generate_email_supportuser();
5437 $data = new stdClass();
5438 $data->firstname
= fullname($user);
5439 $data->sitename
= format_string($site->fullname
);
5440 $data->admin
= generate_email_signoff();
5442 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname
));
5444 $username = urlencode($user->username
);
5445 $username = str_replace('.', '%2E', $username); // prevent problems with trailing dots
5446 $data->link
= $CFG->wwwroot
.'/login/confirm.php?data='. $user->secret
.'/'. $username;
5447 $message = get_string('emailconfirmation', '', $data);
5448 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
5450 $user->mailformat
= 1; // Always send HTML version as well
5452 //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
5453 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
5458 * send_password_change_confirmation_email.
5461 * @param user $user A {@link $USER} object
5462 * @return bool Returns true if mail was sent OK and false if there was an error.
5464 function send_password_change_confirmation_email($user) {
5468 $supportuser = generate_email_supportuser();
5470 $data = new stdClass();
5471 $data->firstname
= $user->firstname
;
5472 $data->lastname
= $user->lastname
;
5473 $data->sitename
= format_string($site->fullname
);
5474 $data->link
= $CFG->httpswwwroot
.'/login/forgot_password.php?p='. $user->secret
.'&s='. urlencode($user->username
);
5475 $data->admin
= generate_email_signoff();
5477 $message = get_string('emailpasswordconfirmation', '', $data);
5478 $subject = get_string('emailpasswordconfirmationsubject', '', format_string($site->fullname
));
5480 //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
5481 return email_to_user($user, $supportuser, $subject, $message);
5486 * send_password_change_info.
5489 * @param user $user A {@link $USER} object
5490 * @return bool Returns true if mail was sent OK and false if there was an error.
5492 function send_password_change_info($user) {
5496 $supportuser = generate_email_supportuser();
5497 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
5499 $data = new stdClass();
5500 $data->firstname
= $user->firstname
;
5501 $data->lastname
= $user->lastname
;
5502 $data->sitename
= format_string($site->fullname
);
5503 $data->admin
= generate_email_signoff();
5505 $userauth = get_auth_plugin($user->auth
);
5507 if (!is_enabled_auth($user->auth
) or $user->auth
== 'nologin') {
5508 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
5509 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
5510 //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
5511 return email_to_user($user, $supportuser, $subject, $message);
5514 if ($userauth->can_change_password() and $userauth->change_password_url()) {
5515 // we have some external url for password changing
5516 $data->link
.= $userauth->change_password_url();
5519 //no way to change password, sorry
5523 if (!empty($data->link
) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id
)) {
5524 $message = get_string('emailpasswordchangeinfo', '', $data);
5525 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
5527 $message = get_string('emailpasswordchangeinfofail', '', $data);
5528 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
5531 //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
5532 return email_to_user($user, $supportuser, $subject, $message);
5537 * Check that an email is allowed. It returns an error message if there
5541 * @param string $email Content of email
5542 * @return string|false
5544 function email_is_not_allowed($email) {
5547 if (!empty($CFG->allowemailaddresses
)) {
5548 $allowed = explode(' ', $CFG->allowemailaddresses
);
5549 foreach ($allowed as $allowedpattern) {
5550 $allowedpattern = trim($allowedpattern);
5551 if (!$allowedpattern) {
5554 if (strpos($allowedpattern, '.') === 0) {
5555 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
5556 // subdomains are in a form ".example.com" - matches "xxx@anything.example.com"
5560 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) { // Match! (bug 5250)
5564 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
5566 } else if (!empty($CFG->denyemailaddresses
)) {
5567 $denied = explode(' ', $CFG->denyemailaddresses
);
5568 foreach ($denied as $deniedpattern) {
5569 $deniedpattern = trim($deniedpattern);
5570 if (!$deniedpattern) {
5573 if (strpos($deniedpattern, '.') === 0) {
5574 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
5575 // subdomains are in a form ".example.com" - matches "xxx@anything.example.com"
5576 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
5579 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) { // Match! (bug 5250)
5580 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
5588 /// FILE HANDLING /////////////////////////////////////////////
5591 * Returns local file storage instance
5593 * @return file_storage
5595 function get_file_storage() {
5604 require_once("$CFG->libdir/filelib.php");
5606 if (isset($CFG->filedir
)) {
5607 $filedir = $CFG->filedir
;
5609 $filedir = $CFG->dataroot
.'/filedir';
5612 if (isset($CFG->trashdir
)) {
5613 $trashdirdir = $CFG->trashdir
;
5615 $trashdirdir = $CFG->dataroot
.'/trashdir';
5618 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions
, $CFG->filepermissions
);
5624 * Returns local file storage instance
5626 * @return file_browser
5628 function get_file_browser() {
5637 require_once("$CFG->libdir/filelib.php");
5639 $fb = new file_browser();
5645 * Returns file packer
5647 * @param string $mimetype default application/zip
5648 * @return file_packer
5650 function get_file_packer($mimetype='application/zip') {
5653 static $fp = array();;
5655 if (isset($fp[$mimetype])) {
5656 return $fp[$mimetype];
5659 switch ($mimetype) {
5660 case 'application/zip':
5661 case 'application/vnd.moodle.backup':
5662 $classname = 'zip_packer';
5664 case 'application/x-tar':
5665 // $classname = 'tar_packer';
5671 require_once("$CFG->libdir/filestorage/$classname.php");
5672 $fp[$mimetype] = new $classname();
5674 return $fp[$mimetype];
5678 * Returns current name of file on disk if it exists.
5680 * @param string $newfile File to be verified
5681 * @return string Current name of file on disk if true
5683 function valid_uploaded_file($newfile) {
5684 if (empty($newfile)) {
5687 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
5688 return $newfile['tmp_name'];
5695 * Returns the maximum size for uploading files.
5697 * There are seven possible upload limits:
5698 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
5699 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
5700 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
5701 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
5702 * 5. by the Moodle admin in $CFG->maxbytes
5703 * 6. by the teacher in the current course $course->maxbytes
5704 * 7. by the teacher for the current module, eg $assignment->maxbytes
5706 * These last two are passed to this function as arguments (in bytes).
5707 * Anything defined as 0 is ignored.
5708 * The smallest of all the non-zero numbers is returned.
5710 * @todo Finish documenting this function
5712 * @param int $sizebytes Set maximum size
5713 * @param int $coursebytes Current course $course->maxbytes (in bytes)
5714 * @param int $modulebytes Current module ->maxbytes (in bytes)
5715 * @return int The maximum size for uploading files.
5717 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
5719 if (! $filesize = ini_get('upload_max_filesize')) {
5722 $minimumsize = get_real_size($filesize);
5724 if ($postsize = ini_get('post_max_size')) {
5725 $postsize = get_real_size($postsize);
5726 if ($postsize < $minimumsize) {
5727 $minimumsize = $postsize;
5731 if ($sitebytes and $sitebytes < $minimumsize) {
5732 $minimumsize = $sitebytes;
5735 if ($coursebytes and $coursebytes < $minimumsize) {
5736 $minimumsize = $coursebytes;
5739 if ($modulebytes and $modulebytes < $minimumsize) {
5740 $minimumsize = $modulebytes;
5743 return $minimumsize;
5747 * Returns an array of possible sizes in local language
5749 * Related to {@link get_max_upload_file_size()} - this function returns an
5750 * array of possible sizes in an array, translated to the
5753 * @todo Finish documenting this function
5756 * @uses SORT_NUMERIC
5757 * @param int $sizebytes Set maximum size
5758 * @param int $coursebytes Current course $course->maxbytes (in bytes)
5759 * @param int $modulebytes Current module ->maxbytes (in bytes)
5762 function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
5765 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
5769 $filesize[intval($maxsize)] = display_size($maxsize);
5771 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
5772 5242880, 10485760, 20971520, 52428800, 104857600);
5774 // Allow maxbytes to be selected if it falls outside the above boundaries
5775 if (isset($CFG->maxbytes
) && !in_array(get_real_size($CFG->maxbytes
), $sizelist)) {
5776 // note: get_real_size() is used in order to prevent problems with invalid values
5777 $sizelist[] = get_real_size($CFG->maxbytes
);
5780 foreach ($sizelist as $sizebytes) {
5781 if ($sizebytes < $maxsize) {
5782 $filesize[intval($sizebytes)] = display_size($sizebytes);
5786 krsort($filesize, SORT_NUMERIC
);
5792 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
5794 * If excludefiles is defined, then that file/directory is ignored
5795 * If getdirs is true, then (sub)directories are included in the output
5796 * If getfiles is true, then files are included in the output
5797 * (at least one of these must be true!)
5799 * @todo Finish documenting this function. Add examples of $excludefile usage.
5801 * @param string $rootdir A given root directory to start from
5802 * @param string|array $excludefile If defined then the specified file/directory is ignored
5803 * @param bool $descend If true then subdirectories are recursed as well
5804 * @param bool $getdirs If true then (sub)directories are included in the output
5805 * @param bool $getfiles If true then files are included in the output
5806 * @return array An array with all the filenames in
5807 * all subdirectories, relative to the given rootdir
5809 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
5813 if (!$getdirs and !$getfiles) { // Nothing to show
5817 if (!is_dir($rootdir)) { // Must be a directory
5821 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
5825 if (!is_array($excludefiles)) {
5826 $excludefiles = array($excludefiles);
5829 while (false !== ($file = readdir($dir))) {
5830 $firstchar = substr($file, 0, 1);
5831 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
5834 $fullfile = $rootdir .'/'. $file;
5835 if (filetype($fullfile) == 'dir') {
5840 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
5841 foreach ($subdirs as $subdir) {
5842 $dirs[] = $file .'/'. $subdir;
5845 } else if ($getfiles) {
5858 * Adds up all the files in a directory and works out the size.
5860 * @todo Finish documenting this function
5862 * @param string $rootdir The directory to start from
5863 * @param string $excludefile A file to exclude when summing directory size
5864 * @return int The summed size of all files and subfiles within the root directory
5866 function get_directory_size($rootdir, $excludefile='') {
5869 // do it this way if we can, it's much faster
5870 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
5871 $command = trim($CFG->pathtodu
).' -sk '.escapeshellarg($rootdir);
5874 exec($command,$output,$return);
5875 if (is_array($output)) {
5876 return get_real_size(intval($output[0]).'k'); // we told it to return k.
5880 if (!is_dir($rootdir)) { // Must be a directory
5884 if (!$dir = @opendir
($rootdir)) { // Can't open it for some reason
5890 while (false !== ($file = readdir($dir))) {
5891 $firstchar = substr($file, 0, 1);
5892 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
5895 $fullfile = $rootdir .'/'. $file;
5896 if (filetype($fullfile) == 'dir') {
5897 $size +
= get_directory_size($fullfile, $excludefile);
5899 $size +
= filesize($fullfile);
5908 * Converts bytes into display form
5910 * @todo Finish documenting this function. Verify return type.
5912 * @staticvar string $gb Localized string for size in gigabytes
5913 * @staticvar string $mb Localized string for size in megabytes
5914 * @staticvar string $kb Localized string for size in kilobytes
5915 * @staticvar string $b Localized string for size in bytes
5916 * @param int $size The size to convert to human readable form
5919 function display_size($size) {
5921 static $gb, $mb, $kb, $b;
5924 $gb = get_string('sizegb');
5925 $mb = get_string('sizemb');
5926 $kb = get_string('sizekb');
5927 $b = get_string('sizeb');
5930 if ($size >= 1073741824) {
5931 $size = round($size / 1073741824 * 10) / 10 . $gb;
5932 } else if ($size >= 1048576) {
5933 $size = round($size / 1048576 * 10) / 10 . $mb;
5934 } else if ($size >= 1024) {
5935 $size = round($size / 1024 * 10) / 10 . $kb;
5937 $size = intval($size) .' '. $b; // file sizes over 2GB can not work in 32bit PHP anyway
5943 * Cleans a given filename by removing suspicious or troublesome characters
5944 * @see clean_param()
5947 * @param string $string file name
5948 * @return string cleaned file name
5950 function clean_filename($string) {
5951 return clean_param($string, PARAM_FILE
);
5955 /// STRING TRANSLATION ////////////////////////////////////////
5958 * Returns the code for the current language
5962 function current_language() {
5963 global $CFG, $USER, $SESSION, $COURSE;
5965 if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) { // Course language can override all other settings for this page
5966 $return = $COURSE->lang
;
5968 } else if (!empty($SESSION->lang
)) { // Session language can override other settings
5969 $return = $SESSION->lang
;
5971 } else if (!empty($USER->lang
)) {
5972 $return = $USER->lang
;
5974 } else if (isset($CFG->lang
)) {
5975 $return = $CFG->lang
;
5981 $return = str_replace('_utf8', '', $return); // Just in case this slipped in from somewhere by accident
5987 * Returns parent language of current active language if defined
5991 * @param string $lang null means current language
5994 function get_parent_language($lang=null) {
5995 global $COURSE, $SESSION;
5997 //let's hack around the current language
5998 if (!empty($lang)) {
5999 $old_course_lang = empty($COURSE->lang
) ?
'' : $COURSE->lang
;
6000 $old_session_lang = empty($SESSION->lang
) ?
'' : $SESSION->lang
;
6002 $SESSION->lang
= $lang;
6005 $parentlang = get_string('parentlanguage', 'langconfig');
6006 if ($parentlang === 'en') {
6010 //let's hack around the current language
6011 if (!empty($lang)) {
6012 $COURSE->lang
= $old_course_lang;
6013 $SESSION->lang
= $old_session_lang;
6020 * Returns current string_manager instance.
6022 * The param $forcereload is needed for CLI installer only where the string_manager instance
6023 * must be replaced during the install.php script life time.
6025 * @param bool $forcereload shall the singleton be released and new instance created instead?
6026 * @return string_manager
6028 function get_string_manager($forcereload=false) {
6031 static $singleton = null;
6036 if ($singleton === null) {
6037 if (empty($CFG->early_install_lang
)) {
6039 if (empty($CFG->langcacheroot
)) {
6040 $langcacheroot = $CFG->cachedir
. '/lang';
6042 $langcacheroot = $CFG->langcacheroot
;
6045 if (empty($CFG->langlist
)) {
6046 $translist = array();
6048 $translist = explode(',', $CFG->langlist
);
6051 if (empty($CFG->langmenucachefile
)) {
6052 $langmenucache = $CFG->cachedir
. '/languages';
6054 $langmenucache = $CFG->langmenucachefile
;
6057 $singleton = new core_string_manager($CFG->langotherroot
, $CFG->langlocalroot
, $langcacheroot,
6058 !empty($CFG->langstringcache
), $translist, $langmenucache);
6061 $singleton = new install_string_manager();
6070 * Interface describing class which is responsible for getting
6071 * of localised strings from language packs.
6073 * @package moodlecore
6074 * @copyright 2010 Petr Skoda (http://skodak.org)
6075 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6077 interface string_manager
{
6079 * Get String returns a requested string
6081 * @param string $identifier The identifier of the string to search for
6082 * @param string $component The module the string is associated with
6083 * @param string|object|array $a An object, string or number that can be used
6084 * within translation strings
6085 * @param string $lang moodle translation language, NULL means use current
6086 * @return string The String !
6088 public function get_string($identifier, $component = '', $a = NULL, $lang = NULL);
6091 * Does the string actually exist?
6093 * get_string() is throwing debug warnings, sometimes we do not want them
6094 * or we want to display better explanation of the problem.
6098 * @param string $identifier The identifier of the string to search for
6099 * @param string $component The module the string is associated with
6100 * @return boot true if exists
6102 public function string_exists($identifier, $component);
6105 * Returns a localised list of all country names, sorted by country keys.
6106 * @param bool $returnall return all or just enabled
6107 * @param string $lang moodle translation language, NULL means use current
6108 * @return array two-letter country code => translated name.
6110 public function get_list_of_countries($returnall = false, $lang = NULL);
6113 * Returns a localised list of languages, sorted by code keys.
6115 * @param string $lang moodle translation language, NULL means use current
6116 * @param string $standard language list standard
6117 * iso6392: three-letter language code (ISO 639-2/T) => translated name.
6118 * @return array language code => translated name
6120 public function get_list_of_languages($lang = NULL, $standard = 'iso6392');
6123 * Does the translation exist?
6125 * @param string $lang moodle translation language code
6126 * @param bool include also disabled translations?
6127 * @return boot true if exists
6129 public function translation_exists($lang, $includeall = true);
6132 * Returns localised list of installed translations
6133 * @param bool $returnall return all or just enabled
6134 * @return array moodle translation code => localised translation name
6136 public function get_list_of_translations($returnall = false);
6139 * Returns localised list of currencies.
6141 * @param string $lang moodle translation language, NULL means use current
6142 * @return array currency code => localised currency name
6144 public function get_list_of_currencies($lang = NULL);
6147 * Load all strings for one component
6148 * @param string $component The module the string is associated with
6149 * @param string $lang
6150 * @param bool $disablecache Do not use caches, force fetching the strings from sources
6151 * @param bool $disablelocal Do not use customized strings in xx_local language packs
6152 * @return array of all string for given component and lang
6154 public function load_component_strings($component, $lang, $disablecache=false, $disablelocal=false);
6157 * Invalidates all caches, should the implementation use any
6159 public function reset_caches();
6164 * Standard string_manager implementation
6166 * @package moodlecore
6167 * @copyright 2010 Petr Skoda (http://skodak.org)
6168 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6170 class core_string_manager
implements string_manager
{
6171 /** @var string location of all packs except 'en' */
6172 protected $otherroot;
6173 /** @var string location of all lang pack local modifications */
6174 protected $localroot;
6175 /** @var string location of on-disk cache of merged strings */
6176 protected $cacheroot;
6177 /** @var array lang string cache - it will be optimised more later */
6178 protected $cache = array();
6179 /** @var int get_string() counter */
6180 protected $countgetstring = 0;
6181 /** @var int in-memory cache hits counter */
6182 protected $countmemcache = 0;
6183 /** @var int on-disk cache hits counter */
6184 protected $countdiskcache = 0;
6185 /** @var bool use disk cache */
6186 protected $usediskcache;
6187 /* @var array limit list of translations */
6188 protected $translist;
6189 /** @var string location of a file that caches the list of available translations */
6190 protected $menucache;
6193 * Create new instance of string manager
6195 * @param string $otherroot location of downlaoded lang packs - usually $CFG->dataroot/lang
6196 * @param string $localroot usually the same as $otherroot
6197 * @param string $cacheroot usually lang dir in cache folder
6198 * @param bool $usediskcache use disk cache
6199 * @param array $translist limit list of visible translations
6200 * @param string $menucache the location of a file that caches the list of available translations
6202 public function __construct($otherroot, $localroot, $cacheroot, $usediskcache, $translist, $menucache) {
6203 $this->otherroot
= $otherroot;
6204 $this->localroot
= $localroot;
6205 $this->cacheroot
= $cacheroot;
6206 $this->usediskcache
= $usediskcache;
6207 $this->translist
= $translist;
6208 $this->menucache
= $menucache;
6212 * Returns dependencies of current language, en is not included.
6213 * @param string $lang
6214 * @return array all parents, the lang itself is last
6216 public function get_language_dependencies($lang) {
6217 if ($lang === 'en') {
6220 if (!file_exists("$this->otherroot/$lang/langconfig.php")) {
6224 include("$this->otherroot/$lang/langconfig.php");
6226 if (empty($string['parentlanguage'])) {
6227 return array($lang);
6229 $parentlang = $string['parentlanguage'];
6231 return array_merge($this->get_language_dependencies($parentlang), array($lang));
6236 * Load all strings for one component
6237 * @param string $component The module the string is associated with
6238 * @param string $lang
6239 * @param bool $disablecache Do not use caches, force fetching the strings from sources
6240 * @param bool $disablelocal Do not use customized strings in xx_local language packs
6241 * @return array of all string for given component and lang
6243 public function load_component_strings($component, $lang, $disablecache=false, $disablelocal=false) {
6246 list($plugintype, $pluginname) = normalize_component($component);
6247 if ($plugintype == 'core' and is_null($pluginname)) {
6248 $component = 'core';
6250 $component = $plugintype . '_' . $pluginname;
6253 if (!$disablecache) {
6254 // try in-memory cache first
6255 if (isset($this->cache
[$lang][$component])) {
6256 $this->countmemcache++
;
6257 return $this->cache
[$lang][$component];
6260 // try on-disk cache then
6261 if ($this->usediskcache
and file_exists($this->cacheroot
. "/$lang/$component.php")) {
6262 $this->countdiskcache++
;
6263 include($this->cacheroot
. "/$lang/$component.php");
6264 return $this->cache
[$lang][$component];
6268 // no cache found - let us merge all possible sources of the strings
6269 if ($plugintype === 'core') {
6270 $file = $pluginname;
6271 if ($file === null) {
6275 // first load english pack
6276 if (!file_exists("$CFG->dirroot/lang/en/$file.php")) {
6279 include("$CFG->dirroot/lang/en/$file.php");
6280 $originalkeys = array_keys($string);
6281 $originalkeys = array_flip($originalkeys);
6283 // and then corresponding local if present and allowed
6284 if (!$disablelocal and file_exists("$this->localroot/en_local/$file.php")) {
6285 include("$this->localroot/en_local/$file.php");
6287 // now loop through all langs in correct order
6288 $deps = $this->get_language_dependencies($lang);
6289 foreach ($deps as $dep) {
6290 // the main lang string location
6291 if (file_exists("$this->otherroot/$dep/$file.php")) {
6292 include("$this->otherroot/$dep/$file.php");
6294 if (!$disablelocal and file_exists("$this->localroot/{$dep}_local/$file.php")) {
6295 include("$this->localroot/{$dep}_local/$file.php");
6300 if (!$location = get_plugin_directory($plugintype, $pluginname) or !is_dir($location)) {
6303 if ($plugintype === 'mod') {
6305 $file = $pluginname;
6307 $file = $plugintype . '_' . $pluginname;
6310 // first load English pack
6311 if (!file_exists("$location/lang/en/$file.php")) {
6312 //English pack does not exist, so do not try to load anything else
6315 include("$location/lang/en/$file.php");
6316 $originalkeys = array_keys($string);
6317 $originalkeys = array_flip($originalkeys);
6318 // and then corresponding local english if present
6319 if (!$disablelocal and file_exists("$this->localroot/en_local/$file.php")) {
6320 include("$this->localroot/en_local/$file.php");
6323 // now loop through all langs in correct order
6324 $deps = $this->get_language_dependencies($lang);
6325 foreach ($deps as $dep) {
6326 // legacy location - used by contrib only
6327 if (file_exists("$location/lang/$dep/$file.php")) {
6328 include("$location/lang/$dep/$file.php");
6330 // the main lang string location
6331 if (file_exists("$this->otherroot/$dep/$file.php")) {
6332 include("$this->otherroot/$dep/$file.php");
6334 // local customisations
6335 if (!$disablelocal and file_exists("$this->localroot/{$dep}_local/$file.php")) {
6336 include("$this->localroot/{$dep}_local/$file.php");
6341 // we do not want any extra strings from other languages - everything must be in en lang pack
6342 $string = array_intersect_key($string, $originalkeys);
6344 // now we have a list of strings from all possible sources. put it into both in-memory and on-disk
6345 // caches so we do not need to do all this merging and dependencies resolving again
6346 $this->cache
[$lang][$component] = $string;
6347 if ($this->usediskcache
) {
6348 check_dir_exists("$this->cacheroot/$lang");
6349 file_put_contents("$this->cacheroot/$lang/$component.php", "<?php \$this->cache['$lang']['$component'] = ".var_export($string, true).";");
6355 * Does the string actually exist?
6357 * get_string() is throwing debug warnings, sometimes we do not want them
6358 * or we want to display better explanation of the problem.
6362 * @param string $identifier The identifier of the string to search for
6363 * @param string $component The module the string is associated with
6364 * @return boot true if exists
6366 public function string_exists($identifier, $component) {
6367 $identifier = clean_param($identifier, PARAM_STRINGID
);
6368 if (empty($identifier)) {
6371 $lang = current_language();
6372 $string = $this->load_component_strings($component, $lang);
6373 return isset($string[$identifier]);
6377 * Get String returns a requested string
6379 * @param string $identifier The identifier of the string to search for
6380 * @param string $component The module the string is associated with
6381 * @param string|object|array $a An object, string or number that can be used
6382 * within translation strings
6383 * @param string $lang moodle translation language, NULL means use current
6384 * @return string The String !
6386 public function get_string($identifier, $component = '', $a = NULL, $lang = NULL) {
6387 $this->countgetstring++
;
6388 // there are very many uses of these time formating strings without the 'langconfig' component,
6389 // it would not be reasonable to expect that all of them would be converted during 2.0 migration
6390 static $langconfigstrs = array(
6391 'strftimedate' => 1,
6392 'strftimedatefullshort' => 1,
6393 'strftimedateshort' => 1,
6394 'strftimedatetime' => 1,
6395 'strftimedatetimeshort' => 1,
6396 'strftimedaydate' => 1,
6397 'strftimedaydatetime' => 1,
6398 'strftimedayshort' => 1,
6399 'strftimedaytime' => 1,
6400 'strftimemonthyear' => 1,
6401 'strftimerecent' => 1,
6402 'strftimerecentfull' => 1,
6403 'strftimetime' => 1);
6405 if (empty($component)) {
6406 if (isset($langconfigstrs[$identifier])) {
6407 $component = 'langconfig';
6409 $component = 'moodle';
6413 if ($lang === NULL) {
6414 $lang = current_language();
6417 $string = $this->load_component_strings($component, $lang);
6419 if (!isset($string[$identifier])) {
6420 if ($component === 'pix' or $component === 'core_pix') {
6421 // this component contains only alt tags for emoticons,
6422 // not all of them are supposed to be defined
6425 if ($identifier === 'parentlanguage' and ($component === 'langconfig' or $component === 'core_langconfig')) {
6426 // parentlanguage is a special string, undefined means use English if not defined
6429 if ($this->usediskcache
) {
6430 // maybe the on-disk cache is dirty - let the last attempt be to find the string in original sources
6431 $string = $this->load_component_strings($component, $lang, true);
6433 if (!isset($string[$identifier])) {
6434 // the string is still missing - should be fixed by developer
6435 list($plugintype, $pluginname) = normalize_component($component);
6436 if ($plugintype == 'core') {
6437 $file = "lang/en/{$component}.php";
6438 } else if ($plugintype == 'mod') {
6439 $file = "mod/{$pluginname}/lang/en/{$pluginname}.php";
6441 $path = get_plugin_directory($plugintype, $pluginname);
6442 $file = "{$path}/lang/en/{$plugintype}_{$pluginname}.php";
6444 debugging("Invalid get_string() identifier: '{$identifier}' or component '{$component}'. " .
6445 "Perhaps you are missing \$string['{$identifier}'] = ''; in {$file}?", DEBUG_DEVELOPER
);
6446 return "[[$identifier]]";
6450 $string = $string[$identifier];
6453 if (is_object($a) or is_array($a)) {
6457 foreach ($a as $key=>$value) {
6459 // we do not support numeric keys - sorry!
6462 if (is_object($value) or is_array($value)) {
6463 // we support just string as value
6466 $search[] = '{$a->'.$key.'}';
6467 $replace[] = (string)$value;
6470 $string = str_replace($search, $replace, $string);
6473 $string = str_replace('{$a}', (string)$a, $string);
6481 * Returns information about the string_manager performance
6484 public function get_performance_summary() {
6486 'langcountgetstring' => $this->countgetstring
,
6487 'langcountmemcache' => $this->countmemcache
,
6488 'langcountdiskcache' => $this->countdiskcache
,
6490 'langcountgetstring' => 'get_string calls',
6491 'langcountmemcache' => 'strings mem cache hits',
6492 'langcountdiskcache' => 'strings disk cache hits',
6497 * Returns a localised list of all country names, sorted by localised name.
6499 * @param bool $returnall return all or just enabled
6500 * @param string $lang moodle translation language, NULL means use current
6501 * @return array two-letter country code => translated name.
6503 public function get_list_of_countries($returnall = false, $lang = NULL) {
6506 if ($lang === NULL) {
6507 $lang = current_language();
6510 $countries = $this->load_component_strings('core_countries', $lang);
6511 collatorlib
::asort($countries);
6512 if (!$returnall and !empty($CFG->allcountrycodes
)) {
6513 $enabled = explode(',', $CFG->allcountrycodes
);
6515 foreach ($enabled as $c) {
6516 if (isset($countries[$c])) {
6517 $return[$c] = $countries[$c];
6527 * Returns a localised list of languages, sorted by code keys.
6529 * @param string $lang moodle translation language, NULL means use current
6530 * @param string $standard language list standard
6531 * - iso6392: three-letter language code (ISO 639-2/T) => translated name
6532 * - iso6391: two-letter langauge code (ISO 639-1) => translated name
6533 * @return array language code => translated name
6535 public function get_list_of_languages($lang = NULL, $standard = 'iso6391') {
6536 if ($lang === NULL) {
6537 $lang = current_language();
6540 if ($standard === 'iso6392') {
6541 $langs = $this->load_component_strings('core_iso6392', $lang);
6545 } else if ($standard === 'iso6391') {
6546 $langs2 = $this->load_component_strings('core_iso6392', $lang);
6547 static $mapping = array('aar' => 'aa', 'abk' => 'ab', 'afr' => 'af', 'aka' => 'ak', 'sqi' => 'sq', 'amh' => 'am', 'ara' => 'ar', 'arg' => 'an', 'hye' => 'hy',
6548 'asm' => 'as', 'ava' => 'av', 'ave' => 'ae', 'aym' => 'ay', 'aze' => 'az', 'bak' => 'ba', 'bam' => 'bm', 'eus' => 'eu', 'bel' => 'be', 'ben' => 'bn', 'bih' => 'bh',
6549 'bis' => 'bi', 'bos' => 'bs', 'bre' => 'br', 'bul' => 'bg', 'mya' => 'my', 'cat' => 'ca', 'cha' => 'ch', 'che' => 'ce', 'zho' => 'zh', 'chu' => 'cu', 'chv' => 'cv',
6550 'cor' => 'kw', 'cos' => 'co', 'cre' => 'cr', 'ces' => 'cs', 'dan' => 'da', 'div' => 'dv', 'nld' => 'nl', 'dzo' => 'dz', 'eng' => 'en', 'epo' => 'eo', 'est' => 'et',
6551 'ewe' => 'ee', 'fao' => 'fo', 'fij' => 'fj', 'fin' => 'fi', 'fra' => 'fr', 'fry' => 'fy', 'ful' => 'ff', 'kat' => 'ka', 'deu' => 'de', 'gla' => 'gd', 'gle' => 'ga',
6552 'glg' => 'gl', 'glv' => 'gv', 'ell' => 'el', 'grn' => 'gn', 'guj' => 'gu', 'hat' => 'ht', 'hau' => 'ha', 'heb' => 'he', 'her' => 'hz', 'hin' => 'hi', 'hmo' => 'ho',
6553 'hrv' => 'hr', 'hun' => 'hu', 'ibo' => 'ig', 'isl' => 'is', 'ido' => 'io', 'iii' => 'ii', 'iku' => 'iu', 'ile' => 'ie', 'ina' => 'ia', 'ind' => 'id', 'ipk' => 'ik',
6554 'ita' => 'it', 'jav' => 'jv', 'jpn' => 'ja', 'kal' => 'kl', 'kan' => 'kn', 'kas' => 'ks', 'kau' => 'kr', 'kaz' => 'kk', 'khm' => 'km', 'kik' => 'ki', 'kin' => 'rw',
6555 'kir' => 'ky', 'kom' => 'kv', 'kon' => 'kg', 'kor' => 'ko', 'kua' => 'kj', 'kur' => 'ku', 'lao' => 'lo', 'lat' => 'la', 'lav' => 'lv', 'lim' => 'li', 'lin' => 'ln',
6556 'lit' => 'lt', 'ltz' => 'lb', 'lub' => 'lu', 'lug' => 'lg', 'mkd' => 'mk', 'mah' => 'mh', 'mal' => 'ml', 'mri' => 'mi', 'mar' => 'mr', 'msa' => 'ms', 'mlg' => 'mg',
6557 'mlt' => 'mt', 'mon' => 'mn', 'nau' => 'na', 'nav' => 'nv', 'nbl' => 'nr', 'nde' => 'nd', 'ndo' => 'ng', 'nep' => 'ne', 'nno' => 'nn', 'nob' => 'nb', 'nor' => 'no',
6558 'nya' => 'ny', 'oci' => 'oc', 'oji' => 'oj', 'ori' => 'or', 'orm' => 'om', 'oss' => 'os', 'pan' => 'pa', 'fas' => 'fa', 'pli' => 'pi', 'pol' => 'pl', 'por' => 'pt',
6559 'pus' => 'ps', 'que' => 'qu', 'roh' => 'rm', 'ron' => 'ro', 'run' => 'rn', 'rus' => 'ru', 'sag' => 'sg', 'san' => 'sa', 'sin' => 'si', 'slk' => 'sk', 'slv' => 'sl',
6560 'sme' => 'se', 'smo' => 'sm', 'sna' => 'sn', 'snd' => 'sd', 'som' => 'so', 'sot' => 'st', 'spa' => 'es', 'srd' => 'sc', 'srp' => 'sr', 'ssw' => 'ss', 'sun' => 'su',
6561 'swa' => 'sw', 'swe' => 'sv', 'tah' => 'ty', 'tam' => 'ta', 'tat' => 'tt', 'tel' => 'te', 'tgk' => 'tg', 'tgl' => 'tl', 'tha' => 'th', 'bod' => 'bo', 'tir' => 'ti',
6562 'ton' => 'to', 'tsn' => 'tn', 'tso' => 'ts', 'tuk' => 'tk', 'tur' => 'tr', 'twi' => 'tw', 'uig' => 'ug', 'ukr' => 'uk', 'urd' => 'ur', 'uzb' => 'uz', 'ven' => 've',
6563 'vie' => 'vi', 'vol' => 'vo', 'cym' => 'cy', 'wln' => 'wa', 'wol' => 'wo', 'xho' => 'xh', 'yid' => 'yi', 'yor' => 'yo', 'zha' => 'za', 'zul' => 'zu');
6565 foreach ($mapping as $c2=>$c1) {
6566 $langs1[$c1] = $langs2[$c2];
6572 debugging('Unsupported $standard parameter in get_list_of_languages() method: '.$standard);
6579 * Does the translation exist?
6581 * @param string $lang moodle translation language code
6582 * @param bool include also disabled translations?
6583 * @return boot true if exists
6585 public function translation_exists($lang, $includeall = true) {
6587 if (strpos($lang, '_local') !== false) {
6588 // _local packs are not real translations
6591 if (!$includeall and !empty($this->translist
)) {
6592 if (!in_array($lang, $this->translist
)) {
6596 if ($lang === 'en') {
6597 // part of distribution
6600 return file_exists("$this->otherroot/$lang/langconfig.php");
6604 * Returns localised list of installed translations
6605 * @param bool $returnall return all or just enabled
6606 * @return array moodle translation code => localised translation name
6608 public function get_list_of_translations($returnall = false) {
6611 $languages = array();
6613 if (!empty($CFG->langcache
) and is_readable($this->menucache
)) {
6614 // try to re-use the cached list of all available languages
6615 $cachedlist = json_decode(file_get_contents($this->menucache
), true);
6617 if (is_array($cachedlist) and !empty($cachedlist)) {
6618 // the cache file is restored correctly
6620 if (!$returnall and !empty($this->translist
)) {
6621 // return just enabled translations
6622 foreach ($cachedlist as $langcode => $langname) {
6623 if (in_array($langcode, $this->translist
)) {
6624 $languages[$langcode] = $langname;
6630 // return all translations
6636 // the cached list of languages is not available, let us populate the list
6638 if (!$returnall and !empty($this->translist
)) {
6639 // return only some translations
6640 foreach ($this->translist
as $lang) {
6641 $lang = trim($lang); //Just trim spaces to be a bit more permissive
6642 if (strstr($lang, '_local') !== false) {
6645 if (strstr($lang, '_utf8') !== false) {
6648 if ($lang !== 'en' and !file_exists("$this->otherroot/$lang/langconfig.php")) {
6649 // some broken or missing lang - can not switch to it anyway
6652 $string = $this->load_component_strings('langconfig', $lang);
6653 if (!empty($string['thislanguage'])) {
6654 $languages[$lang] = $string['thislanguage'].' ('. $lang .')';
6660 // return all languages available in system
6661 $langdirs = get_list_of_plugins('', '', $this->otherroot
);
6663 $langdirs = array_merge($langdirs, array("$CFG->dirroot/lang/en"=>'en'));
6666 // Loop through all langs and get info
6667 foreach ($langdirs as $lang) {
6668 if (strstr($lang, '_local') !== false) {
6671 if (strstr($lang, '_utf8') !== false) {
6674 $string = $this->load_component_strings('langconfig', $lang);
6675 if (!empty($string['thislanguage'])) {
6676 $languages[$lang] = $string['thislanguage'].' ('. $lang .')';
6681 if (!empty($CFG->langcache
) and !empty($this->menucache
)) {
6682 // cache the list so that it can be used next time
6683 collatorlib
::asort($languages);
6684 check_dir_exists(dirname($this->menucache
), true, true);
6685 file_put_contents($this->menucache
, json_encode($languages));
6689 collatorlib
::asort($languages);
6695 * Returns localised list of currencies.
6697 * @param string $lang moodle translation language, NULL means use current
6698 * @return array currency code => localised currency name
6700 public function get_list_of_currencies($lang = NULL) {
6701 if ($lang === NULL) {
6702 $lang = current_language();
6705 $currencies = $this->load_component_strings('core_currencies', $lang);
6712 * Clears both in-memory and on-disk caches
6714 public function reset_caches() {
6716 require_once("$CFG->libdir/filelib.php");
6718 // clear the on-disk disk with aggregated string files
6719 fulldelete($this->cacheroot
);
6721 // clear the in-memory cache of loaded strings
6722 $this->cache
= array();
6724 // clear the cache containing the list of available translations
6725 // and re-populate it again
6726 fulldelete($this->menucache
);
6727 $this->get_list_of_translations(true);
6733 * Minimalistic string fetching implementation
6734 * that is used in installer before we fetch the wanted
6735 * language pack from moodle.org lang download site.
6737 * @package moodlecore
6738 * @copyright 2010 Petr Skoda (http://skodak.org)
6739 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6741 class install_string_manager
implements string_manager
{
6742 /** @var string location of pre-install packs for all langs */
6743 protected $installroot;
6746 * Crate new instance of install string manager
6748 public function __construct() {
6750 $this->installroot
= "$CFG->dirroot/install/lang";
6754 * Load all strings for one component
6755 * @param string $component The module the string is associated with
6756 * @param string $lang
6757 * @param bool $disablecache Do not use caches, force fetching the strings from sources
6758 * @param bool $disablelocal Do not use customized strings in xx_local language packs
6759 * @return array of all string for given component and lang
6761 public function load_component_strings($component, $lang, $disablecache=false, $disablelocal=false) {
6762 // not needed in installer
6767 * Does the string actually exist?
6769 * get_string() is throwing debug warnings, sometimes we do not want them
6770 * or we want to display better explanation of the problem.
6774 * @param string $identifier The identifier of the string to search for
6775 * @param string $component The module the string is associated with
6776 * @return boot true if exists
6778 public function string_exists($identifier, $component) {
6779 $identifier = clean_param($identifier, PARAM_STRINGID
);
6780 if (empty($identifier)) {
6783 // simple old style hack ;)
6784 $str = get_string($identifier, $component);
6785 return (strpos($str, '[[') === false);
6789 * Get String returns a requested string
6791 * @param string $identifier The identifier of the string to search for
6792 * @param string $component The module the string is associated with
6793 * @param string|object|array $a An object, string or number that can be used
6794 * within translation strings
6795 * @param string $lang moodle translation language, NULL means use current
6796 * @return string The String !
6798 public function get_string($identifier, $component = '', $a = NULL, $lang = NULL) {
6800 $component = 'moodle';
6803 if ($lang === NULL) {
6804 $lang = current_language();
6809 if ($lang !== 'en' and $identifier !== 'parentlanguage' and $component !== 'langconfig') {
6810 if (file_exists("$this->installroot/$lang/langconfig.php")) {
6812 include("$this->installroot/$lang/langconfig.php");
6813 if (isset($string['parentlanguage'])) {
6814 $parent = $string['parentlanguage'];
6820 // include en string first
6821 if (!file_exists("$this->installroot/en/$component.php")) {
6822 return "[[$identifier]]";
6825 include("$this->installroot/en/$component.php");
6827 // now override en with parent if defined
6828 if ($parent and $parent !== 'en' and file_exists("$this->installroot/$parent/$component.php")) {
6829 include("$this->installroot/$parent/$component.php");
6832 // finally override with requested language
6833 if ($lang !== 'en' and file_exists("$this->installroot/$lang/$component.php")) {
6834 include("$this->installroot/$lang/$component.php");
6837 if (!isset($string[$identifier])) {
6838 return "[[$identifier]]";
6841 $string = $string[$identifier];
6844 if (is_object($a) or is_array($a)) {
6848 foreach ($a as $key=>$value) {
6850 // we do not support numeric keys - sorry!
6853 $search[] = '{$a->'.$key.'}';
6854 $replace[] = (string)$value;
6857 $string = str_replace($search, $replace, $string);
6860 $string = str_replace('{$a}', (string)$a, $string);
6868 * Returns a localised list of all country names, sorted by country keys.
6870 * @param bool $returnall return all or just enabled
6871 * @param string $lang moodle translation language, NULL means use current
6872 * @return array two-letter country code => translated name.
6874 public function get_list_of_countries($returnall = false, $lang = NULL) {
6875 //not used in installer
6880 * Returns a localised list of languages, sorted by code keys.
6882 * @param string $lang moodle translation language, NULL means use current
6883 * @param string $standard language list standard
6884 * iso6392: three-letter language code (ISO 639-2/T) => translated name.
6885 * @return array language code => translated name
6887 public function get_list_of_languages($lang = NULL, $standard = 'iso6392') {
6888 //not used in installer
6893 * Does the translation exist?
6895 * @param string $lang moodle translation language code
6896 * @param bool include also disabled translations?
6897 * @return boot true if exists
6899 public function translation_exists($lang, $includeall = true) {
6900 return file_exists($this->installroot
.'/'.$lang.'/langconfig.php');
6904 * Returns localised list of installed translations
6905 * @param bool $returnall return all or just enabled
6906 * @return array moodle translation code => localised translation name
6908 public function get_list_of_translations($returnall = false) {
6909 // return all is ignored here - we need to know all langs in installer
6910 $languages = array();
6911 // Get raw list of lang directories
6912 $langdirs = get_list_of_plugins('install/lang');
6914 // Get some info from each lang
6915 foreach ($langdirs as $lang) {
6916 if (file_exists($this->installroot
.'/'.$lang.'/langconfig.php')) {
6918 include($this->installroot
.'/'.$lang.'/langconfig.php');
6919 if (!empty($string['thislanguage'])) {
6920 $languages[$lang] = $string['thislanguage'].' ('.$lang.')';
6929 * Returns localised list of currencies.
6931 * @param string $lang moodle translation language, NULL means use current
6932 * @return array currency code => localised currency name
6934 public function get_list_of_currencies($lang = NULL) {
6935 // not used in installer
6940 * This implementation does not use any caches
6942 public function reset_caches() {}
6947 * Returns a localized string.
6949 * Returns the translated string specified by $identifier as
6950 * for $module. Uses the same format files as STphp.
6951 * $a is an object, string or number that can be used
6952 * within translation strings
6954 * eg 'hello {$a->firstname} {$a->lastname}'
6957 * If you would like to directly echo the localized string use
6958 * the function {@link print_string()}
6960 * Example usage of this function involves finding the string you would
6961 * like a local equivalent of and using its identifier and module information
6962 * to retrieve it.<br/>
6963 * If you open moodle/lang/en/moodle.php and look near line 278
6964 * you will find a string to prompt a user for their word for 'course'
6966 * $string['course'] = 'Course';
6968 * So if you want to display the string 'Course'
6969 * in any language that supports it on your site
6970 * you just need to use the identifier 'course'
6972 * $mystring = '<strong>'. get_string('course') .'</strong>';
6975 * If the string you want is in another file you'd take a slightly
6976 * different approach. Looking in moodle/lang/en/calendar.php you find
6979 * $string['typecourse'] = 'Course event';
6981 * If you want to display the string "Course event" in any language
6982 * supported you would use the identifier 'typecourse' and the module 'calendar'
6983 * (because it is in the file calendar.php):
6985 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6988 * As a last resort, should the identifier fail to map to a string
6989 * the returned string will be [[ $identifier ]]
6991 * @param string $identifier The key identifier for the localized string
6992 * @param string $component The module where the key identifier is stored,
6993 * usually expressed as the filename in the language pack without the
6994 * .php on the end but can also be written as mod/forum or grade/export/xls.
6995 * If none is specified then moodle.php is used.
6996 * @param string|object|array $a An object, string or number that can be used
6997 * within translation strings
6998 * @return string The localized string.
7000 function get_string($identifier, $component = '', $a = NULL) {
7003 $identifier = clean_param($identifier, PARAM_STRINGID
);
7004 if (empty($identifier)) {
7005 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please fix your get_string() call and string definition');
7008 if (func_num_args() > 3) {
7009 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7012 if (strpos($component, '/') !== false) {
7013 debugging('The module name you passed to get_string is the deprecated format ' .
7014 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER
);
7015 $componentpath = explode('/', $component);
7017 switch ($componentpath[0]) {
7019 $component = $componentpath[1];
7023 $component = 'block_'.$componentpath[1];
7026 $component = 'enrol_'.$componentpath[1];
7029 $component = 'format_'.$componentpath[1];
7032 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7037 $result = get_string_manager()->get_string($identifier, $component, $a);
7039 // Debugging feature lets you display string identifier and component
7040 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
7041 $result .= ' {' . $identifier . '/' . $component . '}';
7047 * Converts an array of strings to their localized value.
7049 * @param array $array An array of strings
7050 * @param string $module The language module that these strings can be found in.
7051 * @return array and array of translated strings.
7053 function get_strings($array, $component = '') {
7054 $string = new stdClass
;
7055 foreach ($array as $item) {
7056 $string->$item = get_string($item, $component);
7062 * Prints out a translated string.
7064 * Prints out a translated string using the return value from the {@link get_string()} function.
7066 * Example usage of this function when the string is in the moodle.php file:<br/>
7069 * print_string('course');
7073 * Example usage of this function when the string is not in the moodle.php file:<br/>
7076 * print_string('typecourse', 'calendar');
7080 * @param string $identifier The key identifier for the localized string
7081 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7082 * @param mixed $a An object, string or number that can be used within translation strings
7084 function print_string($identifier, $component = '', $a = NULL) {
7085 echo get_string($identifier, $component, $a);
7089 * Returns a list of charset codes
7091 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7092 * (checking that such charset is supported by the texlib library!)
7094 * @return array And associative array with contents in the form of charset => charset
7096 function get_list_of_charsets() {
7099 'EUC-JP' => 'EUC-JP',
7100 'ISO-2022-JP'=> 'ISO-2022-JP',
7101 'ISO-8859-1' => 'ISO-8859-1',
7102 'SHIFT-JIS' => 'SHIFT-JIS',
7103 'GB2312' => 'GB2312',
7104 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
7105 'UTF-8' => 'UTF-8');
7113 * Returns a list of valid and compatible themes
7117 function get_list_of_themes() {
7122 if (!empty($CFG->themelist
)) { // use admin's list of themes
7123 $themelist = explode(',', $CFG->themelist
);
7125 $themelist = array_keys(get_plugin_list("theme"));
7128 foreach ($themelist as $key => $themename) {
7129 $theme = theme_config
::load($themename);
7130 $themes[$themename] = $theme;
7133 collatorlib
::asort_objects_by_method($themes, 'get_theme_name');
7139 * Returns a list of timezones in the current language
7145 function get_list_of_timezones() {
7150 if (!empty($timezones)) { // This function has been called recently
7154 $timezones = array();
7156 if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
7157 foreach($rawtimezones as $timezone) {
7158 if (!empty($timezone->name
)) {
7159 if (get_string_manager()->string_exists(strtolower($timezone->name
), 'timezones')) {
7160 $timezones[$timezone->name
] = get_string(strtolower($timezone->name
), 'timezones');
7162 $timezones[$timezone->name
] = $timezone->name
;
7164 if (substr($timezones[$timezone->name
], 0, 1) == '[') { // No translation found
7165 $timezones[$timezone->name
] = $timezone->name
;
7173 for ($i = -13; $i <= 13; $i +
= .5) {
7176 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
7177 } else if ($i > 0) {
7178 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
7180 $timezones[sprintf("%.1f", $i)] = $tzstring;
7188 * Factory function for emoticon_manager
7190 * @return emoticon_manager singleton
7192 function get_emoticon_manager() {
7193 static $singleton = null;
7195 if (is_null($singleton)) {
7196 $singleton = new emoticon_manager();
7203 * Provides core support for plugins that have to deal with
7204 * emoticons (like HTML editor or emoticon filter).
7206 * Whenever this manager mentiones 'emoticon object', the following data
7207 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7208 * altidentifier and altcomponent
7210 * @see admin_setting_emoticons
7212 class emoticon_manager
{
7215 * Returns the currently enabled emoticons
7217 * @return array of emoticon objects
7219 public function get_emoticons() {
7222 if (empty($CFG->emoticons
)) {
7226 $emoticons = $this->decode_stored_config($CFG->emoticons
);
7228 if (!is_array($emoticons)) {
7229 // something is wrong with the format of stored setting
7230 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL
);
7238 * Converts emoticon object into renderable pix_emoticon object
7240 * @param stdClass $emoticon emoticon object
7241 * @param array $attributes explicit HTML attributes to set
7242 * @return pix_emoticon
7244 public function prepare_renderable_emoticon(stdClass
$emoticon, array $attributes = array()) {
7245 $stringmanager = get_string_manager();
7246 if ($stringmanager->string_exists($emoticon->altidentifier
, $emoticon->altcomponent
)) {
7247 $alt = get_string($emoticon->altidentifier
, $emoticon->altcomponent
);
7249 $alt = s($emoticon->text
);
7251 return new pix_emoticon($emoticon->imagename
, $alt, $emoticon->imagecomponent
, $attributes);
7255 * Encodes the array of emoticon objects into a string storable in config table
7257 * @see self::decode_stored_config()
7258 * @param array $emoticons array of emtocion objects
7261 public function encode_stored_config(array $emoticons) {
7262 return json_encode($emoticons);
7266 * Decodes the string into an array of emoticon objects
7268 * @see self::encode_stored_config()
7269 * @param string $encoded
7270 * @return string|null
7272 public function decode_stored_config($encoded) {
7273 $decoded = json_decode($encoded);
7274 if (!is_array($decoded)) {
7281 * Returns default set of emoticons supported by Moodle
7283 * @return array of sdtClasses
7285 public function default_emoticons() {
7287 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7288 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7289 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7290 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7291 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7292 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7293 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7294 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7295 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7296 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7297 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7298 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7299 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7300 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7301 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7302 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7303 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7304 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7305 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7306 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7307 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7308 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7309 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7310 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7311 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7312 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7313 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7314 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7315 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7316 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7321 * Helper method preparing the stdClass with the emoticon properties
7323 * @param string|array $text or array of strings
7324 * @param string $imagename to be used by {@see pix_emoticon}
7325 * @param string $altidentifier alternative string identifier, null for no alt
7326 * @param array $altcomponent where the alternative string is defined
7327 * @param string $imagecomponent to be used by {@see pix_emoticon}
7330 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null, $altcomponent = 'core_pix', $imagecomponent = 'core') {
7331 return (object)array(
7333 'imagename' => $imagename,
7334 'imagecomponent' => $imagecomponent,
7335 'altidentifier' => $altidentifier,
7336 'altcomponent' => $altcomponent,
7341 /// ENCRYPTION ////////////////////////////////////////////////
7346 * @todo Finish documenting this function
7348 * @param string $data Data to encrypt.
7349 * @param bool $usesecurekey Lets us know if we are using the old or new password.
7350 * @return string The now encrypted data.
7352 function rc4encrypt($data, $usesecurekey = false) {
7353 if (!$usesecurekey) {
7354 $passwordkey = 'nfgjeingjk';
7356 $passwordkey = get_site_identifier();
7358 return endecrypt($passwordkey, $data, '');
7364 * @todo Finish documenting this function
7366 * @param string $data Data to decrypt.
7367 * @param bool $usesecurekey Lets us know if we are using the old or new password.
7368 * @return string The now decrypted data.
7370 function rc4decrypt($data, $usesecurekey = false) {
7371 if (!$usesecurekey) {
7372 $passwordkey = 'nfgjeingjk';
7374 $passwordkey = get_site_identifier();
7376 return endecrypt($passwordkey, $data, 'de');
7380 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7382 * @todo Finish documenting this function
7384 * @param string $pwd The password to use when encrypting or decrypting
7385 * @param string $data The data to be decrypted/encrypted
7386 * @param string $case Either 'de' for decrypt or '' for encrypt
7389 function endecrypt ($pwd, $data, $case) {
7391 if ($case == 'de') {
7392 $data = urldecode($data);
7400 $pwd_length = strlen($pwd);
7402 for ($i = 0; $i <= 255; $i++
) {
7403 $key[$i] = ord(substr($pwd, ($i %
$pwd_length), 1));
7409 for ($i = 0; $i <= 255; $i++
) {
7410 $x = ($x +
$box[$i] +
$key[$i]) %
256;
7411 $temp_swap = $box[$i];
7412 $box[$i] = $box[$x];
7413 $box[$x] = $temp_swap;
7425 for ($i = 0; $i < strlen($data); $i++
) {
7426 $a = ($a +
1) %
256;
7427 $j = ($j +
$box[$a]) %
256;
7429 $box[$a] = $box[$j];
7431 $k = $box[(($box[$a] +
$box[$j]) %
256)];
7432 $cipherby = ord(substr($data, $i, 1)) ^
$k;
7433 $cipher .= chr($cipherby);
7436 if ($case == 'de') {
7437 $cipher = urldecode(urlencode($cipher));
7439 $cipher = urlencode($cipher);
7445 /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
7448 * Returns the exact absolute path to plugin directory.
7450 * @param string $plugintype type of plugin
7451 * @param string $name name of the plugin
7452 * @return string full path to plugin directory; NULL if not found
7454 function get_plugin_directory($plugintype, $name) {
7457 if ($plugintype === '') {
7458 $plugintype = 'mod';
7461 $types = get_plugin_types(true);
7462 if (!array_key_exists($plugintype, $types)) {
7465 $name = clean_param($name, PARAM_SAFEDIR
); // just in case ;-)
7467 if (!empty($CFG->themedir
) and $plugintype === 'theme') {
7468 if (!is_dir($types['theme'] . '/' . $name)) {
7469 // ok, so the theme is supposed to be in the $CFG->themedir
7470 return $CFG->themedir
. '/' . $name;
7474 return $types[$plugintype].'/'.$name;
7478 * Return exact absolute path to a plugin directory,
7479 * this method support "simpletest_" prefix designed for unit testing.
7481 * @param string $component name such as 'moodle', 'mod_forum' or special simpletest value
7482 * @return string full path to component directory; NULL if not found
7484 function get_component_directory($component) {
7487 $simpletest = false;
7488 if (strpos($component, 'simpletest_') === 0) {
7489 $subdir = substr($component, strlen('simpletest_'));
7490 //TODO: this looks borked, where is it used actually?
7494 list($type, $plugin) = normalize_component($component);
7496 if ($type === 'core') {
7497 if ($plugin === NULL ) {
7498 $path = $CFG->libdir
;
7500 $subsystems = get_core_subsystems();
7501 if (isset($subsystems[$plugin])) {
7502 $path = $CFG->dirroot
.'/'.$subsystems[$plugin];
7509 $path = get_plugin_directory($type, $plugin);
7516 * Normalize the component name using the "frankenstyle" names.
7517 * @param string $component
7518 * @return array $type+$plugin elements
7520 function normalize_component($component) {
7521 if ($component === 'moodle' or $component === 'core') {
7525 } else if (strpos($component, '_') === false) {
7526 $subsystems = get_core_subsystems();
7527 if (array_key_exists($component, $subsystems)) {
7529 $plugin = $component;
7531 // everything else is a module
7533 $plugin = $component;
7537 list($type, $plugin) = explode('_', $component, 2);
7538 $plugintypes = get_plugin_types(false);
7539 if ($type !== 'core' and !array_key_exists($type, $plugintypes)) {
7541 $plugin = $component;
7545 return array($type, $plugin);
7549 * List all core subsystems and their location
7551 * This is a whitelist of components that are part of the core and their
7552 * language strings are defined in /lang/en/<<subsystem>>.php. If a given
7553 * plugin is not listed here and it does not have proper plugintype prefix,
7554 * then it is considered as course activity module.
7556 * The location is dirroot relative path. NULL means there is no special
7557 * directory for this subsystem. If the location is set, the subsystem's
7558 * renderer.php is expected to be there.
7560 * @return array of (string)name => (string|null)location
7562 function get_core_subsystems() {
7565 static $info = null;
7570 'admin' => $CFG->admin
,
7572 'backup' => 'backup/util/ui',
7573 'block' => 'blocks',
7575 'bulkusers' => NULL,
7576 'calendar' => 'calendar',
7577 'cohort' => 'cohort',
7578 'condition' => NULL,
7579 'completion' => NULL,
7580 'countries' => NULL,
7581 'course' => 'course',
7582 'currencies' => NULL,
7583 'dbtransfer' => NULL,
7586 'editor' => 'lib/editor',
7587 'edufields' => NULL,
7590 'filepicker' => NULL,
7594 'form' => 'lib/form',
7595 'grades' => 'grade',
7596 'grading' => 'grade/grading',
7603 'langconfig' => NULL,
7606 'message' => 'message',
7607 'mimetypes' => NULL,
7609 'moodle.org' => NULL, // the dot is nasty, watch out! should be renamed to moodleorg
7614 'plagiarism' => 'plagiarism',
7616 'portfolio' => 'portfolio',
7617 'publish' => 'course/publish',
7618 'question' => 'question',
7619 'rating' => 'rating',
7620 'register' => 'admin/registration', //TODO: this is wrong, unfortunately we would need to modify hub code to pass around the correct url
7621 'repository' => 'repository',
7623 'role' => $CFG->admin
.'/role',
7624 'search' => 'search',
7627 'timezones' => NULL,
7630 'webservice' => 'webservice',
7638 * Lists all plugin types
7639 * @param bool $fullpaths false means relative paths from dirroot
7640 * @return array Array of strings - name=>location
7642 function get_plugin_types($fullpaths=true) {
7645 static $info = null;
7646 static $fullinfo = null;
7649 $info = array('qtype' => 'question/type',
7653 'message' => 'message/output',
7654 'block' => 'blocks',
7655 'filter' => 'filter',
7656 'editor' => 'lib/editor',
7657 'format' => 'course/format',
7658 'profilefield' => 'user/profile/field',
7659 'report' => 'report',
7660 'coursereport' => 'course/report', // must be after system reports
7661 'gradeexport' => 'grade/export',
7662 'gradeimport' => 'grade/import',
7663 'gradereport' => 'grade/report',
7664 'gradingform' => 'grade/grading/form',
7665 'mnetservice' => 'mnet/service',
7666 'webservice' => 'webservice',
7667 'repository' => 'repository',
7668 'portfolio' => 'portfolio',
7669 'qbehaviour' => 'question/behaviour',
7670 'qformat' => 'question/format',
7671 'plagiarism' => 'plagiarism',
7672 'tool' => $CFG->admin
.'/tool',
7673 'theme' => 'theme', // this is a bit hacky, themes may be in $CFG->themedir too
7676 $mods = get_plugin_list('mod');
7677 foreach ($mods as $mod => $moddir) {
7678 if (file_exists("$moddir/db/subplugins.php")) {
7679 $subplugins = array();
7680 include("$moddir/db/subplugins.php");
7681 foreach ($subplugins as $subtype=>$dir) {
7682 $info[$subtype] = $dir;
7687 // local is always last!
7688 $info['local'] = 'local';
7690 $fullinfo = array();
7691 foreach ($info as $type => $dir) {
7692 $fullinfo[$type] = $CFG->dirroot
.'/'.$dir;
7696 return ($fullpaths ?
$fullinfo : $info);
7700 * Simplified version of get_list_of_plugins()
7701 * @param string $plugintype type of plugin
7702 * @return array name=>fulllocation pairs of plugins of given type
7704 function get_plugin_list($plugintype) {
7707 $ignored = array('CVS', '_vti_cnf', 'simpletest', 'db', 'yui', 'phpunit');
7708 if ($plugintype == 'auth') {
7709 // Historically we have had an auth plugin called 'db', so allow a special case.
7710 $key = array_search('db', $ignored);
7711 if ($key !== false) {
7712 unset($ignored[$key]);
7716 if ($plugintype === '') {
7717 $plugintype = 'mod';
7720 $fulldirs = array();
7722 if ($plugintype === 'mod') {
7723 // mod is an exception because we have to call this function from get_plugin_types()
7724 $fulldirs[] = $CFG->dirroot
.'/mod';
7726 } else if ($plugintype === 'theme') {
7727 $fulldirs[] = $CFG->dirroot
.'/theme';
7728 // themes are special because they may be stored also in separate directory
7729 if (!empty($CFG->themedir
) and file_exists($CFG->themedir
) and is_dir($CFG->themedir
) ) {
7730 $fulldirs[] = $CFG->themedir
;
7734 $types = get_plugin_types(true);
7735 if (!array_key_exists($plugintype, $types)) {
7738 $fulldir = $types[$plugintype];
7739 if (!file_exists($fulldir)) {
7742 $fulldirs[] = $fulldir;
7747 foreach ($fulldirs as $fulldir) {
7748 if (!is_dir($fulldir)) {
7751 $items = new DirectoryIterator($fulldir);
7752 foreach ($items as $item) {
7753 if ($item->isDot() or !$item->isDir()) {
7756 $pluginname = $item->getFilename();
7757 if (in_array($pluginname, $ignored)) {
7760 $pluginname = clean_param($pluginname, PARAM_PLUGIN
);
7761 if (empty($pluginname)) {
7762 // better ignore plugins with problematic names here
7765 $result[$pluginname] = $fulldir.'/'.$pluginname;
7771 //TODO: implement better sorting once we migrated all plugin names to 'pluginname', ksort does not work for unicode, that is why we have to sort by the dir name, not the strings!
7777 * Get a list of all the plugins of a given type that contain a particular file.
7778 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7779 * @param string $file the name of file that must be present in the plugin.
7780 * (e.g. 'view.php', 'db/install.xml').
7781 * @param bool $include if true (default false), the file will be include_once-ed if found.
7782 * @return array with plugin name as keys (e.g. 'forum', 'courselist') and the path
7783 * to the file relative to dirroot as value (e.g. "$CFG->dirroot/mod/forum/view.php").
7785 function get_plugin_list_with_file($plugintype, $file, $include = false) {
7786 global $CFG; // Necessary in case it is referenced by include()d PHP scripts.
7790 foreach(get_plugin_list($plugintype) as $plugin => $dir) {
7791 $path = $dir . '/' . $file;
7792 if (file_exists($path)) {
7794 include_once($path);
7796 $plugins[$plugin] = $path;
7804 * Get a list of all the plugins of a given type that define a certain API function
7805 * in a certain file. The plugin component names and function names are returned.
7807 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7808 * @param string $function the part of the name of the function after the
7809 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
7810 * names like report_courselist_hook.
7811 * @param string $file the name of file within the plugin that defines the
7812 * function. Defaults to lib.php.
7813 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7814 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7816 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7817 $pluginfunctions = array();
7818 foreach (get_plugin_list_with_file($plugintype, $file, true) as $plugin => $notused) {
7819 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7821 if (function_exists($fullfunction)) {
7822 // Function exists with standard name. Store, indexed by
7823 // frankenstyle name of plugin
7824 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
7826 } else if ($plugintype === 'mod') {
7827 // For modules, we also allow plugin without full frankenstyle
7828 // but just starting with the module name
7829 $shortfunction = $plugin . '_' . $function;
7830 if (function_exists($shortfunction)) {
7831 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
7835 return $pluginfunctions;
7839 * Get a list of all the plugins of a given type that define a certain class
7840 * in a certain file. The plugin component names and class names are returned.
7842 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7843 * @param string $class the part of the name of the class after the
7844 * frankenstyle prefix. e.g 'thing' if you are looking for classes with
7845 * names like report_courselist_thing. If you are looking for classes with
7846 * the same name as the plugin name (e.g. qtype_multichoice) then pass ''.
7847 * @param string $file the name of file within the plugin that defines the class.
7848 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7849 * and the class names as values (e.g. 'report_courselist_thing', 'qtype_multichoice').
7851 function get_plugin_list_with_class($plugintype, $class, $file) {
7853 $suffix = '_' . $class;
7858 $pluginclasses = array();
7859 foreach (get_plugin_list_with_file($plugintype, $file, true) as $plugin => $notused) {
7860 $classname = $plugintype . '_' . $plugin . $suffix;
7861 if (class_exists($classname)) {
7862 $pluginclasses[$plugintype . '_' . $plugin] = $classname;
7866 return $pluginclasses;
7870 * Lists plugin-like directories within specified directory
7872 * This function was originally used for standard Moodle plugins, please use
7873 * new get_plugin_list() now.
7875 * This function is used for general directory listing and backwards compatility.
7877 * @param string $directory relative directory from root
7878 * @param string $exclude dir name to exclude from the list (defaults to none)
7879 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7880 * @return array Sorted array of directory names found under the requested parameters
7882 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7887 if (empty($basedir)) {
7888 $basedir = $CFG->dirroot
.'/'. $directory;
7891 $basedir = $basedir .'/'. $directory;
7894 if (file_exists($basedir) && filetype($basedir) == 'dir') {
7895 $dirhandle = opendir($basedir);
7896 while (false !== ($dir = readdir($dirhandle))) {
7897 $firstchar = substr($dir, 0, 1);
7898 if ($firstchar === '.' or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or $dir === 'phpunit' or $dir === $exclude) {
7901 if (filetype($basedir .'/'. $dir) != 'dir') {
7906 closedir($dirhandle);
7915 * Invoke plugin's callback functions
7917 * @param string $type plugin type e.g. 'mod'
7918 * @param string $name plugin name
7919 * @param string $feature feature name
7920 * @param string $action feature's action
7921 * @param array $params parameters of callback function, should be an array
7922 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7925 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7927 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7928 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7932 * Invoke component's callback functions
7934 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7935 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7936 * @param array $params parameters of callback function
7937 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7940 function component_callback($component, $function, array $params = array(), $default = null) {
7941 global $CFG; // this is needed for require_once() below
7943 $cleancomponent = clean_param($component, PARAM_COMPONENT
);
7944 if (empty($cleancomponent)) {
7945 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7947 $component = $cleancomponent;
7949 list($type, $name) = normalize_component($component);
7950 $component = $type . '_' . $name;
7952 $oldfunction = $name.'_'.$function;
7953 $function = $component.'_'.$function;
7955 $dir = get_component_directory($component);
7957 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7960 // Load library and look for function
7961 if (file_exists($dir.'/lib.php')) {
7962 require_once($dir.'/lib.php');
7965 if (!function_exists($function) and function_exists($oldfunction)) {
7966 if ($type !== 'mod' and $type !== 'core') {
7967 debugging("Please use new function name $function instead of legacy $oldfunction");
7969 $function = $oldfunction;
7972 if (function_exists($function)) {
7973 // Function exists, so just return function result
7974 $ret = call_user_func_array($function, $params);
7975 if (is_null($ret)) {
7985 * Checks whether a plugin supports a specified feature.
7987 * @param string $type Plugin type e.g. 'mod'
7988 * @param string $name Plugin name e.g. 'forum'
7989 * @param string $feature Feature code (FEATURE_xx constant)
7990 * @param mixed $default default value if feature support unknown
7991 * @return mixed Feature result (false if not supported, null if feature is unknown,
7992 * otherwise usually true but may have other feature-specific value such as array)
7994 function plugin_supports($type, $name, $feature, $default = NULL) {
7997 if ($type === 'mod' and $name === 'NEWMODULE') {
7998 //somebody forgot to rename the module template
8002 $component = clean_param($type . '_' . $name, PARAM_COMPONENT
);
8003 if (empty($component)) {
8004 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8009 if ($type === 'mod') {
8010 // we need this special case because we support subplugins in modules,
8011 // otherwise it would end up in infinite loop
8012 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8013 include_once("$CFG->dirroot/mod/$name/lib.php");
8014 $function = $component.'_supports';
8015 if (!function_exists($function)) {
8016 // legacy non-frankenstyle function name
8017 $function = $name.'_supports';
8024 if (!$path = get_plugin_directory($type, $name)) {
8025 // non existent plugin type
8028 if (file_exists("$path/lib.php")) {
8029 include_once("$path/lib.php");
8030 $function = $component.'_supports';
8034 if ($function and function_exists($function)) {
8035 $supports = $function($feature);
8036 if (is_null($supports)) {
8037 // plugin does not know - use default
8044 //plugin does not care, so use default
8049 * Returns true if the current version of PHP is greater that the specified one.
8051 * @todo Check PHP version being required here is it too low?
8053 * @param string $version The version of php being tested.
8056 function check_php_version($version='5.2.4') {
8057 return (version_compare(phpversion(), $version) >= 0);
8061 * Checks to see if is the browser operating system matches the specified
8064 * Known brand: 'Windows','Linux','Macintosh','SGI','SunOS','HP-UX'
8067 * @param string $brand The operating system identifier being tested
8068 * @return bool true if the given brand below to the detected operating system
8070 function check_browser_operating_system($brand) {
8071 if (empty($_SERVER['HTTP_USER_AGENT'])) {
8075 if (preg_match("/$brand/i", $_SERVER['HTTP_USER_AGENT'])) {
8083 * Checks to see if is a browser matches the specified
8084 * brand and is equal or better version.
8087 * @param string $brand The browser identifier being tested
8088 * @param int $version The version of the browser, if not specified any version (except 5.5 for IE for BC reasons)
8089 * @return bool true if the given version is below that of the detected browser
8091 function check_browser_version($brand, $version = null) {
8092 if (empty($_SERVER['HTTP_USER_AGENT'])) {
8096 $agent = $_SERVER['HTTP_USER_AGENT'];
8100 case 'Camino': /// OSX browser using Gecke engine
8101 if (strpos($agent, 'Camino') === false) {
8104 if (empty($version)) {
8105 return true; // no version specified
8107 if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
8108 if (version_compare($match[1], $version) >= 0) {
8115 case 'Firefox': /// Mozilla Firefox browsers
8116 if (strpos($agent, 'Iceweasel') === false and strpos($agent, 'Firefox') === false) {
8119 if (empty($version)) {
8120 return true; // no version specified
8122 if (preg_match("/(Iceweasel|Firefox)\/([0-9\.]+)/i", $agent, $match)) {
8123 if (version_compare($match[2], $version) >= 0) {
8130 case 'Gecko': /// Gecko based browsers
8131 if (empty($version) and substr_count($agent, 'Camino')) {
8132 // MacOS X Camino support
8133 $version = 20041110;
8136 // the proper string - Gecko/CCYYMMDD Vendor/Version
8137 // Faster version and work-a-round No IDN problem.
8138 if (preg_match("/Gecko\/([0-9]+)/i", $agent, $match)) {
8139 if ($match[1] > $version) {
8146 case 'MSIE': /// Internet Explorer
8147 if (strpos($agent, 'Opera') !== false) { // Reject Opera
8150 // in case of IE we have to deal with BC of the version parameter
8151 if (is_null($version)) {
8152 $version = 5.5; // anything older is not considered a browser at all!
8155 //see: http://www.useragentstring.com/pages/Internet%20Explorer/
8156 if (preg_match("/MSIE ([0-9\.]+)/", $agent, $match)) {
8157 if (version_compare($match[1], $version) >= 0) {
8164 case 'Opera': /// Opera
8165 if (strpos($agent, 'Opera') === false) {
8168 if (empty($version)) {
8169 return true; // no version specified
8171 if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
8172 if (version_compare($match[1], $version) >= 0) {
8179 case 'WebKit': /// WebKit based browser - everything derived from it (Safari, Chrome, iOS, Android and other mobiles)
8180 if (strpos($agent, 'AppleWebKit') === false) {
8183 if (empty($version)) {
8184 return true; // no version specified
8186 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
8187 if (version_compare($match[1], $version) >= 0) {
8194 case 'Safari': /// Desktop version of Apple Safari browser - no mobile or touch devices
8195 if (strpos($agent, 'AppleWebKit') === false) {
8198 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SymbianOS and any other mobile devices
8199 if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
8202 if (strpos($agent, 'Shiira')) { // Reject Shiira
8205 if (strpos($agent, 'SymbianOS')) { // Reject SymbianOS
8208 if (strpos($agent, 'Android')) { // Reject Androids too
8211 if (strpos($agent, 'iPhone') or strpos($agent, 'iPad') or strpos($agent, 'iPod')) {
8212 // No Apple mobile devices here - editor does not work, course ajax is not touch compatible, etc.
8215 if (strpos($agent, 'Chrome')) { // Reject chrome browsers - it needs to be tested explicitly
8219 if (empty($version)) {
8220 return true; // no version specified
8222 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
8223 if (version_compare($match[1], $version) >= 0) {
8231 if (strpos($agent, 'Chrome') === false) {
8234 if (empty($version)) {
8235 return true; // no version specified
8237 if (preg_match("/Chrome\/(.*)[ ]+/i", $agent, $match)) {
8238 if (version_compare($match[1], $version) >= 0) {
8245 case 'Safari iOS': /// Safari on iPhone, iPad and iPod touch
8246 if (strpos($agent, 'AppleWebKit') === false or strpos($agent, 'Safari') === false) {
8249 if (!strpos($agent, 'iPhone') and !strpos($agent, 'iPad') and !strpos($agent, 'iPod')) {
8252 if (empty($version)) {
8253 return true; // no version specified
8255 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
8256 if (version_compare($match[1], $version) >= 0) {
8263 case 'WebKit Android': /// WebKit browser on Android
8264 if (strpos($agent, 'Linux; U; Android') === false) {
8267 if (empty($version)) {
8268 return true; // no version specified
8270 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
8271 if (version_compare($match[1], $version) >= 0) {
8283 * Returns whether a device/browser combination is mobile, tablet, legacy, default or the result of
8284 * an optional admin specified regular expression. If enabledevicedetection is set to no or not set
8285 * it returns default
8287 * @return string device type
8289 function get_device_type() {
8292 if (empty($CFG->enabledevicedetection
) ||
empty($_SERVER['HTTP_USER_AGENT'])) {
8296 $useragent = $_SERVER['HTTP_USER_AGENT'];
8298 if (!empty($CFG->devicedetectregex
)) {
8299 $regexes = json_decode($CFG->devicedetectregex
);
8301 foreach ($regexes as $value=>$regex) {
8302 if (preg_match($regex, $useragent)) {
8308 //mobile detection PHP direct copy from open source detectmobilebrowser.com
8309 $phonesregex = '/android .+ mobile|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i';
8310 $modelsregex = '/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i';
8311 if (preg_match($phonesregex,$useragent) ||
preg_match($modelsregex,substr($useragent, 0, 4))){
8315 $tabletregex = '/Tablet browser|android|iPad|iProd|GT-P1000|GT-I9000|SHW-M180S|SGH-T849|SCH-I800|Build\/ERE27|sholest/i';
8316 if (preg_match($tabletregex, $useragent)) {
8320 // Safe way to check for IE6 and not get false positives for some IE 7/8 users
8321 if (substr($_SERVER['HTTP_USER_AGENT'], 0, 34) === 'Mozilla/4.0 (compatible; MSIE 6.0;') {
8329 * Returns a list of the device types supporting by Moodle
8331 * @param boolean $incusertypes includes types specified using the devicedetectregex admin setting
8332 * @return array $types
8334 function get_device_type_list($incusertypes = true) {
8337 $types = array('default', 'legacy', 'mobile', 'tablet');
8339 if ($incusertypes && !empty($CFG->devicedetectregex
)) {
8340 $regexes = json_decode($CFG->devicedetectregex
);
8342 foreach ($regexes as $value => $regex) {
8351 * Returns the theme selected for a particular device or false if none selected.
8353 * @param string $devicetype
8354 * @return string|false The name of the theme to use for the device or the false if not set
8356 function get_selected_theme_for_device_type($devicetype = null) {
8359 if (empty($devicetype)) {
8360 $devicetype = get_user_device_type();
8363 $themevarname = get_device_cfg_var_name($devicetype);
8364 if (empty($CFG->$themevarname)) {
8368 return $CFG->$themevarname;
8372 * Returns the name of the device type theme var in $CFG (because there is not a standard convention to allow backwards compatability
8374 * @param string $devicetype
8375 * @return string The config variable to use to determine the theme
8377 function get_device_cfg_var_name($devicetype = null) {
8378 if ($devicetype == 'default' ||
empty($devicetype)) {
8382 return 'theme' . $devicetype;
8386 * Allows the user to switch the device they are seeing the theme for.
8387 * This allows mobile users to switch back to the default theme, or theme for any other device.
8389 * @param string $newdevice The device the user is currently using.
8390 * @return string The device the user has switched to
8392 function set_user_device_type($newdevice) {
8395 $devicetype = get_device_type();
8396 $devicetypes = get_device_type_list();
8398 if ($newdevice == $devicetype) {
8399 unset_user_preference('switchdevice'.$devicetype);
8400 } else if (in_array($newdevice, $devicetypes)) {
8401 set_user_preference('switchdevice'.$devicetype, $newdevice);
8406 * Returns the device the user is currently using, or if the user has chosen to switch devices
8407 * for the current device type the type they have switched to.
8409 * @return string The device the user is currently using or wishes to use
8411 function get_user_device_type() {
8412 $device = get_device_type();
8413 $switched = get_user_preferences('switchdevice'.$device, false);
8414 if ($switched != false) {
8421 * Returns one or several CSS class names that match the user's browser. These can be put
8422 * in the body tag of the page to apply browser-specific rules without relying on CSS hacks
8424 * @return array An array of browser version classes
8426 function get_browser_version_classes() {
8429 if (check_browser_version("MSIE", "0")) {
8431 if (check_browser_version("MSIE", 9)) {
8433 } else if (check_browser_version("MSIE", 8)) {
8435 } elseif (check_browser_version("MSIE", 7)) {
8437 } elseif (check_browser_version("MSIE", 6)) {
8441 } else if (check_browser_version("Firefox") ||
check_browser_version("Gecko") ||
check_browser_version("Camino")) {
8442 $classes[] = 'gecko';
8443 if (preg_match('/rv\:([1-2])\.([0-9])/', $_SERVER['HTTP_USER_AGENT'], $matches)) {
8444 $classes[] = "gecko{$matches[1]}{$matches[2]}";
8447 } else if (check_browser_version("WebKit")) {
8448 $classes[] = 'safari';
8449 if (check_browser_version("Safari iOS")) {
8452 } else if (check_browser_version("WebKit Android")) {
8453 $classes[] = 'android';
8456 } else if (check_browser_version("Opera")) {
8457 $classes[] = 'opera';
8465 * Can handle rotated text. Whether it is safe to use the trickery in textrotate.js.
8467 * @return bool True for yes, false for no
8469 function can_use_rotated_text() {
8471 return ajaxenabled(array('Firefox' => 2.0)) && !$USER->screenreader
;;
8475 * Hack to find out the GD version by parsing phpinfo output
8477 * @return int GD version (1, 2, or 0)
8479 function check_gd_version() {
8482 if (function_exists('gd_info')){
8483 $gd_info = gd_info();
8484 if (substr_count($gd_info['GD Version'], '2.')) {
8486 } else if (substr_count($gd_info['GD Version'], '1.')) {
8492 phpinfo(INFO_MODULES
);
8493 $phpinfo = ob_get_contents();
8496 $phpinfo = explode("\n", $phpinfo);
8499 foreach ($phpinfo as $text) {
8500 $parts = explode('</td>', $text);
8501 foreach ($parts as $key => $val) {
8502 $parts[$key] = trim(strip_tags($val));
8504 if ($parts[0] == 'GD Version') {
8505 if (substr_count($parts[1], '2.0')) {
8508 $gdversion = intval($parts[1]);
8513 return $gdversion; // 1, 2 or 0
8517 * Determine if moodle installation requires update
8519 * Checks version numbers of main code and all modules to see
8520 * if there are any mismatches
8526 function moodle_needs_upgrading() {
8527 global $CFG, $DB, $OUTPUT;
8529 if (empty($CFG->version
)) {
8533 // main versio nfirst
8535 include($CFG->dirroot
.'/version.php'); // defines $version and upgrades
8536 if ($version > $CFG->version
) {
8541 $mods = get_plugin_list('mod');
8542 $installed = $DB->get_records('modules', array(), '', 'name, version');
8543 foreach ($mods as $mod => $fullmod) {
8544 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
8547 $module = new stdClass();
8548 if (!is_readable($fullmod.'/version.php')) {
8551 include($fullmod.'/version.php'); // defines $module with version etc
8552 if (empty($installed[$mod])) {
8554 } else if ($module->version
> $installed[$mod]->version
) {
8561 $blocks = get_plugin_list('block');
8562 $installed = $DB->get_records('block', array(), '', 'name, version');
8563 require_once($CFG->dirroot
.'/blocks/moodleblock.class.php');
8564 foreach ($blocks as $blockname=>$fullblock) {
8565 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
8568 if (!is_readable($fullblock.'/version.php')) {
8571 $plugin = new stdClass();
8572 $plugin->version
= NULL;
8573 include($fullblock.'/version.php');
8574 if (empty($installed[$blockname])) {
8576 } else if ($plugin->version
> $installed[$blockname]->version
) {
8582 // now the rest of plugins
8583 $plugintypes = get_plugin_types();
8584 unset($plugintypes['mod']);
8585 unset($plugintypes['block']);
8586 foreach ($plugintypes as $type=>$unused) {
8587 $plugs = get_plugin_list($type);
8588 foreach ($plugs as $plug=>$fullplug) {
8589 $component = $type.'_'.$plug;
8590 if (!is_readable($fullplug.'/version.php')) {
8593 $plugin = new stdClass();
8594 include($fullplug.'/version.php'); // defines $plugin with version etc
8595 $installedversion = get_config($component, 'version');
8596 if (empty($installedversion)) { // new installation
8598 } else if ($installedversion < $plugin->version
) { // upgrade
8608 * Sets maximum expected time needed for upgrade task.
8609 * Please always make sure that upgrade will not run longer!
8611 * The script may be automatically aborted if upgrade times out.
8614 * @param int $max_execution_time in seconds (can not be less than 60 s)
8616 function upgrade_set_timeout($max_execution_time=300) {
8619 if (!isset($CFG->upgraderunning
) or $CFG->upgraderunning
< time()) {
8620 $upgraderunning = get_config(null, 'upgraderunning');
8622 $upgraderunning = $CFG->upgraderunning
;
8625 if (!$upgraderunning) {
8627 // never stop CLI upgrades
8628 $upgraderunning = 0;
8630 // web upgrade not running or aborted
8631 print_error('upgradetimedout', 'admin', "$CFG->wwwroot/$CFG->admin/");
8635 if ($max_execution_time < 60) {
8636 // protection against 0 here
8637 $max_execution_time = 60;
8640 $expected_end = time() +
$max_execution_time;
8642 if ($expected_end < $upgraderunning +
10 and $expected_end > $upgraderunning - 10) {
8643 // no need to store new end, it is nearly the same ;-)
8648 // there is no point in timing out of CLI scripts, admins can stop them if necessary
8651 set_time_limit($max_execution_time);
8653 set_config('upgraderunning', $expected_end); // keep upgrade locked until this time
8656 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
8659 * Sets the system locale
8661 * @todo Finish documenting this function
8664 * @param string $locale Can be used to force a locale
8666 function moodle_setlocale($locale='') {
8669 static $currentlocale = ''; // last locale caching
8671 $oldlocale = $currentlocale;
8673 /// Fetch the correct locale based on ostype
8674 if ($CFG->ostype
== 'WINDOWS') {
8675 $stringtofetch = 'localewin';
8677 $stringtofetch = 'locale';
8680 /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
8681 if (!empty($locale)) {
8682 $currentlocale = $locale;
8683 } else if (!empty($CFG->locale
)) { // override locale for all language packs
8684 $currentlocale = $CFG->locale
;
8686 $currentlocale = get_string($stringtofetch, 'langconfig');
8689 /// do nothing if locale already set up
8690 if ($oldlocale == $currentlocale) {
8694 /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8695 /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8696 /// Some day, numeric, monetary and other categories should be set too, I think. :-/
8698 /// Get current values
8699 $monetary= setlocale (LC_MONETARY
, 0);
8700 $numeric = setlocale (LC_NUMERIC
, 0);
8701 $ctype = setlocale (LC_CTYPE
, 0);
8702 if ($CFG->ostype
!= 'WINDOWS') {
8703 $messages= setlocale (LC_MESSAGES
, 0);
8705 /// Set locale to all
8706 setlocale (LC_ALL
, $currentlocale);
8708 setlocale (LC_MONETARY
, $monetary);
8709 setlocale (LC_NUMERIC
, $numeric);
8710 if ($CFG->ostype
!= 'WINDOWS') {
8711 setlocale (LC_MESSAGES
, $messages);
8713 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
8714 setlocale (LC_CTYPE
, $ctype);
8719 * Converts string to lowercase using most compatible function available.
8721 * @todo Remove this function when no longer in use
8722 * @deprecated Use textlib->strtolower($text) instead.
8724 * @param string $string The string to convert to all lowercase characters.
8725 * @param string $encoding The encoding on the string.
8728 function moodle_strtolower ($string, $encoding='') {
8730 //If not specified use utf8
8731 if (empty($encoding)) {
8732 $encoding = 'UTF-8';
8735 $textlib = textlib_get_instance();
8737 return $textlib->strtolower($string, $encoding);
8741 * Count words in a string.
8743 * Words are defined as things between whitespace.
8745 * @param string $string The text to be searched for words.
8746 * @return int The count of words in the specified string
8748 function count_words($string) {
8749 $string = strip_tags($string);
8750 return count(preg_split("/\w\b/", $string)) - 1;
8753 /** Count letters in a string.
8755 * Letters are defined as chars not in tags and different from whitespace.
8757 * @param string $string The text to be searched for letters.
8758 * @return int The count of letters in the specified text.
8760 function count_letters($string) {
8761 /// Loading the textlib singleton instance. We are going to need it.
8762 $textlib = textlib_get_instance();
8764 $string = strip_tags($string); // Tags are out now
8765 $string = preg_replace('/[[:space:]]*/','',$string); //Whitespace are out now
8767 return $textlib->strlen($string);
8771 * Generate and return a random string of the specified length.
8773 * @param int $length The length of the string to be created.
8776 function random_string ($length=15) {
8777 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8778 $pool .= 'abcdefghijklmnopqrstuvwxyz';
8779 $pool .= '0123456789';
8780 $poollen = strlen($pool);
8781 mt_srand ((double) microtime() * 1000000);
8783 for ($i = 0; $i < $length; $i++
) {
8784 $string .= substr($pool, (mt_rand()%
($poollen)), 1);
8790 * Generate a complex random string (useful for md5 salts)
8792 * This function is based on the above {@link random_string()} however it uses a
8793 * larger pool of characters and generates a string between 24 and 32 characters
8795 * @param int $length Optional if set generates a string to exactly this length
8798 function complex_random_string($length=null) {
8799 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8800 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8801 $poollen = strlen($pool);
8802 mt_srand ((double) microtime() * 1000000);
8803 if ($length===null) {
8804 $length = floor(rand(24,32));
8807 for ($i = 0; $i < $length; $i++
) {
8808 $string .= $pool[(mt_rand()%
$poollen)];
8814 * Given some text (which may contain HTML) and an ideal length,
8815 * this function truncates the text neatly on a word boundary if possible
8818 * @param string $text - text to be shortened
8819 * @param int $ideal - ideal string length
8820 * @param boolean $exact if false, $text will not be cut mid-word
8821 * @param string $ending The string to append if the passed string is truncated
8822 * @return string $truncate - shortened string
8824 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8828 // if the plain text is shorter than the maximum length, return the whole text
8829 if (textlib
::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8833 // Splits on HTML tags. Each open/close/empty tag will be the first thing
8834 // and only tag in its 'line'
8835 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER
);
8837 $total_length = textlib
::strlen($ending);
8840 // This array stores information about open and close tags and their position
8841 // in the truncated string. Each item in the array is an object with fields
8842 // ->open (true if open), ->tag (tag name in lower case), and ->pos
8843 // (byte position in truncated text)
8844 $tagdetails = array();
8846 foreach ($lines as $line_matchings) {
8847 // if there is any html-tag in this line, handle it and add it (uncounted) to the output
8848 if (!empty($line_matchings[1])) {
8849 // if it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>)
8850 if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
8852 // if tag is a closing tag (f.e. </b>)
8853 } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
8854 // record closing tag
8855 $tagdetails[] = (object)array('open'=>false,
8856 'tag'=>textlib
::strtolower($tag_matchings[1]), 'pos'=>textlib
::strlen($truncate));
8857 // if tag is an opening tag (f.e. <b>)
8858 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
8859 // record opening tag
8860 $tagdetails[] = (object)array('open'=>true,
8861 'tag'=>textlib
::strtolower($tag_matchings[1]), 'pos'=>textlib
::strlen($truncate));
8863 // add html-tag to $truncate'd text
8864 $truncate .= $line_matchings[1];
8867 // calculate the length of the plain text part of the line; handle entities as one character
8868 $content_length = textlib
::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
8869 if ($total_length+
$content_length > $ideal) {
8870 // the number of characters which are left
8871 $left = $ideal - $total_length;
8872 $entities_length = 0;
8873 // search for html entities
8874 if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE
)) {
8875 // calculate the real length of all entities in the legal range
8876 foreach ($entities[0] as $entity) {
8877 if ($entity[1]+
1-$entities_length <= $left) {
8879 $entities_length +
= textlib
::strlen($entity[0]);
8881 // no more characters left
8886 $truncate .= textlib
::substr($line_matchings[2], 0, $left+
$entities_length);
8887 // maximum length is reached, so get off the loop
8890 $truncate .= $line_matchings[2];
8891 $total_length +
= $content_length;
8894 // if the maximum length is reached, get off the loop
8895 if($total_length >= $ideal) {
8900 // if the words shouldn't be cut in the middle...
8902 // ...search the last occurence of a space...
8903 for ($k=textlib
::strlen($truncate);$k>0;$k--) {
8904 if ($char = textlib
::substr($truncate, $k, 1)) {
8905 if ($char === '.' or $char === ' ') {
8908 } else if (strlen($char) > 2) { // Chinese/Japanese/Korean text
8909 $breakpos = $k+
1; // can be truncated at any UTF-8
8910 break; // character boundary.
8915 if (isset($breakpos)) {
8916 // ...and cut the text in this position
8917 $truncate = textlib
::substr($truncate, 0, $breakpos);
8921 // add the defined ending to the text
8922 $truncate .= $ending;
8924 // Now calculate the list of open html tags based on the truncate position
8925 $open_tags = array();
8926 foreach ($tagdetails as $taginfo) {
8927 if(isset($breakpos) && $taginfo->pos
>= $breakpos) {
8928 // Don't include tags after we made the break!
8931 if($taginfo->open
) {
8932 // add tag to the beginning of $open_tags list
8933 array_unshift($open_tags, $taginfo->tag
);
8935 $pos = array_search($taginfo->tag
, array_reverse($open_tags, true)); // can have multiple exact same open tags, close the last one
8936 if ($pos !== false) {
8937 unset($open_tags[$pos]);
8942 // close all unclosed html-tags
8943 foreach ($open_tags as $tag) {
8944 $truncate .= '</' . $tag . '>';
8952 * Given dates in seconds, how many weeks is the date from startdate
8953 * The first week is 1, the second 2 etc ...
8955 * @todo Finish documenting this function
8958 * @param int $startdate Timestamp for the start date
8959 * @param int $thedate Timestamp for the end date
8962 function getweek ($startdate, $thedate) {
8963 if ($thedate < $startdate) { // error
8967 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
8971 * returns a randomly generated password of length $maxlen. inspired by
8973 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8974 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8977 * @param int $maxlen The maximum size of the password being generated.
8980 function generate_password($maxlen=10) {
8983 if (empty($CFG->passwordpolicy
)) {
8984 $fillers = PASSWORD_DIGITS
;
8985 $wordlist = file($CFG->wordlist
);
8986 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8987 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8988 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8989 $password = $word1 . $filler1 . $word2;
8991 $minlen = !empty($CFG->minpasswordlength
) ?
$CFG->minpasswordlength
: 0;
8992 $digits = $CFG->minpassworddigits
;
8993 $lower = $CFG->minpasswordlower
;
8994 $upper = $CFG->minpasswordupper
;
8995 $nonalphanum = $CFG->minpasswordnonalphanum
;
8996 $total = $lower +
$upper +
$digits +
$nonalphanum;
8997 // minlength should be the greater one of the two ( $minlen and $total )
8998 $minlen = $minlen < $total ?
$total : $minlen;
8999 // maxlen can never be smaller than minlen
9000 $maxlen = $minlen > $maxlen ?
$minlen : $maxlen;
9001 $additional = $maxlen - $total;
9003 // Make sure we have enough characters to fulfill
9004 // complexity requirements
9005 $passworddigits = PASSWORD_DIGITS
;
9006 while ($digits > strlen($passworddigits)) {
9007 $passworddigits .= PASSWORD_DIGITS
;
9009 $passwordlower = PASSWORD_LOWER
;
9010 while ($lower > strlen($passwordlower)) {
9011 $passwordlower .= PASSWORD_LOWER
;
9013 $passwordupper = PASSWORD_UPPER
;
9014 while ($upper > strlen($passwordupper)) {
9015 $passwordupper .= PASSWORD_UPPER
;
9017 $passwordnonalphanum = PASSWORD_NONALPHANUM
;
9018 while ($nonalphanum > strlen($passwordnonalphanum)) {
9019 $passwordnonalphanum .= PASSWORD_NONALPHANUM
;
9022 // Now mix and shuffle it all
9023 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
9024 substr(str_shuffle ($passwordupper), 0, $upper) .
9025 substr(str_shuffle ($passworddigits), 0, $digits) .
9026 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
9027 substr(str_shuffle ($passwordlower .
9030 $passwordnonalphanum), 0 , $additional));
9033 return substr ($password, 0, $maxlen);
9037 * Given a float, prints it nicely.
9038 * Localized floats must not be used in calculations!
9040 * @param float $float The float to print
9041 * @param int $places The number of decimal places to print.
9042 * @param bool $localized use localized decimal separator
9043 * @return string locale float
9045 function format_float($float, $decimalpoints=1, $localized=true) {
9046 if (is_null($float)) {
9050 return number_format($float, $decimalpoints, get_string('decsep', 'langconfig'), '');
9052 return number_format($float, $decimalpoints, '.', '');
9057 * Converts locale specific floating point/comma number back to standard PHP float value
9058 * Do NOT try to do any math operations before this conversion on any user submitted floats!
9060 * @param string $locale_float locale aware float representation
9063 function unformat_float($locale_float) {
9064 $locale_float = trim($locale_float);
9066 if ($locale_float == '') {
9070 $locale_float = str_replace(' ', '', $locale_float); // no spaces - those might be used as thousand separators
9072 return (float)str_replace(get_string('decsep', 'langconfig'), '.', $locale_float);
9076 * Given a simple array, this shuffles it up just like shuffle()
9077 * Unlike PHP's shuffle() this function works on any machine.
9079 * @param array $array The array to be rearranged
9082 function swapshuffle($array) {
9084 srand ((double) microtime() * 10000000);
9085 $last = count($array) - 1;
9086 for ($i=0;$i<=$last;$i++
) {
9087 $from = rand(0,$last);
9089 $array[$i] = $array[$from];
9090 $array[$from] = $curr;
9096 * Like {@link swapshuffle()}, but works on associative arrays
9098 * @param array $array The associative array to be rearranged
9101 function swapshuffle_assoc($array) {
9103 $newarray = array();
9104 $newkeys = swapshuffle(array_keys($array));
9106 foreach ($newkeys as $newkey) {
9107 $newarray[$newkey] = $array[$newkey];
9113 * Given an arbitrary array, and a number of draws,
9114 * this function returns an array with that amount
9115 * of items. The indexes are retained.
9117 * @todo Finish documenting this function
9119 * @param array $array
9123 function draw_rand_array($array, $draws) {
9124 srand ((double) microtime() * 10000000);
9128 $last = count($array);
9130 if ($draws > $last) {
9134 while ($draws > 0) {
9137 $keys = array_keys($array);
9138 $rand = rand(0, $last);
9140 $return[$keys[$rand]] = $array[$keys[$rand]];
9141 unset($array[$keys[$rand]]);
9150 * Calculate the difference between two microtimes
9152 * @param string $a The first Microtime
9153 * @param string $b The second Microtime
9156 function microtime_diff($a, $b) {
9157 list($a_dec, $a_sec) = explode(' ', $a);
9158 list($b_dec, $b_sec) = explode(' ', $b);
9159 return $b_sec - $a_sec +
$b_dec - $a_dec;
9163 * Given a list (eg a,b,c,d,e) this function returns
9164 * an array of 1->a, 2->b, 3->c etc
9166 * @param string $list The string to explode into array bits
9167 * @param string $separator The separator used within the list string
9168 * @return array The now assembled array
9170 function make_menu_from_list($list, $separator=',') {
9172 $array = array_reverse(explode($separator, $list), true);
9173 foreach ($array as $key => $item) {
9174 $outarray[$key+
1] = trim($item);
9180 * Creates an array that represents all the current grades that
9181 * can be chosen using the given grading type.
9184 * are scales, zero is no grade, and positive numbers are maximum
9187 * @todo Finish documenting this function or better deprecated this completely!
9189 * @param int $gradingtype
9192 function make_grades_menu($gradingtype) {
9196 if ($gradingtype < 0) {
9197 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
9198 return make_menu_from_list($scale->scale
);
9200 } else if ($gradingtype > 0) {
9201 for ($i=$gradingtype; $i>=0; $i--) {
9202 $grades[$i] = $i .' / '. $gradingtype;
9210 * This function returns the number of activities
9211 * using scaleid in a courseid
9213 * @todo Finish documenting this function
9217 * @param int $courseid ?
9218 * @param int $scaleid ?
9221 function course_scale_used($courseid, $scaleid) {
9226 if (!empty($scaleid)) {
9227 if ($cms = get_course_mods($courseid)) {
9228 foreach ($cms as $cm) {
9229 //Check cm->name/lib.php exists
9230 if (file_exists($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php')) {
9231 include_once($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php');
9232 $function_name = $cm->modname
.'_scale_used';
9233 if (function_exists($function_name)) {
9234 if ($function_name($cm->instance
,$scaleid)) {
9242 // check if any course grade item makes use of the scale
9243 $return +
= $DB->count_records('grade_items', array('courseid'=>$courseid, 'scaleid'=>$scaleid));
9245 // check if any outcome in the course makes use of the scale
9246 $return +
= $DB->count_records_sql("SELECT COUNT('x')
9247 FROM {grade_outcomes_courses} goc,
9249 WHERE go.id = goc.outcomeid
9250 AND go.scaleid = ? AND goc.courseid = ?",
9251 array($scaleid, $courseid));
9257 * This function returns the number of activities
9258 * using scaleid in the entire site
9260 * @param int $scaleid
9261 * @param array $courses
9264 function site_scale_used($scaleid, &$courses) {
9267 if (!is_array($courses) ||
count($courses) == 0) {
9268 $courses = get_courses("all",false,"c.id,c.shortname");
9271 if (!empty($scaleid)) {
9272 if (is_array($courses) && count($courses) > 0) {
9273 foreach ($courses as $course) {
9274 $return +
= course_scale_used($course->id
,$scaleid);
9282 * make_unique_id_code
9284 * @todo Finish documenting this function
9287 * @param string $extra Extra string to append to the end of the code
9290 function make_unique_id_code($extra='') {
9292 $hostname = 'unknownhost';
9293 if (!empty($_SERVER['HTTP_HOST'])) {
9294 $hostname = $_SERVER['HTTP_HOST'];
9295 } else if (!empty($_ENV['HTTP_HOST'])) {
9296 $hostname = $_ENV['HTTP_HOST'];
9297 } else if (!empty($_SERVER['SERVER_NAME'])) {
9298 $hostname = $_SERVER['SERVER_NAME'];
9299 } else if (!empty($_ENV['SERVER_NAME'])) {
9300 $hostname = $_ENV['SERVER_NAME'];
9303 $date = gmdate("ymdHis");
9305 $random = random_string(6);
9308 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
9310 return $hostname .'+'. $date .'+'. $random;
9316 * Function to check the passed address is within the passed subnet
9318 * The parameter is a comma separated string of subnet definitions.
9319 * Subnet strings can be in one of three formats:
9320 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
9321 * 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)
9322 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
9323 * Code for type 1 modified from user posted comments by mediator at
9324 * {@link http://au.php.net/manual/en/function.ip2long.php}
9326 * @param string $addr The address you are checking
9327 * @param string $subnetstr The string of subnet addresses
9330 function address_in_subnet($addr, $subnetstr) {
9332 if ($addr == '0.0.0.0') {
9335 $subnets = explode(',', $subnetstr);
9337 $addr = trim($addr);
9338 $addr = cleanremoteaddr($addr, false); // normalise
9339 if ($addr === null) {
9342 $addrparts = explode(':', $addr);
9344 $ipv6 = strpos($addr, ':');
9346 foreach ($subnets as $subnet) {
9347 $subnet = trim($subnet);
9348 if ($subnet === '') {
9352 if (strpos($subnet, '/') !== false) {
9353 ///1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn
9354 list($ip, $mask) = explode('/', $subnet);
9355 $mask = trim($mask);
9356 if (!is_number($mask)) {
9357 continue; // incorect mask number, eh?
9359 $ip = cleanremoteaddr($ip, false); // normalise
9363 if (strpos($ip, ':') !== false) {
9368 if ($mask > 128 or $mask < 0) {
9369 continue; // nonsense
9372 return true; // any address
9375 if ($ip === $addr) {
9380 $ipparts = explode(':', $ip);
9381 $modulo = $mask %
16;
9382 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
9383 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9384 if (implode(':', $ipnet) === implode(':', $addrnet)) {
9388 $pos = ($mask-$modulo)/16;
9389 $ipnet = hexdec($ipparts[$pos]);
9390 $addrnet = hexdec($addrparts[$pos]);
9391 $mask = 0xffff << (16 - $modulo);
9392 if (($addrnet & $mask) == ($ipnet & $mask)) {
9402 if ($mask > 32 or $mask < 0) {
9403 continue; // nonsense
9409 if ($ip === $addr) {
9414 $mask = 0xffffffff << (32 - $mask);
9415 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9420 } else if (strpos($subnet, '-') !== false) {
9421 /// 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.
9422 $parts = explode('-', $subnet);
9423 if (count($parts) != 2) {
9427 if (strpos($subnet, ':') !== false) {
9432 $ipstart = cleanremoteaddr(trim($parts[0]), false); // normalise
9433 if ($ipstart === null) {
9436 $ipparts = explode(':', $ipstart);
9437 $start = hexdec(array_pop($ipparts));
9438 $ipparts[] = trim($parts[1]);
9439 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // normalise
9440 if ($ipend === null) {
9444 $ipnet = implode(':', $ipparts);
9445 if (strpos($addr, $ipnet) !== 0) {
9448 $ipparts = explode(':', $ipend);
9449 $end = hexdec($ipparts[7]);
9451 $addrend = hexdec($addrparts[7]);
9453 if (($addrend >= $start) and ($addrend <= $end)) {
9462 $ipstart = cleanremoteaddr(trim($parts[0]), false); // normalise
9463 if ($ipstart === null) {
9466 $ipparts = explode('.', $ipstart);
9467 $ipparts[3] = trim($parts[1]);
9468 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // normalise
9469 if ($ipend === null) {
9473 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9479 /// 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9480 if (strpos($subnet, ':') !== false) {
9485 $parts = explode(':', $subnet);
9486 $count = count($parts);
9487 if ($parts[$count-1] === '') {
9488 unset($parts[$count-1]); // trim trailing :
9490 $subnet = implode('.', $parts);
9492 $isip = cleanremoteaddr($subnet, false); // normalise
9493 if ($isip !== null) {
9494 if ($isip === $addr) {
9498 } else if ($count > 8) {
9501 $zeros = array_fill(0, 8-$count, '0');
9502 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9503 if (address_in_subnet($addr, $subnet)) {
9512 $parts = explode('.', $subnet);
9513 $count = count($parts);
9514 if ($parts[$count-1] === '') {
9515 unset($parts[$count-1]); // trim trailing .
9517 $subnet = implode('.', $parts);
9520 $subnet = cleanremoteaddr($subnet, false); // normalise
9521 if ($subnet === $addr) {
9525 } else if ($count > 4) {
9528 $zeros = array_fill(0, 4-$count, '0');
9529 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9530 if (address_in_subnet($addr, $subnet)) {
9541 * For outputting debugging info
9544 * @param string $string The string to write
9545 * @param string $eol The end of line char(s) to use
9546 * @param string $sleep Period to make the application sleep
9547 * This ensures any messages have time to display before redirect
9549 function mtrace($string, $eol="\n", $sleep=0) {
9551 if (defined('STDOUT')) {
9552 fwrite(STDOUT
, $string.$eol);
9554 echo $string . $eol;
9559 //delay to keep message on user's screen in case of subsequent redirect
9566 * Replace 1 or more slashes or backslashes to 1 slash
9568 * @param string $path The path to strip
9569 * @return string the path with double slashes removed
9571 function cleardoubleslashes ($path) {
9572 return preg_replace('/(\/|\\\){1,}/','/',$path);
9576 * Is current ip in give list?
9578 * @param string $list
9581 function remoteip_in_list($list){
9583 $client_ip = getremoteaddr(null);
9586 // ensure access on cli
9590 $list = explode("\n", $list);
9591 foreach($list as $subnet) {
9592 $subnet = trim($subnet);
9593 if (address_in_subnet($client_ip, $subnet)) {
9602 * Returns most reliable client address
9605 * @param string $default If an address can't be determined, then return this
9606 * @return string The remote IP address
9608 function getremoteaddr($default='0.0.0.0') {
9611 if (empty($CFG->getremoteaddrconf
)) {
9612 // This will happen, for example, before just after the upgrade, as the
9613 // user is redirected to the admin screen.
9614 $variablestoskip = 0;
9616 $variablestoskip = $CFG->getremoteaddrconf
;
9618 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP
)) {
9619 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9620 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9621 return $address ?
$address : $default;
9624 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR
)) {
9625 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9626 $address = cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
9627 return $address ?
$address : $default;
9630 if (!empty($_SERVER['REMOTE_ADDR'])) {
9631 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9632 return $address ?
$address : $default;
9639 * Cleans an ip address. Internal addresses are now allowed.
9640 * (Originally local addresses were not allowed.)
9642 * @param string $addr IPv4 or IPv6 address
9643 * @param bool $compress use IPv6 address compression
9644 * @return string normalised ip address string, null if error
9646 function cleanremoteaddr($addr, $compress=false) {
9647 $addr = trim($addr);
9649 //TODO: maybe add a separate function is_addr_public() or something like this
9651 if (strpos($addr, ':') !== false) {
9653 $parts = explode(':', $addr);
9654 $count = count($parts);
9656 if (strpos($parts[$count-1], '.') !== false) {
9657 //legacy ipv4 notation
9658 $last = array_pop($parts);
9659 $ipv4 = cleanremoteaddr($last, true);
9660 if ($ipv4 === null) {
9663 $bits = explode('.', $ipv4);
9664 $parts[] = dechex($bits[0]).dechex($bits[1]);
9665 $parts[] = dechex($bits[2]).dechex($bits[3]);
9666 $count = count($parts);
9667 $addr = implode(':', $parts);
9670 if ($count < 3 or $count > 8) {
9671 return null; // severly malformed
9675 if (strpos($addr, '::') === false) {
9676 return null; // malformed
9679 $insertat = array_search('', $parts, true);
9680 $missing = array_fill(0, 1 +
8 - $count, '0');
9681 array_splice($parts, $insertat, 1, $missing);
9682 foreach ($parts as $key=>$part) {
9689 $adr = implode(':', $parts);
9690 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9691 return null; // incorrect format - sorry
9694 // normalise 0s and case
9695 $parts = array_map('hexdec', $parts);
9696 $parts = array_map('dechex', $parts);
9698 $result = implode(':', $parts);
9704 if ($result === '0:0:0:0:0:0:0:0') {
9705 return '::'; // all addresses
9708 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9709 if ($compressed !== $result) {
9713 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9714 if ($compressed !== $result) {
9718 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9719 if ($compressed !== $result) {
9726 // first get all things that look like IPv4 addresses
9728 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9733 foreach ($parts as $key=>$match) {
9737 $parts[$key] = (int)$match; // normalise 0s
9740 return implode('.', $parts);
9744 * This function will make a complete copy of anything it's given,
9745 * regardless of whether it's an object or not.
9747 * @param mixed $thing Something you want cloned
9748 * @return mixed What ever it is you passed it
9750 function fullclone($thing) {
9751 return unserialize(serialize($thing));
9756 * This function expects to called during shutdown
9757 * should be set via register_shutdown_function()
9758 * in lib/setup.php .
9762 function moodle_request_shutdown() {
9765 // help apache server if possible
9766 $apachereleasemem = false;
9767 if (function_exists('apache_child_terminate') && function_exists('memory_get_usage')
9768 && ini_get_bool('child_terminate')) {
9770 $limit = (empty($CFG->apachemaxmem
) ?
64*1024*1024 : $CFG->apachemaxmem
); //64MB default
9771 if (memory_get_usage() > get_real_size($limit)) {
9772 $apachereleasemem = $limit;
9773 @apache_child_terminate
();
9777 // deal with perf logging
9778 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
9779 if ($apachereleasemem) {
9780 error_log('Mem usage over '.$apachereleasemem.': marking Apache child for reaping.');
9782 if (defined('MDL_PERFTOLOG')) {
9783 $perf = get_performance_info();
9784 error_log("PERF: " . $perf['txt']);
9786 if (defined('MDL_PERFINC')) {
9787 $inc = get_included_files();
9789 foreach($inc as $f) {
9790 if (preg_match(':^/:', $f)) {
9793 $hfs = display_size($fs);
9794 error_log(substr($f,strlen($CFG->dirroot
)) . " size: $fs ($hfs)"
9797 error_log($f , NULL, NULL, 0);
9801 $hts = display_size($ts);
9802 error_log("Total size of files included: $ts ($hts)");
9809 * If new messages are waiting for the current user, then insert
9810 * JavaScript to pop up the messaging window into the page
9812 * @global moodle_page $PAGE
9815 function message_popup_window() {
9816 global $USER, $DB, $PAGE, $CFG, $SITE;
9818 if (!$PAGE->get_popup_notification_allowed() ||
empty($CFG->messaging
)) {
9822 if (!isloggedin() ||
isguestuser()) {
9826 if (!isset($USER->message_lastpopup
)) {
9827 $USER->message_lastpopup
= 0;
9828 } else if ($USER->message_lastpopup
> (time()-120)) {
9829 //dont run the query to check whether to display a popup if its been run in the last 2 minutes
9833 //a quick query to check whether the user has new messages
9834 $messagecount = $DB->count_records('message', array('useridto' => $USER->id
));
9835 if ($messagecount<1) {
9839 //got unread messages so now do another query that joins with the user table
9840 $messagesql = "SELECT m.id, m.smallmessage, m.fullmessageformat, m.notification, u.firstname, u.lastname
9842 JOIN {message_working} mw ON m.id=mw.unreadmessageid
9843 JOIN {message_processors} p ON mw.processorid=p.id
9844 JOIN {user} u ON m.useridfrom=u.id
9845 WHERE m.useridto = :userid
9846 AND p.name='popup'";
9848 //if the user was last notified over an hour ago we can renotify them of old messages
9849 //so don't worry about when the new message was sent
9850 $lastnotifiedlongago = $USER->message_lastpopup
< (time()-3600);
9851 if (!$lastnotifiedlongago) {
9852 $messagesql .= 'AND m.timecreated > :lastpopuptime';
9855 $message_users = $DB->get_records_sql($messagesql, array('userid'=>$USER->id
, 'lastpopuptime'=>$USER->message_lastpopup
));
9857 //if we have new messages to notify the user about
9858 if (!empty($message_users)) {
9861 if (count($message_users)>1) {
9862 $strmessages = get_string('unreadnewmessages', 'message', count($message_users));
9864 $message_users = reset($message_users);
9866 //show who the message is from if its not a notification
9867 if (!$message_users->notification
) {
9868 $strmessages = get_string('unreadnewmessage', 'message', fullname($message_users) );
9871 //try to display the small version of the message
9872 $smallmessage = null;
9873 if (!empty($message_users->smallmessage
)) {
9874 //display the first 200 chars of the message in the popup
9875 $textlib = textlib_get_instance();
9876 $smallmessage = null;
9877 if ($textlib->strlen($message_users->smallmessage
) > 200) {
9878 $smallmessage = $textlib->substr($message_users->smallmessage
,0,200).'...';
9880 $smallmessage = $message_users->smallmessage
;
9883 //prevent html symbols being displayed
9884 if ($message_users->fullmessageformat
== FORMAT_HTML
) {
9885 $smallmessage = html_to_text($smallmessage);
9887 $smallmessage = s($smallmessage);
9889 } else if ($message_users->notification
) {
9890 //its a notification with no smallmessage so just say they have a notification
9891 $smallmessage = get_string('unreadnewnotification', 'message');
9893 if (!empty($smallmessage)) {
9894 $strmessages .= '<div id="usermessage">'.s($smallmessage).'</div>';
9898 $strgomessage = get_string('gotomessages', 'message');
9899 $strstaymessage = get_string('ignore','admin');
9901 $url = $CFG->wwwroot
.'/message/index.php';
9902 $content = html_writer
::start_tag('div', array('id'=>'newmessageoverlay','class'=>'mdl-align')).
9903 html_writer
::start_tag('div', array('id'=>'newmessagetext')).
9905 html_writer
::end_tag('div').
9907 html_writer
::start_tag('div', array('id'=>'newmessagelinks')).
9908 html_writer
::link($url, $strgomessage, array('id'=>'notificationyes')).' '.
9909 html_writer
::link('', $strstaymessage, array('id'=>'notificationno')).
9910 html_writer
::end_tag('div');
9911 html_writer
::end_tag('div');
9913 $PAGE->requires
->js_init_call('M.core_message.init_notification', array('', $content, $url));
9915 $USER->message_lastpopup
= time();
9920 * Used to make sure that $min <= $value <= $max
9922 * Make sure that value is between min, and max
9924 * @param int $min The minimum value
9925 * @param int $value The value to check
9926 * @param int $max The maximum value
9928 function bounded_number($min, $value, $max) {
9939 * Check if there is a nested array within the passed array
9941 * @param array $array
9942 * @return bool true if there is a nested array false otherwise
9944 function array_is_nested($array) {
9945 foreach ($array as $value) {
9946 if (is_array($value)) {
9954 * get_performance_info() pairs up with init_performance_info()
9955 * loaded in setup.php. Returns an array with 'html' and 'txt'
9956 * values ready for use, and each of the individual stats provided
9957 * separately as well.
9964 function get_performance_info() {
9965 global $CFG, $PERF, $DB, $PAGE;
9968 $info['html'] = ''; // holds userfriendly HTML representation
9969 $info['txt'] = me() . ' '; // holds log-friendly representation
9971 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
9973 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
9974 $info['txt'] .= 'time: '.$info['realtime'].'s ';
9976 if (function_exists('memory_get_usage')) {
9977 $info['memory_total'] = memory_get_usage();
9978 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
9979 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
9980 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9983 if (function_exists('memory_get_peak_usage')) {
9984 $info['memory_peak'] = memory_get_peak_usage();
9985 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
9986 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9989 $inc = get_included_files();
9990 //error_log(print_r($inc,1));
9991 $info['includecount'] = count($inc);
9992 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
9993 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
9995 $filtermanager = filter_manager
::instance();
9996 if (method_exists($filtermanager, 'get_performance_summary')) {
9997 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9998 $info = array_merge($filterinfo, $info);
9999 foreach ($filterinfo as $key => $value) {
10000 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
10001 $info['txt'] .= "$key: $value ";
10005 $stringmanager = get_string_manager();
10006 if (method_exists($stringmanager, 'get_performance_summary')) {
10007 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
10008 $info = array_merge($filterinfo, $info);
10009 foreach ($filterinfo as $key => $value) {
10010 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
10011 $info['txt'] .= "$key: $value ";
10015 $jsmodules = $PAGE->requires
->get_loaded_modules();
10020 foreach ($jsmodules as $module => $backtraces) {
10021 if (strpos($module, 'yui') === 0) {
10026 $details .= "<div class='yui-module'><p>$module</p>";
10027 foreach ($backtraces as $backtrace) {
10028 $details .= "<div class='backtrace'>$backtrace</div>";
10030 $details .= '</div>';
10032 $info['html'] .= "<span class='includedyuimodules'>Included YUI modules: $yuicount</span> ";
10033 $info['txt'] .= "includedyuimodules: $yuicount ";
10034 $info['html'] .= "<span class='includedjsmodules'>Other JavaScript modules: $othercount</span> ";
10035 $info['txt'] .= "includedjsmodules: $othercount ";
10036 // Slightly odd to output the details in a display: none div. The point
10037 // Is that it takes a lot of space, and if you care you can reveal it
10039 $info['html'] .= '<div id="yui-module-debug" class="notifytiny">'.$details.'</div>';
10042 if (!empty($PERF->logwrites
)) {
10043 $info['logwrites'] = $PERF->logwrites
;
10044 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
10045 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
10048 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites
);
10049 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
10050 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
10052 if (function_exists('posix_times')) {
10053 $ptimes = posix_times();
10054 if (is_array($ptimes)) {
10055 foreach ($ptimes as $key => $val) {
10056 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
10058 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
10059 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
10063 // Grab the load average for the last minute
10064 // /proc will only work under some linux configurations
10065 // while uptime is there under MacOSX/Darwin and other unices
10066 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
10067 list($server_load) = explode(' ', $loadavg[0]);
10069 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
10070 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
10071 $server_load = $matches[1];
10073 trigger_error('Could not parse uptime output!');
10076 if (!empty($server_load)) {
10077 $info['serverload'] = $server_load;
10078 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
10079 $info['txt'] .= "serverload: {$info['serverload']} ";
10082 // Display size of session if session started
10083 if (session_id()) {
10084 $info['sessionsize'] = display_size(strlen(session_encode()));
10085 $info['html'] .= '<span class="sessionsize">Session: ' . $info['sessionsize'] . '</span> ';
10086 $info['txt'] .= "Session: {$info['sessionsize']} ";
10089 /* if (isset($rcache->hits) && isset($rcache->misses)) {
10090 $info['rcachehits'] = $rcache->hits;
10091 $info['rcachemisses'] = $rcache->misses;
10092 $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
10093 "{$rcache->hits}/{$rcache->misses}</span> ";
10094 $info['txt'] .= 'rcache: '.
10095 "{$rcache->hits}/{$rcache->misses} ";
10097 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
10102 * @todo Document this function linux people
10104 function apd_get_profiling() {
10105 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
10109 * Delete directory or only it's content
10111 * @param string $dir directory path
10112 * @param bool $content_only
10113 * @return bool success, true also if dir does not exist
10115 function remove_dir($dir, $content_only=false) {
10116 if (!file_exists($dir)) {
10120 $handle = opendir($dir);
10122 while (false!==($item = readdir($handle))) {
10123 if($item != '.' && $item != '..') {
10124 if(is_dir($dir.'/'.$item)) {
10125 $result = remove_dir($dir.'/'.$item) && $result;
10127 $result = unlink($dir.'/'.$item) && $result;
10132 if ($content_only) {
10133 clearstatcache(); // make sure file stat cache is properly invalidated
10136 $result = rmdir($dir); // if anything left the result will be false, no need for && $result
10137 clearstatcache(); // make sure file stat cache is properly invalidated
10142 * Detect if an object or a class contains a given property
10143 * will take an actual object or the name of a class
10145 * @param mix $obj Name of class or real object to test
10146 * @param string $property name of property to find
10147 * @return bool true if property exists
10149 function object_property_exists( $obj, $property ) {
10150 if (is_string( $obj )) {
10151 $properties = get_class_vars( $obj );
10154 $properties = get_object_vars( $obj );
10156 return array_key_exists( $property, $properties );
10160 * Converts an object into an associative array
10162 * This function converts an object into an associative array by iterating
10163 * over its public properties. Because this function uses the foreach
10164 * construct, Iterators are respected. It works recursively on arrays of objects.
10165 * Arrays and simple values are returned as is.
10167 * If class has magic properties, it can implement IteratorAggregate
10168 * and return all available properties in getIterator()
10170 * @param mixed $var
10173 function convert_to_array($var) {
10175 $references = array();
10177 // loop over elements/properties
10178 foreach ($var as $key => $value) {
10179 // recursively convert objects
10180 if (is_object($value) ||
is_array($value)) {
10181 // but prevent cycles
10182 if (!in_array($value, $references)) {
10183 $result[$key] = convert_to_array($value);
10184 $references[] = $value;
10187 // simple values are untouched
10188 $result[$key] = $value;
10195 * Detect a custom script replacement in the data directory that will
10196 * replace an existing moodle script
10198 * @return string|bool full path name if a custom script exists, false if no custom script exists
10200 function custom_script_path() {
10201 global $CFG, $SCRIPT;
10203 if ($SCRIPT === null) {
10204 // Probably some weird external script
10208 $scriptpath = $CFG->customscripts
. $SCRIPT;
10210 // check the custom script exists
10211 if (file_exists($scriptpath) and is_file($scriptpath)) {
10212 return $scriptpath;
10219 * Returns whether or not the user object is a remote MNET user. This function
10220 * is in moodlelib because it does not rely on loading any of the MNET code.
10223 * @param object $user A valid user object
10224 * @return bool True if the user is from a remote Moodle.
10226 function is_mnet_remote_user($user) {
10229 if (!isset($CFG->mnet_localhost_id
)) {
10230 include_once $CFG->dirroot
. '/mnet/lib.php';
10231 $env = new mnet_environment();
10236 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
10240 * This function will search for browser prefereed languages, setting Moodle
10241 * to use the best one available if $SESSION->lang is undefined
10247 function setup_lang_from_browser() {
10249 global $CFG, $SESSION, $USER;
10251 if (!empty($SESSION->lang
) or !empty($USER->lang
) or empty($CFG->autolang
)) {
10252 // Lang is defined in session or user profile, nothing to do
10256 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
10260 /// Extract and clean langs from headers
10261 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
10262 $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
10263 $rawlangs = explode(',', $rawlangs); // Convert to array
10267 foreach ($rawlangs as $lang) {
10268 if (strpos($lang, ';') === false) {
10269 $langs[(string)$order] = $lang;
10270 $order = $order-0.01;
10272 $parts = explode(';', $lang);
10273 $pos = strpos($parts[1], '=');
10274 $langs[substr($parts[1], $pos+
1)] = $parts[0];
10277 krsort($langs, SORT_NUMERIC
);
10279 /// Look for such langs under standard locations
10280 foreach ($langs as $lang) {
10281 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR
)); // clean it properly for include
10282 if (get_string_manager()->translation_exists($lang, false)) {
10283 $SESSION->lang
= $lang; /// Lang exists, set it in session
10284 break; /// We have finished. Go out
10291 * check if $url matches anything in proxybypass list
10293 * any errors just result in the proxy being used (least bad)
10296 * @param string $url url to check
10297 * @return boolean true if we should bypass the proxy
10299 function is_proxybypass( $url ) {
10303 if (empty($CFG->proxyhost
) or empty($CFG->proxybypass
)) {
10307 // get the host part out of the url
10308 if (!$host = parse_url( $url, PHP_URL_HOST
)) {
10312 // get the possible bypass hosts into an array
10313 $matches = explode( ',', $CFG->proxybypass
);
10315 // check for a match
10316 // (IPs need to match the left hand side and hosts the right of the url,
10317 // but we can recklessly check both as there can't be a false +ve)
10319 foreach ($matches as $match) {
10320 $match = trim($match);
10322 // try for IP match (Left side)
10323 $lhs = substr($host,0,strlen($match));
10324 if (strcasecmp($match,$lhs)==0) {
10328 // try for host match (Right side)
10329 $rhs = substr($host,-strlen($match));
10330 if (strcasecmp($match,$rhs)==0) {
10335 // nothing matched.
10340 ////////////////////////////////////////////////////////////////////////////////
10343 * Check if the passed navigation is of the new style
10345 * @param mixed $navigation
10346 * @return bool true for yes false for no
10348 function is_newnav($navigation) {
10349 if (is_array($navigation) && !empty($navigation['newnav'])) {
10357 * Checks whether the given variable name is defined as a variable within the given object.
10359 * This will NOT work with stdClass objects, which have no class variables.
10361 * @param string $var The variable name
10362 * @param object $object The object to check
10365 function in_object_vars($var, $object) {
10366 $class_vars = get_class_vars(get_class($object));
10367 $class_vars = array_keys($class_vars);
10368 return in_array($var, $class_vars);
10372 * Returns an array without repeated objects.
10373 * This function is similar to array_unique, but for arrays that have objects as values
10375 * @param array $array
10376 * @param bool $keep_key_assoc
10379 function object_array_unique($array, $keep_key_assoc = true) {
10380 $duplicate_keys = array();
10383 foreach ($array as $key=>$val) {
10384 // convert objects to arrays, in_array() does not support objects
10385 if (is_object($val)) {
10386 $val = (array)$val;
10389 if (!in_array($val, $tmp)) {
10392 $duplicate_keys[] = $key;
10396 foreach ($duplicate_keys as $key) {
10397 unset($array[$key]);
10400 return $keep_key_assoc ?
$array : array_values($array);
10404 * Is a userid the primary administrator?
10406 * @param int $userid int id of user to check
10409 function is_primary_admin($userid){
10410 $primaryadmin = get_admin();
10412 if($userid == $primaryadmin->id
){
10420 * Returns the site identifier
10423 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10425 function get_site_identifier() {
10427 // Check to see if it is missing. If so, initialise it.
10428 if (empty($CFG->siteidentifier
)) {
10429 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10432 return $CFG->siteidentifier
;
10436 * Check whether the given password has no more than the specified
10437 * number of consecutive identical characters.
10439 * @param string $password password to be checked against the password policy
10440 * @param integer $maxchars maximum number of consecutive identical characters
10442 function check_consecutive_identical_characters($password, $maxchars) {
10444 if ($maxchars < 1) {
10445 return true; // 0 is to disable this check
10447 if (strlen($password) <= $maxchars) {
10448 return true; // too short to fail this test
10451 $previouschar = '';
10452 $consecutivecount = 1;
10453 foreach (str_split($password) as $char) {
10454 if ($char != $previouschar) {
10455 $consecutivecount = 1;
10458 $consecutivecount++
;
10459 if ($consecutivecount > $maxchars) {
10460 return false; // check failed already
10464 $previouschar = $char;
10471 * helper function to do partial function binding
10472 * so we can use it for preg_replace_callback, for example
10473 * this works with php functions, user functions, static methods and class methods
10474 * it returns you a callback that you can pass on like so:
10476 * $callback = partial('somefunction', $arg1, $arg2);
10478 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10480 * $obj = new someclass();
10481 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10483 * and then the arguments that are passed through at calltime are appended to the argument list.
10485 * @param mixed $function a php callback
10486 * $param mixed $arg1.. $argv arguments to partially bind with
10490 function partial() {
10491 if (!class_exists('partial')) {
10493 var $values = array();
10496 function __construct($func, $args) {
10497 $this->values
= $args;
10498 $this->func
= $func;
10501 function method() {
10502 $args = func_get_args();
10503 return call_user_func_array($this->func
, array_merge($this->values
, $args));
10507 $args = func_get_args();
10508 $func = array_shift($args);
10509 $p = new partial($func, $args);
10510 return array($p, 'method');
10514 * helper function to load up and initialise the mnet environment
10515 * this must be called before you use mnet functions.
10517 * @return mnet_environment the equivalent of old $MNET global
10519 function get_mnet_environment() {
10521 require_once($CFG->dirroot
. '/mnet/lib.php');
10522 static $instance = null;
10523 if (empty($instance)) {
10524 $instance = new mnet_environment();
10531 * during xmlrpc server code execution, any code wishing to access
10532 * information about the remote peer must use this to get it.
10534 * @return mnet_remote_client the equivalent of old $MNET_REMOTE_CLIENT global
10536 function get_mnet_remote_client() {
10537 if (!defined('MNET_SERVER')) {
10538 debugging(get_string('notinxmlrpcserver', 'mnet'));
10541 global $MNET_REMOTE_CLIENT;
10542 if (isset($MNET_REMOTE_CLIENT)) {
10543 return $MNET_REMOTE_CLIENT;
10549 * during the xmlrpc server code execution, this will be called
10550 * to setup the object returned by {@see get_mnet_remote_client}
10552 * @param mnet_remote_client $client the client to set up
10554 function set_mnet_remote_client($client) {
10555 if (!defined('MNET_SERVER')) {
10556 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10558 global $MNET_REMOTE_CLIENT;
10559 $MNET_REMOTE_CLIENT = $client;
10563 * return the jump url for a given remote user
10564 * this is used for rewriting forum post links in emails, etc
10566 * @param stdclass $user the user to get the idp url for
10568 function mnet_get_idp_jump_url($user) {
10571 static $mnetjumps = array();
10572 if (!array_key_exists($user->mnethostid
, $mnetjumps)) {
10573 $idp = mnet_get_peer_host($user->mnethostid
);
10574 $idpjumppath = mnet_get_app_jumppath($idp->applicationid
);
10575 $mnetjumps[$user->mnethostid
] = $idp->wwwroot
. $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot
. '&wantsurl=';
10577 return $mnetjumps[$user->mnethostid
];
10581 * Gets the homepage to use for the current user
10583 * @return int One of HOMEPAGE_*
10585 function get_home_page() {
10588 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage
)) {
10589 if ($CFG->defaulthomepage
== HOMEPAGE_MY
) {
10590 return HOMEPAGE_MY
;
10592 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY
);
10595 return HOMEPAGE_SITE
;