MDL-40490 - database: Fixed a check on database port options.
[moodle.git] / lib / moodlelib.php
bloba6661f5aea0d0a536f07e9844a3de6468507343e
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * moodlelib.php - Moodle main library
20 * Main library file of miscellaneous general-purpose Moodle functions.
21 * Other main libraries:
22 * - weblib.php - functions that produce web output
23 * - datalib.php - functions that access the database
25 * @package core
26 * @subpackage lib
27 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
28 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
35 /// Date and time constants ///
36 /**
37 * Time constant - the number of seconds in a year
39 define('YEARSECS', 31536000);
41 /**
42 * Time constant - the number of seconds in a week
44 define('WEEKSECS', 604800);
46 /**
47 * Time constant - the number of seconds in a day
49 define('DAYSECS', 86400);
51 /**
52 * Time constant - the number of seconds in an hour
54 define('HOURSECS', 3600);
56 /**
57 * Time constant - the number of seconds in a minute
59 define('MINSECS', 60);
61 /**
62 * Time constant - the number of minutes in a day
64 define('DAYMINS', 1440);
66 /**
67 * Time constant - the number of minutes in an hour
69 define('HOURMINS', 60);
71 /// Parameter constants - every call to optional_param(), required_param() ///
72 /// or clean_param() should have a specified type of parameter. //////////////
76 /**
77 * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
79 define('PARAM_ALPHA', 'alpha');
81 /**
82 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
83 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
85 define('PARAM_ALPHAEXT', 'alphaext');
87 /**
88 * PARAM_ALPHANUM - expected numbers and letters only.
90 define('PARAM_ALPHANUM', 'alphanum');
92 /**
93 * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
95 define('PARAM_ALPHANUMEXT', 'alphanumext');
97 /**
98 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
100 define('PARAM_AUTH', 'auth');
103 * PARAM_BASE64 - Base 64 encoded format
105 define('PARAM_BASE64', 'base64');
108 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
110 define('PARAM_BOOL', 'bool');
113 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
114 * checked against the list of capabilities in the database.
116 define('PARAM_CAPABILITY', 'capability');
119 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
120 * to use this. The normal mode of operation is to use PARAM_RAW when recieving
121 * the input (required/optional_param or formslib) and then sanitse the HTML
122 * using format_text on output. This is for the rare cases when you want to
123 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
125 define('PARAM_CLEANHTML', 'cleanhtml');
128 * PARAM_EMAIL - an email address following the RFC
130 define('PARAM_EMAIL', 'email');
133 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
135 define('PARAM_FILE', 'file');
138 * PARAM_FLOAT - a real/floating point number.
140 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
141 * It does not work for languages that use , as a decimal separator.
142 * Instead, do something like
143 * $rawvalue = required_param('name', PARAM_RAW);
144 * // ... other code including require_login, which sets current lang ...
145 * $realvalue = unformat_float($rawvalue);
146 * // ... then use $realvalue
148 define('PARAM_FLOAT', 'float');
151 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
153 define('PARAM_HOST', 'host');
156 * PARAM_INT - integers only, use when expecting only numbers.
158 define('PARAM_INT', 'int');
161 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
163 define('PARAM_LANG', 'lang');
166 * 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!)
168 define('PARAM_LOCALURL', 'localurl');
171 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
173 define('PARAM_NOTAGS', 'notags');
176 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
177 * note: the leading slash is not removed, window drive letter is not allowed
179 define('PARAM_PATH', 'path');
182 * PARAM_PEM - Privacy Enhanced Mail format
184 define('PARAM_PEM', 'pem');
187 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
189 define('PARAM_PERMISSION', 'permission');
192 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
194 define('PARAM_RAW', 'raw');
197 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
199 define('PARAM_RAW_TRIMMED', 'raw_trimmed');
202 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
204 define('PARAM_SAFEDIR', 'safedir');
207 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
209 define('PARAM_SAFEPATH', 'safepath');
212 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
214 define('PARAM_SEQUENCE', 'sequence');
217 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
219 define('PARAM_TAG', 'tag');
222 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
224 define('PARAM_TAGLIST', 'taglist');
227 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
229 define('PARAM_TEXT', 'text');
232 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
234 define('PARAM_THEME', 'theme');
237 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
239 define('PARAM_URL', 'url');
242 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user accounts, do NOT use when syncing with external systems!!
244 define('PARAM_USERNAME', 'username');
247 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
249 define('PARAM_STRINGID', 'stringid');
251 ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
253 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
254 * It was one of the first types, that is why it is abused so much ;-)
255 * @deprecated since 2.0
257 define('PARAM_CLEAN', 'clean');
260 * PARAM_INTEGER - deprecated alias for PARAM_INT
261 * @deprecated since 2.0
263 define('PARAM_INTEGER', 'int');
266 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
267 * @deprecated since 2.0
269 define('PARAM_NUMBER', 'float');
272 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
273 * NOTE: originally alias for PARAM_APLHA
274 * @deprecated since 2.0
276 define('PARAM_ACTION', 'alphanumext');
279 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
280 * NOTE: originally alias for PARAM_APLHA
281 * @deprecated since 2.0
283 define('PARAM_FORMAT', 'alphanumext');
286 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
287 * @deprecated since 2.0
289 define('PARAM_MULTILANG', 'text');
292 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
293 * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
294 * America/Port-au-Prince)
296 define('PARAM_TIMEZONE', 'timezone');
299 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
301 define('PARAM_CLEANFILE', 'file');
304 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
305 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
306 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
307 * NOTE: numbers and underscores are strongly discouraged in plugin names!
309 define('PARAM_COMPONENT', 'component');
312 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
313 * It is usually used together with context id and component.
314 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
316 define('PARAM_AREA', 'area');
319 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
320 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
321 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
323 define('PARAM_PLUGIN', 'plugin');
326 /// Web Services ///
329 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
331 define('VALUE_REQUIRED', 1);
334 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
336 define('VALUE_OPTIONAL', 2);
339 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
341 define('VALUE_DEFAULT', 0);
344 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
346 define('NULL_NOT_ALLOWED', false);
349 * NULL_ALLOWED - the parameter can be set to null in the database
351 define('NULL_ALLOWED', true);
353 /// Page types ///
355 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
357 define('PAGE_COURSE_VIEW', 'course-view');
359 /** Get remote addr constant */
360 define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
361 /** Get remote addr constant */
362 define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
364 /// Blog access level constant declaration ///
365 define ('BLOG_USER_LEVEL', 1);
366 define ('BLOG_GROUP_LEVEL', 2);
367 define ('BLOG_COURSE_LEVEL', 3);
368 define ('BLOG_SITE_LEVEL', 4);
369 define ('BLOG_GLOBAL_LEVEL', 5);
372 ///Tag constants///
374 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
375 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
376 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
378 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
380 define('TAG_MAX_LENGTH', 50);
382 /// Password policy constants ///
383 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
384 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
385 define ('PASSWORD_DIGITS', '0123456789');
386 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
388 /// Feature constants ///
389 // Used for plugin_supports() to report features that are, or are not, supported by a module.
391 /** True if module can provide a grade */
392 define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
393 /** True if module supports outcomes */
394 define('FEATURE_GRADE_OUTCOMES', 'outcomes');
395 /** True if module supports advanced grading methods */
396 define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
397 /** True if module controls the grade visibility over the gradebook */
398 define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
399 /** True if module supports plagiarism plugins */
400 define('FEATURE_PLAGIARISM', 'plagiarism');
402 /** True if module has code to track whether somebody viewed it */
403 define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
404 /** True if module has custom completion rules */
405 define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
407 /** True if module has no 'view' page (like label) */
408 define('FEATURE_NO_VIEW_LINK', 'viewlink');
409 /** True if module supports outcomes */
410 define('FEATURE_IDNUMBER', 'idnumber');
411 /** True if module supports groups */
412 define('FEATURE_GROUPS', 'groups');
413 /** True if module supports groupings */
414 define('FEATURE_GROUPINGS', 'groupings');
415 /** True if module supports groupmembersonly */
416 define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
418 /** Type of module */
419 define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
420 /** True if module supports intro editor */
421 define('FEATURE_MOD_INTRO', 'mod_intro');
422 /** True if module has default completion */
423 define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
425 define('FEATURE_COMMENT', 'comment');
427 define('FEATURE_RATE', 'rate');
428 /** True if module supports backup/restore of moodle2 format */
429 define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
431 /** True if module can show description on course main page */
432 define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
434 /** Unspecified module archetype */
435 define('MOD_ARCHETYPE_OTHER', 0);
436 /** Resource-like type module */
437 define('MOD_ARCHETYPE_RESOURCE', 1);
438 /** Assignment module archetype */
439 define('MOD_ARCHETYPE_ASSIGNMENT', 2);
440 /** System (not user-addable) module archetype */
441 define('MOD_ARCHETYPE_SYSTEM', 3);
444 * Security token used for allowing access
445 * from external application such as web services.
446 * Scripts do not use any session, performance is relatively
447 * low because we need to load access info in each request.
448 * Scripts are executed in parallel.
450 define('EXTERNAL_TOKEN_PERMANENT', 0);
453 * Security token used for allowing access
454 * of embedded applications, the code is executed in the
455 * active user session. Token is invalidated after user logs out.
456 * Scripts are executed serially - normal session locking is used.
458 define('EXTERNAL_TOKEN_EMBEDDED', 1);
461 * The home page should be the site home
463 define('HOMEPAGE_SITE', 0);
465 * The home page should be the users my page
467 define('HOMEPAGE_MY', 1);
469 * The home page can be chosen by the user
471 define('HOMEPAGE_USER', 2);
474 * Hub directory url (should be moodle.org)
476 define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
480 * Moodle.org url (should be moodle.org)
482 define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
485 * Moodle mobile app service name
487 define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
490 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
492 define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
495 * Course display settings
497 define('COURSE_DISPLAY_SINGLEPAGE', 0); // display all sections on one page
498 define('COURSE_DISPLAY_MULTIPAGE', 1); // split pages into a page per section
501 * Authentication constants.
503 define('AUTH_PASSWORD_NOT_CACHED', 'not cached'); // String used in password field when password is not stored.
505 /// PARAMETER HANDLING ////////////////////////////////////////////////////
508 * Returns a particular value for the named variable, taken from
509 * POST or GET. If the parameter doesn't exist then an error is
510 * thrown because we require this variable.
512 * This function should be used to initialise all required values
513 * in a script that are based on parameters. Usually it will be
514 * used like this:
515 * $id = required_param('id', PARAM_INT);
517 * Please note the $type parameter is now required and the value can not be array.
519 * @param string $parname the name of the page parameter we want
520 * @param string $type expected type of parameter
521 * @return mixed
523 function required_param($parname, $type) {
524 if (func_num_args() != 2 or empty($parname) or empty($type)) {
525 throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
527 if (isset($_POST[$parname])) { // POST has precedence
528 $param = $_POST[$parname];
529 } else if (isset($_GET[$parname])) {
530 $param = $_GET[$parname];
531 } else {
532 print_error('missingparam', '', '', $parname);
535 if (is_array($param)) {
536 debugging('Invalid array parameter detected in required_param(): '.$parname);
537 // TODO: switch to fatal error in Moodle 2.3
538 //print_error('missingparam', '', '', $parname);
539 return required_param_array($parname, $type);
542 return clean_param($param, $type);
546 * Returns a particular array value for the named variable, taken from
547 * POST or GET. If the parameter doesn't exist then an error is
548 * thrown because we require this variable.
550 * This function should be used to initialise all required values
551 * in a script that are based on parameters. Usually it will be
552 * used like this:
553 * $ids = required_param_array('ids', PARAM_INT);
555 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
557 * @param string $parname the name of the page parameter we want
558 * @param string $type expected type of parameter
559 * @return array
561 function required_param_array($parname, $type) {
562 if (func_num_args() != 2 or empty($parname) or empty($type)) {
563 throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
565 if (isset($_POST[$parname])) { // POST has precedence
566 $param = $_POST[$parname];
567 } else if (isset($_GET[$parname])) {
568 $param = $_GET[$parname];
569 } else {
570 print_error('missingparam', '', '', $parname);
572 if (!is_array($param)) {
573 print_error('missingparam', '', '', $parname);
576 $result = array();
577 foreach($param as $key=>$value) {
578 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
579 debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
580 continue;
582 $result[$key] = clean_param($value, $type);
585 return $result;
589 * Returns a particular value for the named variable, taken from
590 * POST or GET, otherwise returning a given default.
592 * This function should be used to initialise all optional values
593 * in a script that are based on parameters. Usually it will be
594 * used like this:
595 * $name = optional_param('name', 'Fred', PARAM_TEXT);
597 * Please note the $type parameter is now required and the value can not be array.
599 * @param string $parname the name of the page parameter we want
600 * @param mixed $default the default value to return if nothing is found
601 * @param string $type expected type of parameter
602 * @return mixed
604 function optional_param($parname, $default, $type) {
605 if (func_num_args() != 3 or empty($parname) or empty($type)) {
606 throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
608 if (!isset($default)) {
609 $default = null;
612 if (isset($_POST[$parname])) { // POST has precedence
613 $param = $_POST[$parname];
614 } else if (isset($_GET[$parname])) {
615 $param = $_GET[$parname];
616 } else {
617 return $default;
620 if (is_array($param)) {
621 debugging('Invalid array parameter detected in required_param(): '.$parname);
622 // TODO: switch to $default in Moodle 2.3
623 //return $default;
624 return optional_param_array($parname, $default, $type);
627 return clean_param($param, $type);
631 * Returns a particular array value for the named variable, taken from
632 * POST or GET, otherwise returning a given default.
634 * This function should be used to initialise all optional values
635 * in a script that are based on parameters. Usually it will be
636 * used like this:
637 * $ids = optional_param('id', array(), PARAM_INT);
639 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
641 * @param string $parname the name of the page parameter we want
642 * @param mixed $default the default value to return if nothing is found
643 * @param string $type expected type of parameter
644 * @return array
646 function optional_param_array($parname, $default, $type) {
647 if (func_num_args() != 3 or empty($parname) or empty($type)) {
648 throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
651 if (isset($_POST[$parname])) { // POST has precedence
652 $param = $_POST[$parname];
653 } else if (isset($_GET[$parname])) {
654 $param = $_GET[$parname];
655 } else {
656 return $default;
658 if (!is_array($param)) {
659 debugging('optional_param_array() expects array parameters only: '.$parname);
660 return $default;
663 $result = array();
664 foreach($param as $key=>$value) {
665 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
666 debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
667 continue;
669 $result[$key] = clean_param($value, $type);
672 return $result;
676 * Strict validation of parameter values, the values are only converted
677 * to requested PHP type. Internally it is using clean_param, the values
678 * before and after cleaning must be equal - otherwise
679 * an invalid_parameter_exception is thrown.
680 * Objects and classes are not accepted.
682 * @param mixed $param
683 * @param string $type PARAM_ constant
684 * @param bool $allownull are nulls valid value?
685 * @param string $debuginfo optional debug information
686 * @return mixed the $param value converted to PHP type
687 * @throws invalid_parameter_exception if $param is not of given type
689 function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
690 if (is_null($param)) {
691 if ($allownull == NULL_ALLOWED) {
692 return null;
693 } else {
694 throw new invalid_parameter_exception($debuginfo);
697 if (is_array($param) or is_object($param)) {
698 throw new invalid_parameter_exception($debuginfo);
701 $cleaned = clean_param($param, $type);
703 if ($type == PARAM_FLOAT) {
704 // Do not detect precision loss here.
705 if (is_float($param) or is_int($param)) {
706 // These always fit.
707 } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
708 throw new invalid_parameter_exception($debuginfo);
710 } else if ((string)$param !== (string)$cleaned) {
711 // conversion to string is usually lossless
712 throw new invalid_parameter_exception($debuginfo);
715 return $cleaned;
719 * Makes sure array contains only the allowed types,
720 * this function does not validate array key names!
721 * <code>
722 * $options = clean_param($options, PARAM_INT);
723 * </code>
725 * @param array $param the variable array we are cleaning
726 * @param string $type expected format of param after cleaning.
727 * @param bool $recursive clean recursive arrays
728 * @return array
730 function clean_param_array(array $param = null, $type, $recursive = false) {
731 $param = (array)$param; // convert null to empty array
732 foreach ($param as $key => $value) {
733 if (is_array($value)) {
734 if ($recursive) {
735 $param[$key] = clean_param_array($value, $type, true);
736 } else {
737 throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.');
739 } else {
740 $param[$key] = clean_param($value, $type);
743 return $param;
747 * Used by {@link optional_param()} and {@link required_param()} to
748 * clean the variables and/or cast to specific types, based on
749 * an options field.
750 * <code>
751 * $course->format = clean_param($course->format, PARAM_ALPHA);
752 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
753 * </code>
755 * @param mixed $param the variable we are cleaning
756 * @param string $type expected format of param after cleaning.
757 * @return mixed
759 function clean_param($param, $type) {
761 global $CFG;
763 if (is_array($param)) {
764 throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
765 } else if (is_object($param)) {
766 if (method_exists($param, '__toString')) {
767 $param = $param->__toString();
768 } else {
769 throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
773 switch ($type) {
774 case PARAM_RAW: // no cleaning at all
775 $param = fix_utf8($param);
776 return $param;
778 case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
779 $param = fix_utf8($param);
780 return trim($param);
782 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
783 // this is deprecated!, please use more specific type instead
784 if (is_numeric($param)) {
785 return $param;
787 $param = fix_utf8($param);
788 return clean_text($param); // Sweep for scripts, etc
790 case PARAM_CLEANHTML: // clean html fragment
791 $param = fix_utf8($param);
792 $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
793 return trim($param);
795 case PARAM_INT:
796 return (int)$param; // Convert to integer
798 case PARAM_FLOAT:
799 return (float)$param; // Convert to float
801 case PARAM_ALPHA: // Remove everything not a-z
802 return preg_replace('/[^a-zA-Z]/i', '', $param);
804 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
805 return preg_replace('/[^a-zA-Z_-]/i', '', $param);
807 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
808 return preg_replace('/[^A-Za-z0-9]/i', '', $param);
810 case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
811 return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
813 case PARAM_SEQUENCE: // Remove everything not 0-9,
814 return preg_replace('/[^0-9,]/i', '', $param);
816 case PARAM_BOOL: // Convert to 1 or 0
817 $tempstr = strtolower($param);
818 if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
819 $param = 1;
820 } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
821 $param = 0;
822 } else {
823 $param = empty($param) ? 0 : 1;
825 return $param;
827 case PARAM_NOTAGS: // Strip all tags
828 $param = fix_utf8($param);
829 return strip_tags($param);
831 case PARAM_TEXT: // leave only tags needed for multilang
832 $param = fix_utf8($param);
833 // if the multilang syntax is not correct we strip all tags
834 // because it would break xhtml strict which is required for accessibility standards
835 // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
836 do {
837 if (strpos($param, '</lang>') !== false) {
838 // old and future mutilang syntax
839 $param = strip_tags($param, '<lang>');
840 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
841 break;
843 $open = false;
844 foreach ($matches[0] as $match) {
845 if ($match === '</lang>') {
846 if ($open) {
847 $open = false;
848 continue;
849 } else {
850 break 2;
853 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
854 break 2;
855 } else {
856 $open = true;
859 if ($open) {
860 break;
862 return $param;
864 } else if (strpos($param, '</span>') !== false) {
865 // current problematic multilang syntax
866 $param = strip_tags($param, '<span>');
867 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
868 break;
870 $open = false;
871 foreach ($matches[0] as $match) {
872 if ($match === '</span>') {
873 if ($open) {
874 $open = false;
875 continue;
876 } else {
877 break 2;
880 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
881 break 2;
882 } else {
883 $open = true;
886 if ($open) {
887 break;
889 return $param;
891 } while (false);
892 // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
893 return strip_tags($param);
895 case PARAM_COMPONENT:
896 // we do not want any guessing here, either the name is correct or not
897 // please note only normalised component names are accepted
898 if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
899 return '';
901 if (strpos($param, '__') !== false) {
902 return '';
904 if (strpos($param, 'mod_') === 0) {
905 // module names must not contain underscores because we need to differentiate them from invalid plugin types
906 if (substr_count($param, '_') != 1) {
907 return '';
910 return $param;
912 case PARAM_PLUGIN:
913 case PARAM_AREA:
914 // we do not want any guessing here, either the name is correct or not
915 if (!is_valid_plugin_name($param)) {
916 return '';
918 return $param;
920 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
921 return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
923 case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
924 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
926 case PARAM_FILE: // Strip all suspicious characters from filename
927 $param = fix_utf8($param);
928 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
929 if ($param === '.' || $param === '..') {
930 $param = '';
932 return $param;
934 case PARAM_PATH: // Strip all suspicious characters from file path
935 $param = fix_utf8($param);
936 $param = str_replace('\\', '/', $param);
938 // Explode the path and clean each element using the PARAM_FILE rules.
939 $breadcrumb = explode('/', $param);
940 foreach ($breadcrumb as $key => $crumb) {
941 if ($crumb === '.' && $key === 0) {
942 // Special condition to allow for relative current path such as ./currentdirfile.txt.
943 } else {
944 $crumb = clean_param($crumb, PARAM_FILE);
946 $breadcrumb[$key] = $crumb;
948 $param = implode('/', $breadcrumb);
950 // Remove multiple current path (./././) and multiple slashes (///).
951 $param = preg_replace('~//+~', '/', $param);
952 $param = preg_replace('~/(\./)+~', '/', $param);
953 return $param;
955 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
956 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
957 // match ipv4 dotted quad
958 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
959 // confirm values are ok
960 if ( $match[0] > 255
961 || $match[1] > 255
962 || $match[3] > 255
963 || $match[4] > 255 ) {
964 // hmmm, what kind of dotted quad is this?
965 $param = '';
967 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
968 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
969 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
971 // all is ok - $param is respected
972 } else {
973 // all is not ok...
974 $param='';
976 return $param;
978 case PARAM_URL: // allow safe ftp, http, mailto urls
979 $param = fix_utf8($param);
980 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
981 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
982 // all is ok, param is respected
983 } else {
984 $param =''; // not really ok
986 return $param;
988 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
989 $param = clean_param($param, PARAM_URL);
990 if (!empty($param)) {
991 if (preg_match(':^/:', $param)) {
992 // root-relative, ok!
993 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
994 // absolute, and matches our wwwroot
995 } else {
996 // relative - let's make sure there are no tricks
997 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
998 // looks ok.
999 } else {
1000 $param = '';
1004 return $param;
1006 case PARAM_PEM:
1007 $param = trim($param);
1008 // PEM formatted strings may contain letters/numbers and the symbols
1009 // forward slash: /
1010 // plus sign: +
1011 // equal sign: =
1012 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
1013 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1014 list($wholething, $body) = $matches;
1015 unset($wholething, $matches);
1016 $b64 = clean_param($body, PARAM_BASE64);
1017 if (!empty($b64)) {
1018 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1019 } else {
1020 return '';
1023 return '';
1025 case PARAM_BASE64:
1026 if (!empty($param)) {
1027 // PEM formatted strings may contain letters/numbers and the symbols
1028 // forward slash: /
1029 // plus sign: +
1030 // equal sign: =
1031 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1032 return '';
1034 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1035 // Each line of base64 encoded data must be 64 characters in
1036 // length, except for the last line which may be less than (or
1037 // equal to) 64 characters long.
1038 for ($i=0, $j=count($lines); $i < $j; $i++) {
1039 if ($i + 1 == $j) {
1040 if (64 < strlen($lines[$i])) {
1041 return '';
1043 continue;
1046 if (64 != strlen($lines[$i])) {
1047 return '';
1050 return implode("\n",$lines);
1051 } else {
1052 return '';
1055 case PARAM_TAG:
1056 $param = fix_utf8($param);
1057 // Please note it is not safe to use the tag name directly anywhere,
1058 // it must be processed with s(), urlencode() before embedding anywhere.
1059 // remove some nasties
1060 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1061 //convert many whitespace chars into one
1062 $param = preg_replace('/\s+/', ' ', $param);
1063 $param = textlib::substr(trim($param), 0, TAG_MAX_LENGTH);
1064 return $param;
1066 case PARAM_TAGLIST:
1067 $param = fix_utf8($param);
1068 $tags = explode(',', $param);
1069 $result = array();
1070 foreach ($tags as $tag) {
1071 $res = clean_param($tag, PARAM_TAG);
1072 if ($res !== '') {
1073 $result[] = $res;
1076 if ($result) {
1077 return implode(',', $result);
1078 } else {
1079 return '';
1082 case PARAM_CAPABILITY:
1083 if (get_capability_info($param)) {
1084 return $param;
1085 } else {
1086 return '';
1089 case PARAM_PERMISSION:
1090 $param = (int)$param;
1091 if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1092 return $param;
1093 } else {
1094 return CAP_INHERIT;
1097 case PARAM_AUTH:
1098 $param = clean_param($param, PARAM_PLUGIN);
1099 if (empty($param)) {
1100 return '';
1101 } else if (exists_auth_plugin($param)) {
1102 return $param;
1103 } else {
1104 return '';
1107 case PARAM_LANG:
1108 $param = clean_param($param, PARAM_SAFEDIR);
1109 if (get_string_manager()->translation_exists($param)) {
1110 return $param;
1111 } else {
1112 return ''; // Specified language is not installed or param malformed
1115 case PARAM_THEME:
1116 $param = clean_param($param, PARAM_PLUGIN);
1117 if (empty($param)) {
1118 return '';
1119 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1120 return $param;
1121 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1122 return $param;
1123 } else {
1124 return ''; // Specified theme is not installed
1127 case PARAM_USERNAME:
1128 $param = fix_utf8($param);
1129 $param = str_replace(" " , "", $param);
1130 $param = textlib::strtolower($param); // Convert uppercase to lowercase MDL-16919
1131 if (empty($CFG->extendedusernamechars)) {
1132 // regular expression, eliminate all chars EXCEPT:
1133 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1134 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1136 return $param;
1138 case PARAM_EMAIL:
1139 $param = fix_utf8($param);
1140 if (validate_email($param)) {
1141 return $param;
1142 } else {
1143 return '';
1146 case PARAM_STRINGID:
1147 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1148 return $param;
1149 } else {
1150 return '';
1153 case PARAM_TIMEZONE: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
1154 $param = fix_utf8($param);
1155 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1156 if (preg_match($timezonepattern, $param)) {
1157 return $param;
1158 } else {
1159 return '';
1162 default: // throw error, switched parameters in optional_param or another serious problem
1163 print_error("unknownparamtype", '', '', $type);
1168 * Makes sure the data is using valid utf8, invalid characters are discarded.
1170 * Note: this function is not intended for full objects with methods and private properties.
1172 * @param mixed $value
1173 * @return mixed with proper utf-8 encoding
1175 function fix_utf8($value) {
1176 if (is_null($value) or $value === '') {
1177 return $value;
1179 } else if (is_string($value)) {
1180 if ((string)(int)$value === $value) {
1181 // shortcut
1182 return $value;
1185 // Lower error reporting because glibc throws bogus notices.
1186 $olderror = error_reporting();
1187 if ($olderror & E_NOTICE) {
1188 error_reporting($olderror ^ E_NOTICE);
1191 // Note: this duplicates min_fix_utf8() intentionally.
1192 static $buggyiconv = null;
1193 if ($buggyiconv === null) {
1194 $buggyiconv = (!function_exists('iconv') or iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1197 if ($buggyiconv) {
1198 if (function_exists('mb_convert_encoding')) {
1199 $subst = mb_substitute_character();
1200 mb_substitute_character('');
1201 $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1202 mb_substitute_character($subst);
1204 } else {
1205 // Warn admins on admin/index.php page.
1206 $result = $value;
1209 } else {
1210 $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
1213 if ($olderror & E_NOTICE) {
1214 error_reporting($olderror);
1217 return $result;
1219 } else if (is_array($value)) {
1220 foreach ($value as $k=>$v) {
1221 $value[$k] = fix_utf8($v);
1223 return $value;
1225 } else if (is_object($value)) {
1226 $value = clone($value); // do not modify original
1227 foreach ($value as $k=>$v) {
1228 $value->$k = fix_utf8($v);
1230 return $value;
1232 } else {
1233 // this is some other type, no utf-8 here
1234 return $value;
1239 * Return true if given value is integer or string with integer value
1241 * @param mixed $value String or Int
1242 * @return bool true if number, false if not
1244 function is_number($value) {
1245 if (is_int($value)) {
1246 return true;
1247 } else if (is_string($value)) {
1248 return ((string)(int)$value) === $value;
1249 } else {
1250 return false;
1255 * Returns host part from url
1256 * @param string $url full url
1257 * @return string host, null if not found
1259 function get_host_from_url($url) {
1260 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1261 if ($matches) {
1262 return $matches[1];
1264 return null;
1268 * Tests whether anything was returned by text editor
1270 * This function is useful for testing whether something you got back from
1271 * the HTML editor actually contains anything. Sometimes the HTML editor
1272 * appear to be empty, but actually you get back a <br> tag or something.
1274 * @param string $string a string containing HTML.
1275 * @return boolean does the string contain any actual content - that is text,
1276 * images, objects, etc.
1278 function html_is_blank($string) {
1279 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1283 * Set a key in global configuration
1285 * Set a key/value pair in both this session's {@link $CFG} global variable
1286 * and in the 'config' database table for future sessions.
1288 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1289 * In that case it doesn't affect $CFG.
1291 * A NULL value will delete the entry.
1293 * @global object
1294 * @global object
1295 * @param string $name the key to set
1296 * @param string $value the value to set (without magic quotes)
1297 * @param string $plugin (optional) the plugin scope, default NULL
1298 * @return bool true or exception
1300 function set_config($name, $value, $plugin=NULL) {
1301 global $CFG, $DB;
1303 if (empty($plugin)) {
1304 if (!array_key_exists($name, $CFG->config_php_settings)) {
1305 // So it's defined for this invocation at least
1306 if (is_null($value)) {
1307 unset($CFG->$name);
1308 } else {
1309 $CFG->$name = (string)$value; // settings from db are always strings
1313 if ($DB->get_field('config', 'name', array('name'=>$name))) {
1314 if ($value === null) {
1315 $DB->delete_records('config', array('name'=>$name));
1316 } else {
1317 $DB->set_field('config', 'value', $value, array('name'=>$name));
1319 } else {
1320 if ($value !== null) {
1321 $config = new stdClass();
1322 $config->name = $name;
1323 $config->value = $value;
1324 $DB->insert_record('config', $config, false);
1327 if ($name === 'siteidentifier') {
1328 cache_helper::update_site_identifier($value);
1330 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1331 } else { // plugin scope
1332 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
1333 if ($value===null) {
1334 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1335 } else {
1336 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
1338 } else {
1339 if ($value !== null) {
1340 $config = new stdClass();
1341 $config->plugin = $plugin;
1342 $config->name = $name;
1343 $config->value = $value;
1344 $DB->insert_record('config_plugins', $config, false);
1347 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1350 return true;
1354 * Get configuration values from the global config table
1355 * or the config_plugins table.
1357 * If called with one parameter, it will load all the config
1358 * variables for one plugin, and return them as an object.
1360 * If called with 2 parameters it will return a string single
1361 * value or false if the value is not found.
1363 * @static $siteidentifier The site identifier is not cached. We use this static cache so
1364 * that we need only fetch it once per request.
1365 * @param string $plugin full component name
1366 * @param string $name default NULL
1367 * @return mixed hash-like object or single value, return false no config found
1369 function get_config($plugin, $name = NULL) {
1370 global $CFG, $DB;
1372 static $siteidentifier = null;
1374 if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1375 $forced =& $CFG->config_php_settings;
1376 $iscore = true;
1377 $plugin = 'core';
1378 } else {
1379 if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1380 $forced =& $CFG->forced_plugin_settings[$plugin];
1381 } else {
1382 $forced = array();
1384 $iscore = false;
1387 if ($siteidentifier === null) {
1388 try {
1389 // This may fail during installation.
1390 // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1391 // install the database.
1392 $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1393 } catch (dml_exception $ex) {
1394 // Set siteidentifier to false. We don't want to trip this continually.
1395 $siteidentifier = false;
1396 throw $ex;
1400 if (!empty($name)) {
1401 if (array_key_exists($name, $forced)) {
1402 return (string)$forced[$name];
1403 } else if ($name === 'siteidentifier' && $plugin == 'core') {
1404 return $siteidentifier;
1408 $cache = cache::make('core', 'config');
1409 $result = $cache->get($plugin);
1410 if ($result === false) {
1411 // the user is after a recordset
1412 $result = new stdClass;
1413 if (!$iscore) {
1414 $result = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
1415 } else {
1416 // this part is not really used any more, but anyway...
1417 $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1419 $cache->set($plugin, $result);
1422 if (!empty($name)) {
1423 if (array_key_exists($name, $result)) {
1424 return $result[$name];
1426 return false;
1429 if ($plugin === 'core') {
1430 $result['siteidentifier'] = $siteidentifier;
1433 foreach ($forced as $key => $value) {
1434 if (is_null($value) or is_array($value) or is_object($value)) {
1435 // we do not want any extra mess here, just real settings that could be saved in db
1436 unset($result[$key]);
1437 } else {
1438 //convert to string as if it went through the DB
1439 $result[$key] = (string)$value;
1443 return (object)$result;
1447 * Removes a key from global configuration
1449 * @param string $name the key to set
1450 * @param string $plugin (optional) the plugin scope
1451 * @global object
1452 * @return boolean whether the operation succeeded.
1454 function unset_config($name, $plugin=NULL) {
1455 global $CFG, $DB;
1457 if (empty($plugin)) {
1458 unset($CFG->$name);
1459 $DB->delete_records('config', array('name'=>$name));
1460 cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1461 } else {
1462 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
1463 cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1466 return true;
1470 * Remove all the config variables for a given plugin.
1472 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1473 * @return boolean whether the operation succeeded.
1475 function unset_all_config_for_plugin($plugin) {
1476 global $DB;
1477 // Delete from the obvious config_plugins first
1478 $DB->delete_records('config_plugins', array('plugin' => $plugin));
1479 // Next delete any suspect settings from config
1480 $like = $DB->sql_like('name', '?', true, true, false, '|');
1481 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1482 $DB->delete_records_select('config', $like, $params);
1483 // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1484 cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1486 return true;
1490 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1492 * All users are verified if they still have the necessary capability.
1494 * @param string $value the value of the config setting.
1495 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1496 * @param bool $include admins, include administrators
1497 * @return array of user objects.
1499 function get_users_from_config($value, $capability, $includeadmins = true) {
1500 global $CFG, $DB;
1502 if (empty($value) or $value === '$@NONE@$') {
1503 return array();
1506 // we have to make sure that users still have the necessary capability,
1507 // it should be faster to fetch them all first and then test if they are present
1508 // instead of validating them one-by-one
1509 $users = get_users_by_capability(context_system::instance(), $capability);
1510 if ($includeadmins) {
1511 $admins = get_admins();
1512 foreach ($admins as $admin) {
1513 $users[$admin->id] = $admin;
1517 if ($value === '$@ALL@$') {
1518 return $users;
1521 $result = array(); // result in correct order
1522 $allowed = explode(',', $value);
1523 foreach ($allowed as $uid) {
1524 if (isset($users[$uid])) {
1525 $user = $users[$uid];
1526 $result[$user->id] = $user;
1530 return $result;
1535 * Invalidates browser caches and cached data in temp
1537 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1538 * {@see phpunit_util::reset_dataroot()}
1540 * @return void
1542 function purge_all_caches() {
1543 global $CFG;
1545 reset_text_filters_cache();
1546 js_reset_all_caches();
1547 theme_reset_all_caches();
1548 get_string_manager()->reset_caches();
1549 textlib::reset_caches();
1551 cache_helper::purge_all();
1553 // purge all other caches: rss, simplepie, etc.
1554 remove_dir($CFG->cachedir.'', true);
1556 // make sure cache dir is writable, throws exception if not
1557 make_cache_directory('');
1559 // hack: this script may get called after the purifier was initialised,
1560 // but we do not want to verify repeatedly this exists in each call
1561 make_cache_directory('htmlpurifier');
1565 * Get volatile flags
1567 * @param string $type
1568 * @param int $changedsince default null
1569 * @return records array
1571 function get_cache_flags($type, $changedsince=NULL) {
1572 global $DB;
1574 $params = array('type'=>$type, 'expiry'=>time());
1575 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1576 if ($changedsince !== NULL) {
1577 $params['changedsince'] = $changedsince;
1578 $sqlwhere .= " AND timemodified > :changedsince";
1580 $cf = array();
1582 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1583 foreach ($flags as $flag) {
1584 $cf[$flag->name] = $flag->value;
1587 return $cf;
1591 * Get volatile flags
1593 * @param string $type
1594 * @param string $name
1595 * @param int $changedsince default null
1596 * @return records array
1598 function get_cache_flag($type, $name, $changedsince=NULL) {
1599 global $DB;
1601 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
1603 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1604 if ($changedsince !== NULL) {
1605 $params['changedsince'] = $changedsince;
1606 $sqlwhere .= " AND timemodified > :changedsince";
1609 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1613 * Set a volatile flag
1615 * @param string $type the "type" namespace for the key
1616 * @param string $name the key to set
1617 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1618 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1619 * @return bool Always returns true
1621 function set_cache_flag($type, $name, $value, $expiry=NULL) {
1622 global $DB;
1624 $timemodified = time();
1625 if ($expiry===NULL || $expiry < $timemodified) {
1626 $expiry = $timemodified + 24 * 60 * 60;
1627 } else {
1628 $expiry = (int)$expiry;
1631 if ($value === NULL) {
1632 unset_cache_flag($type,$name);
1633 return true;
1636 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
1637 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1638 return true; //no need to update
1640 $f->value = $value;
1641 $f->expiry = $expiry;
1642 $f->timemodified = $timemodified;
1643 $DB->update_record('cache_flags', $f);
1644 } else {
1645 $f = new stdClass();
1646 $f->flagtype = $type;
1647 $f->name = $name;
1648 $f->value = $value;
1649 $f->expiry = $expiry;
1650 $f->timemodified = $timemodified;
1651 $DB->insert_record('cache_flags', $f);
1653 return true;
1657 * Removes a single volatile flag
1659 * @global object
1660 * @param string $type the "type" namespace for the key
1661 * @param string $name the key to set
1662 * @return bool
1664 function unset_cache_flag($type, $name) {
1665 global $DB;
1666 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1667 return true;
1671 * Garbage-collect volatile flags
1673 * @return bool Always returns true
1675 function gc_cache_flags() {
1676 global $DB;
1677 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1678 return true;
1681 // USER PREFERENCE API
1684 * Refresh user preference cache. This is used most often for $USER
1685 * object that is stored in session, but it also helps with performance in cron script.
1687 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1689 * @package core
1690 * @category preference
1691 * @access public
1692 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1693 * @param int $cachelifetime Cache life time on the current page (in seconds)
1694 * @throws coding_exception
1695 * @return null
1697 function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1698 global $DB;
1699 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
1701 if (!isset($user->id)) {
1702 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1705 if (empty($user->id) or isguestuser($user->id)) {
1706 // No permanent storage for not-logged-in users and guest
1707 if (!isset($user->preference)) {
1708 $user->preference = array();
1710 return;
1713 $timenow = time();
1715 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1716 // Already loaded at least once on this page. Are we up to date?
1717 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1718 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1719 return;
1721 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1722 // no change since the lastcheck on this page
1723 $user->preference['_lastloaded'] = $timenow;
1724 return;
1728 // OK, so we have to reload all preferences
1729 $loadedusers[$user->id] = true;
1730 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1731 $user->preference['_lastloaded'] = $timenow;
1735 * Called from set/unset_user_preferences, so that the prefs can
1736 * be correctly reloaded in different sessions.
1738 * NOTE: internal function, do not call from other code.
1740 * @package core
1741 * @access private
1742 * @param integer $userid the user whose prefs were changed.
1744 function mark_user_preferences_changed($userid) {
1745 global $CFG;
1747 if (empty($userid) or isguestuser($userid)) {
1748 // no cache flags for guest and not-logged-in users
1749 return;
1752 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1756 * Sets a preference for the specified user.
1758 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1760 * @package core
1761 * @category preference
1762 * @access public
1763 * @param string $name The key to set as preference for the specified user
1764 * @param string $value The value to set for the $name key in the specified user's
1765 * record, null means delete current value.
1766 * @param stdClass|int|null $user A moodle user object or id, null means current user
1767 * @throws coding_exception
1768 * @return bool Always true or exception
1770 function set_user_preference($name, $value, $user = null) {
1771 global $USER, $DB;
1773 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1774 throw new coding_exception('Invalid preference name in set_user_preference() call');
1777 if (is_null($value)) {
1778 // null means delete current
1779 return unset_user_preference($name, $user);
1780 } else if (is_object($value)) {
1781 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1782 } else if (is_array($value)) {
1783 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1785 $value = (string)$value;
1786 if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
1787 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1790 if (is_null($user)) {
1791 $user = $USER;
1792 } else if (isset($user->id)) {
1793 // $user is valid object
1794 } else if (is_numeric($user)) {
1795 $user = (object)array('id'=>(int)$user);
1796 } else {
1797 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1800 check_user_preferences_loaded($user);
1802 if (empty($user->id) or isguestuser($user->id)) {
1803 // no permanent storage for not-logged-in users and guest
1804 $user->preference[$name] = $value;
1805 return true;
1808 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1809 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1810 // preference already set to this value
1811 return true;
1813 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
1815 } else {
1816 $preference = new stdClass();
1817 $preference->userid = $user->id;
1818 $preference->name = $name;
1819 $preference->value = $value;
1820 $DB->insert_record('user_preferences', $preference);
1823 // update value in cache
1824 $user->preference[$name] = $value;
1826 // set reload flag for other sessions
1827 mark_user_preferences_changed($user->id);
1829 return true;
1833 * Sets a whole array of preferences for the current user
1835 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1837 * @package core
1838 * @category preference
1839 * @access public
1840 * @param array $prefarray An array of key/value pairs to be set
1841 * @param stdClass|int|null $user A moodle user object or id, null means current user
1842 * @return bool Always true or exception
1844 function set_user_preferences(array $prefarray, $user = null) {
1845 foreach ($prefarray as $name => $value) {
1846 set_user_preference($name, $value, $user);
1848 return true;
1852 * Unsets a preference completely by deleting it from the database
1854 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1856 * @package core
1857 * @category preference
1858 * @access public
1859 * @param string $name The key to unset as preference for the specified user
1860 * @param stdClass|int|null $user A moodle user object or id, null means current user
1861 * @throws coding_exception
1862 * @return bool Always true or exception
1864 function unset_user_preference($name, $user = null) {
1865 global $USER, $DB;
1867 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1868 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1871 if (is_null($user)) {
1872 $user = $USER;
1873 } else if (isset($user->id)) {
1874 // $user is valid object
1875 } else if (is_numeric($user)) {
1876 $user = (object)array('id'=>(int)$user);
1877 } else {
1878 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1881 check_user_preferences_loaded($user);
1883 if (empty($user->id) or isguestuser($user->id)) {
1884 // no permanent storage for not-logged-in user and guest
1885 unset($user->preference[$name]);
1886 return true;
1889 // delete from DB
1890 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1892 // delete the preference from cache
1893 unset($user->preference[$name]);
1895 // set reload flag for other sessions
1896 mark_user_preferences_changed($user->id);
1898 return true;
1902 * Used to fetch user preference(s)
1904 * If no arguments are supplied this function will return
1905 * all of the current user preferences as an array.
1907 * If a name is specified then this function
1908 * attempts to return that particular preference value. If
1909 * none is found, then the optional value $default is returned,
1910 * otherwise NULL.
1912 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1914 * @package core
1915 * @category preference
1916 * @access public
1917 * @param string $name Name of the key to use in finding a preference value
1918 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1919 * @param stdClass|int|null $user A moodle user object or id, null means current user
1920 * @throws coding_exception
1921 * @return string|mixed|null A string containing the value of a single preference. An
1922 * array with all of the preferences or null
1924 function get_user_preferences($name = null, $default = null, $user = null) {
1925 global $USER;
1927 if (is_null($name)) {
1928 // all prefs
1929 } else if (is_numeric($name) or $name === '_lastloaded') {
1930 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1933 if (is_null($user)) {
1934 $user = $USER;
1935 } else if (isset($user->id)) {
1936 // $user is valid object
1937 } else if (is_numeric($user)) {
1938 $user = (object)array('id'=>(int)$user);
1939 } else {
1940 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1943 check_user_preferences_loaded($user);
1945 if (empty($name)) {
1946 return $user->preference; // All values
1947 } else if (isset($user->preference[$name])) {
1948 return $user->preference[$name]; // The single string value
1949 } else {
1950 return $default; // Default value (null if not specified)
1954 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1957 * Given date parts in user time produce a GMT timestamp.
1959 * @package core
1960 * @category time
1961 * @param int $year The year part to create timestamp of
1962 * @param int $month The month part to create timestamp of
1963 * @param int $day The day part to create timestamp of
1964 * @param int $hour The hour part to create timestamp of
1965 * @param int $minute The minute part to create timestamp of
1966 * @param int $second The second part to create timestamp of
1967 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
1968 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
1969 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1970 * applied only if timezone is 99 or string.
1971 * @return int GMT timestamp
1973 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1975 //save input timezone, required for dst offset check.
1976 $passedtimezone = $timezone;
1978 $timezone = get_user_timezone_offset($timezone);
1980 if (abs($timezone) > 13) { //server time
1981 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1982 } else {
1983 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1984 $time = usertime($time, $timezone);
1986 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1987 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1988 $time -= dst_offset_on($time, $passedtimezone);
1992 return $time;
1997 * Format a date/time (seconds) as weeks, days, hours etc as needed
1999 * Given an amount of time in seconds, returns string
2000 * formatted nicely as weeks, days, hours etc as needed
2002 * @package core
2003 * @category time
2004 * @uses MINSECS
2005 * @uses HOURSECS
2006 * @uses DAYSECS
2007 * @uses YEARSECS
2008 * @param int $totalsecs Time in seconds
2009 * @param object $str Should be a time object
2010 * @return string A nicely formatted date/time string
2012 function format_time($totalsecs, $str=NULL) {
2014 $totalsecs = abs($totalsecs);
2016 if (!$str) { // Create the str structure the slow way
2017 $str = new stdClass();
2018 $str->day = get_string('day');
2019 $str->days = get_string('days');
2020 $str->hour = get_string('hour');
2021 $str->hours = get_string('hours');
2022 $str->min = get_string('min');
2023 $str->mins = get_string('mins');
2024 $str->sec = get_string('sec');
2025 $str->secs = get_string('secs');
2026 $str->year = get_string('year');
2027 $str->years = get_string('years');
2031 $years = floor($totalsecs/YEARSECS);
2032 $remainder = $totalsecs - ($years*YEARSECS);
2033 $days = floor($remainder/DAYSECS);
2034 $remainder = $totalsecs - ($days*DAYSECS);
2035 $hours = floor($remainder/HOURSECS);
2036 $remainder = $remainder - ($hours*HOURSECS);
2037 $mins = floor($remainder/MINSECS);
2038 $secs = $remainder - ($mins*MINSECS);
2040 $ss = ($secs == 1) ? $str->sec : $str->secs;
2041 $sm = ($mins == 1) ? $str->min : $str->mins;
2042 $sh = ($hours == 1) ? $str->hour : $str->hours;
2043 $sd = ($days == 1) ? $str->day : $str->days;
2044 $sy = ($years == 1) ? $str->year : $str->years;
2046 $oyears = '';
2047 $odays = '';
2048 $ohours = '';
2049 $omins = '';
2050 $osecs = '';
2052 if ($years) $oyears = $years .' '. $sy;
2053 if ($days) $odays = $days .' '. $sd;
2054 if ($hours) $ohours = $hours .' '. $sh;
2055 if ($mins) $omins = $mins .' '. $sm;
2056 if ($secs) $osecs = $secs .' '. $ss;
2058 if ($years) return trim($oyears .' '. $odays);
2059 if ($days) return trim($odays .' '. $ohours);
2060 if ($hours) return trim($ohours .' '. $omins);
2061 if ($mins) return trim($omins .' '. $osecs);
2062 if ($secs) return $osecs;
2063 return get_string('now');
2067 * Returns a formatted string that represents a date in user time
2069 * Returns a formatted string that represents a date in user time
2070 * <b>WARNING: note that the format is for strftime(), not date().</b>
2071 * Because of a bug in most Windows time libraries, we can't use
2072 * the nicer %e, so we have to use %d which has leading zeroes.
2073 * A lot of the fuss in the function is just getting rid of these leading
2074 * zeroes as efficiently as possible.
2076 * If parameter fixday = true (default), then take off leading
2077 * zero from %d, else maintain it.
2079 * @package core
2080 * @category time
2081 * @param int $date the timestamp in UTC, as obtained from the database.
2082 * @param string $format strftime format. You should probably get this using
2083 * get_string('strftime...', 'langconfig');
2084 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2085 * not 99 then daylight saving will not be added.
2086 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2087 * @param bool $fixday If true (default) then the leading zero from %d is removed.
2088 * If false then the leading zero is maintained.
2089 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2090 * @return string the formatted date/time.
2092 function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2094 global $CFG;
2096 if (empty($format)) {
2097 $format = get_string('strftimedaydatetime', 'langconfig');
2100 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
2101 $fixday = false;
2102 } else if ($fixday) {
2103 $formatnoday = str_replace('%d', 'DD', $format);
2104 $fixday = ($formatnoday != $format);
2105 $format = $formatnoday;
2108 // Note: This logic about fixing 12-hour time to remove unnecessary leading
2109 // zero is required because on Windows, PHP strftime function does not
2110 // support the correct 'hour without leading zero' parameter (%l).
2111 if (!empty($CFG->nofixhour)) {
2112 // Config.php can force %I not to be fixed.
2113 $fixhour = false;
2114 } else if ($fixhour) {
2115 $formatnohour = str_replace('%I', 'HH', $format);
2116 $fixhour = ($formatnohour != $format);
2117 $format = $formatnohour;
2120 //add daylight saving offset for string timezones only, as we can't get dst for
2121 //float values. if timezone is 99 (user default timezone), then try update dst.
2122 if ((99 == $timezone) || !is_numeric($timezone)) {
2123 $date += dst_offset_on($date, $timezone);
2126 $timezone = get_user_timezone_offset($timezone);
2128 // If we are running under Windows convert to windows encoding and then back to UTF-8
2129 // (because it's impossible to specify UTF-8 to fetch locale info in Win32)
2131 if (abs($timezone) > 13) { /// Server time
2132 $datestring = date_format_string($date, $format, $timezone);
2133 if ($fixday) {
2134 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
2135 $datestring = str_replace('DD', $daystring, $datestring);
2137 if ($fixhour) {
2138 $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
2139 $datestring = str_replace('HH', $hourstring, $datestring);
2142 } else {
2143 $date += (int)($timezone * 3600);
2144 $datestring = date_format_string($date, $format, $timezone);
2145 if ($fixday) {
2146 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
2147 $datestring = str_replace('DD', $daystring, $datestring);
2149 if ($fixhour) {
2150 $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
2151 $datestring = str_replace('HH', $hourstring, $datestring);
2155 return $datestring;
2159 * Returns a formatted date ensuring it is UTF-8.
2161 * If we are running under Windows convert to Windows encoding and then back to UTF-8
2162 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2164 * This function does not do any calculation regarding the user preferences and should
2165 * therefore receive the final date timestamp, format and timezone. Timezone being only used
2166 * to differenciate the use of server time or not (strftime() against gmstrftime()).
2168 * @param int $date the timestamp.
2169 * @param string $format strftime format.
2170 * @param int|float $timezone the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
2171 * @return string the formatted date/time.
2172 * @since 2.3.3
2174 function date_format_string($date, $format, $tz = 99) {
2175 global $CFG;
2176 if (abs($tz) > 13) {
2177 if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
2178 $format = textlib::convert($format, 'utf-8', $localewincharset);
2179 $datestring = strftime($format, $date);
2180 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2181 } else {
2182 $datestring = strftime($format, $date);
2184 } else {
2185 if ($CFG->ostype == 'WINDOWS' and $localewincharset = get_string('localewincharset', 'langconfig')) {
2186 $format = textlib::convert($format, 'utf-8', $localewincharset);
2187 $datestring = gmstrftime($format, $date);
2188 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
2189 } else {
2190 $datestring = gmstrftime($format, $date);
2193 return $datestring;
2197 * Given a $time timestamp in GMT (seconds since epoch),
2198 * returns an array that represents the date in user time
2200 * @package core
2201 * @category time
2202 * @uses HOURSECS
2203 * @param int $time Timestamp in GMT
2204 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2205 * dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
2206 * @return array An array that represents the date in user time
2208 function usergetdate($time, $timezone=99) {
2210 //save input timezone, required for dst offset check.
2211 $passedtimezone = $timezone;
2213 $timezone = get_user_timezone_offset($timezone);
2215 if (abs($timezone) > 13) { // Server time
2216 return getdate($time);
2219 //add daylight saving offset for string timezones only, as we can't get dst for
2220 //float values. if timezone is 99 (user default timezone), then try update dst.
2221 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2222 $time += dst_offset_on($time, $passedtimezone);
2225 $time += intval((float)$timezone * HOURSECS);
2227 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
2229 //be careful to ensure the returned array matches that produced by getdate() above
2230 list(
2231 $getdate['month'],
2232 $getdate['weekday'],
2233 $getdate['yday'],
2234 $getdate['year'],
2235 $getdate['mon'],
2236 $getdate['wday'],
2237 $getdate['mday'],
2238 $getdate['hours'],
2239 $getdate['minutes'],
2240 $getdate['seconds']
2241 ) = explode('_', $datestring);
2243 // set correct datatype to match with getdate()
2244 $getdate['seconds'] = (int)$getdate['seconds'];
2245 $getdate['yday'] = (int)$getdate['yday'] - 1; // gettime returns 0 through 365
2246 $getdate['year'] = (int)$getdate['year'];
2247 $getdate['mon'] = (int)$getdate['mon'];
2248 $getdate['wday'] = (int)$getdate['wday'];
2249 $getdate['mday'] = (int)$getdate['mday'];
2250 $getdate['hours'] = (int)$getdate['hours'];
2251 $getdate['minutes'] = (int)$getdate['minutes'];
2252 return $getdate;
2256 * Given a GMT timestamp (seconds since epoch), offsets it by
2257 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2259 * @package core
2260 * @category time
2261 * @uses HOURSECS
2262 * @param int $date Timestamp in GMT
2263 * @param float|int|string $timezone timezone to calculate GMT time offset before
2264 * calculating user time, 99 is default user timezone
2265 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2266 * @return int
2268 function usertime($date, $timezone=99) {
2270 $timezone = get_user_timezone_offset($timezone);
2272 if (abs($timezone) > 13) {
2273 return $date;
2275 return $date - (int)($timezone * HOURSECS);
2279 * Given a time, return the GMT timestamp of the most recent midnight
2280 * for the current user.
2282 * @package core
2283 * @category time
2284 * @param int $date Timestamp in GMT
2285 * @param float|int|string $timezone timezone to calculate GMT time offset before
2286 * calculating user midnight time, 99 is default user timezone
2287 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2288 * @return int Returns a GMT timestamp
2290 function usergetmidnight($date, $timezone=99) {
2292 $userdate = usergetdate($date, $timezone);
2294 // Time of midnight of this user's day, in GMT
2295 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2300 * Returns a string that prints the user's timezone
2302 * @package core
2303 * @category time
2304 * @param float|int|string $timezone timezone to calculate GMT time offset before
2305 * calculating user timezone, 99 is default user timezone
2306 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2307 * @return string
2309 function usertimezone($timezone=99) {
2311 $tz = get_user_timezone($timezone);
2313 if (!is_float($tz)) {
2314 return $tz;
2317 if(abs($tz) > 13) { // Server time
2318 return get_string('serverlocaltime');
2321 if($tz == intval($tz)) {
2322 // Don't show .0 for whole hours
2323 $tz = intval($tz);
2326 if($tz == 0) {
2327 return 'UTC';
2329 else if($tz > 0) {
2330 return 'UTC+'.$tz;
2332 else {
2333 return 'UTC'.$tz;
2339 * Returns a float which represents the user's timezone difference from GMT in hours
2340 * Checks various settings and picks the most dominant of those which have a value
2342 * @package core
2343 * @category time
2344 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2345 * 99 is default user timezone
2346 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2347 * @return float
2349 function get_user_timezone_offset($tz = 99) {
2351 global $USER, $CFG;
2353 $tz = get_user_timezone($tz);
2355 if (is_float($tz)) {
2356 return $tz;
2357 } else {
2358 $tzrecord = get_timezone_record($tz);
2359 if (empty($tzrecord)) {
2360 return 99.0;
2362 return (float)$tzrecord->gmtoff / HOURMINS;
2367 * Returns an int which represents the systems's timezone difference from GMT in seconds
2369 * @package core
2370 * @category time
2371 * @param float|int|string $tz timezone for which offset is required.
2372 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2373 * @return int|bool if found, false is timezone 99 or error
2375 function get_timezone_offset($tz) {
2376 global $CFG;
2378 if ($tz == 99) {
2379 return false;
2382 if (is_numeric($tz)) {
2383 return intval($tz * 60*60);
2386 if (!$tzrecord = get_timezone_record($tz)) {
2387 return false;
2389 return intval($tzrecord->gmtoff * 60);
2393 * Returns a float or a string which denotes the user's timezone
2394 * 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)
2395 * means that for this timezone there are also DST rules to be taken into account
2396 * Checks various settings and picks the most dominant of those which have a value
2398 * @package core
2399 * @category time
2400 * @param float|int|string $tz timezone to calculate GMT time offset before
2401 * calculating user timezone, 99 is default user timezone
2402 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2403 * @return float|string
2405 function get_user_timezone($tz = 99) {
2406 global $USER, $CFG;
2408 $timezones = array(
2409 $tz,
2410 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2411 isset($USER->timezone) ? $USER->timezone : 99,
2412 isset($CFG->timezone) ? $CFG->timezone : 99,
2415 $tz = 99;
2417 // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array
2418 while(((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
2419 $tz = $next['value'];
2421 return is_numeric($tz) ? (float) $tz : $tz;
2425 * Returns cached timezone record for given $timezonename
2427 * @package core
2428 * @param string $timezonename name of the timezone
2429 * @return stdClass|bool timezonerecord or false
2431 function get_timezone_record($timezonename) {
2432 global $CFG, $DB;
2433 static $cache = NULL;
2435 if ($cache === NULL) {
2436 $cache = array();
2439 if (isset($cache[$timezonename])) {
2440 return $cache[$timezonename];
2443 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
2444 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
2448 * Build and store the users Daylight Saving Time (DST) table
2450 * @package core
2451 * @param int $from_year Start year for the table, defaults to 1971
2452 * @param int $to_year End year for the table, defaults to 2035
2453 * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
2454 * @return bool
2456 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2457 global $CFG, $SESSION, $DB;
2459 $usertz = get_user_timezone($strtimezone);
2461 if (is_float($usertz)) {
2462 // Trivial timezone, no DST
2463 return false;
2466 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
2467 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2468 unset($SESSION->dst_offsets);
2469 unset($SESSION->dst_range);
2472 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
2473 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2474 // This will be the return path most of the time, pretty light computationally
2475 return true;
2478 // Reaching here means we either need to extend our table or create it from scratch
2480 // Remember which TZ we calculated these changes for
2481 $SESSION->dst_offsettz = $usertz;
2483 if(empty($SESSION->dst_offsets)) {
2484 // If we 're creating from scratch, put the two guard elements in there
2485 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
2487 if(empty($SESSION->dst_range)) {
2488 // If creating from scratch
2489 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2490 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2492 // Fill in the array with the extra years we need to process
2493 $yearstoprocess = array();
2494 for($i = $from; $i <= $to; ++$i) {
2495 $yearstoprocess[] = $i;
2498 // Take note of which years we have processed for future calls
2499 $SESSION->dst_range = array($from, $to);
2501 else {
2502 // If needing to extend the table, do the same
2503 $yearstoprocess = array();
2505 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2506 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
2508 if($from < $SESSION->dst_range[0]) {
2509 // Take note of which years we need to process and then note that we have processed them for future calls
2510 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
2511 $yearstoprocess[] = $i;
2513 $SESSION->dst_range[0] = $from;
2515 if($to > $SESSION->dst_range[1]) {
2516 // Take note of which years we need to process and then note that we have processed them for future calls
2517 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
2518 $yearstoprocess[] = $i;
2520 $SESSION->dst_range[1] = $to;
2524 if(empty($yearstoprocess)) {
2525 // This means that there was a call requesting a SMALLER range than we have already calculated
2526 return true;
2529 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2530 // Also, the array is sorted in descending timestamp order!
2532 // Get DB data
2534 static $presets_cache = array();
2535 if (!isset($presets_cache[$usertz])) {
2536 $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');
2538 if(empty($presets_cache[$usertz])) {
2539 return false;
2542 // Remove ending guard (first element of the array)
2543 reset($SESSION->dst_offsets);
2544 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
2546 // Add all required change timestamps
2547 foreach($yearstoprocess as $y) {
2548 // Find the record which is in effect for the year $y
2549 foreach($presets_cache[$usertz] as $year => $preset) {
2550 if($year <= $y) {
2551 break;
2555 $changes = dst_changes_for_year($y, $preset);
2557 if($changes === NULL) {
2558 continue;
2560 if($changes['dst'] != 0) {
2561 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
2563 if($changes['std'] != 0) {
2564 $SESSION->dst_offsets[$changes['std']] = 0;
2568 // Put in a guard element at the top
2569 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2570 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
2572 // Sort again
2573 krsort($SESSION->dst_offsets);
2575 return true;
2579 * Calculates the required DST change and returns a Timestamp Array
2581 * @package core
2582 * @category time
2583 * @uses HOURSECS
2584 * @uses MINSECS
2585 * @param int|string $year Int or String Year to focus on
2586 * @param object $timezone Instatiated Timezone object
2587 * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
2589 function dst_changes_for_year($year, $timezone) {
2591 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2592 return NULL;
2595 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2596 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2598 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2599 list($std_hour, $std_min) = explode(':', $timezone->std_time);
2601 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2602 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
2604 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2605 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2606 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2608 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2609 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
2611 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
2615 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2616 * - Note: Daylight saving only works for string timezones and not for float.
2618 * @package core
2619 * @category time
2620 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2621 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2622 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
2623 * @return int
2625 function dst_offset_on($time, $strtimezone = NULL) {
2626 global $SESSION;
2628 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
2629 return 0;
2632 reset($SESSION->dst_offsets);
2633 while(list($from, $offset) = each($SESSION->dst_offsets)) {
2634 if($from <= $time) {
2635 break;
2639 // This is the normal return path
2640 if($offset !== NULL) {
2641 return $offset;
2644 // Reaching this point means we haven't calculated far enough, do it now:
2645 // Calculate extra DST changes if needed and recurse. The recursion always
2646 // moves toward the stopping condition, so will always end.
2648 if($from == 0) {
2649 // We need a year smaller than $SESSION->dst_range[0]
2650 if($SESSION->dst_range[0] == 1971) {
2651 return 0;
2653 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2654 return dst_offset_on($time, $strtimezone);
2656 else {
2657 // We need a year larger than $SESSION->dst_range[1]
2658 if($SESSION->dst_range[1] == 2035) {
2659 return 0;
2661 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2662 return dst_offset_on($time, $strtimezone);
2667 * Calculates when the day appears in specific month
2669 * @package core
2670 * @category time
2671 * @param int $startday starting day of the month
2672 * @param int $weekday The day when week starts (normally taken from user preferences)
2673 * @param int $month The month whose day is sought
2674 * @param int $year The year of the month whose day is sought
2675 * @return int
2677 function find_day_in_month($startday, $weekday, $month, $year) {
2679 $daysinmonth = days_in_month($month, $year);
2681 if($weekday == -1) {
2682 // Don't care about weekday, so return:
2683 // abs($startday) if $startday != -1
2684 // $daysinmonth otherwise
2685 return ($startday == -1) ? $daysinmonth : abs($startday);
2688 // From now on we 're looking for a specific weekday
2690 // Give "end of month" its actual value, since we know it
2691 if($startday == -1) {
2692 $startday = -1 * $daysinmonth;
2695 // Starting from day $startday, the sign is the direction
2697 if($startday < 1) {
2699 $startday = abs($startday);
2700 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
2702 // This is the last such weekday of the month
2703 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2704 if($lastinmonth > $daysinmonth) {
2705 $lastinmonth -= 7;
2708 // Find the first such weekday <= $startday
2709 while($lastinmonth > $startday) {
2710 $lastinmonth -= 7;
2713 return $lastinmonth;
2716 else {
2718 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
2720 $diff = $weekday - $indexweekday;
2721 if($diff < 0) {
2722 $diff += 7;
2725 // This is the first such weekday of the month equal to or after $startday
2726 $firstfromindex = $startday + $diff;
2728 return $firstfromindex;
2734 * Calculate the number of days in a given month
2736 * @package core
2737 * @category time
2738 * @param int $month The month whose day count is sought
2739 * @param int $year The year of the month whose day count is sought
2740 * @return int
2742 function days_in_month($month, $year) {
2743 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
2747 * Calculate the position in the week of a specific calendar day
2749 * @package core
2750 * @category time
2751 * @param int $day The day of the date whose position in the week is sought
2752 * @param int $month The month of the date whose position in the week is sought
2753 * @param int $year The year of the date whose position in the week is sought
2754 * @return int
2756 function dayofweek($day, $month, $year) {
2757 // I wonder if this is any different from
2758 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
2759 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
2762 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
2765 * Returns full login url.
2767 * @return string login url
2769 function get_login_url() {
2770 global $CFG;
2772 $url = "$CFG->wwwroot/login/index.php";
2774 if (!empty($CFG->loginhttps)) {
2775 $url = str_replace('http:', 'https:', $url);
2778 return $url;
2782 * This function checks that the current user is logged in and has the
2783 * required privileges
2785 * This function checks that the current user is logged in, and optionally
2786 * whether they are allowed to be in a particular course and view a particular
2787 * course module.
2788 * If they are not logged in, then it redirects them to the site login unless
2789 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2790 * case they are automatically logged in as guests.
2791 * If $courseid is given and the user is not enrolled in that course then the
2792 * user is redirected to the course enrolment page.
2793 * If $cm is given and the course module is hidden and the user is not a teacher
2794 * in the course then the user is redirected to the course home page.
2796 * When $cm parameter specified, this function sets page layout to 'module'.
2797 * You need to change it manually later if some other layout needed.
2799 * @package core_access
2800 * @category access
2802 * @param mixed $courseorid id of the course or course object
2803 * @param bool $autologinguest default true
2804 * @param object $cm course module object
2805 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2806 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2807 * in order to keep redirects working properly. MDL-14495
2808 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2809 * @return mixed Void, exit, and die depending on path
2811 function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
2812 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2814 // Must not redirect when byteserving already started.
2815 if (!empty($_SERVER['HTTP_RANGE'])) {
2816 $preventredirect = true;
2819 // setup global $COURSE, themes, language and locale
2820 if (!empty($courseorid)) {
2821 if (is_object($courseorid)) {
2822 $course = $courseorid;
2823 } else if ($courseorid == SITEID) {
2824 $course = clone($SITE);
2825 } else {
2826 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2828 if ($cm) {
2829 if ($cm->course != $course->id) {
2830 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2832 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
2833 if (!($cm instanceof cm_info)) {
2834 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2835 // db queries so this is not really a performance concern, however it is obviously
2836 // better if you use get_fast_modinfo to get the cm before calling this.
2837 $modinfo = get_fast_modinfo($course);
2838 $cm = $modinfo->get_cm($cm->id);
2840 $PAGE->set_cm($cm, $course); // set's up global $COURSE
2841 $PAGE->set_pagelayout('incourse');
2842 } else {
2843 $PAGE->set_course($course); // set's up global $COURSE
2845 } else {
2846 // do not touch global $COURSE via $PAGE->set_course(),
2847 // the reasons is we need to be able to call require_login() at any time!!
2848 $course = $SITE;
2849 if ($cm) {
2850 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2854 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2855 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2856 // risk leading the user back to the AJAX request URL.
2857 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2858 $setwantsurltome = false;
2861 // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2862 if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
2863 if ($setwantsurltome) {
2864 $SESSION->wantsurl = qualified_me();
2866 redirect(get_login_url());
2869 // If the user is not even logged in yet then make sure they are
2870 if (!isloggedin()) {
2871 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2872 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2873 // misconfigured site guest, just redirect to login page
2874 redirect(get_login_url());
2875 exit; // never reached
2877 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2878 complete_user_login($guest);
2879 $USER->autologinguest = true;
2880 $SESSION->lang = $lang;
2881 } else {
2882 //NOTE: $USER->site check was obsoleted by session test cookie,
2883 // $USER->confirmed test is in login/index.php
2884 if ($preventredirect) {
2885 throw new require_login_exception('You are not logged in');
2888 if ($setwantsurltome) {
2889 $SESSION->wantsurl = qualified_me();
2891 if (!empty($_SERVER['HTTP_REFERER'])) {
2892 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2894 redirect(get_login_url());
2895 exit; // never reached
2899 // loginas as redirection if needed
2900 if ($course->id != SITEID and session_is_loggedinas()) {
2901 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2902 if ($USER->loginascontext->instanceid != $course->id) {
2903 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2908 // check whether the user should be changing password (but only if it is REALLY them)
2909 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
2910 $userauth = get_auth_plugin($USER->auth);
2911 if ($userauth->can_change_password() and !$preventredirect) {
2912 if ($setwantsurltome) {
2913 $SESSION->wantsurl = qualified_me();
2915 if ($changeurl = $userauth->change_password_url()) {
2916 //use plugin custom url
2917 redirect($changeurl);
2918 } else {
2919 //use moodle internal method
2920 if (empty($CFG->loginhttps)) {
2921 redirect($CFG->wwwroot .'/login/change_password.php');
2922 } else {
2923 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2924 redirect($wwwroot .'/login/change_password.php');
2927 } else {
2928 print_error('nopasswordchangeforced', 'auth');
2932 // Check that the user account is properly set up
2933 if (user_not_fully_set_up($USER)) {
2934 if ($preventredirect) {
2935 throw new require_login_exception('User not fully set-up');
2937 if ($setwantsurltome) {
2938 $SESSION->wantsurl = qualified_me();
2940 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2943 // Make sure the USER has a sesskey set up. Used for CSRF protection.
2944 sesskey();
2946 // Do not bother admins with any formalities
2947 if (is_siteadmin()) {
2948 //set accesstime or the user will appear offline which messes up messaging
2949 user_accesstime_log($course->id);
2950 return;
2953 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2954 if (!$USER->policyagreed and !is_siteadmin()) {
2955 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2956 if ($preventredirect) {
2957 throw new require_login_exception('Policy not agreed');
2959 if ($setwantsurltome) {
2960 $SESSION->wantsurl = qualified_me();
2962 redirect($CFG->wwwroot .'/user/policy.php');
2963 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2964 if ($preventredirect) {
2965 throw new require_login_exception('Policy not agreed');
2967 if ($setwantsurltome) {
2968 $SESSION->wantsurl = qualified_me();
2970 redirect($CFG->wwwroot .'/user/policy.php');
2974 // Fetch the system context, the course context, and prefetch its child contexts
2975 $sysctx = context_system::instance();
2976 $coursecontext = context_course::instance($course->id, MUST_EXIST);
2977 if ($cm) {
2978 $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2979 } else {
2980 $cmcontext = null;
2983 // If the site is currently under maintenance, then print a message
2984 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
2985 if ($preventredirect) {
2986 throw new require_login_exception('Maintenance in progress');
2989 print_maintenance_message();
2992 // make sure the course itself is not hidden
2993 if ($course->id == SITEID) {
2994 // frontpage can not be hidden
2995 } else {
2996 if (is_role_switched($course->id)) {
2997 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2998 } else {
2999 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
3000 // originally there was also test of parent category visibility,
3001 // BUT is was very slow in complex queries involving "my courses"
3002 // now it is also possible to simply hide all courses user is not enrolled in :-)
3003 if ($preventredirect) {
3004 throw new require_login_exception('Course is hidden');
3006 // We need to override the navigation URL as the course won't have
3007 // been added to the navigation and thus the navigation will mess up
3008 // when trying to find it.
3009 navigation_node::override_active_url(new moodle_url('/'));
3010 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3015 // is the user enrolled?
3016 if ($course->id == SITEID) {
3017 // everybody is enrolled on the frontpage
3019 } else {
3020 if (session_is_loggedinas()) {
3021 // Make sure the REAL person can access this course first
3022 $realuser = session_get_realuser();
3023 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
3024 if ($preventredirect) {
3025 throw new require_login_exception('Invalid course login-as access');
3027 echo $OUTPUT->header();
3028 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
3032 $access = false;
3034 if (is_role_switched($course->id)) {
3035 // ok, user had to be inside this course before the switch
3036 $access = true;
3038 } else if (is_viewing($coursecontext, $USER)) {
3039 // ok, no need to mess with enrol
3040 $access = true;
3042 } else {
3043 if (isset($USER->enrol['enrolled'][$course->id])) {
3044 if ($USER->enrol['enrolled'][$course->id] > time()) {
3045 $access = true;
3046 if (isset($USER->enrol['tempguest'][$course->id])) {
3047 unset($USER->enrol['tempguest'][$course->id]);
3048 remove_temp_course_roles($coursecontext);
3050 } else {
3051 //expired
3052 unset($USER->enrol['enrolled'][$course->id]);
3055 if (isset($USER->enrol['tempguest'][$course->id])) {
3056 if ($USER->enrol['tempguest'][$course->id] == 0) {
3057 $access = true;
3058 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
3059 $access = true;
3060 } else {
3061 //expired
3062 unset($USER->enrol['tempguest'][$course->id]);
3063 remove_temp_course_roles($coursecontext);
3067 if ($access) {
3068 // cache ok
3069 } else {
3070 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
3071 if ($until !== false) {
3072 // active participants may always access, a timestamp in the future, 0 (always) or false.
3073 if ($until == 0) {
3074 $until = ENROL_MAX_TIMESTAMP;
3076 $USER->enrol['enrolled'][$course->id] = $until;
3077 $access = true;
3079 } else {
3080 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
3081 $enrols = enrol_get_plugins(true);
3082 // first ask all enabled enrol instances in course if they want to auto enrol user
3083 foreach($instances as $instance) {
3084 if (!isset($enrols[$instance->enrol])) {
3085 continue;
3087 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
3088 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
3089 if ($until !== false) {
3090 if ($until == 0) {
3091 $until = ENROL_MAX_TIMESTAMP;
3093 $USER->enrol['enrolled'][$course->id] = $until;
3094 $access = true;
3095 break;
3098 // if not enrolled yet try to gain temporary guest access
3099 if (!$access) {
3100 foreach($instances as $instance) {
3101 if (!isset($enrols[$instance->enrol])) {
3102 continue;
3104 // Get a duration for the guest access, a timestamp in the future or false.
3105 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3106 if ($until !== false and $until > time()) {
3107 $USER->enrol['tempguest'][$course->id] = $until;
3108 $access = true;
3109 break;
3117 if (!$access) {
3118 if ($preventredirect) {
3119 throw new require_login_exception('Not enrolled');
3121 if ($setwantsurltome) {
3122 $SESSION->wantsurl = qualified_me();
3124 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3128 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
3129 // conditional availability, etc
3130 if ($cm && !$cm->uservisible) {
3131 if ($preventredirect) {
3132 throw new require_login_exception('Activity is hidden');
3134 if ($course->id != SITEID) {
3135 $url = new moodle_url('/course/view.php', array('id'=>$course->id));
3136 } else {
3137 $url = new moodle_url('/');
3139 redirect($url, get_string('activityiscurrentlyhidden'));
3142 // Finally access granted, update lastaccess times
3143 user_accesstime_log($course->id);
3148 * This function just makes sure a user is logged out.
3150 * @package core_access
3152 function require_logout() {
3153 global $USER;
3155 $params = $USER;
3157 if (isloggedin()) {
3158 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
3160 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
3161 foreach($authsequence as $authname) {
3162 $authplugin = get_auth_plugin($authname);
3163 $authplugin->prelogout_hook();
3167 events_trigger('user_logout', $params);
3168 session_get_instance()->terminate_current();
3169 unset($params);
3173 * Weaker version of require_login()
3175 * This is a weaker version of {@link require_login()} which only requires login
3176 * when called from within a course rather than the site page, unless
3177 * the forcelogin option is turned on.
3178 * @see require_login()
3180 * @package core_access
3181 * @category access
3183 * @param mixed $courseorid The course object or id in question
3184 * @param bool $autologinguest Allow autologin guests if that is wanted
3185 * @param object $cm Course activity module if known
3186 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3187 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3188 * in order to keep redirects working properly. MDL-14495
3189 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3190 * @return void
3192 function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
3193 global $CFG, $PAGE, $SITE;
3194 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
3195 or (!is_object($courseorid) and $courseorid == SITEID);
3196 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3197 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
3198 // db queries so this is not really a performance concern, however it is obviously
3199 // better if you use get_fast_modinfo to get the cm before calling this.
3200 if (is_object($courseorid)) {
3201 $course = $courseorid;
3202 } else {
3203 $course = clone($SITE);
3205 $modinfo = get_fast_modinfo($course);
3206 $cm = $modinfo->get_cm($cm->id);
3208 if (!empty($CFG->forcelogin)) {
3209 // login required for both SITE and courses
3210 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3212 } else if ($issite && !empty($cm) and !$cm->uservisible) {
3213 // always login for hidden activities
3214 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3216 } else if ($issite) {
3217 //login for SITE not required
3218 if ($cm and empty($cm->visible)) {
3219 // hidden activities are not accessible without login
3220 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3221 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3222 // not-logged-in users do not have any group membership
3223 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3224 } else {
3225 // We still need to instatiate PAGE vars properly so that things
3226 // that rely on it like navigation function correctly.
3227 if (!empty($courseorid)) {
3228 if (is_object($courseorid)) {
3229 $course = $courseorid;
3230 } else {
3231 $course = clone($SITE);
3233 if ($cm) {
3234 if ($cm->course != $course->id) {
3235 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3237 $PAGE->set_cm($cm, $course);
3238 $PAGE->set_pagelayout('incourse');
3239 } else {
3240 $PAGE->set_course($course);
3242 } else {
3243 // If $PAGE->course, and hence $PAGE->context, have not already been set
3244 // up properly, set them up now.
3245 $PAGE->set_course($PAGE->course);
3247 //TODO: verify conditional activities here
3248 user_accesstime_log(SITEID);
3249 return;
3252 } else {
3253 // course login always required
3254 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3259 * Require key login. Function terminates with error if key not found or incorrect.
3261 * @global object
3262 * @global object
3263 * @global object
3264 * @global object
3265 * @uses NO_MOODLE_COOKIES
3266 * @uses PARAM_ALPHANUM
3267 * @param string $script unique script identifier
3268 * @param int $instance optional instance id
3269 * @return int Instance ID
3271 function require_user_key_login($script, $instance=null) {
3272 global $USER, $SESSION, $CFG, $DB;
3274 if (!NO_MOODLE_COOKIES) {
3275 print_error('sessioncookiesdisable');
3278 /// extra safety
3279 @session_write_close();
3281 $keyvalue = required_param('key', PARAM_ALPHANUM);
3283 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
3284 print_error('invalidkey');
3287 if (!empty($key->validuntil) and $key->validuntil < time()) {
3288 print_error('expiredkey');
3291 if ($key->iprestriction) {
3292 $remoteaddr = getremoteaddr(null);
3293 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3294 print_error('ipmismatch');
3298 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
3299 print_error('invaliduserid');
3302 /// emulate normal session
3303 enrol_check_plugins($user);
3304 session_set_user($user);
3306 /// note we are not using normal login
3307 if (!defined('USER_KEY_LOGIN')) {
3308 define('USER_KEY_LOGIN', true);
3311 /// return instance id - it might be empty
3312 return $key->instance;
3316 * Creates a new private user access key.
3318 * @global object
3319 * @param string $script unique target identifier
3320 * @param int $userid
3321 * @param int $instance optional instance id
3322 * @param string $iprestriction optional ip restricted access
3323 * @param timestamp $validuntil key valid only until given data
3324 * @return string access key value
3326 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3327 global $DB;
3329 $key = new stdClass();
3330 $key->script = $script;
3331 $key->userid = $userid;
3332 $key->instance = $instance;
3333 $key->iprestriction = $iprestriction;
3334 $key->validuntil = $validuntil;
3335 $key->timecreated = time();
3337 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
3338 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
3339 // must be unique
3340 $key->value = md5($userid.'_'.time().random_string(40));
3342 $DB->insert_record('user_private_key', $key);
3343 return $key->value;
3347 * Delete the user's new private user access keys for a particular script.
3349 * @global object
3350 * @param string $script unique target identifier
3351 * @param int $userid
3352 * @return void
3354 function delete_user_key($script,$userid) {
3355 global $DB;
3356 $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
3360 * Gets a private user access key (and creates one if one doesn't exist).
3362 * @global object
3363 * @param string $script unique target identifier
3364 * @param int $userid
3365 * @param int $instance optional instance id
3366 * @param string $iprestriction optional ip restricted access
3367 * @param timestamp $validuntil key valid only until given data
3368 * @return string access key value
3370 function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3371 global $DB;
3373 if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
3374 'instance'=>$instance, 'iprestriction'=>$iprestriction,
3375 'validuntil'=>$validuntil))) {
3376 return $key->value;
3377 } else {
3378 return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3384 * Modify the user table by setting the currently logged in user's
3385 * last login to now.
3387 * @global object
3388 * @global object
3389 * @return bool Always returns true
3391 function update_user_login_times() {
3392 global $USER, $DB;
3394 if (isguestuser()) {
3395 // Do not update guest access times/ips for performance.
3396 return true;
3399 $now = time();
3401 $user = new stdClass();
3402 $user->id = $USER->id;
3404 // Make sure all users that logged in have some firstaccess.
3405 if ($USER->firstaccess == 0) {
3406 $USER->firstaccess = $user->firstaccess = $now;
3409 // Store the previous current as lastlogin.
3410 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3412 $USER->currentlogin = $user->currentlogin = $now;
3414 // Function user_accesstime_log() may not update immediately, better do it here.
3415 $USER->lastaccess = $user->lastaccess = $now;
3416 $USER->lastip = $user->lastip = getremoteaddr();
3418 $DB->update_record('user', $user);
3419 return true;
3423 * Determines if a user has completed setting up their account.
3425 * @param user $user A {@link $USER} object to test for the existence of a valid name and email
3426 * @return bool
3428 function user_not_fully_set_up($user) {
3429 if (isguestuser($user)) {
3430 return false;
3432 return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
3436 * Check whether the user has exceeded the bounce threshold
3438 * @global object
3439 * @global object
3440 * @param user $user A {@link $USER} object
3441 * @return bool true=>User has exceeded bounce threshold
3443 function over_bounce_threshold($user) {
3444 global $CFG, $DB;
3446 if (empty($CFG->handlebounces)) {
3447 return false;
3450 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3451 return false;
3454 // set sensible defaults
3455 if (empty($CFG->minbounces)) {
3456 $CFG->minbounces = 10;
3458 if (empty($CFG->bounceratio)) {
3459 $CFG->bounceratio = .20;
3461 $bouncecount = 0;
3462 $sendcount = 0;
3463 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3464 $bouncecount = $bounce->value;
3466 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3467 $sendcount = $send->value;
3469 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3473 * Used to increment or reset email sent count
3475 * @global object
3476 * @param user $user object containing an id
3477 * @param bool $reset will reset the count to 0
3478 * @return void
3480 function set_send_count($user,$reset=false) {
3481 global $DB;
3483 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
3484 return;
3487 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
3488 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3489 $DB->update_record('user_preferences', $pref);
3491 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3492 // make a new one
3493 $pref = new stdClass();
3494 $pref->name = 'email_send_count';
3495 $pref->value = 1;
3496 $pref->userid = $user->id;
3497 $DB->insert_record('user_preferences', $pref, false);
3502 * Increment or reset user's email bounce count
3504 * @global object
3505 * @param user $user object containing an id
3506 * @param bool $reset will reset the count to 0
3508 function set_bounce_count($user,$reset=false) {
3509 global $DB;
3511 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
3512 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3513 $DB->update_record('user_preferences', $pref);
3515 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
3516 // make a new one
3517 $pref = new stdClass();
3518 $pref->name = 'email_bounce_count';
3519 $pref->value = 1;
3520 $pref->userid = $user->id;
3521 $DB->insert_record('user_preferences', $pref, false);
3526 * Determines if the currently logged in user is in editing mode.
3527 * Note: originally this function had $userid parameter - it was not usable anyway
3529 * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
3530 * @todo Deprecated function remove when ready
3532 * @global object
3533 * @uses DEBUG_DEVELOPER
3534 * @return bool
3536 function isediting() {
3537 global $PAGE;
3538 debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
3539 return $PAGE->user_is_editing();
3543 * Determines if the logged in user is currently moving an activity
3545 * @global object
3546 * @param int $courseid The id of the course being tested
3547 * @return bool
3549 function ismoving($courseid) {
3550 global $USER;
3552 if (!empty($USER->activitycopy)) {
3553 return ($USER->activitycopycourse == $courseid);
3555 return false;
3559 * Returns a persons full name
3561 * Given an object containing firstname and lastname
3562 * values, this function returns a string with the
3563 * full name of the person.
3564 * The result may depend on system settings
3565 * or language. 'override' will force both names
3566 * to be used even if system settings specify one.
3568 * @global object
3569 * @global object
3570 * @param object $user A {@link $USER} object to get full name of
3571 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
3572 * @return string
3574 function fullname($user, $override=false) {
3575 global $CFG, $SESSION;
3577 if (!isset($user->firstname) and !isset($user->lastname)) {
3578 return '';
3581 if (!$override) {
3582 if (!empty($CFG->forcefirstname)) {
3583 $user->firstname = $CFG->forcefirstname;
3585 if (!empty($CFG->forcelastname)) {
3586 $user->lastname = $CFG->forcelastname;
3590 if (!empty($SESSION->fullnamedisplay)) {
3591 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3594 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
3595 return $user->firstname .' '. $user->lastname;
3597 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
3598 return $user->lastname .' '. $user->firstname;
3600 } else if ($CFG->fullnamedisplay == 'firstname') {
3601 if ($override) {
3602 return get_string('fullnamedisplay', '', $user);
3603 } else {
3604 return $user->firstname;
3608 return get_string('fullnamedisplay', '', $user);
3612 * Checks if current user is shown any extra fields when listing users.
3613 * @param object $context Context
3614 * @param array $already Array of fields that we're going to show anyway
3615 * so don't bother listing them
3616 * @return array Array of field names from user table, not including anything
3617 * listed in $already
3619 function get_extra_user_fields($context, $already = array()) {
3620 global $CFG;
3622 // Only users with permission get the extra fields
3623 if (!has_capability('moodle/site:viewuseridentity', $context)) {
3624 return array();
3627 // Split showuseridentity on comma
3628 if (empty($CFG->showuseridentity)) {
3629 // Explode gives wrong result with empty string
3630 $extra = array();
3631 } else {
3632 $extra = explode(',', $CFG->showuseridentity);
3634 $renumber = false;
3635 foreach ($extra as $key => $field) {
3636 if (in_array($field, $already)) {
3637 unset($extra[$key]);
3638 $renumber = true;
3641 if ($renumber) {
3642 // For consistency, if entries are removed from array, renumber it
3643 // so they are numbered as you would expect
3644 $extra = array_merge($extra);
3646 return $extra;
3650 * If the current user is to be shown extra user fields when listing or
3651 * selecting users, returns a string suitable for including in an SQL select
3652 * clause to retrieve those fields.
3653 * @param object $context Context
3654 * @param string $alias Alias of user table, e.g. 'u' (default none)
3655 * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
3656 * @param array $already Array of fields that we're going to include anyway
3657 * so don't list them (default none)
3658 * @return string Partial SQL select clause, beginning with comma, for example
3659 * ',u.idnumber,u.department' unless it is blank
3661 function get_extra_user_fields_sql($context, $alias='', $prefix='',
3662 $already = array()) {
3663 $fields = get_extra_user_fields($context, $already);
3664 $result = '';
3665 // Add punctuation for alias
3666 if ($alias !== '') {
3667 $alias .= '.';
3669 foreach ($fields as $field) {
3670 $result .= ', ' . $alias . $field;
3671 if ($prefix) {
3672 $result .= ' AS ' . $prefix . $field;
3675 return $result;
3679 * Returns the display name of a field in the user table. Works for most fields
3680 * that are commonly displayed to users.
3681 * @param string $field Field name, e.g. 'phone1'
3682 * @return string Text description taken from language file, e.g. 'Phone number'
3684 function get_user_field_name($field) {
3685 // Some fields have language strings which are not the same as field name
3686 switch ($field) {
3687 case 'phone1' : return get_string('phone');
3688 case 'url' : return get_string('webpage');
3689 case 'icq' : return get_string('icqnumber');
3690 case 'skype' : return get_string('skypeid');
3691 case 'aim' : return get_string('aimid');
3692 case 'yahoo' : return get_string('yahooid');
3693 case 'msn' : return get_string('msnid');
3695 // Otherwise just use the same lang string
3696 return get_string($field);
3700 * Returns whether a given authentication plugin exists.
3702 * @global object
3703 * @param string $auth Form of authentication to check for. Defaults to the
3704 * global setting in {@link $CFG}.
3705 * @return boolean Whether the plugin is available.
3707 function exists_auth_plugin($auth) {
3708 global $CFG;
3710 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3711 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3713 return false;
3717 * Checks if a given plugin is in the list of enabled authentication plugins.
3719 * @param string $auth Authentication plugin.
3720 * @return boolean Whether the plugin is enabled.
3722 function is_enabled_auth($auth) {
3723 if (empty($auth)) {
3724 return false;
3727 $enabled = get_enabled_auth_plugins();
3729 return in_array($auth, $enabled);
3733 * Returns an authentication plugin instance.
3735 * @global object
3736 * @param string $auth name of authentication plugin
3737 * @return auth_plugin_base An instance of the required authentication plugin.
3739 function get_auth_plugin($auth) {
3740 global $CFG;
3742 // check the plugin exists first
3743 if (! exists_auth_plugin($auth)) {
3744 print_error('authpluginnotfound', 'debug', '', $auth);
3747 // return auth plugin instance
3748 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
3749 $class = "auth_plugin_$auth";
3750 return new $class;
3754 * Returns array of active auth plugins.
3756 * @param bool $fix fix $CFG->auth if needed
3757 * @return array
3759 function get_enabled_auth_plugins($fix=false) {
3760 global $CFG;
3762 $default = array('manual', 'nologin');
3764 if (empty($CFG->auth)) {
3765 $auths = array();
3766 } else {
3767 $auths = explode(',', $CFG->auth);
3770 if ($fix) {
3771 $auths = array_unique($auths);
3772 foreach($auths as $k=>$authname) {
3773 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
3774 unset($auths[$k]);
3777 $newconfig = implode(',', $auths);
3778 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3779 set_config('auth', $newconfig);
3783 return (array_merge($default, $auths));
3787 * Returns true if an internal authentication method is being used.
3788 * if method not specified then, global default is assumed
3790 * @param string $auth Form of authentication required
3791 * @return bool
3793 function is_internal_auth($auth) {
3794 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
3795 return $authplugin->is_internal();
3799 * Returns true if the user is a 'restored' one
3801 * Used in the login process to inform the user
3802 * and allow him/her to reset the password
3804 * @uses $CFG
3805 * @uses $DB
3806 * @param string $username username to be checked
3807 * @return bool
3809 function is_restored_user($username) {
3810 global $CFG, $DB;
3812 return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
3816 * Returns an array of user fields
3818 * @return array User field/column names
3820 function get_user_fieldnames() {
3821 global $DB;
3823 $fieldarray = $DB->get_columns('user');
3824 unset($fieldarray['id']);
3825 $fieldarray = array_keys($fieldarray);
3827 return $fieldarray;
3831 * Creates a bare-bones user record
3833 * @todo Outline auth types and provide code example
3835 * @param string $username New user's username to add to record
3836 * @param string $password New user's password to add to record
3837 * @param string $auth Form of authentication required
3838 * @return stdClass A complete user object
3840 function create_user_record($username, $password, $auth = 'manual') {
3841 global $CFG, $DB;
3842 require_once($CFG->dirroot."/user/profile/lib.php");
3843 //just in case check text case
3844 $username = trim(textlib::strtolower($username));
3846 $authplugin = get_auth_plugin($auth);
3847 $customfields = $authplugin->get_custom_user_profile_fields();
3848 $newuser = new stdClass();
3849 if ($newinfo = $authplugin->get_userinfo($username)) {
3850 $newinfo = truncate_userinfo($newinfo);
3851 foreach ($newinfo as $key => $value){
3852 if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3853 $newuser->$key = $value;
3858 if (!empty($newuser->email)) {
3859 if (email_is_not_allowed($newuser->email)) {
3860 unset($newuser->email);
3864 if (!isset($newuser->city)) {
3865 $newuser->city = '';
3868 $newuser->auth = $auth;
3869 $newuser->username = $username;
3871 // fix for MDL-8480
3872 // user CFG lang for user if $newuser->lang is empty
3873 // or $user->lang is not an installed language
3874 if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3875 $newuser->lang = $CFG->lang;
3877 $newuser->confirmed = 1;
3878 $newuser->lastip = getremoteaddr();
3879 $newuser->timecreated = time();
3880 $newuser->timemodified = $newuser->timecreated;
3881 $newuser->mnethostid = $CFG->mnet_localhost_id;
3883 $newuser->id = $DB->insert_record('user', $newuser);
3885 // Save user profile data.
3886 profile_save_data($newuser);
3888 $user = get_complete_user_data('id', $newuser->id);
3889 if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
3890 set_user_preference('auth_forcepasswordchange', 1, $user);
3892 // Set the password.
3893 update_internal_user_password($user, $password);
3895 // fetch full user record for the event, the complete user data contains too much info
3896 // and we want to be consistent with other places that trigger this event
3897 events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id)));
3899 return $user;
3903 * Will update a local user record from an external source.
3904 * (MNET users can not be updated using this method!)
3906 * @param string $username user's username to update the record
3907 * @return stdClass A complete user object
3909 function update_user_record($username) {
3910 global $DB, $CFG;
3911 require_once($CFG->dirroot."/user/profile/lib.php");
3912 $username = trim(textlib::strtolower($username)); /// just in case check text case
3914 $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
3915 $newuser = array();
3916 $userauth = get_auth_plugin($oldinfo->auth);
3918 if ($newinfo = $userauth->get_userinfo($username)) {
3919 $newinfo = truncate_userinfo($newinfo);
3920 $customfields = $userauth->get_custom_user_profile_fields();
3922 foreach ($newinfo as $key => $value){
3923 $key = strtolower($key);
3924 $iscustom = in_array($key, $customfields);
3925 if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3926 or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3927 // unknown or must not be changed
3928 continue;
3930 $confval = $userauth->config->{'field_updatelocal_' . $key};
3931 $lockval = $userauth->config->{'field_lock_' . $key};
3932 if (empty($confval) || empty($lockval)) {
3933 continue;
3935 if ($confval === 'onlogin') {
3936 // MDL-4207 Don't overwrite modified user profile values with
3937 // empty LDAP values when 'unlocked if empty' is set. The purpose
3938 // of the setting 'unlocked if empty' is to allow the user to fill
3939 // in a value for the selected field _if LDAP is giving
3940 // nothing_ for this field. Thus it makes sense to let this value
3941 // stand in until LDAP is giving a value for this field.
3942 if (!(empty($value) && $lockval === 'unlockedifempty')) {
3943 if ($iscustom || (in_array($key, $userauth->userfields) &&
3944 ((string)$oldinfo->$key !== (string)$value))) {
3945 $newuser[$key] = (string)$value;
3950 if ($newuser) {
3951 $newuser['id'] = $oldinfo->id;
3952 $newuser['timemodified'] = time();
3953 $DB->update_record('user', $newuser);
3955 // Save user profile data.
3956 profile_save_data((object) $newuser);
3958 // fetch full user record for the event, the complete user data contains too much info
3959 // and we want to be consistent with other places that trigger this event
3960 events_trigger('user_updated', $DB->get_record('user', array('id'=>$oldinfo->id)));
3964 return get_complete_user_data('id', $oldinfo->id);
3968 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
3969 * which may have large fields
3971 * @todo Add vartype handling to ensure $info is an array
3973 * @param array $info Array of user properties to truncate if needed
3974 * @return array The now truncated information that was passed in
3976 function truncate_userinfo($info) {
3977 // define the limits
3978 $limit = array(
3979 'username' => 100,
3980 'idnumber' => 255,
3981 'firstname' => 100,
3982 'lastname' => 100,
3983 'email' => 100,
3984 'icq' => 15,
3985 'phone1' => 20,
3986 'phone2' => 20,
3987 'institution' => 40,
3988 'department' => 30,
3989 'address' => 70,
3990 'city' => 120,
3991 'country' => 2,
3992 'url' => 255,
3995 // apply where needed
3996 foreach (array_keys($info) as $key) {
3997 if (!empty($limit[$key])) {
3998 $info[$key] = trim(textlib::substr($info[$key],0, $limit[$key]));
4002 return $info;
4006 * Marks user deleted in internal user database and notifies the auth plugin.
4007 * Also unenrols user from all roles and does other cleanup.
4009 * Any plugin that needs to purge user data should register the 'user_deleted' event.
4011 * @param stdClass $user full user object before delete
4012 * @return boolean success
4013 * @throws coding_exception if invalid $user parameter detected
4015 function delete_user(stdClass $user) {
4016 global $CFG, $DB;
4017 require_once($CFG->libdir.'/grouplib.php');
4018 require_once($CFG->libdir.'/gradelib.php');
4019 require_once($CFG->dirroot.'/message/lib.php');
4020 require_once($CFG->dirroot.'/tag/lib.php');
4022 // Make sure nobody sends bogus record type as parameter.
4023 if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4024 throw new coding_exception('Invalid $user parameter in delete_user() detected');
4027 // Better not trust the parameter and fetch the latest info,
4028 // this will be very expensive anyway.
4029 if (!$user = $DB->get_record('user', array('id'=>$user->id))) {
4030 debugging('Attempt to delete unknown user account.');
4031 return false;
4034 // There must be always exactly one guest record,
4035 // originally the guest account was identified by username only,
4036 // now we use $CFG->siteguest for performance reasons.
4037 if ($user->username === 'guest' or isguestuser($user)) {
4038 debugging('Guest user account can not be deleted.');
4039 return false;
4042 // Admin can be theoretically from different auth plugin,
4043 // but we want to prevent deletion of internal accoutns only,
4044 // if anything goes wrong ppl may force somebody to be admin via
4045 // config.php setting $CFG->siteadmins.
4046 if ($user->auth === 'manual' and is_siteadmin($user)) {
4047 debugging('Local administrator accounts can not be deleted.');
4048 return false;
4051 // delete all grades - backup is kept in grade_grades_history table
4052 grade_user_delete($user->id);
4054 //move unread messages from this user to read
4055 message_move_userfrom_unread2read($user->id);
4057 // TODO: remove from cohorts using standard API here
4059 // remove user tags
4060 tag_set('user', $user->id, array());
4062 // unconditionally unenrol from all courses
4063 enrol_user_delete($user);
4065 // unenrol from all roles in all contexts
4066 role_unassign_all(array('userid'=>$user->id)); // this might be slow but it is really needed - modules might do some extra cleanup!
4068 //now do a brute force cleanup
4070 // remove from all cohorts
4071 $DB->delete_records('cohort_members', array('userid'=>$user->id));
4073 // remove from all groups
4074 $DB->delete_records('groups_members', array('userid'=>$user->id));
4076 // brute force unenrol from all courses
4077 $DB->delete_records('user_enrolments', array('userid'=>$user->id));
4079 // purge user preferences
4080 $DB->delete_records('user_preferences', array('userid'=>$user->id));
4082 // purge user extra profile info
4083 $DB->delete_records('user_info_data', array('userid'=>$user->id));
4085 // last course access not necessary either
4086 $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
4088 // remove all user tokens
4089 $DB->delete_records('external_tokens', array('userid'=>$user->id));
4091 // unauthorise the user for all services
4092 $DB->delete_records('external_services_users', array('userid'=>$user->id));
4094 // Remove users private keys.
4095 $DB->delete_records('user_private_key', array('userid' => $user->id));
4097 // force logout - may fail if file based sessions used, sorry
4098 session_kill_user($user->id);
4100 // now do a final accesslib cleanup - removes all role assignments in user context and context itself
4101 delete_context(CONTEXT_USER, $user->id);
4103 // workaround for bulk deletes of users with the same email address
4104 $delname = "$user->email.".time();
4105 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
4106 $delname++;
4109 // mark internal user record as "deleted"
4110 $updateuser = new stdClass();
4111 $updateuser->id = $user->id;
4112 $updateuser->deleted = 1;
4113 $updateuser->username = $delname; // Remember it just in case
4114 $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users
4115 $updateuser->idnumber = ''; // Clear this field to free it up
4116 $updateuser->picture = 0;
4117 $updateuser->timemodified = time();
4119 $DB->update_record('user', $updateuser);
4120 // Add this action to log
4121 add_to_log(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
4124 // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4125 // should know about this updated property persisted to the user's table.
4126 $user->timemodified = $updateuser->timemodified;
4128 // notify auth plugin - do not block the delete even when plugin fails
4129 $authplugin = get_auth_plugin($user->auth);
4130 $authplugin->user_delete($user);
4132 // any plugin that needs to cleanup should register this event
4133 events_trigger('user_deleted', $user);
4135 return true;
4139 * Retrieve the guest user object
4141 * @global object
4142 * @global object
4143 * @return user A {@link $USER} object
4145 function guest_user() {
4146 global $CFG, $DB;
4148 if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest))) {
4149 $newuser->confirmed = 1;
4150 $newuser->lang = $CFG->lang;
4151 $newuser->lastip = getremoteaddr();
4154 return $newuser;
4158 * Authenticates a user against the chosen authentication mechanism
4160 * Given a username and password, this function looks them
4161 * up using the currently selected authentication mechanism,
4162 * and if the authentication is successful, it returns a
4163 * valid $user object from the 'user' table.
4165 * Uses auth_ functions from the currently active auth module
4167 * After authenticate_user_login() returns success, you will need to
4168 * log that the user has logged in, and call complete_user_login() to set
4169 * the session up.
4171 * Note: this function works only with non-mnet accounts!
4173 * @param string $username User's username
4174 * @param string $password User's password
4175 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4176 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4177 * @return stdClass|false A {@link $USER} object or false if error
4179 function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
4180 global $CFG, $DB;
4181 require_once("$CFG->libdir/authlib.php");
4183 $authsenabled = get_enabled_auth_plugins();
4185 if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4186 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
4187 if (!empty($user->suspended)) {
4188 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4189 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4190 $failurereason = AUTH_LOGIN_SUSPENDED;
4191 return false;
4193 if ($auth=='nologin' or !is_enabled_auth($auth)) {
4194 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4195 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4196 $failurereason = AUTH_LOGIN_SUSPENDED; // Legacy way to suspend user.
4197 return false;
4199 $auths = array($auth);
4201 } else {
4202 // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4203 if ($DB->get_field('user', 'id', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>1))) {
4204 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4205 $failurereason = AUTH_LOGIN_NOUSER;
4206 return false;
4209 // Do not try to authenticate non-existent accounts when user creation is not disabled.
4210 if (!empty($CFG->authpreventaccountcreation)) {
4211 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4212 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".$_SERVER['HTTP_USER_AGENT']);
4213 $failurereason = AUTH_LOGIN_NOUSER;
4214 return false;
4217 // User does not exist
4218 $auths = $authsenabled;
4219 $user = new stdClass();
4220 $user->id = 0;
4223 if ($ignorelockout) {
4224 // Some other mechanism protects against brute force password guessing,
4225 // for example login form might include reCAPTCHA or this function
4226 // is called from a SSO script.
4228 } else if ($user->id) {
4229 // Verify login lockout after other ways that may prevent user login.
4230 if (login_is_lockedout($user)) {
4231 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4232 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
4233 $failurereason = AUTH_LOGIN_LOCKOUT;
4234 return false;
4237 } else {
4238 // We can not lockout non-existing accounts.
4241 foreach ($auths as $auth) {
4242 $authplugin = get_auth_plugin($auth);
4244 // on auth fail fall through to the next plugin
4245 if (!$authplugin->user_login($username, $password)) {
4246 continue;
4249 // successful authentication
4250 if ($user->id) { // User already exists in database
4251 if (empty($user->auth)) { // For some reason auth isn't set yet
4252 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
4253 $user->auth = $auth;
4256 // If the existing hash is using an out-of-date algorithm (or the
4257 // legacy md5 algorithm), then we should update to the current
4258 // hash algorithm while we have access to the user's password.
4259 update_internal_user_password($user, $password);
4261 if ($authplugin->is_synchronised_with_external()) { // update user record from external DB
4262 $user = update_user_record($username);
4264 } else {
4265 // Create account, we verified above that user creation is allowed.
4266 $user = create_user_record($username, $password, $auth);
4269 $authplugin->sync_roles($user);
4271 foreach ($authsenabled as $hau) {
4272 $hauth = get_auth_plugin($hau);
4273 $hauth->user_authenticated_hook($user, $username, $password);
4276 if (empty($user->id)) {
4277 $failurereason = AUTH_LOGIN_NOUSER;
4278 return false;
4281 if (!empty($user->suspended)) {
4282 // just in case some auth plugin suspended account
4283 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4284 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4285 $failurereason = AUTH_LOGIN_SUSPENDED;
4286 return false;
4289 login_attempt_valid($user);
4290 $failurereason = AUTH_LOGIN_OK;
4291 return $user;
4294 // failed if all the plugins have failed
4295 add_to_log(SITEID, 'login', 'error', 'index.php', $username);
4296 if (debugging('', DEBUG_ALL)) {
4297 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
4300 if ($user->id) {
4301 login_attempt_failed($user);
4302 $failurereason = AUTH_LOGIN_FAILED;
4303 } else {
4304 $failurereason = AUTH_LOGIN_NOUSER;
4307 return false;
4311 * Call to complete the user login process after authenticate_user_login()
4312 * has succeeded. It will setup the $USER variable and other required bits
4313 * and pieces.
4315 * NOTE:
4316 * - It will NOT log anything -- up to the caller to decide what to log.
4317 * - this function does not set any cookies any more!
4319 * @param object $user
4320 * @return object A {@link $USER} object - BC only, do not use
4322 function complete_user_login($user) {
4323 global $CFG, $USER;
4325 // regenerate session id and delete old session,
4326 // this helps prevent session fixation attacks from the same domain
4327 session_regenerate_id(true);
4329 // let enrol plugins deal with new enrolments if necessary
4330 enrol_check_plugins($user);
4332 // check enrolments, load caps and setup $USER object
4333 session_set_user($user);
4335 // reload preferences from DB
4336 unset($USER->preference);
4337 check_user_preferences_loaded($USER);
4339 // update login times
4340 update_user_login_times();
4342 // extra session prefs init
4343 set_login_session_preferences();
4345 if (isguestuser()) {
4346 // no need to continue when user is THE guest
4347 return $USER;
4350 /// Select password change url
4351 $userauth = get_auth_plugin($USER->auth);
4353 /// check whether the user should be changing password
4354 if (get_user_preferences('auth_forcepasswordchange', false)){
4355 if ($userauth->can_change_password()) {
4356 if ($changeurl = $userauth->change_password_url()) {
4357 redirect($changeurl);
4358 } else {
4359 redirect($CFG->httpswwwroot.'/login/change_password.php');
4361 } else {
4362 print_error('nopasswordchangeforced', 'auth');
4365 return $USER;
4369 * Check a password hash to see if it was hashed using the
4370 * legacy hash algorithm (md5).
4372 * @param string $password String to check.
4373 * @return boolean True if the $password matches the format of an md5 sum.
4375 function password_is_legacy_hash($password) {
4376 return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4380 * Checks whether the password compatibility library will work with the current
4381 * version of PHP. This cannot be done using PHP version numbers since the fix
4382 * has been backported to earlier versions in some distributions.
4384 * See https://github.com/ircmaxell/password_compat/issues/10 for
4385 * more details.
4387 * @return bool True if the library is NOT supported.
4389 function password_compat_not_supported() {
4391 $hash = '$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG';
4393 // Create a one off application cache to store bcrypt support status as
4394 // the support status doesn't change and crypt() is slow.
4395 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'password_compat');
4397 if (!$bcryptsupport = $cache->get('bcryptsupport')) {
4398 $test = crypt('password', $hash);
4399 // Cache string instead of boolean to avoid MDL-37472.
4400 if ($test == $hash) {
4401 $bcryptsupport = 'supported';
4402 } else {
4403 $bcryptsupport = 'not supported';
4405 $cache->set('bcryptsupport', $bcryptsupport);
4408 // Return true if bcrypt *not* supported.
4409 return ($bcryptsupport !== 'supported');
4413 * Compare password against hash stored in user object to determine if it is valid.
4415 * If necessary it also updates the stored hash to the current format.
4417 * @param stdClass $user (Password property may be updated).
4418 * @param string $password Plain text password.
4419 * @return bool True if password is valid.
4421 function validate_internal_user_password($user, $password) {
4422 global $CFG;
4423 require_once($CFG->libdir.'/password_compat/lib/password.php');
4425 if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4426 // Internal password is not used at all, it can not validate.
4427 return false;
4430 // If hash isn't a legacy (md5) hash, validate using the library function.
4431 if (!password_is_legacy_hash($user->password)) {
4432 return password_verify($password, $user->password);
4435 // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4436 // is valid we can then update it to the new algorithm.
4438 $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4439 $validated = false;
4441 if ($user->password === md5($password.$sitesalt)
4442 or $user->password === md5($password)
4443 or $user->password === md5(addslashes($password).$sitesalt)
4444 or $user->password === md5(addslashes($password))) {
4445 // note: we are intentionally using the addslashes() here because we
4446 // need to accept old password hashes of passwords with magic quotes
4447 $validated = true;
4449 } else {
4450 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
4451 $alt = 'passwordsaltalt'.$i;
4452 if (!empty($CFG->$alt)) {
4453 if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4454 $validated = true;
4455 break;
4461 if ($validated) {
4462 // If the password matches the existing md5 hash, update to the
4463 // current hash algorithm while we have access to the user's password.
4464 update_internal_user_password($user, $password);
4467 return $validated;
4471 * Calculate hash for a plain text password.
4473 * @param string $password Plain text password to be hashed.
4474 * @param bool $fasthash If true, use a low cost factor when generating the hash
4475 * This is much faster to generate but makes the hash
4476 * less secure. It is used when lots of hashes need to
4477 * be generated quickly.
4478 * @return string The hashed password.
4480 * @throws moodle_exception If a problem occurs while generating the hash.
4482 function hash_internal_user_password($password, $fasthash = false) {
4483 global $CFG;
4484 require_once($CFG->libdir.'/password_compat/lib/password.php');
4486 // Use the legacy hashing algorithm (md5) if PHP is not new enough
4487 // to support bcrypt properly
4488 if (password_compat_not_supported()) {
4489 if (isset($CFG->passwordsaltmain)) {
4490 return md5($password.$CFG->passwordsaltmain);
4491 } else {
4492 return md5($password);
4496 // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4497 $options = ($fasthash) ? array('cost' => 4) : array();
4499 $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4501 if ($generatedhash === false || $generatedhash === null) {
4502 throw new moodle_exception('Failed to generate password hash.');
4505 return $generatedhash;
4509 * Update password hash in user object (if necessary).
4511 * The password is updated if:
4512 * 1. The password has changed (the hash of $user->password is different
4513 * to the hash of $password).
4514 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4515 * md5 algorithm).
4517 * Updating the password will modify the $user object and the database
4518 * record to use the current hashing algorithm.
4520 * @param stdClass $user User object (password property may be updated).
4521 * @param string $password Plain text password.
4522 * @return bool Always returns true.
4524 function update_internal_user_password($user, $password) {
4525 global $CFG, $DB;
4526 require_once($CFG->libdir.'/password_compat/lib/password.php');
4528 // Use the legacy hashing algorithm (md5) if PHP doesn't support
4529 // bcrypt properly.
4530 $legacyhash = password_compat_not_supported();
4532 // Figure out what the hashed password should be.
4533 $authplugin = get_auth_plugin($user->auth);
4534 if ($authplugin->prevent_local_passwords()) {
4535 $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4536 } else {
4537 $hashedpassword = hash_internal_user_password($password);
4540 if ($legacyhash) {
4541 $passwordchanged = ($user->password !== $hashedpassword);
4542 $algorithmchanged = false;
4543 } else {
4544 // If verification fails then it means the password has changed.
4545 $passwordchanged = !password_verify($password, $user->password);
4546 $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4549 if ($passwordchanged || $algorithmchanged) {
4550 $DB->set_field('user', 'password', $hashedpassword, array('id'=>$user->id));
4551 $user->password = $hashedpassword;
4554 return true;
4558 * Get a complete user record, which includes all the info
4559 * in the user record.
4561 * Intended for setting as $USER session variable
4563 * @param string $field The user field to be checked for a given value.
4564 * @param string $value The value to match for $field.
4565 * @param int $mnethostid
4566 * @return mixed False, or A {@link $USER} object.
4568 function get_complete_user_data($field, $value, $mnethostid = null) {
4569 global $CFG, $DB;
4571 if (!$field || !$value) {
4572 return false;
4575 /// Build the WHERE clause for an SQL query
4576 $params = array('fieldval'=>$value);
4577 $constraints = "$field = :fieldval AND deleted <> 1";
4579 // If we are loading user data based on anything other than id,
4580 // we must also restrict our search based on mnet host.
4581 if ($field != 'id') {
4582 if (empty($mnethostid)) {
4583 // if empty, we restrict to local users
4584 $mnethostid = $CFG->mnet_localhost_id;
4587 if (!empty($mnethostid)) {
4588 $params['mnethostid'] = $mnethostid;
4589 $constraints .= " AND mnethostid = :mnethostid";
4592 /// Get all the basic user data
4594 if (! $user = $DB->get_record_select('user', $constraints, $params)) {
4595 return false;
4598 /// Get various settings and preferences
4600 // preload preference cache
4601 check_user_preferences_loaded($user);
4603 // load course enrolment related stuff
4604 $user->lastcourseaccess = array(); // during last session
4605 $user->currentcourseaccess = array(); // during current session
4606 if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid'=>$user->id))) {
4607 foreach ($lastaccesses as $lastaccess) {
4608 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4612 $sql = "SELECT g.id, g.courseid
4613 FROM {groups} g, {groups_members} gm
4614 WHERE gm.groupid=g.id AND gm.userid=?";
4616 // this is a special hack to speedup calendar display
4617 $user->groupmember = array();
4618 if (!isguestuser($user)) {
4619 if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4620 foreach ($groups as $group) {
4621 if (!array_key_exists($group->courseid, $user->groupmember)) {
4622 $user->groupmember[$group->courseid] = array();
4624 $user->groupmember[$group->courseid][$group->id] = $group->id;
4629 /// Add the custom profile fields to the user record
4630 $user->profile = array();
4631 if (!isguestuser($user)) {
4632 require_once($CFG->dirroot.'/user/profile/lib.php');
4633 profile_load_custom_fields($user);
4636 /// Rewrite some variables if necessary
4637 if (!empty($user->description)) {
4638 $user->description = true; // No need to cart all of it around
4640 if (isguestuser($user)) {
4641 $user->lang = $CFG->lang; // Guest language always same as site
4642 $user->firstname = get_string('guestuser'); // Name always in current language
4643 $user->lastname = ' ';
4646 return $user;
4650 * Validate a password against the configured password policy
4652 * @global object
4653 * @param string $password the password to be checked against the password policy
4654 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4655 * @return bool true if the password is valid according to the policy. false otherwise.
4657 function check_password_policy($password, &$errmsg) {
4658 global $CFG;
4660 if (empty($CFG->passwordpolicy)) {
4661 return true;
4664 $errmsg = '';
4665 if (textlib::strlen($password) < $CFG->minpasswordlength) {
4666 $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4669 if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4670 $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4673 if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4674 $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4677 if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4678 $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4681 if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4682 $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4684 if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4685 $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4688 if ($errmsg == '') {
4689 return true;
4690 } else {
4691 return false;
4697 * When logging in, this function is run to set certain preferences
4698 * for the current SESSION
4700 * @global object
4701 * @global object
4703 function set_login_session_preferences() {
4704 global $SESSION, $CFG;
4706 $SESSION->justloggedin = true;
4708 unset($SESSION->lang);
4713 * Delete a course, including all related data from the database,
4714 * and any associated files.
4716 * @global object
4717 * @global object
4718 * @param mixed $courseorid The id of the course or course object to delete.
4719 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4720 * @return bool true if all the removals succeeded. false if there were any failures. If this
4721 * method returns false, some of the removals will probably have succeeded, and others
4722 * failed, but you have no way of knowing which.
4724 function delete_course($courseorid, $showfeedback = true) {
4725 global $DB;
4727 if (is_object($courseorid)) {
4728 $courseid = $courseorid->id;
4729 $course = $courseorid;
4730 } else {
4731 $courseid = $courseorid;
4732 if (!$course = $DB->get_record('course', array('id'=>$courseid))) {
4733 return false;
4736 $context = context_course::instance($courseid);
4738 // frontpage course can not be deleted!!
4739 if ($courseid == SITEID) {
4740 return false;
4743 // make the course completely empty
4744 remove_course_contents($courseid, $showfeedback);
4746 // delete the course and related context instance
4747 delete_context(CONTEXT_COURSE, $courseid);
4749 // We will update the course's timemodified, as it will be passed to the course_deleted event,
4750 // which should know about this updated property, as this event is meant to pass the full course record
4751 $course->timemodified = time();
4753 $DB->delete_records("course", array("id" => $courseid));
4754 $DB->delete_records("course_format_options", array("courseid" => $courseid));
4756 //trigger events
4757 $course->context = $context; // you can not fetch context in the event because it was already deleted
4758 events_trigger('course_deleted', $course);
4760 return true;
4764 * Clear a course out completely, deleting all content
4765 * but don't delete the course itself.
4766 * This function does not verify any permissions.
4768 * Please note this function also deletes all user enrolments,
4769 * enrolment instances and role assignments by default.
4771 * $options:
4772 * - 'keep_roles_and_enrolments' - false by default
4773 * - 'keep_groups_and_groupings' - false by default
4775 * @param int $courseid The id of the course that is being deleted
4776 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4777 * @param array $options extra options
4778 * @return bool true if all the removals succeeded. false if there were any failures. If this
4779 * method returns false, some of the removals will probably have succeeded, and others
4780 * failed, but you have no way of knowing which.
4782 function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4783 global $CFG, $DB, $OUTPUT;
4784 require_once($CFG->libdir.'/badgeslib.php');
4785 require_once($CFG->libdir.'/completionlib.php');
4786 require_once($CFG->libdir.'/questionlib.php');
4787 require_once($CFG->libdir.'/gradelib.php');
4788 require_once($CFG->dirroot.'/group/lib.php');
4789 require_once($CFG->dirroot.'/tag/coursetagslib.php');
4790 require_once($CFG->dirroot.'/comment/lib.php');
4791 require_once($CFG->dirroot.'/rating/lib.php');
4793 // Handle course badges.
4794 badges_handle_course_deletion($courseid);
4796 // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4797 $strdeleted = get_string('deleted').' - ';
4799 // Some crazy wishlist of stuff we should skip during purging of course content
4800 $options = (array)$options;
4802 $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
4803 $coursecontext = context_course::instance($courseid);
4804 $fs = get_file_storage();
4806 // Delete course completion information, this has to be done before grades and enrols
4807 $cc = new completion_info($course);
4808 $cc->clear_criteria();
4809 if ($showfeedback) {
4810 echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4813 // Remove all data from gradebook - this needs to be done before course modules
4814 // because while deleting this information, the system may need to reference
4815 // the course modules that own the grades.
4816 remove_course_grades($courseid, $showfeedback);
4817 remove_grade_letters($coursecontext, $showfeedback);
4819 // Delete course blocks in any all child contexts,
4820 // they may depend on modules so delete them first
4821 $childcontexts = $coursecontext->get_child_contexts(); // returns all subcontexts since 2.2
4822 foreach ($childcontexts as $childcontext) {
4823 blocks_delete_all_for_context($childcontext->id);
4825 unset($childcontexts);
4826 blocks_delete_all_for_context($coursecontext->id);
4827 if ($showfeedback) {
4828 echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4831 // Delete every instance of every module,
4832 // this has to be done before deleting of course level stuff
4833 $locations = core_component::get_plugin_list('mod');
4834 foreach ($locations as $modname=>$moddir) {
4835 if ($modname === 'NEWMODULE') {
4836 continue;
4838 if ($module = $DB->get_record('modules', array('name'=>$modname))) {
4839 include_once("$moddir/lib.php"); // Shows php warning only if plugin defective
4840 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
4841 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
4843 if ($instances = $DB->get_records($modname, array('course'=>$course->id))) {
4844 foreach ($instances as $instance) {
4845 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
4846 /// Delete activity context questions and question categories
4847 question_delete_activity($cm, $showfeedback);
4849 if (function_exists($moddelete)) {
4850 // This purges all module data in related tables, extra user prefs, settings, etc.
4851 $moddelete($instance->id);
4852 } else {
4853 // NOTE: we should not allow installation of modules with missing delete support!
4854 debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4855 $DB->delete_records($modname, array('id'=>$instance->id));
4858 if ($cm) {
4859 // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition
4860 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4861 $DB->delete_records('course_modules', array('id'=>$cm->id));
4865 if (function_exists($moddeletecourse)) {
4866 // Execute ptional course cleanup callback
4867 $moddeletecourse($course, $showfeedback);
4869 if ($instances and $showfeedback) {
4870 echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4872 } else {
4873 // Ooops, this module is not properly installed, force-delete it in the next block
4877 // We have tried to delete everything the nice way - now let's force-delete any remaining module data
4879 // Remove all data from availability and completion tables that is associated
4880 // with course-modules belonging to this course. Note this is done even if the
4881 // features are not enabled now, in case they were enabled previously.
4882 $DB->delete_records_select('course_modules_completion',
4883 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4884 array($courseid));
4885 $DB->delete_records_select('course_modules_availability',
4886 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4887 array($courseid));
4888 $DB->delete_records_select('course_modules_avail_fields',
4889 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
4890 array($courseid));
4892 // Remove course-module data.
4893 $cms = $DB->get_records('course_modules', array('course'=>$course->id));
4894 foreach ($cms as $cm) {
4895 if ($module = $DB->get_record('modules', array('id'=>$cm->module))) {
4896 try {
4897 $DB->delete_records($module->name, array('id'=>$cm->instance));
4898 } catch (Exception $e) {
4899 // Ignore weird or missing table problems
4902 context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4903 $DB->delete_records('course_modules', array('id'=>$cm->id));
4906 if ($showfeedback) {
4907 echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
4910 // Cleanup the rest of plugins
4911 $cleanuplugintypes = array('report', 'coursereport', 'format');
4912 foreach ($cleanuplugintypes as $type) {
4913 $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
4914 foreach ($plugins as $plugin=>$pluginfunction) {
4915 $pluginfunction($course->id, $showfeedback);
4917 if ($showfeedback) {
4918 echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
4922 // Delete questions and question categories
4923 question_delete_course($course, $showfeedback);
4924 if ($showfeedback) {
4925 echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
4928 // Make sure there are no subcontexts left - all valid blocks and modules should be already gone
4929 $childcontexts = $coursecontext->get_child_contexts(); // returns all subcontexts since 2.2
4930 foreach ($childcontexts as $childcontext) {
4931 $childcontext->delete();
4933 unset($childcontexts);
4935 // Remove all roles and enrolments by default
4936 if (empty($options['keep_roles_and_enrolments'])) {
4937 // this hack is used in restore when deleting contents of existing course
4938 role_unassign_all(array('contextid'=>$coursecontext->id, 'component'=>''), true);
4939 enrol_course_delete($course);
4940 if ($showfeedback) {
4941 echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
4945 // Delete any groups, removing members and grouping/course links first.
4946 if (empty($options['keep_groups_and_groupings'])) {
4947 groups_delete_groupings($course->id, $showfeedback);
4948 groups_delete_groups($course->id, $showfeedback);
4951 // filters be gone!
4952 filter_delete_all_for_context($coursecontext->id);
4954 // die comments!
4955 comment::delete_comments($coursecontext->id);
4957 // ratings are history too
4958 $delopt = new stdclass();
4959 $delopt->contextid = $coursecontext->id;
4960 $rm = new rating_manager();
4961 $rm->delete_ratings($delopt);
4963 // Delete course tags
4964 coursetag_delete_course_tags($course->id, $showfeedback);
4966 // Delete calendar events
4967 $DB->delete_records('event', array('courseid'=>$course->id));
4968 $fs->delete_area_files($coursecontext->id, 'calendar');
4970 // Delete all related records in other core tables that may have a courseid
4971 // This array stores the tables that need to be cleared, as
4972 // table_name => column_name that contains the course id.
4973 $tablestoclear = array(
4974 'log' => 'course', // Course logs (NOTE: this might be changed in the future)
4975 'backup_courses' => 'courseid', // Scheduled backup stuff
4976 'user_lastaccess' => 'courseid', // User access info
4978 foreach ($tablestoclear as $table => $col) {
4979 $DB->delete_records($table, array($col=>$course->id));
4982 // delete all course backup files
4983 $fs->delete_area_files($coursecontext->id, 'backup');
4985 // cleanup course record - remove links to deleted stuff
4986 $oldcourse = new stdClass();
4987 $oldcourse->id = $course->id;
4988 $oldcourse->summary = '';
4989 $oldcourse->modinfo = NULL;
4990 $oldcourse->legacyfiles = 0;
4991 $oldcourse->enablecompletion = 0;
4992 if (!empty($options['keep_groups_and_groupings'])) {
4993 $oldcourse->defaultgroupingid = 0;
4995 $DB->update_record('course', $oldcourse);
4997 // Delete course sections and availability options.
4998 $DB->delete_records_select('course_sections_availability',
4999 'coursesectionid IN (SELECT id from {course_sections} WHERE course=?)',
5000 array($course->id));
5001 $DB->delete_records_select('course_sections_avail_fields',
5002 'coursesectionid IN (SELECT id from {course_sections} WHERE course=?)',
5003 array($course->id));
5004 $DB->delete_records('course_sections', array('course'=>$course->id));
5006 // delete legacy, section and any other course files
5007 $fs->delete_area_files($coursecontext->id, 'course'); // files from summary and section
5009 // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5010 if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5011 // Easy, do not delete the context itself...
5012 $coursecontext->delete_content();
5014 } else {
5015 // Hack alert!!!!
5016 // We can not drop all context stuff because it would bork enrolments and roles,
5017 // there might be also files used by enrol plugins...
5020 // Delete legacy files - just in case some files are still left there after conversion to new file api,
5021 // also some non-standard unsupported plugins may try to store something there
5022 fulldelete($CFG->dataroot.'/'.$course->id);
5024 // Finally trigger the event
5025 $course->context = $coursecontext; // you can not access context in cron event later after course is deleted
5026 $course->options = $options; // not empty if we used any crazy hack
5027 events_trigger('course_content_removed', $course);
5029 return true;
5033 * Change dates in module - used from course reset.
5035 * @global object
5036 * @global object
5037 * @param string $modname forum, assignment, etc
5038 * @param array $fields array of date fields from mod table
5039 * @param int $timeshift time difference
5040 * @param int $courseid
5041 * @return bool success
5043 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid) {
5044 global $CFG, $DB;
5045 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5047 $return = true;
5048 foreach ($fields as $field) {
5049 $updatesql = "UPDATE {".$modname."}
5050 SET $field = $field + ?
5051 WHERE course=? AND $field<>0";
5052 $return = $DB->execute($updatesql, array($timeshift, $courseid)) && $return;
5055 $refreshfunction = $modname.'_refresh_events';
5056 if (function_exists($refreshfunction)) {
5057 $refreshfunction($courseid);
5060 return $return;
5064 * This function will empty a course of user data.
5065 * It will retain the activities and the structure of the course.
5067 * @param object $data an object containing all the settings including courseid (without magic quotes)
5068 * @return array status array of array component, item, error
5070 function reset_course_userdata($data) {
5071 global $CFG, $USER, $DB;
5072 require_once($CFG->libdir.'/gradelib.php');
5073 require_once($CFG->libdir.'/completionlib.php');
5074 require_once($CFG->dirroot.'/group/lib.php');
5076 $data->courseid = $data->id;
5077 $context = context_course::instance($data->courseid);
5079 // calculate the time shift of dates
5080 if (!empty($data->reset_start_date)) {
5081 // time part of course startdate should be zero
5082 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5083 } else {
5084 $data->timeshift = 0;
5087 // result array: component, item, error
5088 $status = array();
5090 // start the resetting
5091 $componentstr = get_string('general');
5093 // move the course start time
5094 if (!empty($data->reset_start_date) and $data->timeshift) {
5095 // change course start data
5096 $DB->set_field('course', 'startdate', $data->reset_start_date, array('id'=>$data->courseid));
5097 // update all course and group events - do not move activity events
5098 $updatesql = "UPDATE {event}
5099 SET timestart = timestart + ?
5100 WHERE courseid=? AND instance=0";
5101 $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5103 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
5106 if (!empty($data->reset_logs)) {
5107 $DB->delete_records('log', array('course'=>$data->courseid));
5108 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletelogs'), 'error'=>false);
5111 if (!empty($data->reset_events)) {
5112 $DB->delete_records('event', array('courseid'=>$data->courseid));
5113 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteevents', 'calendar'), 'error'=>false);
5116 if (!empty($data->reset_notes)) {
5117 require_once($CFG->dirroot.'/notes/lib.php');
5118 note_delete_all($data->courseid);
5119 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotes', 'notes'), 'error'=>false);
5122 if (!empty($data->delete_blog_associations)) {
5123 require_once($CFG->dirroot.'/blog/lib.php');
5124 blog_remove_associations_for_course($data->courseid);
5125 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteblogassociations', 'blog'), 'error'=>false);
5128 if (!empty($data->reset_completion)) {
5129 // Delete course and activity completion information.
5130 $course = $DB->get_record('course', array('id'=>$data->courseid));
5131 $cc = new completion_info($course);
5132 $cc->delete_all_completion_data();
5133 $status[] = array('component' => $componentstr,
5134 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5137 $componentstr = get_string('roles');
5139 if (!empty($data->reset_roles_overrides)) {
5140 $children = get_child_contexts($context);
5141 foreach ($children as $child) {
5142 $DB->delete_records('role_capabilities', array('contextid'=>$child->id));
5144 $DB->delete_records('role_capabilities', array('contextid'=>$context->id));
5145 //force refresh for logged in users
5146 mark_context_dirty($context->path);
5147 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletecourseoverrides', 'role'), 'error'=>false);
5150 if (!empty($data->reset_roles_local)) {
5151 $children = get_child_contexts($context);
5152 foreach ($children as $child) {
5153 role_unassign_all(array('contextid'=>$child->id));
5155 //force refresh for logged in users
5156 mark_context_dirty($context->path);
5157 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletelocalroles', 'role'), 'error'=>false);
5160 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5161 $data->unenrolled = array();
5162 if (!empty($data->unenrol_users)) {
5163 $plugins = enrol_get_plugins(true);
5164 $instances = enrol_get_instances($data->courseid, true);
5165 foreach ($instances as $key=>$instance) {
5166 if (!isset($plugins[$instance->enrol])) {
5167 unset($instances[$key]);
5168 continue;
5172 foreach($data->unenrol_users as $withroleid) {
5173 if ($withroleid) {
5174 $sql = "SELECT ue.*
5175 FROM {user_enrolments} ue
5176 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5177 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5178 JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5179 $params = array('courseid'=>$data->courseid, 'roleid'=>$withroleid, 'courselevel'=>CONTEXT_COURSE);
5181 } else {
5182 // without any role assigned at course context
5183 $sql = "SELECT ue.*
5184 FROM {user_enrolments} ue
5185 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5186 JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5187 LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5188 WHERE ra.id IS NULL";
5189 $params = array('courseid'=>$data->courseid, 'courselevel'=>CONTEXT_COURSE);
5192 $rs = $DB->get_recordset_sql($sql, $params);
5193 foreach ($rs as $ue) {
5194 if (!isset($instances[$ue->enrolid])) {
5195 continue;
5197 $instance = $instances[$ue->enrolid];
5198 $plugin = $plugins[$instance->enrol];
5199 if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5200 continue;
5203 $plugin->unenrol_user($instance, $ue->userid);
5204 $data->unenrolled[$ue->userid] = $ue->userid;
5206 $rs->close();
5209 if (!empty($data->unenrolled)) {
5210 $status[] = array('component'=>$componentstr, 'item'=>get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')', 'error'=>false);
5214 $componentstr = get_string('groups');
5216 // remove all group members
5217 if (!empty($data->reset_groups_members)) {
5218 groups_delete_group_members($data->courseid);
5219 $status[] = array('component'=>$componentstr, 'item'=>get_string('removegroupsmembers', 'group'), 'error'=>false);
5222 // remove all groups
5223 if (!empty($data->reset_groups_remove)) {
5224 groups_delete_groups($data->courseid, false);
5225 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallgroups', 'group'), 'error'=>false);
5228 // remove all grouping members
5229 if (!empty($data->reset_groupings_members)) {
5230 groups_delete_groupings_groups($data->courseid, false);
5231 $status[] = array('component'=>$componentstr, 'item'=>get_string('removegroupingsmembers', 'group'), 'error'=>false);
5234 // remove all groupings
5235 if (!empty($data->reset_groupings_remove)) {
5236 groups_delete_groupings($data->courseid, false);
5237 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallgroupings', 'group'), 'error'=>false);
5240 // Look in every instance of every module for data to delete
5241 $unsupported_mods = array();
5242 if ($allmods = $DB->get_records('modules') ) {
5243 foreach ($allmods as $mod) {
5244 $modname = $mod->name;
5245 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5246 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data
5247 if (file_exists($modfile)) {
5248 if (!$DB->count_records($modname, array('course'=>$data->courseid))) {
5249 continue; // Skip mods with no instances
5251 include_once($modfile);
5252 if (function_exists($moddeleteuserdata)) {
5253 $modstatus = $moddeleteuserdata($data);
5254 if (is_array($modstatus)) {
5255 $status = array_merge($status, $modstatus);
5256 } else {
5257 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5259 } else {
5260 $unsupported_mods[] = $mod;
5262 } else {
5263 debugging('Missing lib.php in '.$modname.' module!');
5268 // mention unsupported mods
5269 if (!empty($unsupported_mods)) {
5270 foreach($unsupported_mods as $mod) {
5271 $status[] = array('component'=>get_string('modulenameplural', $mod->name), 'item'=>'', 'error'=>get_string('resetnotimplemented'));
5276 $componentstr = get_string('gradebook', 'grades');
5277 // reset gradebook
5278 if (!empty($data->reset_gradebook_items)) {
5279 remove_course_grades($data->courseid, false);
5280 grade_grab_course_grades($data->courseid);
5281 grade_regrade_final_grades($data->courseid);
5282 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeallcourseitems', 'grades'), 'error'=>false);
5284 } else if (!empty($data->reset_gradebook_grades)) {
5285 grade_course_reset($data->courseid);
5286 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeallcoursegrades', 'grades'), 'error'=>false);
5288 // reset comments
5289 if (!empty($data->reset_comments)) {
5290 require_once($CFG->dirroot.'/comment/lib.php');
5291 comment::reset_course_page_comments($context);
5294 return $status;
5298 * Generate an email processing address
5300 * @param int $modid
5301 * @param string $modargs
5302 * @return string Returns email processing address
5304 function generate_email_processing_address($modid,$modargs) {
5305 global $CFG;
5307 $header = $CFG->mailprefix . substr(base64_encode(pack('C',$modid)),0,2).$modargs;
5308 return $header . substr(md5($header.get_site_identifier()),0,16).'@'.$CFG->maildomain;
5314 * @todo Finish documenting this function
5316 * @global object
5317 * @param string $modargs
5318 * @param string $body Currently unused
5320 function moodle_process_email($modargs,$body) {
5321 global $DB;
5323 // the first char should be an unencoded letter. We'll take this as an action
5324 switch ($modargs{0}) {
5325 case 'B': { // bounce
5326 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
5327 if ($user = $DB->get_record("user", array('id'=>$userid), "id,email")) {
5328 // check the half md5 of their email
5329 $md5check = substr(md5($user->email),0,16);
5330 if ($md5check == substr($modargs, -16)) {
5331 set_bounce_count($user);
5333 // else maybe they've already changed it?
5336 break;
5337 // maybe more later?
5341 /// CORRESPONDENCE ////////////////////////////////////////////////
5344 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5346 * @param string $action 'get', 'buffer', 'close' or 'flush'
5347 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5349 function get_mailer($action='get') {
5350 global $CFG;
5352 static $mailer = null;
5353 static $counter = 0;
5355 if (!isset($CFG->smtpmaxbulk)) {
5356 $CFG->smtpmaxbulk = 1;
5359 if ($action == 'get') {
5360 $prevkeepalive = false;
5362 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5363 if ($counter < $CFG->smtpmaxbulk and !$mailer->IsError()) {
5364 $counter++;
5365 // reset the mailer
5366 $mailer->Priority = 3;
5367 $mailer->CharSet = 'UTF-8'; // our default
5368 $mailer->ContentType = "text/plain";
5369 $mailer->Encoding = "8bit";
5370 $mailer->From = "root@localhost";
5371 $mailer->FromName = "Root User";
5372 $mailer->Sender = "";
5373 $mailer->Subject = "";
5374 $mailer->Body = "";
5375 $mailer->AltBody = "";
5376 $mailer->ConfirmReadingTo = "";
5378 $mailer->ClearAllRecipients();
5379 $mailer->ClearReplyTos();
5380 $mailer->ClearAttachments();
5381 $mailer->ClearCustomHeaders();
5382 return $mailer;
5385 $prevkeepalive = $mailer->SMTPKeepAlive;
5386 get_mailer('flush');
5389 include_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5390 $mailer = new moodle_phpmailer();
5392 $counter = 1;
5394 $mailer->Version = 'Moodle '.$CFG->version; // mailer version
5395 $mailer->PluginDir = $CFG->libdir.'/phpmailer/'; // plugin directory (eg smtp plugin)
5396 $mailer->CharSet = 'UTF-8';
5398 // some MTAs may do double conversion of LF if CRLF used, CRLF is required line ending in RFC 822bis
5399 if (isset($CFG->mailnewline) and $CFG->mailnewline == 'CRLF') {
5400 $mailer->LE = "\r\n";
5401 } else {
5402 $mailer->LE = "\n";
5405 if ($CFG->smtphosts == 'qmail') {
5406 $mailer->IsQmail(); // use Qmail system
5408 } else if (empty($CFG->smtphosts)) {
5409 $mailer->IsMail(); // use PHP mail() = sendmail
5411 } else {
5412 $mailer->IsSMTP(); // use SMTP directly
5413 if (!empty($CFG->debugsmtp)) {
5414 $mailer->SMTPDebug = true;
5416 $mailer->Host = $CFG->smtphosts; // specify main and backup servers
5417 $mailer->SMTPSecure = $CFG->smtpsecure; // specify secure connection protocol
5418 $mailer->SMTPKeepAlive = $prevkeepalive; // use previous keepalive
5420 if ($CFG->smtpuser) { // Use SMTP authentication
5421 $mailer->SMTPAuth = true;
5422 $mailer->Username = $CFG->smtpuser;
5423 $mailer->Password = $CFG->smtppass;
5427 return $mailer;
5430 $nothing = null;
5432 // keep smtp session open after sending
5433 if ($action == 'buffer') {
5434 if (!empty($CFG->smtpmaxbulk)) {
5435 get_mailer('flush');
5436 $m = get_mailer();
5437 if ($m->Mailer == 'smtp') {
5438 $m->SMTPKeepAlive = true;
5441 return $nothing;
5444 // close smtp session, but continue buffering
5445 if ($action == 'flush') {
5446 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5447 if (!empty($mailer->SMTPDebug)) {
5448 echo '<pre>'."\n";
5450 $mailer->SmtpClose();
5451 if (!empty($mailer->SMTPDebug)) {
5452 echo '</pre>';
5455 return $nothing;
5458 // close smtp session, do not buffer anymore
5459 if ($action == 'close') {
5460 if (isset($mailer) and $mailer->Mailer == 'smtp') {
5461 get_mailer('flush');
5462 $mailer->SMTPKeepAlive = false;
5464 $mailer = null; // better force new instance
5465 return $nothing;
5470 * Send an email to a specified user
5472 * @global object
5473 * @global string
5474 * @global string IdentityProvider(IDP) URL user hits to jump to mnet peer.
5475 * @uses SITEID
5476 * @param stdClass $user A {@link $USER} object
5477 * @param stdClass $from A {@link $USER} object
5478 * @param string $subject plain text subject line of the email
5479 * @param string $messagetext plain text version of the message
5480 * @param string $messagehtml complete html version of the message (optional)
5481 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
5482 * @param string $attachname the name of the file (extension indicates MIME)
5483 * @param bool $usetrueaddress determines whether $from email address should
5484 * be sent out. Will be overruled by user profile setting for maildisplay
5485 * @param string $replyto Email address to reply to
5486 * @param string $replytoname Name of reply to recipient
5487 * @param int $wordwrapwidth custom word wrap width, default 79
5488 * @return bool Returns true if mail was sent OK and false if there was an error.
5490 function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='', $wordwrapwidth=79) {
5492 global $CFG;
5494 if (empty($user) || empty($user->email)) {
5495 $nulluser = 'User is null or has no email';
5496 error_log($nulluser);
5497 if (CLI_SCRIPT) {
5498 mtrace('Error: lib/moodlelib.php email_to_user(): '.$nulluser);
5500 return false;
5503 if (!empty($user->deleted)) {
5504 // do not mail deleted users
5505 $userdeleted = 'User is deleted';
5506 error_log($userdeleted);
5507 if (CLI_SCRIPT) {
5508 mtrace('Error: lib/moodlelib.php email_to_user(): '.$userdeleted);
5510 return false;
5513 if (!empty($CFG->noemailever)) {
5514 // hidden setting for development sites, set in config.php if needed
5515 $noemail = 'Not sending email due to noemailever config setting';
5516 error_log($noemail);
5517 if (CLI_SCRIPT) {
5518 mtrace('Error: lib/moodlelib.php email_to_user(): '.$noemail);
5520 return true;
5523 if (!empty($CFG->divertallemailsto)) {
5524 $subject = "[DIVERTED {$user->email}] $subject";
5525 $user = clone($user);
5526 $user->email = $CFG->divertallemailsto;
5529 // skip mail to suspended users
5530 if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5531 return true;
5534 if (!validate_email($user->email)) {
5535 // we can not send emails to invalid addresses - it might create security issue or confuse the mailer
5536 $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
5537 error_log($invalidemail);
5538 if (CLI_SCRIPT) {
5539 mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
5541 return false;
5544 if (over_bounce_threshold($user)) {
5545 $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
5546 error_log($bouncemsg);
5547 if (CLI_SCRIPT) {
5548 mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
5550 return false;
5553 // If the user is a remote mnet user, parse the email text for URL to the
5554 // wwwroot and modify the url to direct the user's browser to login at their
5555 // home site (identity provider - idp) before hitting the link itself
5556 if (is_mnet_remote_user($user)) {
5557 require_once($CFG->dirroot.'/mnet/lib.php');
5559 $jumpurl = mnet_get_idp_jump_url($user);
5560 $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5562 $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5563 $callback,
5564 $messagetext);
5565 $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5566 $callback,
5567 $messagehtml);
5569 $mail = get_mailer();
5571 if (!empty($mail->SMTPDebug)) {
5572 echo '<pre>' . "\n";
5575 $temprecipients = array();
5576 $tempreplyto = array();
5578 $supportuser = generate_email_supportuser();
5580 // make up an email address for handling bounces
5581 if (!empty($CFG->handlebounces)) {
5582 $modargs = 'B'.base64_encode(pack('V',$user->id)).substr(md5($user->email),0,16);
5583 $mail->Sender = generate_email_processing_address(0,$modargs);
5584 } else {
5585 $mail->Sender = $supportuser->email;
5588 if (is_string($from)) { // So we can pass whatever we want if there is need
5589 $mail->From = $CFG->noreplyaddress;
5590 $mail->FromName = $from;
5591 } else if ($usetrueaddress and $from->maildisplay) {
5592 $mail->From = $from->email;
5593 $mail->FromName = fullname($from);
5594 } else {
5595 $mail->From = $CFG->noreplyaddress;
5596 $mail->FromName = fullname($from);
5597 if (empty($replyto)) {
5598 $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
5602 if (!empty($replyto)) {
5603 $tempreplyto[] = array($replyto, $replytoname);
5606 $mail->Subject = substr($subject, 0, 900);
5608 $temprecipients[] = array($user->email, fullname($user));
5610 $mail->WordWrap = $wordwrapwidth; // set word wrap
5612 if (!empty($from->customheaders)) { // Add custom headers
5613 if (is_array($from->customheaders)) {
5614 foreach ($from->customheaders as $customheader) {
5615 $mail->AddCustomHeader($customheader);
5617 } else {
5618 $mail->AddCustomHeader($from->customheaders);
5622 if (!empty($from->priority)) {
5623 $mail->Priority = $from->priority;
5626 if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) { // Don't ever send HTML to users who don't want it
5627 $mail->IsHTML(true);
5628 $mail->Encoding = 'quoted-printable'; // Encoding to use
5629 $mail->Body = $messagehtml;
5630 $mail->AltBody = "\n$messagetext\n";
5631 } else {
5632 $mail->IsHTML(false);
5633 $mail->Body = "\n$messagetext\n";
5636 if ($attachment && $attachname) {
5637 if (preg_match( "~\\.\\.~" ,$attachment )) { // Security check for ".." in dir path
5638 $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5639 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5640 } else {
5641 require_once($CFG->libdir.'/filelib.php');
5642 $mimetype = mimeinfo('type', $attachname);
5643 $mail->AddAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
5647 // Check if the email should be sent in an other charset then the default UTF-8
5648 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5650 // use the defined site mail charset or eventually the one preferred by the recipient
5651 $charset = $CFG->sitemailcharset;
5652 if (!empty($CFG->allowusermailcharset)) {
5653 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5654 $charset = $useremailcharset;
5658 // convert all the necessary strings if the charset is supported
5659 $charsets = get_list_of_charsets();
5660 unset($charsets['UTF-8']);
5661 if (in_array($charset, $charsets)) {
5662 $mail->CharSet = $charset;
5663 $mail->FromName = textlib::convert($mail->FromName, 'utf-8', strtolower($charset));
5664 $mail->Subject = textlib::convert($mail->Subject, 'utf-8', strtolower($charset));
5665 $mail->Body = textlib::convert($mail->Body, 'utf-8', strtolower($charset));
5666 $mail->AltBody = textlib::convert($mail->AltBody, 'utf-8', strtolower($charset));
5668 foreach ($temprecipients as $key => $values) {
5669 $temprecipients[$key][1] = textlib::convert($values[1], 'utf-8', strtolower($charset));
5671 foreach ($tempreplyto as $key => $values) {
5672 $tempreplyto[$key][1] = textlib::convert($values[1], 'utf-8', strtolower($charset));
5677 foreach ($temprecipients as $values) {
5678 $mail->AddAddress($values[0], $values[1]);
5680 foreach ($tempreplyto as $values) {
5681 $mail->AddReplyTo($values[0], $values[1]);
5684 if ($mail->Send()) {
5685 set_send_count($user);
5686 if (!empty($mail->SMTPDebug)) {
5687 echo '</pre>';
5689 return true;
5690 } else {
5691 add_to_log(SITEID, 'library', 'mailer', qualified_me(), 'ERROR: '. $mail->ErrorInfo);
5692 if (CLI_SCRIPT) {
5693 mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5695 if (!empty($mail->SMTPDebug)) {
5696 echo '</pre>';
5698 return false;
5703 * Generate a signoff for emails based on support settings
5705 * @global object
5706 * @return string
5708 function generate_email_signoff() {
5709 global $CFG;
5711 $signoff = "\n";
5712 if (!empty($CFG->supportname)) {
5713 $signoff .= $CFG->supportname."\n";
5715 if (!empty($CFG->supportemail)) {
5716 $signoff .= $CFG->supportemail."\n";
5718 if (!empty($CFG->supportpage)) {
5719 $signoff .= $CFG->supportpage."\n";
5721 return $signoff;
5725 * Generate a fake user for emails based on support settings
5726 * @global object
5727 * @return object user info
5729 function generate_email_supportuser() {
5730 global $CFG;
5732 static $supportuser;
5734 if (!empty($supportuser)) {
5735 return $supportuser;
5738 $supportuser = new stdClass();
5739 $supportuser->email = $CFG->supportemail ? $CFG->supportemail : $CFG->noreplyaddress;
5740 $supportuser->firstname = $CFG->supportname ? $CFG->supportname : get_string('noreplyname');
5741 $supportuser->lastname = '';
5742 $supportuser->maildisplay = true;
5744 return $supportuser;
5749 * Sets specified user's password and send the new password to the user via email.
5751 * @global object
5752 * @global object
5753 * @param user $user A {@link $USER} object
5754 * @param boolean $fasthash If true, use a low cost factor when generating the hash for speed.
5755 * @return boolean|string Returns "true" if mail was sent OK and "false" if there was an error
5757 function setnew_password_and_mail($user, $fasthash = false) {
5758 global $CFG, $DB;
5760 // we try to send the mail in language the user understands,
5761 // unfortunately the filter_string() does not support alternative langs yet
5762 // so multilang will not work properly for site->fullname
5763 $lang = empty($user->lang) ? $CFG->lang : $user->lang;
5765 $site = get_site();
5767 $supportuser = generate_email_supportuser();
5769 $newpassword = generate_password();
5771 $hashedpassword = hash_internal_user_password($newpassword, $fasthash);
5772 $DB->set_field('user', 'password', $hashedpassword, array('id'=>$user->id));
5774 $a = new stdClass();
5775 $a->firstname = fullname($user, true);
5776 $a->sitename = format_string($site->fullname);
5777 $a->username = $user->username;
5778 $a->newpassword = $newpassword;
5779 $a->link = $CFG->wwwroot .'/login/';
5780 $a->signoff = generate_email_signoff();
5782 $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
5784 $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
5786 //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
5787 return email_to_user($user, $supportuser, $subject, $message);
5792 * Resets specified user's password and send the new password to the user via email.
5794 * @param stdClass $user A {@link $USER} object
5795 * @return bool Returns true if mail was sent OK and false if there was an error.
5797 function reset_password_and_mail($user) {
5798 global $CFG;
5800 $site = get_site();
5801 $supportuser = generate_email_supportuser();
5803 $userauth = get_auth_plugin($user->auth);
5804 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
5805 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
5806 return false;
5809 $newpassword = generate_password();
5811 if (!$userauth->user_update_password($user, $newpassword)) {
5812 print_error("cannotsetpassword");
5815 $a = new stdClass();
5816 $a->firstname = $user->firstname;
5817 $a->lastname = $user->lastname;
5818 $a->sitename = format_string($site->fullname);
5819 $a->username = $user->username;
5820 $a->newpassword = $newpassword;
5821 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
5822 $a->signoff = generate_email_signoff();
5824 $message = get_string('newpasswordtext', '', $a);
5826 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
5828 unset_user_preference('create_password', $user); // prevent cron from generating the password
5830 //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
5831 return email_to_user($user, $supportuser, $subject, $message);
5836 * Send email to specified user with confirmation text and activation link.
5838 * @global object
5839 * @param user $user A {@link $USER} object
5840 * @return bool Returns true if mail was sent OK and false if there was an error.
5842 function send_confirmation_email($user) {
5843 global $CFG;
5845 $site = get_site();
5846 $supportuser = generate_email_supportuser();
5848 $data = new stdClass();
5849 $data->firstname = fullname($user);
5850 $data->sitename = format_string($site->fullname);
5851 $data->admin = generate_email_signoff();
5853 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
5855 $username = urlencode($user->username);
5856 $username = str_replace('.', '%2E', $username); // prevent problems with trailing dots
5857 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
5858 $message = get_string('emailconfirmation', '', $data);
5859 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
5861 $user->mailformat = 1; // Always send HTML version as well
5863 //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
5864 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
5869 * send_password_change_confirmation_email.
5871 * @global object
5872 * @param user $user A {@link $USER} object
5873 * @return bool Returns true if mail was sent OK and false if there was an error.
5875 function send_password_change_confirmation_email($user) {
5876 global $CFG;
5878 $site = get_site();
5879 $supportuser = generate_email_supportuser();
5881 $data = new stdClass();
5882 $data->firstname = $user->firstname;
5883 $data->lastname = $user->lastname;
5884 $data->sitename = format_string($site->fullname);
5885 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?p='. $user->secret .'&s='. urlencode($user->username);
5886 $data->admin = generate_email_signoff();
5888 $message = get_string('emailpasswordconfirmation', '', $data);
5889 $subject = get_string('emailpasswordconfirmationsubject', '', format_string($site->fullname));
5891 //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
5892 return email_to_user($user, $supportuser, $subject, $message);
5897 * send_password_change_info.
5899 * @global object
5900 * @param user $user A {@link $USER} object
5901 * @return bool Returns true if mail was sent OK and false if there was an error.
5903 function send_password_change_info($user) {
5904 global $CFG;
5906 $site = get_site();
5907 $supportuser = generate_email_supportuser();
5908 $systemcontext = context_system::instance();
5910 $data = new stdClass();
5911 $data->firstname = $user->firstname;
5912 $data->lastname = $user->lastname;
5913 $data->sitename = format_string($site->fullname);
5914 $data->admin = generate_email_signoff();
5916 $userauth = get_auth_plugin($user->auth);
5918 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
5919 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
5920 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5921 //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
5922 return email_to_user($user, $supportuser, $subject, $message);
5925 if ($userauth->can_change_password() and $userauth->change_password_url()) {
5926 // we have some external url for password changing
5927 $data->link .= $userauth->change_password_url();
5929 } else {
5930 //no way to change password, sorry
5931 $data->link = '';
5934 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
5935 $message = get_string('emailpasswordchangeinfo', '', $data);
5936 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5937 } else {
5938 $message = get_string('emailpasswordchangeinfofail', '', $data);
5939 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
5942 //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
5943 return email_to_user($user, $supportuser, $subject, $message);
5948 * Check that an email is allowed. It returns an error message if there
5949 * was a problem.
5951 * @global object
5952 * @param string $email Content of email
5953 * @return string|false
5955 function email_is_not_allowed($email) {
5956 global $CFG;
5958 if (!empty($CFG->allowemailaddresses)) {
5959 $allowed = explode(' ', $CFG->allowemailaddresses);
5960 foreach ($allowed as $allowedpattern) {
5961 $allowedpattern = trim($allowedpattern);
5962 if (!$allowedpattern) {
5963 continue;
5965 if (strpos($allowedpattern, '.') === 0) {
5966 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
5967 // subdomains are in a form ".example.com" - matches "xxx@anything.example.com"
5968 return false;
5971 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) { // Match! (bug 5250)
5972 return false;
5975 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
5977 } else if (!empty($CFG->denyemailaddresses)) {
5978 $denied = explode(' ', $CFG->denyemailaddresses);
5979 foreach ($denied as $deniedpattern) {
5980 $deniedpattern = trim($deniedpattern);
5981 if (!$deniedpattern) {
5982 continue;
5984 if (strpos($deniedpattern, '.') === 0) {
5985 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
5986 // subdomains are in a form ".example.com" - matches "xxx@anything.example.com"
5987 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
5990 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) { // Match! (bug 5250)
5991 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
5996 return false;
5999 /// FILE HANDLING /////////////////////////////////////////////
6002 * Returns local file storage instance
6004 * @return file_storage
6006 function get_file_storage() {
6007 global $CFG;
6009 static $fs = null;
6011 if ($fs) {
6012 return $fs;
6015 require_once("$CFG->libdir/filelib.php");
6017 if (isset($CFG->filedir)) {
6018 $filedir = $CFG->filedir;
6019 } else {
6020 $filedir = $CFG->dataroot.'/filedir';
6023 if (isset($CFG->trashdir)) {
6024 $trashdirdir = $CFG->trashdir;
6025 } else {
6026 $trashdirdir = $CFG->dataroot.'/trashdir';
6029 $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
6031 return $fs;
6035 * Returns local file storage instance
6037 * @return file_browser
6039 function get_file_browser() {
6040 global $CFG;
6042 static $fb = null;
6044 if ($fb) {
6045 return $fb;
6048 require_once("$CFG->libdir/filelib.php");
6050 $fb = new file_browser();
6052 return $fb;
6056 * Returns file packer
6058 * @param string $mimetype default application/zip
6059 * @return file_packer
6061 function get_file_packer($mimetype='application/zip') {
6062 global $CFG;
6064 static $fp = array();
6066 if (isset($fp[$mimetype])) {
6067 return $fp[$mimetype];
6070 switch ($mimetype) {
6071 case 'application/zip':
6072 case 'application/vnd.moodle.backup':
6073 $classname = 'zip_packer';
6074 break;
6075 case 'application/x-tar':
6076 // $classname = 'tar_packer';
6077 // break;
6078 default:
6079 return false;
6082 require_once("$CFG->libdir/filestorage/$classname.php");
6083 $fp[$mimetype] = new $classname();
6085 return $fp[$mimetype];
6089 * Returns current name of file on disk if it exists.
6091 * @param string $newfile File to be verified
6092 * @return string Current name of file on disk if true
6094 function valid_uploaded_file($newfile) {
6095 if (empty($newfile)) {
6096 return '';
6098 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6099 return $newfile['tmp_name'];
6100 } else {
6101 return '';
6106 * Returns the maximum size for uploading files.
6108 * There are seven possible upload limits:
6109 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6110 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6111 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6112 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6113 * 5. by the Moodle admin in $CFG->maxbytes
6114 * 6. by the teacher in the current course $course->maxbytes
6115 * 7. by the teacher for the current module, eg $assignment->maxbytes
6117 * These last two are passed to this function as arguments (in bytes).
6118 * Anything defined as 0 is ignored.
6119 * The smallest of all the non-zero numbers is returned.
6121 * @todo Finish documenting this function
6123 * @param int $sizebytes Set maximum size
6124 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6125 * @param int $modulebytes Current module ->maxbytes (in bytes)
6126 * @return int The maximum size for uploading files.
6128 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
6130 if (! $filesize = ini_get('upload_max_filesize')) {
6131 $filesize = '5M';
6133 $minimumsize = get_real_size($filesize);
6135 if ($postsize = ini_get('post_max_size')) {
6136 $postsize = get_real_size($postsize);
6137 if ($postsize < $minimumsize) {
6138 $minimumsize = $postsize;
6142 if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6143 $minimumsize = $sitebytes;
6146 if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6147 $minimumsize = $coursebytes;
6150 if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6151 $minimumsize = $modulebytes;
6154 return $minimumsize;
6158 * Returns the maximum size for uploading files for the current user
6160 * This function takes in account @see:get_max_upload_file_size() the user's capabilities
6162 * @param context $context The context in which to check user capabilities
6163 * @param int $sizebytes Set maximum size
6164 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6165 * @param int $modulebytes Current module ->maxbytes (in bytes)
6166 * @param stdClass The user
6167 * @return int The maximum size for uploading files.
6169 function get_user_max_upload_file_size($context, $sitebytes=0, $coursebytes=0, $modulebytes=0, $user=null) {
6170 global $USER;
6172 if (empty($user)) {
6173 $user = $USER;
6176 if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6177 return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6180 return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6184 * Returns an array of possible sizes in local language
6186 * Related to {@link get_max_upload_file_size()} - this function returns an
6187 * array of possible sizes in an array, translated to the
6188 * local language.
6190 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6192 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6193 * with the value set to 0. This option will be the first in the list.
6195 * @global object
6196 * @uses SORT_NUMERIC
6197 * @param int $sizebytes Set maximum size
6198 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6199 * @param int $modulebytes Current module ->maxbytes (in bytes)
6200 * @param int|array $custombytes custom upload size/s which will be added to list,
6201 * Only value/s smaller then maxsize will be added to list.
6202 * @return array
6204 function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6205 global $CFG;
6207 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6208 return array();
6211 if ($sitebytes == 0) {
6212 // Will get the minimum of upload_max_filesize or post_max_size.
6213 $sitebytes = get_max_upload_file_size();
6216 $filesize = array();
6217 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6218 5242880, 10485760, 20971520, 52428800, 104857600);
6220 // If custombytes is given and is valid then add it to the list.
6221 if (is_number($custombytes) and $custombytes > 0) {
6222 $custombytes = (int)$custombytes;
6223 if (!in_array($custombytes, $sizelist)) {
6224 $sizelist[] = $custombytes;
6226 } else if (is_array($custombytes)) {
6227 $sizelist = array_unique(array_merge($sizelist, $custombytes));
6230 // Allow maxbytes to be selected if it falls outside the above boundaries
6231 if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6232 // note: get_real_size() is used in order to prevent problems with invalid values
6233 $sizelist[] = get_real_size($CFG->maxbytes);
6236 foreach ($sizelist as $sizebytes) {
6237 if ($sizebytes < $maxsize && $sizebytes > 0) {
6238 $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6242 $limitlevel = '';
6243 $displaysize = '';
6244 if ($modulebytes &&
6245 (($modulebytes < $coursebytes || $coursebytes == 0) &&
6246 ($modulebytes < $sitebytes || $sitebytes == 0))) {
6247 $limitlevel = get_string('activity', 'core');
6248 $displaysize = display_size($modulebytes);
6249 $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6251 } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6252 $limitlevel = get_string('course', 'core');
6253 $displaysize = display_size($coursebytes);
6254 $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6256 } else if ($sitebytes) {
6257 $limitlevel = get_string('site', 'core');
6258 $displaysize = display_size($sitebytes);
6259 $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6262 krsort($filesize, SORT_NUMERIC);
6263 if ($limitlevel) {
6264 $params = (object) array('contextname'=>$limitlevel, 'displaysize'=>$displaysize);
6265 $filesize = array('0'=>get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6268 return $filesize;
6272 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6274 * If excludefiles is defined, then that file/directory is ignored
6275 * If getdirs is true, then (sub)directories are included in the output
6276 * If getfiles is true, then files are included in the output
6277 * (at least one of these must be true!)
6279 * @todo Finish documenting this function. Add examples of $excludefile usage.
6281 * @param string $rootdir A given root directory to start from
6282 * @param string|array $excludefile If defined then the specified file/directory is ignored
6283 * @param bool $descend If true then subdirectories are recursed as well
6284 * @param bool $getdirs If true then (sub)directories are included in the output
6285 * @param bool $getfiles If true then files are included in the output
6286 * @return array An array with all the filenames in
6287 * all subdirectories, relative to the given rootdir
6289 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6291 $dirs = array();
6293 if (!$getdirs and !$getfiles) { // Nothing to show
6294 return $dirs;
6297 if (!is_dir($rootdir)) { // Must be a directory
6298 return $dirs;
6301 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
6302 return $dirs;
6305 if (!is_array($excludefiles)) {
6306 $excludefiles = array($excludefiles);
6309 while (false !== ($file = readdir($dir))) {
6310 $firstchar = substr($file, 0, 1);
6311 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6312 continue;
6314 $fullfile = $rootdir .'/'. $file;
6315 if (filetype($fullfile) == 'dir') {
6316 if ($getdirs) {
6317 $dirs[] = $file;
6319 if ($descend) {
6320 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6321 foreach ($subdirs as $subdir) {
6322 $dirs[] = $file .'/'. $subdir;
6325 } else if ($getfiles) {
6326 $dirs[] = $file;
6329 closedir($dir);
6331 asort($dirs);
6333 return $dirs;
6338 * Adds up all the files in a directory and works out the size.
6340 * @todo Finish documenting this function
6342 * @param string $rootdir The directory to start from
6343 * @param string $excludefile A file to exclude when summing directory size
6344 * @return int The summed size of all files and subfiles within the root directory
6346 function get_directory_size($rootdir, $excludefile='') {
6347 global $CFG;
6349 // do it this way if we can, it's much faster
6350 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6351 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6352 $output = null;
6353 $return = null;
6354 exec($command,$output,$return);
6355 if (is_array($output)) {
6356 return get_real_size(intval($output[0]).'k'); // we told it to return k.
6360 if (!is_dir($rootdir)) { // Must be a directory
6361 return 0;
6364 if (!$dir = @opendir($rootdir)) { // Can't open it for some reason
6365 return 0;
6368 $size = 0;
6370 while (false !== ($file = readdir($dir))) {
6371 $firstchar = substr($file, 0, 1);
6372 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6373 continue;
6375 $fullfile = $rootdir .'/'. $file;
6376 if (filetype($fullfile) == 'dir') {
6377 $size += get_directory_size($fullfile, $excludefile);
6378 } else {
6379 $size += filesize($fullfile);
6382 closedir($dir);
6384 return $size;
6388 * Converts bytes into display form
6390 * @todo Finish documenting this function. Verify return type.
6392 * @staticvar string $gb Localized string for size in gigabytes
6393 * @staticvar string $mb Localized string for size in megabytes
6394 * @staticvar string $kb Localized string for size in kilobytes
6395 * @staticvar string $b Localized string for size in bytes
6396 * @param int $size The size to convert to human readable form
6397 * @return string
6399 function display_size($size) {
6401 static $gb, $mb, $kb, $b;
6403 if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6404 return get_string('unlimited');
6407 if (empty($gb)) {
6408 $gb = get_string('sizegb');
6409 $mb = get_string('sizemb');
6410 $kb = get_string('sizekb');
6411 $b = get_string('sizeb');
6414 if ($size >= 1073741824) {
6415 $size = round($size / 1073741824 * 10) / 10 . $gb;
6416 } else if ($size >= 1048576) {
6417 $size = round($size / 1048576 * 10) / 10 . $mb;
6418 } else if ($size >= 1024) {
6419 $size = round($size / 1024 * 10) / 10 . $kb;
6420 } else {
6421 $size = intval($size) .' '. $b; // file sizes over 2GB can not work in 32bit PHP anyway
6423 return $size;
6427 * Cleans a given filename by removing suspicious or troublesome characters
6428 * @see clean_param()
6430 * @uses PARAM_FILE
6431 * @param string $string file name
6432 * @return string cleaned file name
6434 function clean_filename($string) {
6435 return clean_param($string, PARAM_FILE);
6439 /// STRING TRANSLATION ////////////////////////////////////////
6442 * Returns the code for the current language
6444 * @category string
6445 * @return string
6447 function current_language() {
6448 global $CFG, $USER, $SESSION, $COURSE;
6450 if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) { // Course language can override all other settings for this page
6451 $return = $COURSE->lang;
6453 } else if (!empty($SESSION->lang)) { // Session language can override other settings
6454 $return = $SESSION->lang;
6456 } else if (!empty($USER->lang)) {
6457 $return = $USER->lang;
6459 } else if (isset($CFG->lang)) {
6460 $return = $CFG->lang;
6462 } else {
6463 $return = 'en';
6466 $return = str_replace('_utf8', '', $return); // Just in case this slipped in from somewhere by accident
6468 return $return;
6472 * Returns parent language of current active language if defined
6474 * @category string
6475 * @uses COURSE
6476 * @uses SESSION
6477 * @param string $lang null means current language
6478 * @return string
6480 function get_parent_language($lang=null) {
6481 global $COURSE, $SESSION;
6483 //let's hack around the current language
6484 if (!empty($lang)) {
6485 $old_course_lang = empty($COURSE->lang) ? '' : $COURSE->lang;
6486 $old_session_lang = empty($SESSION->lang) ? '' : $SESSION->lang;
6487 $COURSE->lang = '';
6488 $SESSION->lang = $lang;
6491 $parentlang = get_string('parentlanguage', 'langconfig');
6492 if ($parentlang === 'en') {
6493 $parentlang = '';
6496 //let's hack around the current language
6497 if (!empty($lang)) {
6498 $COURSE->lang = $old_course_lang;
6499 $SESSION->lang = $old_session_lang;
6502 return $parentlang;
6506 * Returns current string_manager instance.
6508 * The param $forcereload is needed for CLI installer only where the string_manager instance
6509 * must be replaced during the install.php script life time.
6511 * @category string
6512 * @param bool $forcereload shall the singleton be released and new instance created instead?
6513 * @return string_manager
6515 function get_string_manager($forcereload=false) {
6516 global $CFG;
6518 static $singleton = null;
6520 if ($forcereload) {
6521 $singleton = null;
6523 if ($singleton === null) {
6524 if (empty($CFG->early_install_lang)) {
6526 if (empty($CFG->langlist)) {
6527 $translist = array();
6528 } else {
6529 $translist = explode(',', $CFG->langlist);
6532 if (empty($CFG->langmenucachefile)) {
6533 $langmenucache = $CFG->cachedir . '/languages';
6534 } else {
6535 $langmenucache = $CFG->langmenucachefile;
6538 $singleton = new core_string_manager($CFG->langotherroot, $CFG->langlocalroot,
6539 !empty($CFG->langstringcache), $translist, $langmenucache);
6541 } else {
6542 $singleton = new install_string_manager();
6546 return $singleton;
6551 * Interface for string manager
6553 * Interface describing class which is responsible for getting
6554 * of localised strings from language packs.
6556 * @package core
6557 * @copyright 2010 Petr Skoda (http://skodak.org)
6558 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6560 interface string_manager {
6562 * Get String returns a requested string
6564 * @param string $identifier The identifier of the string to search for
6565 * @param string $component The module the string is associated with
6566 * @param string|object|array $a An object, string or number that can be used
6567 * within translation strings
6568 * @param string $lang moodle translation language, NULL means use current
6569 * @return string The String !
6571 public function get_string($identifier, $component = '', $a = NULL, $lang = NULL);
6574 * Does the string actually exist?
6576 * get_string() is throwing debug warnings, sometimes we do not want them
6577 * or we want to display better explanation of the problem.
6579 * Use with care!
6581 * @param string $identifier The identifier of the string to search for
6582 * @param string $component The module the string is associated with
6583 * @return boot true if exists
6585 public function string_exists($identifier, $component);
6588 * Returns a localised list of all country names, sorted by country keys.
6589 * @param bool $returnall return all or just enabled
6590 * @param string $lang moodle translation language, NULL means use current
6591 * @return array two-letter country code => translated name.
6593 public function get_list_of_countries($returnall = false, $lang = NULL);
6596 * Returns a localised list of languages, sorted by code keys.
6598 * @param string $lang moodle translation language, NULL means use current
6599 * @param string $standard language list standard
6600 * iso6392: three-letter language code (ISO 639-2/T) => translated name.
6601 * @return array language code => translated name
6603 public function get_list_of_languages($lang = NULL, $standard = 'iso6392');
6606 * Checks if the translation exists for the language
6608 * @param string $lang moodle translation language code
6609 * @param bool $includeall include also disabled translations
6610 * @return bool true if exists
6612 public function translation_exists($lang, $includeall = true);
6615 * Returns localised list of installed translations
6616 * @param bool $returnall return all or just enabled
6617 * @return array moodle translation code => localised translation name
6619 public function get_list_of_translations($returnall = false);
6622 * Returns localised list of currencies.
6624 * @param string $lang moodle translation language, NULL means use current
6625 * @return array currency code => localised currency name
6627 public function get_list_of_currencies($lang = NULL);
6630 * Load all strings for one component
6631 * @param string $component The module the string is associated with
6632 * @param string $lang
6633 * @param bool $disablecache Do not use caches, force fetching the strings from sources
6634 * @param bool $disablelocal Do not use customized strings in xx_local language packs
6635 * @return array of all string for given component and lang
6637 public function load_component_strings($component, $lang, $disablecache=false, $disablelocal=false);
6640 * Invalidates all caches, should the implementation use any
6641 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
6643 public function reset_caches($phpunitreset = false);
6646 * Returns string revision counter, this is incremented after any
6647 * string cache reset.
6648 * @return int lang string revision counter, -1 if unknown
6650 public function get_revision();
6655 * Standard string_manager implementation
6657 * Implements string_manager with getting and printing localised strings
6659 * @package core
6660 * @category string
6661 * @copyright 2010 Petr Skoda (http://skodak.org)
6662 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6664 class core_string_manager implements string_manager {
6665 /** @var string location of all packs except 'en' */
6666 protected $otherroot;
6667 /** @var string location of all lang pack local modifications */
6668 protected $localroot;
6669 /** @var cache lang string cache - it will be optimised more later */
6670 protected $cache;
6671 /** @var int get_string() counter */
6672 protected $countgetstring = 0;
6673 /** @var bool use disk cache */
6674 protected $usecache;
6675 /** @var array limit list of translations */
6676 protected $translist;
6677 /** @var string location of a file that caches the list of available translations */
6678 protected $menucache;
6681 * Create new instance of string manager
6683 * @param string $otherroot location of downlaoded lang packs - usually $CFG->dataroot/lang
6684 * @param string $localroot usually the same as $otherroot
6685 * @param bool $usecache use disk cache
6686 * @param array $translist limit list of visible translations
6687 * @param string $menucache the location of a file that caches the list of available translations
6689 public function __construct($otherroot, $localroot, $usecache, $translist, $menucache) {
6690 $this->otherroot = $otherroot;
6691 $this->localroot = $localroot;
6692 $this->usecache = $usecache;
6693 $this->translist = $translist;
6694 $this->menucache = $menucache;
6696 if ($this->usecache) {
6697 // We can use a proper cache, establish the cache using the 'String cache' definition.
6698 $this->cache = cache::make('core', 'string');
6699 } else {
6700 // We only want a cache for the length of the request, create a static cache.
6701 $options = array(
6702 'simplekeys' => true,
6703 'simpledata' => true
6705 $this->cache = cache::make_from_params(cache_store::MODE_REQUEST, 'core', 'string', array(), $options);
6710 * Returns list of all explicit parent languages for the given language.
6712 * English (en) is considered as the top implicit parent of all language packs
6713 * and is not included in the returned list. The language itself is appended to the
6714 * end of the list. The method is aware of circular dependency risk.
6716 * @see self::populate_parent_languages()
6717 * @param string $lang the code of the language
6718 * @return array all explicit parent languages with the lang itself appended
6720 public function get_language_dependencies($lang) {
6721 return $this->populate_parent_languages($lang);
6725 * Load all strings for one component
6727 * @param string $component The module the string is associated with
6728 * @param string $lang
6729 * @param bool $disablecache Do not use caches, force fetching the strings from sources
6730 * @param bool $disablelocal Do not use customized strings in xx_local language packs
6731 * @return array of all string for given component and lang
6733 public function load_component_strings($component, $lang, $disablecache=false, $disablelocal=false) {
6734 global $CFG;
6736 list($plugintype, $pluginname) = core_component::normalize_component($component);
6737 if ($plugintype == 'core' and is_null($pluginname)) {
6738 $component = 'core';
6739 } else {
6740 $component = $plugintype . '_' . $pluginname;
6743 $cachekey = $lang.'_'.$component;
6745 if (!$disablecache and !$disablelocal) {
6746 $string = $this->cache->get($cachekey);
6747 if ($string) {
6748 return $string;
6752 // no cache found - let us merge all possible sources of the strings
6753 if ($plugintype === 'core') {
6754 $file = $pluginname;
6755 if ($file === null) {
6756 $file = 'moodle';
6758 $string = array();
6759 // first load english pack
6760 if (!file_exists("$CFG->dirroot/lang/en/$file.php")) {
6761 return array();
6763 include("$CFG->dirroot/lang/en/$file.php");
6764 $originalkeys = array_keys($string);
6765 $originalkeys = array_flip($originalkeys);
6767 // and then corresponding local if present and allowed
6768 if (!$disablelocal and file_exists("$this->localroot/en_local/$file.php")) {
6769 include("$this->localroot/en_local/$file.php");
6771 // now loop through all langs in correct order
6772 $deps = $this->get_language_dependencies($lang);
6773 foreach ($deps as $dep) {
6774 // the main lang string location
6775 if (file_exists("$this->otherroot/$dep/$file.php")) {
6776 include("$this->otherroot/$dep/$file.php");
6778 if (!$disablelocal and file_exists("$this->localroot/{$dep}_local/$file.php")) {
6779 include("$this->localroot/{$dep}_local/$file.php");
6783 } else {
6784 if (!$location = core_component::get_plugin_directory($plugintype, $pluginname) or !is_dir($location)) {
6785 return array();
6787 if ($plugintype === 'mod') {
6788 // bloody mod hack
6789 $file = $pluginname;
6790 } else {
6791 $file = $plugintype . '_' . $pluginname;
6793 $string = array();
6794 // first load English pack
6795 if (!file_exists("$location/lang/en/$file.php")) {
6796 //English pack does not exist, so do not try to load anything else
6797 return array();
6799 include("$location/lang/en/$file.php");
6800 $originalkeys = array_keys($string);
6801 $originalkeys = array_flip($originalkeys);
6802 // and then corresponding local english if present
6803 if (!$disablelocal and file_exists("$this->localroot/en_local/$file.php")) {
6804 include("$this->localroot/en_local/$file.php");
6807 // now loop through all langs in correct order
6808 $deps = $this->get_language_dependencies($lang);
6809 foreach ($deps as $dep) {
6810 // legacy location - used by contrib only
6811 if (file_exists("$location/lang/$dep/$file.php")) {
6812 include("$location/lang/$dep/$file.php");
6814 // the main lang string location
6815 if (file_exists("$this->otherroot/$dep/$file.php")) {
6816 include("$this->otherroot/$dep/$file.php");
6818 // local customisations
6819 if (!$disablelocal and file_exists("$this->localroot/{$dep}_local/$file.php")) {
6820 include("$this->localroot/{$dep}_local/$file.php");
6825 // we do not want any extra strings from other languages - everything must be in en lang pack
6826 $string = array_intersect_key($string, $originalkeys);
6828 if (!$disablelocal) {
6829 // now we have a list of strings from all possible sources. put it into both in-memory and on-disk
6830 // caches so we do not need to do all this merging and dependencies resolving again
6831 $this->cache->set($cachekey, $string);
6833 return $string;
6837 * Does the string actually exist?
6839 * get_string() is throwing debug warnings, sometimes we do not want them
6840 * or we want to display better explanation of the problem.
6841 * Note: Use with care!
6843 * @param string $identifier The identifier of the string to search for
6844 * @param string $component The module the string is associated with
6845 * @return boot true if exists
6847 public function string_exists($identifier, $component) {
6848 $lang = current_language();
6849 $string = $this->load_component_strings($component, $lang);
6850 return isset($string[$identifier]);
6854 * Get String returns a requested string
6856 * @param string $identifier The identifier of the string to search for
6857 * @param string $component The module the string is associated with
6858 * @param string|object|array $a An object, string or number that can be used
6859 * within translation strings
6860 * @param string $lang moodle translation language, NULL means use current
6861 * @return string The String !
6863 public function get_string($identifier, $component = '', $a = NULL, $lang = NULL) {
6864 $this->countgetstring++;
6865 // there are very many uses of these time formating strings without the 'langconfig' component,
6866 // it would not be reasonable to expect that all of them would be converted during 2.0 migration
6867 static $langconfigstrs = array(
6868 'strftimedate' => 1,
6869 'strftimedatefullshort' => 1,
6870 'strftimedateshort' => 1,
6871 'strftimedatetime' => 1,
6872 'strftimedatetimeshort' => 1,
6873 'strftimedaydate' => 1,
6874 'strftimedaydatetime' => 1,
6875 'strftimedayshort' => 1,
6876 'strftimedaytime' => 1,
6877 'strftimemonthyear' => 1,
6878 'strftimerecent' => 1,
6879 'strftimerecentfull' => 1,
6880 'strftimetime' => 1);
6882 if (empty($component)) {
6883 if (isset($langconfigstrs[$identifier])) {
6884 $component = 'langconfig';
6885 } else {
6886 $component = 'moodle';
6890 if ($lang === NULL) {
6891 $lang = current_language();
6894 $string = $this->load_component_strings($component, $lang);
6896 if (!isset($string[$identifier])) {
6897 if ($component === 'pix' or $component === 'core_pix') {
6898 // this component contains only alt tags for emoticons,
6899 // not all of them are supposed to be defined
6900 return '';
6902 if ($identifier === 'parentlanguage' and ($component === 'langconfig' or $component === 'core_langconfig')) {
6903 // parentlanguage is a special string, undefined means use English if not defined
6904 return 'en';
6906 if ($this->usecache) {
6907 // maybe the on-disk cache is dirty - let the last attempt be to find the string in original sources,
6908 // do NOT write the results to disk cache because it may end up in race conditions see MDL-31904
6909 $this->usecache = false;
6910 $string = $this->load_component_strings($component, $lang, true);
6911 $this->usecache = true;
6913 if (!isset($string[$identifier])) {
6914 // the string is still missing - should be fixed by developer
6915 list($plugintype, $pluginname) = core_component::normalize_component($component);
6916 if ($plugintype == 'core') {
6917 $file = "lang/en/{$component}.php";
6918 } else if ($plugintype == 'mod') {
6919 $file = "mod/{$pluginname}/lang/en/{$pluginname}.php";
6920 } else {
6921 $path = core_component::get_plugin_directory($plugintype, $pluginname);
6922 $file = "{$path}/lang/en/{$plugintype}_{$pluginname}.php";
6924 debugging("Invalid get_string() identifier: '{$identifier}' or component '{$component}'. " .
6925 "Perhaps you are missing \$string['{$identifier}'] = ''; in {$file}?", DEBUG_DEVELOPER);
6926 return "[[$identifier]]";
6930 $string = $string[$identifier];
6932 if ($a !== NULL) {
6933 // Process array's and objects (except lang_strings)
6934 if (is_array($a) or (is_object($a) && !($a instanceof lang_string))) {
6935 $a = (array)$a;
6936 $search = array();
6937 $replace = array();
6938 foreach ($a as $key=>$value) {
6939 if (is_int($key)) {
6940 // we do not support numeric keys - sorry!
6941 continue;
6943 if (is_array($value) or (is_object($value) && !($value instanceof lang_string))) {
6944 // we support just string or lang_string as value
6945 continue;
6947 $search[] = '{$a->'.$key.'}';
6948 $replace[] = (string)$value;
6950 if ($search) {
6951 $string = str_replace($search, $replace, $string);
6953 } else {
6954 $string = str_replace('{$a}', (string)$a, $string);
6958 return $string;
6962 * Returns information about the string_manager performance
6964 * @return array
6966 public function get_performance_summary() {
6967 return array(array(
6968 'langcountgetstring' => $this->countgetstring,
6969 ), array(
6970 'langcountgetstring' => 'get_string calls',
6975 * Returns a localised list of all country names, sorted by localised name.
6977 * @param bool $returnall return all or just enabled
6978 * @param string $lang moodle translation language, NULL means use current
6979 * @return array two-letter country code => translated name.
6981 public function get_list_of_countries($returnall = false, $lang = NULL) {
6982 global $CFG;
6984 if ($lang === NULL) {
6985 $lang = current_language();
6988 $countries = $this->load_component_strings('core_countries', $lang);
6989 collatorlib::asort($countries);
6990 if (!$returnall and !empty($CFG->allcountrycodes)) {
6991 $enabled = explode(',', $CFG->allcountrycodes);
6992 $return = array();
6993 foreach ($enabled as $c) {
6994 if (isset($countries[$c])) {
6995 $return[$c] = $countries[$c];
6998 return $return;
7001 return $countries;
7005 * Returns a localised list of languages, sorted by code keys.
7007 * @param string $lang moodle translation language, NULL means use current
7008 * @param string $standard language list standard
7009 * - iso6392: three-letter language code (ISO 639-2/T) => translated name
7010 * - iso6391: two-letter langauge code (ISO 639-1) => translated name
7011 * @return array language code => translated name
7013 public function get_list_of_languages($lang = NULL, $standard = 'iso6391') {
7014 if ($lang === NULL) {
7015 $lang = current_language();
7018 if ($standard === 'iso6392') {
7019 $langs = $this->load_component_strings('core_iso6392', $lang);
7020 ksort($langs);
7021 return $langs;
7023 } else if ($standard === 'iso6391') {
7024 $langs2 = $this->load_component_strings('core_iso6392', $lang);
7025 static $mapping = array('aar' => 'aa', 'abk' => 'ab', 'afr' => 'af', 'aka' => 'ak', 'sqi' => 'sq', 'amh' => 'am', 'ara' => 'ar', 'arg' => 'an', 'hye' => 'hy',
7026 'asm' => 'as', 'ava' => 'av', 'ave' => 'ae', 'aym' => 'ay', 'aze' => 'az', 'bak' => 'ba', 'bam' => 'bm', 'eus' => 'eu', 'bel' => 'be', 'ben' => 'bn', 'bih' => 'bh',
7027 'bis' => 'bi', 'bos' => 'bs', 'bre' => 'br', 'bul' => 'bg', 'mya' => 'my', 'cat' => 'ca', 'cha' => 'ch', 'che' => 'ce', 'zho' => 'zh', 'chu' => 'cu', 'chv' => 'cv',
7028 'cor' => 'kw', 'cos' => 'co', 'cre' => 'cr', 'ces' => 'cs', 'dan' => 'da', 'div' => 'dv', 'nld' => 'nl', 'dzo' => 'dz', 'eng' => 'en', 'epo' => 'eo', 'est' => 'et',
7029 'ewe' => 'ee', 'fao' => 'fo', 'fij' => 'fj', 'fin' => 'fi', 'fra' => 'fr', 'fry' => 'fy', 'ful' => 'ff', 'kat' => 'ka', 'deu' => 'de', 'gla' => 'gd', 'gle' => 'ga',
7030 'glg' => 'gl', 'glv' => 'gv', 'ell' => 'el', 'grn' => 'gn', 'guj' => 'gu', 'hat' => 'ht', 'hau' => 'ha', 'heb' => 'he', 'her' => 'hz', 'hin' => 'hi', 'hmo' => 'ho',
7031 'hrv' => 'hr', 'hun' => 'hu', 'ibo' => 'ig', 'isl' => 'is', 'ido' => 'io', 'iii' => 'ii', 'iku' => 'iu', 'ile' => 'ie', 'ina' => 'ia', 'ind' => 'id', 'ipk' => 'ik',
7032 'ita' => 'it', 'jav' => 'jv', 'jpn' => 'ja', 'kal' => 'kl', 'kan' => 'kn', 'kas' => 'ks', 'kau' => 'kr', 'kaz' => 'kk', 'khm' => 'km', 'kik' => 'ki', 'kin' => 'rw',
7033 'kir' => 'ky', 'kom' => 'kv', 'kon' => 'kg', 'kor' => 'ko', 'kua' => 'kj', 'kur' => 'ku', 'lao' => 'lo', 'lat' => 'la', 'lav' => 'lv', 'lim' => 'li', 'lin' => 'ln',
7034 'lit' => 'lt', 'ltz' => 'lb', 'lub' => 'lu', 'lug' => 'lg', 'mkd' => 'mk', 'mah' => 'mh', 'mal' => 'ml', 'mri' => 'mi', 'mar' => 'mr', 'msa' => 'ms', 'mlg' => 'mg',
7035 'mlt' => 'mt', 'mon' => 'mn', 'nau' => 'na', 'nav' => 'nv', 'nbl' => 'nr', 'nde' => 'nd', 'ndo' => 'ng', 'nep' => 'ne', 'nno' => 'nn', 'nob' => 'nb', 'nor' => 'no',
7036 'nya' => 'ny', 'oci' => 'oc', 'oji' => 'oj', 'ori' => 'or', 'orm' => 'om', 'oss' => 'os', 'pan' => 'pa', 'fas' => 'fa', 'pli' => 'pi', 'pol' => 'pl', 'por' => 'pt',
7037 'pus' => 'ps', 'que' => 'qu', 'roh' => 'rm', 'ron' => 'ro', 'run' => 'rn', 'rus' => 'ru', 'sag' => 'sg', 'san' => 'sa', 'sin' => 'si', 'slk' => 'sk', 'slv' => 'sl',
7038 'sme' => 'se', 'smo' => 'sm', 'sna' => 'sn', 'snd' => 'sd', 'som' => 'so', 'sot' => 'st', 'spa' => 'es', 'srd' => 'sc', 'srp' => 'sr', 'ssw' => 'ss', 'sun' => 'su',
7039 'swa' => 'sw', 'swe' => 'sv', 'tah' => 'ty', 'tam' => 'ta', 'tat' => 'tt', 'tel' => 'te', 'tgk' => 'tg', 'tgl' => 'tl', 'tha' => 'th', 'bod' => 'bo', 'tir' => 'ti',
7040 'ton' => 'to', 'tsn' => 'tn', 'tso' => 'ts', 'tuk' => 'tk', 'tur' => 'tr', 'twi' => 'tw', 'uig' => 'ug', 'ukr' => 'uk', 'urd' => 'ur', 'uzb' => 'uz', 'ven' => 've',
7041 'vie' => 'vi', 'vol' => 'vo', 'cym' => 'cy', 'wln' => 'wa', 'wol' => 'wo', 'xho' => 'xh', 'yid' => 'yi', 'yor' => 'yo', 'zha' => 'za', 'zul' => 'zu');
7042 $langs1 = array();
7043 foreach ($mapping as $c2=>$c1) {
7044 $langs1[$c1] = $langs2[$c2];
7046 ksort($langs1);
7047 return $langs1;
7049 } else {
7050 debugging('Unsupported $standard parameter in get_list_of_languages() method: '.$standard);
7053 return array();
7057 * Checks if the translation exists for the language
7059 * @param string $lang moodle translation language code
7060 * @param bool $includeall include also disabled translations
7061 * @return bool true if exists
7063 public function translation_exists($lang, $includeall = true) {
7065 if (strpos($lang, '_local') !== false) {
7066 // _local packs are not real translations
7067 return false;
7069 if (!$includeall and !empty($this->translist)) {
7070 if (!in_array($lang, $this->translist)) {
7071 return false;
7074 if ($lang === 'en') {
7075 // part of distribution
7076 return true;
7078 return file_exists("$this->otherroot/$lang/langconfig.php");
7082 * Returns localised list of installed translations
7084 * @param bool $returnall return all or just enabled
7085 * @return array moodle translation code => localised translation name
7087 public function get_list_of_translations($returnall = false) {
7088 global $CFG;
7090 $languages = array();
7092 if (!empty($CFG->langcache) and is_readable($this->menucache)) {
7093 // try to re-use the cached list of all available languages
7094 $cachedlist = json_decode(file_get_contents($this->menucache), true);
7096 if (is_array($cachedlist) and !empty($cachedlist)) {
7097 // the cache file is restored correctly
7099 if (!$returnall and !empty($this->translist)) {
7100 // return just enabled translations
7101 foreach ($cachedlist as $langcode => $langname) {
7102 if (in_array($langcode, $this->translist)) {
7103 $languages[$langcode] = $langname;
7106 return $languages;
7108 } else {
7109 // return all translations
7110 return $cachedlist;
7115 // the cached list of languages is not available, let us populate the list
7117 if (!$returnall and !empty($this->translist)) {
7118 // return only some translations
7119 foreach ($this->translist as $lang) {
7120 $lang = trim($lang); //Just trim spaces to be a bit more permissive
7121 if (strstr($lang, '_local') !== false) {
7122 continue;
7124 if (strstr($lang, '_utf8') !== false) {
7125 continue;
7127 if ($lang !== 'en' and !file_exists("$this->otherroot/$lang/langconfig.php")) {
7128 // some broken or missing lang - can not switch to it anyway
7129 continue;
7131 $string = $this->load_component_strings('langconfig', $lang);
7132 if (!empty($string['thislanguage'])) {
7133 $languages[$lang] = $string['thislanguage'].' ('. $lang .')';
7135 unset($string);
7138 } else {
7139 // return all languages available in system
7140 $langdirs = get_list_of_plugins('', '', $this->otherroot);
7142 $langdirs = array_merge($langdirs, array("$CFG->dirroot/lang/en"=>'en'));
7143 // Sort all
7145 // Loop through all langs and get info
7146 foreach ($langdirs as $lang) {
7147 if (strstr($lang, '_local') !== false) {
7148 continue;
7150 if (strstr($lang, '_utf8') !== false) {
7151 continue;
7153 $string = $this->load_component_strings('langconfig', $lang);
7154 if (!empty($string['thislanguage'])) {
7155 $languages[$lang] = $string['thislanguage'].' ('. $lang .')';
7157 unset($string);
7160 if (!empty($CFG->langcache) and !empty($this->menucache)) {
7161 // cache the list so that it can be used next time
7162 collatorlib::asort($languages);
7163 check_dir_exists(dirname($this->menucache), true, true);
7164 file_put_contents($this->menucache, json_encode($languages));
7168 collatorlib::asort($languages);
7170 return $languages;
7174 * Returns localised list of currencies.
7176 * @param string $lang moodle translation language, NULL means use current
7177 * @return array currency code => localised currency name
7179 public function get_list_of_currencies($lang = NULL) {
7180 if ($lang === NULL) {
7181 $lang = current_language();
7184 $currencies = $this->load_component_strings('core_currencies', $lang);
7185 asort($currencies);
7187 return $currencies;
7191 * Clears both in-memory and on-disk caches
7192 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
7194 public function reset_caches($phpunitreset = false) {
7195 global $CFG;
7196 require_once("$CFG->libdir/filelib.php");
7198 // clear the on-disk disk with aggregated string files
7199 $this->cache->purge();
7201 if (!$phpunitreset) {
7202 // Increment the revision counter.
7203 $langrev = get_config('core', 'langrev');
7204 $next = time();
7205 if ($langrev !== false and $next <= $langrev and $langrev - $next < 60*60) {
7206 // This resolves problems when reset is requested repeatedly within 1s,
7207 // the < 1h condition prevents accidental switching to future dates
7208 // because we might not recover from it.
7209 $next = $langrev+1;
7211 set_config('langrev', $next);
7214 // clear the cache containing the list of available translations
7215 // and re-populate it again
7216 fulldelete($this->menucache);
7217 $this->get_list_of_translations(true);
7221 * Returns string revision counter, this is incremented after any
7222 * string cache reset.
7223 * @return int lang string revision counter, -1 if unknown
7225 public function get_revision() {
7226 global $CFG;
7227 if (isset($CFG->langrev)) {
7228 return (int)$CFG->langrev;
7229 } else {
7230 return -1;
7234 /// End of external API ////////////////////////////////////////////////////
7237 * Helper method that recursively loads all parents of the given language.
7239 * @see self::get_language_dependencies()
7240 * @param string $lang language code
7241 * @param array $stack list of parent languages already populated in previous recursive calls
7242 * @return array list of all parents of the given language with the $lang itself added as the last element
7244 protected function populate_parent_languages($lang, array $stack = array()) {
7246 // English does not have a parent language.
7247 if ($lang === 'en') {
7248 return $stack;
7251 // Prevent circular dependency (and thence the infinitive recursion loop).
7252 if (in_array($lang, $stack)) {
7253 return $stack;
7256 // Load language configuration and look for the explicit parent language.
7257 if (!file_exists("$this->otherroot/$lang/langconfig.php")) {
7258 return $stack;
7260 $string = array();
7261 include("$this->otherroot/$lang/langconfig.php");
7263 if (empty($string['parentlanguage']) or $string['parentlanguage'] === 'en') {
7264 unset($string);
7265 return array_merge(array($lang), $stack);
7267 } else {
7268 $parentlang = $string['parentlanguage'];
7269 unset($string);
7270 return $this->populate_parent_languages($parentlang, array_merge(array($lang), $stack));
7277 * Fetches minimum strings for installation
7279 * Minimalistic string fetching implementation
7280 * that is used in installer before we fetch the wanted
7281 * language pack from moodle.org lang download site.
7283 * @package core
7284 * @copyright 2010 Petr Skoda (http://skodak.org)
7285 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7287 class install_string_manager implements string_manager {
7288 /** @var string location of pre-install packs for all langs */
7289 protected $installroot;
7292 * Crate new instance of install string manager
7294 public function __construct() {
7295 global $CFG;
7296 $this->installroot = "$CFG->dirroot/install/lang";
7300 * Load all strings for one component
7301 * @param string $component The module the string is associated with
7302 * @param string $lang
7303 * @param bool $disablecache Do not use caches, force fetching the strings from sources
7304 * @param bool $disablelocal Do not use customized strings in xx_local language packs
7305 * @return array of all string for given component and lang
7307 public function load_component_strings($component, $lang, $disablecache=false, $disablelocal=false) {
7308 // not needed in installer
7309 return array();
7313 * Does the string actually exist?
7315 * get_string() is throwing debug warnings, sometimes we do not want them
7316 * or we want to display better explanation of the problem.
7318 * Use with care!
7320 * @param string $identifier The identifier of the string to search for
7321 * @param string $component The module the string is associated with
7322 * @return boot true if exists
7324 public function string_exists($identifier, $component) {
7325 // simple old style hack ;)
7326 $str = get_string($identifier, $component);
7327 return (strpos($str, '[[') === false);
7331 * Get String returns a requested string
7333 * @param string $identifier The identifier of the string to search for
7334 * @param string $component The module the string is associated with
7335 * @param string|object|array $a An object, string or number that can be used
7336 * within translation strings
7337 * @param string $lang moodle translation language, NULL means use current
7338 * @return string The String !
7340 public function get_string($identifier, $component = '', $a = NULL, $lang = NULL) {
7341 if (!$component) {
7342 $component = 'moodle';
7345 if ($lang === NULL) {
7346 $lang = current_language();
7349 //get parent lang
7350 $parent = '';
7351 if ($lang !== 'en' and $identifier !== 'parentlanguage' and $component !== 'langconfig') {
7352 if (file_exists("$this->installroot/$lang/langconfig.php")) {
7353 $string = array();
7354 include("$this->installroot/$lang/langconfig.php");
7355 if (isset($string['parentlanguage'])) {
7356 $parent = $string['parentlanguage'];
7358 unset($string);
7362 // include en string first
7363 if (!file_exists("$this->installroot/en/$component.php")) {
7364 return "[[$identifier]]";
7366 $string = array();
7367 include("$this->installroot/en/$component.php");
7369 // now override en with parent if defined
7370 if ($parent and $parent !== 'en' and file_exists("$this->installroot/$parent/$component.php")) {
7371 include("$this->installroot/$parent/$component.php");
7374 // finally override with requested language
7375 if ($lang !== 'en' and file_exists("$this->installroot/$lang/$component.php")) {
7376 include("$this->installroot/$lang/$component.php");
7379 if (!isset($string[$identifier])) {
7380 return "[[$identifier]]";
7383 $string = $string[$identifier];
7385 if ($a !== NULL) {
7386 if (is_object($a) or is_array($a)) {
7387 $a = (array)$a;
7388 $search = array();
7389 $replace = array();
7390 foreach ($a as $key=>$value) {
7391 if (is_int($key)) {
7392 // we do not support numeric keys - sorry!
7393 continue;
7395 $search[] = '{$a->'.$key.'}';
7396 $replace[] = (string)$value;
7398 if ($search) {
7399 $string = str_replace($search, $replace, $string);
7401 } else {
7402 $string = str_replace('{$a}', (string)$a, $string);
7406 return $string;
7410 * Returns a localised list of all country names, sorted by country keys.
7412 * @param bool $returnall return all or just enabled
7413 * @param string $lang moodle translation language, NULL means use current
7414 * @return array two-letter country code => translated name.
7416 public function get_list_of_countries($returnall = false, $lang = NULL) {
7417 //not used in installer
7418 return array();
7422 * Returns a localised list of languages, sorted by code keys.
7424 * @param string $lang moodle translation language, NULL means use current
7425 * @param string $standard language list standard
7426 * iso6392: three-letter language code (ISO 639-2/T) => translated name.
7427 * @return array language code => translated name
7429 public function get_list_of_languages($lang = NULL, $standard = 'iso6392') {
7430 //not used in installer
7431 return array();
7435 * Checks if the translation exists for the language
7437 * @param string $lang moodle translation language code
7438 * @param bool $includeall include also disabled translations
7439 * @return bool true if exists
7441 public function translation_exists($lang, $includeall = true) {
7442 return file_exists($this->installroot.'/'.$lang.'/langconfig.php');
7446 * Returns localised list of installed translations
7447 * @param bool $returnall return all or just enabled
7448 * @return array moodle translation code => localised translation name
7450 public function get_list_of_translations($returnall = false) {
7451 // return all is ignored here - we need to know all langs in installer
7452 $languages = array();
7453 // Get raw list of lang directories
7454 $langdirs = get_list_of_plugins('install/lang');
7455 asort($langdirs);
7456 // Get some info from each lang
7457 foreach ($langdirs as $lang) {
7458 if (file_exists($this->installroot.'/'.$lang.'/langconfig.php')) {
7459 $string = array();
7460 include($this->installroot.'/'.$lang.'/langconfig.php');
7461 if (!empty($string['thislanguage'])) {
7462 $languages[$lang] = $string['thislanguage'].' ('.$lang.')';
7466 // Return array
7467 return $languages;
7471 * Returns localised list of currencies.
7473 * @param string $lang moodle translation language, NULL means use current
7474 * @return array currency code => localised currency name
7476 public function get_list_of_currencies($lang = NULL) {
7477 // not used in installer
7478 return array();
7482 * This implementation does not use any caches
7483 * @param bool $phpunitreset true means called from our PHPUnit integration test reset
7485 public function reset_caches($phpunitreset = false) {
7486 // Nothing to do.
7490 * Returns string revision counter, this is incremented after any
7491 * string cache reset.
7492 * @return int lang string revision counter, -1 if unknown
7494 public function get_revision() {
7495 return -1;
7501 * Returns a localized string.
7503 * Returns the translated string specified by $identifier as
7504 * for $module. Uses the same format files as STphp.
7505 * $a is an object, string or number that can be used
7506 * within translation strings
7508 * eg 'hello {$a->firstname} {$a->lastname}'
7509 * or 'hello {$a}'
7511 * If you would like to directly echo the localized string use
7512 * the function {@link print_string()}
7514 * Example usage of this function involves finding the string you would
7515 * like a local equivalent of and using its identifier and module information
7516 * to retrieve it.<br/>
7517 * If you open moodle/lang/en/moodle.php and look near line 278
7518 * you will find a string to prompt a user for their word for 'course'
7519 * <code>
7520 * $string['course'] = 'Course';
7521 * </code>
7522 * So if you want to display the string 'Course'
7523 * in any language that supports it on your site
7524 * you just need to use the identifier 'course'
7525 * <code>
7526 * $mystring = '<strong>'. get_string('course') .'</strong>';
7527 * or
7528 * </code>
7529 * If the string you want is in another file you'd take a slightly
7530 * different approach. Looking in moodle/lang/en/calendar.php you find
7531 * around line 75:
7532 * <code>
7533 * $string['typecourse'] = 'Course event';
7534 * </code>
7535 * If you want to display the string "Course event" in any language
7536 * supported you would use the identifier 'typecourse' and the module 'calendar'
7537 * (because it is in the file calendar.php):
7538 * <code>
7539 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7540 * </code>
7542 * As a last resort, should the identifier fail to map to a string
7543 * the returned string will be [[ $identifier ]]
7545 * In Moodle 2.3 there is a new argument to this function $lazyload.
7546 * Setting $lazyload to true causes get_string to return a lang_string object
7547 * rather than the string itself. The fetching of the string is then put off until
7548 * the string object is first used. The object can be used by calling it's out
7549 * method or by casting the object to a string, either directly e.g.
7550 * (string)$stringobject
7551 * or indirectly by using the string within another string or echoing it out e.g.
7552 * echo $stringobject
7553 * return "<p>{$stringobject}</p>";
7554 * It is worth noting that using $lazyload and attempting to use the string as an
7555 * array key will cause a fatal error as objects cannot be used as array keys.
7556 * But you should never do that anyway!
7557 * For more information {@see lang_string}
7559 * @category string
7560 * @param string $identifier The key identifier for the localized string
7561 * @param string $component The module where the key identifier is stored,
7562 * usually expressed as the filename in the language pack without the
7563 * .php on the end but can also be written as mod/forum or grade/export/xls.
7564 * If none is specified then moodle.php is used.
7565 * @param string|object|array $a An object, string or number that can be used
7566 * within translation strings
7567 * @param bool $lazyload If set to true a string object is returned instead of
7568 * the string itself. The string then isn't calculated until it is first used.
7569 * @return string The localized string.
7571 function get_string($identifier, $component = '', $a = NULL, $lazyload = false) {
7572 global $CFG;
7574 // If the lazy load argument has been supplied return a lang_string object
7575 // instead.
7576 // We need to make sure it is true (and a bool) as you will see below there
7577 // used to be a forth argument at one point.
7578 if ($lazyload === true) {
7579 return new lang_string($identifier, $component, $a);
7582 if (debugging('', DEBUG_DEVELOPER) && clean_param($identifier, PARAM_STRINGID) === '') {
7583 throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.');
7586 // There is now a forth argument again, this time it is a boolean however so
7587 // we can still check for the old extralocations parameter.
7588 if (!is_bool($lazyload) && !empty($lazyload)) {
7589 debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7592 if (strpos($component, '/') !== false) {
7593 debugging('The module name you passed to get_string is the deprecated format ' .
7594 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7595 $componentpath = explode('/', $component);
7597 switch ($componentpath[0]) {
7598 case 'mod':
7599 $component = $componentpath[1];
7600 break;
7601 case 'blocks':
7602 case 'block':
7603 $component = 'block_'.$componentpath[1];
7604 break;
7605 case 'enrol':
7606 $component = 'enrol_'.$componentpath[1];
7607 break;
7608 case 'format':
7609 $component = 'format_'.$componentpath[1];
7610 break;
7611 case 'grade':
7612 $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7613 break;
7617 $result = get_string_manager()->get_string($identifier, $component, $a);
7619 // Debugging feature lets you display string identifier and component
7620 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7621 $result .= ' {' . $identifier . '/' . $component . '}';
7623 return $result;
7627 * Converts an array of strings to their localized value.
7629 * @param array $array An array of strings
7630 * @param string $component The language module that these strings can be found in.
7631 * @return stdClass translated strings.
7633 function get_strings($array, $component = '') {
7634 $string = new stdClass;
7635 foreach ($array as $item) {
7636 $string->$item = get_string($item, $component);
7638 return $string;
7642 * Prints out a translated string.
7644 * Prints out a translated string using the return value from the {@link get_string()} function.
7646 * Example usage of this function when the string is in the moodle.php file:<br/>
7647 * <code>
7648 * echo '<strong>';
7649 * print_string('course');
7650 * echo '</strong>';
7651 * </code>
7653 * Example usage of this function when the string is not in the moodle.php file:<br/>
7654 * <code>
7655 * echo '<h1>';
7656 * print_string('typecourse', 'calendar');
7657 * echo '</h1>';
7658 * </code>
7660 * @category string
7661 * @param string $identifier The key identifier for the localized string
7662 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7663 * @param string|object|array $a An object, string or number that can be used within translation strings
7665 function print_string($identifier, $component = '', $a = NULL) {
7666 echo get_string($identifier, $component, $a);
7670 * Returns a list of charset codes
7672 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7673 * (checking that such charset is supported by the texlib library!)
7675 * @return array And associative array with contents in the form of charset => charset
7677 function get_list_of_charsets() {
7679 $charsets = array(
7680 'EUC-JP' => 'EUC-JP',
7681 'ISO-2022-JP'=> 'ISO-2022-JP',
7682 'ISO-8859-1' => 'ISO-8859-1',
7683 'SHIFT-JIS' => 'SHIFT-JIS',
7684 'GB2312' => 'GB2312',
7685 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
7686 'UTF-8' => 'UTF-8');
7688 asort($charsets);
7690 return $charsets;
7694 * Returns a list of valid and compatible themes
7696 * @return array
7698 function get_list_of_themes() {
7699 global $CFG;
7701 $themes = array();
7703 if (!empty($CFG->themelist)) { // use admin's list of themes
7704 $themelist = explode(',', $CFG->themelist);
7705 } else {
7706 $themelist = array_keys(core_component::get_plugin_list("theme"));
7709 foreach ($themelist as $key => $themename) {
7710 $theme = theme_config::load($themename);
7711 $themes[$themename] = $theme;
7714 collatorlib::asort_objects_by_method($themes, 'get_theme_name');
7716 return $themes;
7720 * Returns a list of timezones in the current language
7722 * @global object
7723 * @global object
7724 * @return array
7726 function get_list_of_timezones() {
7727 global $CFG, $DB;
7729 static $timezones;
7731 if (!empty($timezones)) { // This function has been called recently
7732 return $timezones;
7735 $timezones = array();
7737 if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
7738 foreach($rawtimezones as $timezone) {
7739 if (!empty($timezone->name)) {
7740 if (get_string_manager()->string_exists(strtolower($timezone->name), 'timezones')) {
7741 $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
7742 } else {
7743 $timezones[$timezone->name] = $timezone->name;
7745 if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found
7746 $timezones[$timezone->name] = $timezone->name;
7752 asort($timezones);
7754 for ($i = -13; $i <= 13; $i += .5) {
7755 $tzstring = 'UTC';
7756 if ($i < 0) {
7757 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
7758 } else if ($i > 0) {
7759 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
7760 } else {
7761 $timezones[sprintf("%.1f", $i)] = $tzstring;
7765 return $timezones;
7769 * Factory function for emoticon_manager
7771 * @return emoticon_manager singleton
7773 function get_emoticon_manager() {
7774 static $singleton = null;
7776 if (is_null($singleton)) {
7777 $singleton = new emoticon_manager();
7780 return $singleton;
7784 * Provides core support for plugins that have to deal with
7785 * emoticons (like HTML editor or emoticon filter).
7787 * Whenever this manager mentiones 'emoticon object', the following data
7788 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7789 * altidentifier and altcomponent
7791 * @see admin_setting_emoticons
7793 class emoticon_manager {
7796 * Returns the currently enabled emoticons
7798 * @return array of emoticon objects
7800 public function get_emoticons() {
7801 global $CFG;
7803 if (empty($CFG->emoticons)) {
7804 return array();
7807 $emoticons = $this->decode_stored_config($CFG->emoticons);
7809 if (!is_array($emoticons)) {
7810 // something is wrong with the format of stored setting
7811 debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7812 return array();
7815 return $emoticons;
7819 * Converts emoticon object into renderable pix_emoticon object
7821 * @param stdClass $emoticon emoticon object
7822 * @param array $attributes explicit HTML attributes to set
7823 * @return pix_emoticon
7825 public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7826 $stringmanager = get_string_manager();
7827 if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7828 $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7829 } else {
7830 $alt = s($emoticon->text);
7832 return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7836 * Encodes the array of emoticon objects into a string storable in config table
7838 * @see self::decode_stored_config()
7839 * @param array $emoticons array of emtocion objects
7840 * @return string
7842 public function encode_stored_config(array $emoticons) {
7843 return json_encode($emoticons);
7847 * Decodes the string into an array of emoticon objects
7849 * @see self::encode_stored_config()
7850 * @param string $encoded
7851 * @return string|null
7853 public function decode_stored_config($encoded) {
7854 $decoded = json_decode($encoded);
7855 if (!is_array($decoded)) {
7856 return null;
7858 return $decoded;
7862 * Returns default set of emoticons supported by Moodle
7864 * @return array of sdtClasses
7866 public function default_emoticons() {
7867 return array(
7868 $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7869 $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7870 $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7871 $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7872 $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7873 $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7874 $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7875 $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7876 $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7877 $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7878 $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7879 $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7880 $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7881 $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7882 $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7883 $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7884 $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7885 $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7886 $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7887 $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7888 $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7889 $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7890 $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7891 $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7892 $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7893 $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7894 $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7895 $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7896 $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7897 $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7902 * Helper method preparing the stdClass with the emoticon properties
7904 * @param string|array $text or array of strings
7905 * @param string $imagename to be used by {@see pix_emoticon}
7906 * @param string $altidentifier alternative string identifier, null for no alt
7907 * @param array $altcomponent where the alternative string is defined
7908 * @param string $imagecomponent to be used by {@see pix_emoticon}
7909 * @return stdClass
7911 protected function prepare_emoticon_object($text, $imagename, $altidentifier = null, $altcomponent = 'core_pix', $imagecomponent = 'core') {
7912 return (object)array(
7913 'text' => $text,
7914 'imagename' => $imagename,
7915 'imagecomponent' => $imagecomponent,
7916 'altidentifier' => $altidentifier,
7917 'altcomponent' => $altcomponent,
7922 /// ENCRYPTION ////////////////////////////////////////////////
7925 * rc4encrypt
7927 * Please note that in this version of moodle that the default for rc4encryption is
7928 * using the slightly more secure password key. There may be an issue when upgrading
7929 * from an older version of moodle.
7931 * @todo MDL-31836 Remove the old password key in version 2.4
7932 * Code also needs to be changed in sessionlib.php
7933 * @see get_moodle_cookie()
7934 * @see set_moodle_cookie()
7936 * @param string $data Data to encrypt.
7937 * @param bool $usesecurekey Lets us know if we are using the old or new secure password key.
7938 * @return string The now encrypted data.
7940 function rc4encrypt($data, $usesecurekey = true) {
7941 if (!$usesecurekey) {
7942 $passwordkey = 'nfgjeingjk';
7943 } else {
7944 $passwordkey = get_site_identifier();
7946 return endecrypt($passwordkey, $data, '');
7950 * rc4decrypt
7952 * Please note that in this version of moodle that the default for rc4encryption is
7953 * using the slightly more secure password key. There may be an issue when upgrading
7954 * from an older version of moodle.
7956 * @todo MDL-31836 Remove the old password key in version 2.4
7957 * Code also needs to be changed in sessionlib.php
7958 * @see get_moodle_cookie()
7959 * @see set_moodle_cookie()
7961 * @param string $data Data to decrypt.
7962 * @param bool $usesecurekey Lets us know if we are using the old or new secure password key.
7963 * @return string The now decrypted data.
7965 function rc4decrypt($data, $usesecurekey = true) {
7966 if (!$usesecurekey) {
7967 $passwordkey = 'nfgjeingjk';
7968 } else {
7969 $passwordkey = get_site_identifier();
7971 return endecrypt($passwordkey, $data, 'de');
7975 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7977 * @todo Finish documenting this function
7979 * @param string $pwd The password to use when encrypting or decrypting
7980 * @param string $data The data to be decrypted/encrypted
7981 * @param string $case Either 'de' for decrypt or '' for encrypt
7982 * @return string
7984 function endecrypt ($pwd, $data, $case) {
7986 if ($case == 'de') {
7987 $data = urldecode($data);
7990 $key[] = '';
7991 $box[] = '';
7992 $temp_swap = '';
7993 $pwd_length = 0;
7995 $pwd_length = strlen($pwd);
7997 for ($i = 0; $i <= 255; $i++) {
7998 $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
7999 $box[$i] = $i;
8002 $x = 0;
8004 for ($i = 0; $i <= 255; $i++) {
8005 $x = ($x + $box[$i] + $key[$i]) % 256;
8006 $temp_swap = $box[$i];
8007 $box[$i] = $box[$x];
8008 $box[$x] = $temp_swap;
8011 $temp = '';
8012 $k = '';
8014 $cipherby = '';
8015 $cipher = '';
8017 $a = 0;
8018 $j = 0;
8020 for ($i = 0; $i < strlen($data); $i++) {
8021 $a = ($a + 1) % 256;
8022 $j = ($j + $box[$a]) % 256;
8023 $temp = $box[$a];
8024 $box[$a] = $box[$j];
8025 $box[$j] = $temp;
8026 $k = $box[(($box[$a] + $box[$j]) % 256)];
8027 $cipherby = ord(substr($data, $i, 1)) ^ $k;
8028 $cipher .= chr($cipherby);
8031 if ($case == 'de') {
8032 $cipher = urldecode(urlencode($cipher));
8033 } else {
8034 $cipher = urlencode($cipher);
8037 return $cipher;
8040 /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
8043 * This method validates a plug name. It is much faster than calling clean_param.
8044 * @param string $name a string that might be a plugin name.
8045 * @return bool if this string is a valid plugin name.
8047 function is_valid_plugin_name($name) {
8048 // This does not work for 'mod', bad luck, use any other type.
8049 return core_component::is_valid_plugin_name('tool', $name);
8053 * Get a list of all the plugins of a given type that contain a particular file.
8054 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
8055 * @param string $file the name of file that must be present in the plugin.
8056 * (e.g. 'view.php', 'db/install.xml').
8057 * @param bool $include if true (default false), the file will be include_once-ed if found.
8058 * @return array with plugin name as keys (e.g. 'forum', 'courselist') and the path
8059 * to the file relative to dirroot as value (e.g. "$CFG->dirroot/mod/forum/view.php").
8061 function get_plugin_list_with_file($plugintype, $file, $include = false) {
8062 global $CFG; // Necessary in case it is referenced by include()d PHP scripts.
8064 $plugins = array();
8066 foreach (core_component::get_plugin_list($plugintype) as $plugin => $dir) {
8067 $path = $dir . '/' . $file;
8068 if (file_exists($path)) {
8069 if ($include) {
8070 include_once($path);
8072 $plugins[$plugin] = $path;
8076 return $plugins;
8080 * Get a list of all the plugins of a given type that define a certain API function
8081 * in a certain file. The plugin component names and function names are returned.
8083 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
8084 * @param string $function the part of the name of the function after the
8085 * frankenstyle prefix. e.g 'hook' if you are looking for functions with
8086 * names like report_courselist_hook.
8087 * @param string $file the name of file within the plugin that defines the
8088 * function. Defaults to lib.php.
8089 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
8090 * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
8092 function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
8093 $pluginfunctions = array();
8094 foreach (get_plugin_list_with_file($plugintype, $file, true) as $plugin => $notused) {
8095 $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
8097 if (function_exists($fullfunction)) {
8098 // Function exists with standard name. Store, indexed by
8099 // frankenstyle name of plugin
8100 $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
8102 } else if ($plugintype === 'mod') {
8103 // For modules, we also allow plugin without full frankenstyle
8104 // but just starting with the module name
8105 $shortfunction = $plugin . '_' . $function;
8106 if (function_exists($shortfunction)) {
8107 $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
8111 return $pluginfunctions;
8115 * Lists plugin-like directories within specified directory
8117 * This function was originally used for standard Moodle plugins, please use
8118 * new get_plugin_list() now.
8120 * This function is used for general directory listing and backwards compatility.
8122 * @param string $directory relative directory from root
8123 * @param string $exclude dir name to exclude from the list (defaults to none)
8124 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
8125 * @return array Sorted array of directory names found under the requested parameters
8127 function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
8128 global $CFG;
8130 $plugins = array();
8132 if (empty($basedir)) {
8133 $basedir = $CFG->dirroot .'/'. $directory;
8135 } else {
8136 $basedir = $basedir .'/'. $directory;
8139 if (empty($exclude) and debugging('', DEBUG_DEVELOPER)) {
8140 // Make sure devs do not use this to list normal plugins,
8141 // this is intended for general directories that are not plugins!
8143 $subtypes = core_component::get_plugin_types();
8144 if (in_array($basedir, $subtypes)) {
8145 debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
8147 unset($subtypes);
8150 if (file_exists($basedir) && filetype($basedir) == 'dir') {
8151 if (!$dirhandle = opendir($basedir)) {
8152 debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
8153 return array();
8155 while (false !== ($dir = readdir($dirhandle))) {
8156 $firstchar = substr($dir, 0, 1);
8157 if ($firstchar === '.' or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
8158 continue;
8160 if (filetype($basedir .'/'. $dir) != 'dir') {
8161 continue;
8163 $plugins[] = $dir;
8165 closedir($dirhandle);
8167 if ($plugins) {
8168 asort($plugins);
8170 return $plugins;
8174 * Invoke plugin's callback functions
8176 * @param string $type plugin type e.g. 'mod'
8177 * @param string $name plugin name
8178 * @param string $feature feature name
8179 * @param string $action feature's action
8180 * @param array $params parameters of callback function, should be an array
8181 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
8182 * @return mixed
8184 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
8186 function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
8187 return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
8191 * Invoke component's callback functions
8193 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
8194 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
8195 * @param array $params parameters of callback function
8196 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
8197 * @return mixed
8199 function component_callback($component, $function, array $params = array(), $default = null) {
8200 global $CFG; // this is needed for require_once() below
8202 $cleancomponent = clean_param($component, PARAM_COMPONENT);
8203 if (empty($cleancomponent)) {
8204 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8206 $component = $cleancomponent;
8208 list($type, $name) = core_component::normalize_component($component);
8209 $component = $type . '_' . $name;
8211 $oldfunction = $name.'_'.$function;
8212 $function = $component.'_'.$function;
8214 $dir = core_component::get_component_directory($component);
8215 if (empty($dir)) {
8216 throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8219 // Load library and look for function
8220 if (file_exists($dir.'/lib.php')) {
8221 require_once($dir.'/lib.php');
8224 if (!function_exists($function) and function_exists($oldfunction)) {
8225 if ($type !== 'mod' and $type !== 'core') {
8226 debugging("Please use new function name $function instead of legacy $oldfunction");
8228 $function = $oldfunction;
8231 if (function_exists($function)) {
8232 // Function exists, so just return function result
8233 $ret = call_user_func_array($function, $params);
8234 if (is_null($ret)) {
8235 return $default;
8236 } else {
8237 return $ret;
8240 return $default;
8244 * Checks whether a plugin supports a specified feature.
8246 * @param string $type Plugin type e.g. 'mod'
8247 * @param string $name Plugin name e.g. 'forum'
8248 * @param string $feature Feature code (FEATURE_xx constant)
8249 * @param mixed $default default value if feature support unknown
8250 * @return mixed Feature result (false if not supported, null if feature is unknown,
8251 * otherwise usually true but may have other feature-specific value such as array)
8253 function plugin_supports($type, $name, $feature, $default = NULL) {
8254 global $CFG;
8256 if ($type === 'mod' and $name === 'NEWMODULE') {
8257 //somebody forgot to rename the module template
8258 return false;
8261 $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
8262 if (empty($component)) {
8263 throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8266 $function = null;
8268 if ($type === 'mod') {
8269 // we need this special case because we support subplugins in modules,
8270 // otherwise it would end up in infinite loop
8271 if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8272 include_once("$CFG->dirroot/mod/$name/lib.php");
8273 $function = $component.'_supports';
8274 if (!function_exists($function)) {
8275 // legacy non-frankenstyle function name
8276 $function = $name.'_supports';
8278 } else {
8279 // invalid module
8282 } else {
8283 if (!$path = core_component::get_plugin_directory($type, $name)) {
8284 // non existent plugin type
8285 return false;
8287 if (file_exists("$path/lib.php")) {
8288 include_once("$path/lib.php");
8289 $function = $component.'_supports';
8293 if ($function and function_exists($function)) {
8294 $supports = $function($feature);
8295 if (is_null($supports)) {
8296 // plugin does not know - use default
8297 return $default;
8298 } else {
8299 return $supports;
8303 //plugin does not care, so use default
8304 return $default;
8308 * Returns true if the current version of PHP is greater that the specified one.
8310 * @todo Check PHP version being required here is it too low?
8312 * @param string $version The version of php being tested.
8313 * @return bool
8315 function check_php_version($version='5.2.4') {
8316 return (version_compare(phpversion(), $version) >= 0);
8320 * Checks to see if is the browser operating system matches the specified
8321 * brand.
8323 * Known brand: 'Windows','Linux','Macintosh','SGI','SunOS','HP-UX'
8325 * @uses $_SERVER
8326 * @param string $brand The operating system identifier being tested
8327 * @return bool true if the given brand below to the detected operating system
8329 function check_browser_operating_system($brand) {
8330 if (empty($_SERVER['HTTP_USER_AGENT'])) {
8331 return false;
8334 if (preg_match("/$brand/i", $_SERVER['HTTP_USER_AGENT'])) {
8335 return true;
8338 return false;
8342 * Checks to see if is a browser matches the specified
8343 * brand and is equal or better version.
8345 * @uses $_SERVER
8346 * @param string $brand The browser identifier being tested
8347 * @param int $version The version of the browser, if not specified any version (except 5.5 for IE for BC reasons)
8348 * @return bool true if the given version is below that of the detected browser
8350 function check_browser_version($brand, $version = null) {
8351 if (empty($_SERVER['HTTP_USER_AGENT'])) {
8352 return false;
8355 $agent = $_SERVER['HTTP_USER_AGENT'];
8357 switch ($brand) {
8359 case 'Camino': /// OSX browser using Gecke engine
8360 if (strpos($agent, 'Camino') === false) {
8361 return false;
8363 if (empty($version)) {
8364 return true; // no version specified
8366 if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
8367 if (version_compare($match[1], $version) >= 0) {
8368 return true;
8371 break;
8374 case 'Firefox': /// Mozilla Firefox browsers
8375 if (strpos($agent, 'Iceweasel') === false and strpos($agent, 'Firefox') === false) {
8376 return false;
8378 if (empty($version)) {
8379 return true; // no version specified
8381 if (preg_match("/(Iceweasel|Firefox)\/([0-9\.]+)/i", $agent, $match)) {
8382 if (version_compare($match[2], $version) >= 0) {
8383 return true;
8386 break;
8389 case 'Gecko': /// Gecko based browsers
8390 // Do not look for dates any more, we expect real Firefox version here.
8391 if (empty($version)) {
8392 $version = 1;
8393 } else if ($version > 20000000) {
8394 // This is just a guess, it is not supposed to be 100% accurate!
8395 if (preg_match('/^201/', $version)) {
8396 $version = 3.6;
8397 } else if (preg_match('/^200[7-9]/', $version)) {
8398 $version = 3;
8399 } else if (preg_match('/^2006/', $version)) {
8400 $version = 2;
8401 } else {
8402 $version = 1.5;
8405 if (preg_match("/(Iceweasel|Firefox)\/([0-9\.]+)/i", $agent, $match)) {
8406 // Use real Firefox version if specified in user agent string.
8407 if (version_compare($match[2], $version) >= 0) {
8408 return true;
8410 } else if (preg_match("/Gecko\/([0-9\.]+)/i", $agent, $match)) {
8411 // Gecko might contain date or Firefox revision, let's just guess the Firefox version from the date.
8412 $browserver = $match[1];
8413 if ($browserver > 20000000) {
8414 // This is just a guess, it is not supposed to be 100% accurate!
8415 if (preg_match('/^201/', $browserver)) {
8416 $browserver = 3.6;
8417 } else if (preg_match('/^200[7-9]/', $browserver)) {
8418 $browserver = 3;
8419 } else if (preg_match('/^2006/', $version)) {
8420 $browserver = 2;
8421 } else {
8422 $browserver = 1.5;
8425 if (version_compare($browserver, $version) >= 0) {
8426 return true;
8429 break;
8432 case 'MSIE': /// Internet Explorer
8433 if (strpos($agent, 'Opera') !== false) { // Reject Opera
8434 return false;
8436 // In case of IE we have to deal with BC of the version parameter.
8437 if (is_null($version)) {
8438 $version = 5.5; // Anything older is not considered a browser at all!
8440 // IE uses simple versions, let's cast it to float to simplify the logic here.
8441 $version = round($version, 1);
8442 // See: http://www.useragentstring.com/pages/Internet%20Explorer/
8443 if (preg_match("/MSIE ([0-9\.]+)/", $agent, $match)) {
8444 $browser = $match[1];
8445 } else {
8446 return false;
8448 // IE8 and later versions may pretend to be IE7 for intranet sites, use Trident version instead,
8449 // the Trident should always describe the capabilities of IE in any emulation mode.
8450 if ($browser === '7.0' and preg_match("/Trident\/([0-9\.]+)/", $agent, $match)) {
8451 $browser = $match[1] + 4; // NOTE: Hopefully this will work also for future IE versions.
8453 $browser = round($browser, 1);
8454 return ($browser >= $version);
8455 break;
8458 case 'Opera': /// Opera
8459 if (strpos($agent, 'Opera') === false) {
8460 return false;
8462 if (empty($version)) {
8463 return true; // no version specified
8465 // Recent Opera useragents have Version/ with the actual version, e.g.:
8466 // Opera/9.80 (Windows NT 6.1; WOW64; U; en) Presto/2.10.289 Version/12.01
8467 // That's Opera 12.01, not 9.8.
8468 if (preg_match("/Version\/([0-9\.]+)/i", $agent, $match)) {
8469 if (version_compare($match[1], $version) >= 0) {
8470 return true;
8472 } else if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
8473 if (version_compare($match[1], $version) >= 0) {
8474 return true;
8477 break;
8480 case 'WebKit': /// WebKit based browser - everything derived from it (Safari, Chrome, iOS, Android and other mobiles)
8481 if (strpos($agent, 'AppleWebKit') === false) {
8482 return false;
8484 if (empty($version)) {
8485 return true; // no version specified
8487 if (preg_match("/AppleWebKit\/([0-9.]+)/i", $agent, $match)) {
8488 if (version_compare($match[1], $version) >= 0) {
8489 return true;
8492 break;
8495 case 'Safari': /// Desktop version of Apple Safari browser - no mobile or touch devices
8496 if (strpos($agent, 'AppleWebKit') === false) {
8497 return false;
8499 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SymbianOS and any other mobile devices
8500 if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
8501 return false;
8503 if (strpos($agent, 'Shiira')) { // Reject Shiira
8504 return false;
8506 if (strpos($agent, 'SymbianOS')) { // Reject SymbianOS
8507 return false;
8509 if (strpos($agent, 'Android')) { // Reject Androids too
8510 return false;
8512 if (strpos($agent, 'iPhone') or strpos($agent, 'iPad') or strpos($agent, 'iPod')) {
8513 // No Apple mobile devices here - editor does not work, course ajax is not touch compatible, etc.
8514 return false;
8516 if (strpos($agent, 'Chrome')) { // Reject chrome browsers - it needs to be tested explicitly
8517 return false;
8520 if (empty($version)) {
8521 return true; // no version specified
8523 if (preg_match("/AppleWebKit\/([0-9.]+)/i", $agent, $match)) {
8524 if (version_compare($match[1], $version) >= 0) {
8525 return true;
8528 break;
8531 case 'Chrome':
8532 if (strpos($agent, 'Chrome') === false) {
8533 return false;
8535 if (empty($version)) {
8536 return true; // no version specified
8538 if (preg_match("/Chrome\/(.*)[ ]+/i", $agent, $match)) {
8539 if (version_compare($match[1], $version) >= 0) {
8540 return true;
8543 break;
8546 case 'Safari iOS': /// Safari on iPhone, iPad and iPod touch
8547 if (strpos($agent, 'AppleWebKit') === false or strpos($agent, 'Safari') === false) {
8548 return false;
8550 if (!strpos($agent, 'iPhone') and !strpos($agent, 'iPad') and !strpos($agent, 'iPod')) {
8551 return false;
8553 if (empty($version)) {
8554 return true; // no version specified
8556 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
8557 if (version_compare($match[1], $version) >= 0) {
8558 return true;
8561 break;
8564 case 'WebKit Android': /// WebKit browser on Android
8565 if (strpos($agent, 'Linux; U; Android') === false) {
8566 return false;
8568 if (empty($version)) {
8569 return true; // no version specified
8571 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
8572 if (version_compare($match[1], $version) >= 0) {
8573 return true;
8576 break;
8580 return false;
8584 * Returns whether a device/browser combination is mobile, tablet, legacy, default or the result of
8585 * an optional admin specified regular expression. If enabledevicedetection is set to no or not set
8586 * it returns default
8588 * @return string device type
8590 function get_device_type() {
8591 global $CFG;
8593 if (empty($CFG->enabledevicedetection) || empty($_SERVER['HTTP_USER_AGENT'])) {
8594 return 'default';
8597 $useragent = $_SERVER['HTTP_USER_AGENT'];
8599 if (!empty($CFG->devicedetectregex)) {
8600 $regexes = json_decode($CFG->devicedetectregex);
8602 foreach ($regexes as $value=>$regex) {
8603 if (preg_match($regex, $useragent)) {
8604 return $value;
8609 //mobile detection PHP direct copy from open source detectmobilebrowser.com
8610 $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';
8611 $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';
8612 if (preg_match($phonesregex,$useragent) || preg_match($modelsregex,substr($useragent, 0, 4))){
8613 return 'mobile';
8616 $tabletregex = '/Tablet browser|android|iPad|iProd|GT-P1000|GT-I9000|SHW-M180S|SGH-T849|SCH-I800|Build\/ERE27|sholest/i';
8617 if (preg_match($tabletregex, $useragent)) {
8618 return 'tablet';
8621 // Safe way to check for IE6 and not get false positives for some IE 7/8 users
8622 if (substr($_SERVER['HTTP_USER_AGENT'], 0, 34) === 'Mozilla/4.0 (compatible; MSIE 6.0;') {
8623 return 'legacy';
8626 return 'default';
8630 * Returns a list of the device types supporting by Moodle
8632 * @param boolean $incusertypes includes types specified using the devicedetectregex admin setting
8633 * @return array $types
8635 function get_device_type_list($incusertypes = true) {
8636 global $CFG;
8638 $types = array('default', 'legacy', 'mobile', 'tablet');
8640 if ($incusertypes && !empty($CFG->devicedetectregex)) {
8641 $regexes = json_decode($CFG->devicedetectregex);
8643 foreach ($regexes as $value => $regex) {
8644 $types[] = $value;
8648 return $types;
8652 * Returns the theme selected for a particular device or false if none selected.
8654 * @param string $devicetype
8655 * @return string|false The name of the theme to use for the device or the false if not set
8657 function get_selected_theme_for_device_type($devicetype = null) {
8658 global $CFG;
8660 if (empty($devicetype)) {
8661 $devicetype = get_user_device_type();
8664 $themevarname = get_device_cfg_var_name($devicetype);
8665 if (empty($CFG->$themevarname)) {
8666 return false;
8669 return $CFG->$themevarname;
8673 * Returns the name of the device type theme var in $CFG (because there is not a standard convention to allow backwards compatability
8675 * @param string $devicetype
8676 * @return string The config variable to use to determine the theme
8678 function get_device_cfg_var_name($devicetype = null) {
8679 if ($devicetype == 'default' || empty($devicetype)) {
8680 return 'theme';
8683 return 'theme' . $devicetype;
8687 * Allows the user to switch the device they are seeing the theme for.
8688 * This allows mobile users to switch back to the default theme, or theme for any other device.
8690 * @param string $newdevice The device the user is currently using.
8691 * @return string The device the user has switched to
8693 function set_user_device_type($newdevice) {
8694 global $USER;
8696 $devicetype = get_device_type();
8697 $devicetypes = get_device_type_list();
8699 if ($newdevice == $devicetype) {
8700 unset_user_preference('switchdevice'.$devicetype);
8701 } else if (in_array($newdevice, $devicetypes)) {
8702 set_user_preference('switchdevice'.$devicetype, $newdevice);
8707 * Returns the device the user is currently using, or if the user has chosen to switch devices
8708 * for the current device type the type they have switched to.
8710 * @return string The device the user is currently using or wishes to use
8712 function get_user_device_type() {
8713 $device = get_device_type();
8714 $switched = get_user_preferences('switchdevice'.$device, false);
8715 if ($switched != false) {
8716 return $switched;
8718 return $device;
8722 * Returns one or several CSS class names that match the user's browser. These can be put
8723 * in the body tag of the page to apply browser-specific rules without relying on CSS hacks
8725 * @return array An array of browser version classes
8727 function get_browser_version_classes() {
8728 $classes = array();
8730 if (check_browser_version("MSIE", "0")) {
8731 $classes[] = 'ie';
8732 for($i=12; $i>=6; $i--) {
8733 if (check_browser_version("MSIE", $i)) {
8734 $classes[] = 'ie'.$i;
8735 break;
8739 } else if (check_browser_version("Firefox") || check_browser_version("Gecko") || check_browser_version("Camino")) {
8740 $classes[] = 'gecko';
8741 if (preg_match('/rv\:([1-2])\.([0-9])/', $_SERVER['HTTP_USER_AGENT'], $matches)) {
8742 $classes[] = "gecko{$matches[1]}{$matches[2]}";
8745 } else if (check_browser_version("WebKit")) {
8746 $classes[] = 'safari';
8747 if (check_browser_version("Safari iOS")) {
8748 $classes[] = 'ios';
8750 } else if (check_browser_version("WebKit Android")) {
8751 $classes[] = 'android';
8754 } else if (check_browser_version("Opera")) {
8755 $classes[] = 'opera';
8759 return $classes;
8763 * Determine if moodle installation requires update
8765 * Checks version numbers of main code and all modules to see
8766 * if there are any mismatches
8768 * @global moodle_database $DB
8769 * @return bool
8771 function moodle_needs_upgrading() {
8772 global $CFG, $DB, $OUTPUT;
8774 if (empty($CFG->version)) {
8775 return true;
8778 // We have to purge plugin related caches now to be sure we have fresh data
8779 // and new plugins can be detected.
8780 cache::make('core', 'plugininfo_base')->purge();
8781 cache::make('core', 'plugininfo_mod')->purge();
8782 cache::make('core', 'plugininfo_block')->purge();
8783 cache::make('core', 'plugininfo_filter')->purge();
8784 cache::make('core', 'plugininfo_repository')->purge();
8785 cache::make('core', 'plugininfo_portfolio')->purge();
8787 // Check the main version first.
8788 $version = null;
8789 include($CFG->dirroot.'/version.php'); // defines $version and upgrades
8790 if ($version > $CFG->version) {
8791 return true;
8794 // modules
8795 $mods = core_component::get_plugin_list('mod');
8796 $installed = $DB->get_records('modules', array(), '', 'name, version');
8797 foreach ($mods as $mod => $fullmod) {
8798 if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
8799 continue;
8801 $module = new stdClass();
8802 $plugin = new stdClass();
8803 if (!is_readable($fullmod.'/version.php')) {
8804 continue;
8806 include($fullmod.'/version.php'); // defines $module with version etc
8807 if (!isset($module->version) and isset($plugin->version)) {
8808 $module = $plugin;
8810 if (empty($installed[$mod])) {
8811 return true;
8812 } else if ($module->version > $installed[$mod]->version) {
8813 return true;
8816 unset($installed);
8818 // blocks
8819 $blocks = core_component::get_plugin_list('block');
8820 $installed = $DB->get_records('block', array(), '', 'name, version');
8821 require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
8822 foreach ($blocks as $blockname=>$fullblock) {
8823 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
8824 continue;
8826 if (!is_readable($fullblock.'/version.php')) {
8827 continue;
8829 $plugin = new stdClass();
8830 $plugin->version = NULL;
8831 include($fullblock.'/version.php');
8832 if (empty($installed[$blockname])) {
8833 return true;
8834 } else if ($plugin->version > $installed[$blockname]->version) {
8835 return true;
8838 unset($installed);
8840 // now the rest of plugins
8841 $plugintypes = core_component::get_plugin_types();
8842 unset($plugintypes['mod']);
8843 unset($plugintypes['block']);
8845 $versions = $DB->get_records_menu('config_plugins', array('name' => 'version'), 'plugin', 'plugin, value');
8846 foreach ($plugintypes as $type=>$unused) {
8847 $plugs = core_component::get_plugin_list($type);
8848 foreach ($plugs as $plug=>$fullplug) {
8849 $component = $type.'_'.$plug;
8850 if (!is_readable($fullplug.'/version.php')) {
8851 continue;
8853 $plugin = new stdClass();
8854 include($fullplug.'/version.php'); // defines $plugin with version etc
8855 if (array_key_exists($component, $versions)) {
8856 $installedversion = $versions[$component];
8857 } else {
8858 $installedversion = get_config($component, 'version');
8860 if (empty($installedversion)) { // new installation
8861 return true;
8862 } else if ($installedversion < $plugin->version) { // upgrade
8863 return true;
8868 return false;
8872 * Returns the major version of this site
8874 * Moodle version numbers consist of three numbers separated by a dot, for
8875 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8876 * called major version. This function extracts the major version from either
8877 * $CFG->release (default) or eventually from the $release variable defined in
8878 * the main version.php.
8880 * @param bool $fromdisk should the version if source code files be used
8881 * @return string|false the major version like '2.3', false if could not be determined
8883 function moodle_major_version($fromdisk = false) {
8884 global $CFG;
8886 if ($fromdisk) {
8887 $release = null;
8888 require($CFG->dirroot.'/version.php');
8889 if (empty($release)) {
8890 return false;
8893 } else {
8894 if (empty($CFG->release)) {
8895 return false;
8897 $release = $CFG->release;
8900 if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8901 return $matches[0];
8902 } else {
8903 return false;
8907 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
8910 * Sets the system locale
8912 * @category string
8913 * @param string $locale Can be used to force a locale
8915 function moodle_setlocale($locale='') {
8916 global $CFG;
8918 static $currentlocale = ''; // last locale caching
8920 $oldlocale = $currentlocale;
8922 /// Fetch the correct locale based on ostype
8923 if ($CFG->ostype == 'WINDOWS') {
8924 $stringtofetch = 'localewin';
8925 } else {
8926 $stringtofetch = 'locale';
8929 /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
8930 if (!empty($locale)) {
8931 $currentlocale = $locale;
8932 } else if (!empty($CFG->locale)) { // override locale for all language packs
8933 $currentlocale = $CFG->locale;
8934 } else {
8935 $currentlocale = get_string($stringtofetch, 'langconfig');
8938 /// do nothing if locale already set up
8939 if ($oldlocale == $currentlocale) {
8940 return;
8943 /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8944 /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8945 /// Some day, numeric, monetary and other categories should be set too, I think. :-/
8947 /// Get current values
8948 $monetary= setlocale (LC_MONETARY, 0);
8949 $numeric = setlocale (LC_NUMERIC, 0);
8950 $ctype = setlocale (LC_CTYPE, 0);
8951 if ($CFG->ostype != 'WINDOWS') {
8952 $messages= setlocale (LC_MESSAGES, 0);
8954 /// Set locale to all
8955 setlocale (LC_ALL, $currentlocale);
8956 /// Set old values
8957 setlocale (LC_MONETARY, $monetary);
8958 setlocale (LC_NUMERIC, $numeric);
8959 if ($CFG->ostype != 'WINDOWS') {
8960 setlocale (LC_MESSAGES, $messages);
8962 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
8963 setlocale (LC_CTYPE, $ctype);
8968 * Count words in a string.
8970 * Words are defined as things between whitespace.
8972 * @category string
8973 * @param string $string The text to be searched for words.
8974 * @return int The count of words in the specified string
8976 function count_words($string) {
8977 $string = strip_tags($string);
8978 return count(preg_split("/\w\b/", $string)) - 1;
8981 /** Count letters in a string.
8983 * Letters are defined as chars not in tags and different from whitespace.
8985 * @category string
8986 * @param string $string The text to be searched for letters.
8987 * @return int The count of letters in the specified text.
8989 function count_letters($string) {
8990 /// Loading the textlib singleton instance. We are going to need it.
8991 $string = strip_tags($string); // Tags are out now
8992 $string = preg_replace('/[[:space:]]*/','',$string); //Whitespace are out now
8994 return textlib::strlen($string);
8998 * Generate and return a random string of the specified length.
9000 * @param int $length The length of the string to be created.
9001 * @return string
9003 function random_string ($length=15) {
9004 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
9005 $pool .= 'abcdefghijklmnopqrstuvwxyz';
9006 $pool .= '0123456789';
9007 $poollen = strlen($pool);
9008 mt_srand ((double) microtime() * 1000000);
9009 $string = '';
9010 for ($i = 0; $i < $length; $i++) {
9011 $string .= substr($pool, (mt_rand()%($poollen)), 1);
9013 return $string;
9017 * Generate a complex random string (useful for md5 salts)
9019 * This function is based on the above {@link random_string()} however it uses a
9020 * larger pool of characters and generates a string between 24 and 32 characters
9022 * @param int $length Optional if set generates a string to exactly this length
9023 * @return string
9025 function complex_random_string($length=null) {
9026 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
9027 $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
9028 $poollen = strlen($pool);
9029 mt_srand ((double) microtime() * 1000000);
9030 if ($length===null) {
9031 $length = floor(rand(24,32));
9033 $string = '';
9034 for ($i = 0; $i < $length; $i++) {
9035 $string .= $pool[(mt_rand()%$poollen)];
9037 return $string;
9041 * Given some text (which may contain HTML) and an ideal length,
9042 * this function truncates the text neatly on a word boundary if possible
9044 * @category string
9045 * @global stdClass $CFG
9046 * @param string $text text to be shortened
9047 * @param int $ideal ideal string length
9048 * @param boolean $exact if false, $text will not be cut mid-word
9049 * @param string $ending The string to append if the passed string is truncated
9050 * @return string $truncate shortened string
9052 function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
9054 global $CFG;
9056 // If the plain text is shorter than the maximum length, return the whole text.
9057 if (textlib::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
9058 return $text;
9061 // Splits on HTML tags. Each open/close/empty tag will be the first thing
9062 // and only tag in its 'line'.
9063 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
9065 $total_length = textlib::strlen($ending);
9066 $truncate = '';
9068 // This array stores information about open and close tags and their position
9069 // in the truncated string. Each item in the array is an object with fields
9070 // ->open (true if open), ->tag (tag name in lower case), and ->pos
9071 // (byte position in truncated text).
9072 $tagdetails = array();
9074 foreach ($lines as $line_matchings) {
9075 // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
9076 if (!empty($line_matchings[1])) {
9077 // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
9078 if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
9079 // Do nothing.
9081 } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
9082 // Record closing tag.
9083 $tagdetails[] = (object) array(
9084 'open' => false,
9085 'tag' => textlib::strtolower($tag_matchings[1]),
9086 'pos' => textlib::strlen($truncate),
9089 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
9090 // Record opening tag.
9091 $tagdetails[] = (object) array(
9092 'open' => true,
9093 'tag' => textlib::strtolower($tag_matchings[1]),
9094 'pos' => textlib::strlen($truncate),
9097 // Add html-tag to $truncate'd text.
9098 $truncate .= $line_matchings[1];
9101 // Calculate the length of the plain text part of the line; handle entities as one character.
9102 $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]));
9103 if ($total_length + $content_length > $ideal) {
9104 // The number of characters which are left.
9105 $left = $ideal - $total_length;
9106 $entities_length = 0;
9107 // Search for html entities.
9108 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)) {
9109 // calculate the real length of all entities in the legal range
9110 foreach ($entities[0] as $entity) {
9111 if ($entity[1]+1-$entities_length <= $left) {
9112 $left--;
9113 $entities_length += textlib::strlen($entity[0]);
9114 } else {
9115 // no more characters left
9116 break;
9120 $breakpos = $left + $entities_length;
9122 // if the words shouldn't be cut in the middle...
9123 if (!$exact) {
9124 // ...search the last occurence of a space...
9125 for (; $breakpos > 0; $breakpos--) {
9126 if ($char = textlib::substr($line_matchings[2], $breakpos, 1)) {
9127 if ($char === '.' or $char === ' ') {
9128 $breakpos += 1;
9129 break;
9130 } else if (strlen($char) > 2) { // Chinese/Japanese/Korean text
9131 $breakpos += 1; // can be truncated at any UTF-8
9132 break; // character boundary.
9137 if ($breakpos == 0) {
9138 // This deals with the test_shorten_text_no_spaces case.
9139 $breakpos = $left + $entities_length;
9140 } else if ($breakpos > $left + $entities_length) {
9141 // This deals with the previous for loop breaking on the first char.
9142 $breakpos = $left + $entities_length;
9145 $truncate .= textlib::substr($line_matchings[2], 0, $breakpos);
9146 // maximum length is reached, so get off the loop
9147 break;
9148 } else {
9149 $truncate .= $line_matchings[2];
9150 $total_length += $content_length;
9153 // If the maximum length is reached, get off the loop.
9154 if($total_length >= $ideal) {
9155 break;
9159 // Add the defined ending to the text.
9160 $truncate .= $ending;
9162 // Now calculate the list of open html tags based on the truncate position.
9163 $open_tags = array();
9164 foreach ($tagdetails as $taginfo) {
9165 if ($taginfo->open) {
9166 // Add tag to the beginning of $open_tags list.
9167 array_unshift($open_tags, $taginfo->tag);
9168 } else {
9169 // Can have multiple exact same open tags, close the last one.
9170 $pos = array_search($taginfo->tag, array_reverse($open_tags, true));
9171 if ($pos !== false) {
9172 unset($open_tags[$pos]);
9177 // Close all unclosed html-tags.
9178 foreach ($open_tags as $tag) {
9179 $truncate .= '</' . $tag . '>';
9182 return $truncate;
9187 * Given dates in seconds, how many weeks is the date from startdate
9188 * The first week is 1, the second 2 etc ...
9190 * @todo Finish documenting this function
9192 * @uses WEEKSECS
9193 * @param int $startdate Timestamp for the start date
9194 * @param int $thedate Timestamp for the end date
9195 * @return string
9197 function getweek ($startdate, $thedate) {
9198 if ($thedate < $startdate) { // error
9199 return 0;
9202 return floor(($thedate - $startdate) / WEEKSECS) + 1;
9206 * returns a randomly generated password of length $maxlen. inspired by
9208 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
9209 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
9211 * @global stdClass $CFG
9212 * @param int $maxlen The maximum size of the password being generated.
9213 * @return string
9215 function generate_password($maxlen=10) {
9216 global $CFG;
9218 if (empty($CFG->passwordpolicy)) {
9219 $fillers = PASSWORD_DIGITS;
9220 $wordlist = file($CFG->wordlist);
9221 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
9222 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
9223 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
9224 $password = $word1 . $filler1 . $word2;
9225 } else {
9226 $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
9227 $digits = $CFG->minpassworddigits;
9228 $lower = $CFG->minpasswordlower;
9229 $upper = $CFG->minpasswordupper;
9230 $nonalphanum = $CFG->minpasswordnonalphanum;
9231 $total = $lower + $upper + $digits + $nonalphanum;
9232 // minlength should be the greater one of the two ( $minlen and $total )
9233 $minlen = $minlen < $total ? $total : $minlen;
9234 // maxlen can never be smaller than minlen
9235 $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
9236 $additional = $maxlen - $total;
9238 // Make sure we have enough characters to fulfill
9239 // complexity requirements
9240 $passworddigits = PASSWORD_DIGITS;
9241 while ($digits > strlen($passworddigits)) {
9242 $passworddigits .= PASSWORD_DIGITS;
9244 $passwordlower = PASSWORD_LOWER;
9245 while ($lower > strlen($passwordlower)) {
9246 $passwordlower .= PASSWORD_LOWER;
9248 $passwordupper = PASSWORD_UPPER;
9249 while ($upper > strlen($passwordupper)) {
9250 $passwordupper .= PASSWORD_UPPER;
9252 $passwordnonalphanum = PASSWORD_NONALPHANUM;
9253 while ($nonalphanum > strlen($passwordnonalphanum)) {
9254 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
9257 // Now mix and shuffle it all
9258 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
9259 substr(str_shuffle ($passwordupper), 0, $upper) .
9260 substr(str_shuffle ($passworddigits), 0, $digits) .
9261 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
9262 substr(str_shuffle ($passwordlower .
9263 $passwordupper .
9264 $passworddigits .
9265 $passwordnonalphanum), 0 , $additional));
9268 return substr ($password, 0, $maxlen);
9272 * Given a float, prints it nicely.
9273 * Localized floats must not be used in calculations!
9275 * The stripzeros feature is intended for making numbers look nicer in small
9276 * areas where it is not necessary to indicate the degree of accuracy by showing
9277 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
9278 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
9280 * @param float $float The float to print
9281 * @param int $decimalpoints The number of decimal places to print.
9282 * @param bool $localized use localized decimal separator
9283 * @param bool $stripzeros If true, removes final zeros after decimal point
9284 * @return string locale float
9286 function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
9287 if (is_null($float)) {
9288 return '';
9290 if ($localized) {
9291 $separator = get_string('decsep', 'langconfig');
9292 } else {
9293 $separator = '.';
9295 $result = number_format($float, $decimalpoints, $separator, '');
9296 if ($stripzeros) {
9297 // Remove zeros and final dot if not needed
9298 $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
9300 return $result;
9304 * Converts locale specific floating point/comma number back to standard PHP float value
9305 * Do NOT try to do any math operations before this conversion on any user submitted floats!
9307 * @param string $locale_float locale aware float representation
9308 * @param bool $strict If true, then check the input and return false if it is not a valid number.
9309 * @return mixed float|bool - false or the parsed float.
9311 function unformat_float($locale_float, $strict = false) {
9312 $locale_float = trim($locale_float);
9314 if ($locale_float == '') {
9315 return null;
9318 $locale_float = str_replace(' ', '', $locale_float); // no spaces - those might be used as thousand separators
9319 $locale_float = str_replace(get_string('decsep', 'langconfig'), '.', $locale_float);
9321 if ($strict && !is_numeric($locale_float)) {
9322 return false;
9325 return (float)$locale_float;
9329 * Given a simple array, this shuffles it up just like shuffle()
9330 * Unlike PHP's shuffle() this function works on any machine.
9332 * @param array $array The array to be rearranged
9333 * @return array
9335 function swapshuffle($array) {
9337 srand ((double) microtime() * 10000000);
9338 $last = count($array) - 1;
9339 for ($i=0;$i<=$last;$i++) {
9340 $from = rand(0,$last);
9341 $curr = $array[$i];
9342 $array[$i] = $array[$from];
9343 $array[$from] = $curr;
9345 return $array;
9349 * Like {@link swapshuffle()}, but works on associative arrays
9351 * @param array $array The associative array to be rearranged
9352 * @return array
9354 function swapshuffle_assoc($array) {
9356 $newarray = array();
9357 $newkeys = swapshuffle(array_keys($array));
9359 foreach ($newkeys as $newkey) {
9360 $newarray[$newkey] = $array[$newkey];
9362 return $newarray;
9366 * Given an arbitrary array, and a number of draws,
9367 * this function returns an array with that amount
9368 * of items. The indexes are retained.
9370 * @todo Finish documenting this function
9372 * @param array $array
9373 * @param int $draws
9374 * @return array
9376 function draw_rand_array($array, $draws) {
9377 srand ((double) microtime() * 10000000);
9379 $return = array();
9381 $last = count($array);
9383 if ($draws > $last) {
9384 $draws = $last;
9387 while ($draws > 0) {
9388 $last--;
9390 $keys = array_keys($array);
9391 $rand = rand(0, $last);
9393 $return[$keys[$rand]] = $array[$keys[$rand]];
9394 unset($array[$keys[$rand]]);
9396 $draws--;
9399 return $return;
9403 * Calculate the difference between two microtimes
9405 * @param string $a The first Microtime
9406 * @param string $b The second Microtime
9407 * @return string
9409 function microtime_diff($a, $b) {
9410 list($a_dec, $a_sec) = explode(' ', $a);
9411 list($b_dec, $b_sec) = explode(' ', $b);
9412 return $b_sec - $a_sec + $b_dec - $a_dec;
9416 * Given a list (eg a,b,c,d,e) this function returns
9417 * an array of 1->a, 2->b, 3->c etc
9419 * @param string $list The string to explode into array bits
9420 * @param string $separator The separator used within the list string
9421 * @return array The now assembled array
9423 function make_menu_from_list($list, $separator=',') {
9425 $array = array_reverse(explode($separator, $list), true);
9426 foreach ($array as $key => $item) {
9427 $outarray[$key+1] = trim($item);
9429 return $outarray;
9433 * Creates an array that represents all the current grades that
9434 * can be chosen using the given grading type.
9436 * Negative numbers
9437 * are scales, zero is no grade, and positive numbers are maximum
9438 * grades.
9440 * @todo Finish documenting this function or better deprecated this completely!
9442 * @param int $gradingtype
9443 * @return array
9445 function make_grades_menu($gradingtype) {
9446 global $DB;
9448 $grades = array();
9449 if ($gradingtype < 0) {
9450 if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
9451 return make_menu_from_list($scale->scale);
9453 } else if ($gradingtype > 0) {
9454 for ($i=$gradingtype; $i>=0; $i--) {
9455 $grades[$i] = $i .' / '. $gradingtype;
9457 return $grades;
9459 return $grades;
9463 * This function returns the number of activities
9464 * using scaleid in a courseid
9466 * @todo Finish documenting this function
9468 * @global object
9469 * @global object
9470 * @param int $courseid ?
9471 * @param int $scaleid ?
9472 * @return int
9474 function course_scale_used($courseid, $scaleid) {
9475 global $CFG, $DB;
9477 $return = 0;
9479 if (!empty($scaleid)) {
9480 if ($cms = get_course_mods($courseid)) {
9481 foreach ($cms as $cm) {
9482 //Check cm->name/lib.php exists
9483 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
9484 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
9485 $function_name = $cm->modname.'_scale_used';
9486 if (function_exists($function_name)) {
9487 if ($function_name($cm->instance,$scaleid)) {
9488 $return++;
9495 // check if any course grade item makes use of the scale
9496 $return += $DB->count_records('grade_items', array('courseid'=>$courseid, 'scaleid'=>$scaleid));
9498 // check if any outcome in the course makes use of the scale
9499 $return += $DB->count_records_sql("SELECT COUNT('x')
9500 FROM {grade_outcomes_courses} goc,
9501 {grade_outcomes} go
9502 WHERE go.id = goc.outcomeid
9503 AND go.scaleid = ? AND goc.courseid = ?",
9504 array($scaleid, $courseid));
9506 return $return;
9510 * This function returns the number of activities
9511 * using scaleid in the entire site
9513 * @param int $scaleid
9514 * @param array $courses
9515 * @return int
9517 function site_scale_used($scaleid, &$courses) {
9518 $return = 0;
9520 if (!is_array($courses) || count($courses) == 0) {
9521 $courses = get_courses("all",false,"c.id,c.shortname");
9524 if (!empty($scaleid)) {
9525 if (is_array($courses) && count($courses) > 0) {
9526 foreach ($courses as $course) {
9527 $return += course_scale_used($course->id,$scaleid);
9531 return $return;
9535 * make_unique_id_code
9537 * @todo Finish documenting this function
9539 * @uses $_SERVER
9540 * @param string $extra Extra string to append to the end of the code
9541 * @return string
9543 function make_unique_id_code($extra='') {
9545 $hostname = 'unknownhost';
9546 if (!empty($_SERVER['HTTP_HOST'])) {
9547 $hostname = $_SERVER['HTTP_HOST'];
9548 } else if (!empty($_ENV['HTTP_HOST'])) {
9549 $hostname = $_ENV['HTTP_HOST'];
9550 } else if (!empty($_SERVER['SERVER_NAME'])) {
9551 $hostname = $_SERVER['SERVER_NAME'];
9552 } else if (!empty($_ENV['SERVER_NAME'])) {
9553 $hostname = $_ENV['SERVER_NAME'];
9556 $date = gmdate("ymdHis");
9558 $random = random_string(6);
9560 if ($extra) {
9561 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
9562 } else {
9563 return $hostname .'+'. $date .'+'. $random;
9569 * Function to check the passed address is within the passed subnet
9571 * The parameter is a comma separated string of subnet definitions.
9572 * Subnet strings can be in one of three formats:
9573 * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
9574 * 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)
9575 * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
9576 * Code for type 1 modified from user posted comments by mediator at
9577 * {@link http://au.php.net/manual/en/function.ip2long.php}
9579 * @param string $addr The address you are checking
9580 * @param string $subnetstr The string of subnet addresses
9581 * @return bool
9583 function address_in_subnet($addr, $subnetstr) {
9585 if ($addr == '0.0.0.0') {
9586 return false;
9588 $subnets = explode(',', $subnetstr);
9589 $found = false;
9590 $addr = trim($addr);
9591 $addr = cleanremoteaddr($addr, false); // normalise
9592 if ($addr === null) {
9593 return false;
9595 $addrparts = explode(':', $addr);
9597 $ipv6 = strpos($addr, ':');
9599 foreach ($subnets as $subnet) {
9600 $subnet = trim($subnet);
9601 if ($subnet === '') {
9602 continue;
9605 if (strpos($subnet, '/') !== false) {
9606 ///1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn
9607 list($ip, $mask) = explode('/', $subnet);
9608 $mask = trim($mask);
9609 if (!is_number($mask)) {
9610 continue; // incorect mask number, eh?
9612 $ip = cleanremoteaddr($ip, false); // normalise
9613 if ($ip === null) {
9614 continue;
9616 if (strpos($ip, ':') !== false) {
9617 // IPv6
9618 if (!$ipv6) {
9619 continue;
9621 if ($mask > 128 or $mask < 0) {
9622 continue; // nonsense
9624 if ($mask == 0) {
9625 return true; // any address
9627 if ($mask == 128) {
9628 if ($ip === $addr) {
9629 return true;
9631 continue;
9633 $ipparts = explode(':', $ip);
9634 $modulo = $mask % 16;
9635 $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
9636 $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9637 if (implode(':', $ipnet) === implode(':', $addrnet)) {
9638 if ($modulo == 0) {
9639 return true;
9641 $pos = ($mask-$modulo)/16;
9642 $ipnet = hexdec($ipparts[$pos]);
9643 $addrnet = hexdec($addrparts[$pos]);
9644 $mask = 0xffff << (16 - $modulo);
9645 if (($addrnet & $mask) == ($ipnet & $mask)) {
9646 return true;
9650 } else {
9651 // IPv4
9652 if ($ipv6) {
9653 continue;
9655 if ($mask > 32 or $mask < 0) {
9656 continue; // nonsense
9658 if ($mask == 0) {
9659 return true;
9661 if ($mask == 32) {
9662 if ($ip === $addr) {
9663 return true;
9665 continue;
9667 $mask = 0xffffffff << (32 - $mask);
9668 if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9669 return true;
9673 } else if (strpos($subnet, '-') !== false) {
9674 /// 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.
9675 $parts = explode('-', $subnet);
9676 if (count($parts) != 2) {
9677 continue;
9680 if (strpos($subnet, ':') !== false) {
9681 // IPv6
9682 if (!$ipv6) {
9683 continue;
9685 $ipstart = cleanremoteaddr(trim($parts[0]), false); // normalise
9686 if ($ipstart === null) {
9687 continue;
9689 $ipparts = explode(':', $ipstart);
9690 $start = hexdec(array_pop($ipparts));
9691 $ipparts[] = trim($parts[1]);
9692 $ipend = cleanremoteaddr(implode(':', $ipparts), false); // normalise
9693 if ($ipend === null) {
9694 continue;
9696 $ipparts[7] = '';
9697 $ipnet = implode(':', $ipparts);
9698 if (strpos($addr, $ipnet) !== 0) {
9699 continue;
9701 $ipparts = explode(':', $ipend);
9702 $end = hexdec($ipparts[7]);
9704 $addrend = hexdec($addrparts[7]);
9706 if (($addrend >= $start) and ($addrend <= $end)) {
9707 return true;
9710 } else {
9711 // IPv4
9712 if ($ipv6) {
9713 continue;
9715 $ipstart = cleanremoteaddr(trim($parts[0]), false); // normalise
9716 if ($ipstart === null) {
9717 continue;
9719 $ipparts = explode('.', $ipstart);
9720 $ipparts[3] = trim($parts[1]);
9721 $ipend = cleanremoteaddr(implode('.', $ipparts), false); // normalise
9722 if ($ipend === null) {
9723 continue;
9726 if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9727 return true;
9731 } else {
9732 /// 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9733 if (strpos($subnet, ':') !== false) {
9734 // IPv6
9735 if (!$ipv6) {
9736 continue;
9738 $parts = explode(':', $subnet);
9739 $count = count($parts);
9740 if ($parts[$count-1] === '') {
9741 unset($parts[$count-1]); // trim trailing :
9742 $count--;
9743 $subnet = implode('.', $parts);
9745 $isip = cleanremoteaddr($subnet, false); // normalise
9746 if ($isip !== null) {
9747 if ($isip === $addr) {
9748 return true;
9750 continue;
9751 } else if ($count > 8) {
9752 continue;
9754 $zeros = array_fill(0, 8-$count, '0');
9755 $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9756 if (address_in_subnet($addr, $subnet)) {
9757 return true;
9760 } else {
9761 // IPv4
9762 if ($ipv6) {
9763 continue;
9765 $parts = explode('.', $subnet);
9766 $count = count($parts);
9767 if ($parts[$count-1] === '') {
9768 unset($parts[$count-1]); // trim trailing .
9769 $count--;
9770 $subnet = implode('.', $parts);
9772 if ($count == 4) {
9773 $subnet = cleanremoteaddr($subnet, false); // normalise
9774 if ($subnet === $addr) {
9775 return true;
9777 continue;
9778 } else if ($count > 4) {
9779 continue;
9781 $zeros = array_fill(0, 4-$count, '0');
9782 $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9783 if (address_in_subnet($addr, $subnet)) {
9784 return true;
9790 return false;
9794 * For outputting debugging info
9796 * @uses STDOUT
9797 * @param string $string The string to write
9798 * @param string $eol The end of line char(s) to use
9799 * @param string $sleep Period to make the application sleep
9800 * This ensures any messages have time to display before redirect
9802 function mtrace($string, $eol="\n", $sleep=0) {
9804 if (defined('STDOUT') and !PHPUNIT_TEST) {
9805 fwrite(STDOUT, $string.$eol);
9806 } else {
9807 echo $string . $eol;
9810 flush();
9812 //delay to keep message on user's screen in case of subsequent redirect
9813 if ($sleep) {
9814 sleep($sleep);
9819 * Replace 1 or more slashes or backslashes to 1 slash
9821 * @param string $path The path to strip
9822 * @return string the path with double slashes removed
9824 function cleardoubleslashes ($path) {
9825 return preg_replace('/(\/|\\\){1,}/','/',$path);
9829 * Is current ip in give list?
9831 * @param string $list
9832 * @return bool
9834 function remoteip_in_list($list){
9835 $inlist = false;
9836 $client_ip = getremoteaddr(null);
9838 if(!$client_ip){
9839 // ensure access on cli
9840 return true;
9843 $list = explode("\n", $list);
9844 foreach($list as $subnet) {
9845 $subnet = trim($subnet);
9846 if (address_in_subnet($client_ip, $subnet)) {
9847 $inlist = true;
9848 break;
9851 return $inlist;
9855 * Returns most reliable client address
9857 * @global object
9858 * @param string $default If an address can't be determined, then return this
9859 * @return string The remote IP address
9861 function getremoteaddr($default='0.0.0.0') {
9862 global $CFG;
9864 if (empty($CFG->getremoteaddrconf)) {
9865 // This will happen, for example, before just after the upgrade, as the
9866 // user is redirected to the admin screen.
9867 $variablestoskip = 0;
9868 } else {
9869 $variablestoskip = $CFG->getremoteaddrconf;
9871 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9872 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9873 $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9874 return $address ? $address : $default;
9877 if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9878 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9879 $address = cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
9880 return $address ? $address : $default;
9883 if (!empty($_SERVER['REMOTE_ADDR'])) {
9884 $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9885 return $address ? $address : $default;
9886 } else {
9887 return $default;
9892 * Cleans an ip address. Internal addresses are now allowed.
9893 * (Originally local addresses were not allowed.)
9895 * @param string $addr IPv4 or IPv6 address
9896 * @param bool $compress use IPv6 address compression
9897 * @return string normalised ip address string, null if error
9899 function cleanremoteaddr($addr, $compress=false) {
9900 $addr = trim($addr);
9902 //TODO: maybe add a separate function is_addr_public() or something like this
9904 if (strpos($addr, ':') !== false) {
9905 // can be only IPv6
9906 $parts = explode(':', $addr);
9907 $count = count($parts);
9909 if (strpos($parts[$count-1], '.') !== false) {
9910 //legacy ipv4 notation
9911 $last = array_pop($parts);
9912 $ipv4 = cleanremoteaddr($last, true);
9913 if ($ipv4 === null) {
9914 return null;
9916 $bits = explode('.', $ipv4);
9917 $parts[] = dechex($bits[0]).dechex($bits[1]);
9918 $parts[] = dechex($bits[2]).dechex($bits[3]);
9919 $count = count($parts);
9920 $addr = implode(':', $parts);
9923 if ($count < 3 or $count > 8) {
9924 return null; // severly malformed
9927 if ($count != 8) {
9928 if (strpos($addr, '::') === false) {
9929 return null; // malformed
9931 // uncompress ::
9932 $insertat = array_search('', $parts, true);
9933 $missing = array_fill(0, 1 + 8 - $count, '0');
9934 array_splice($parts, $insertat, 1, $missing);
9935 foreach ($parts as $key=>$part) {
9936 if ($part === '') {
9937 $parts[$key] = '0';
9942 $adr = implode(':', $parts);
9943 if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9944 return null; // incorrect format - sorry
9947 // normalise 0s and case
9948 $parts = array_map('hexdec', $parts);
9949 $parts = array_map('dechex', $parts);
9951 $result = implode(':', $parts);
9953 if (!$compress) {
9954 return $result;
9957 if ($result === '0:0:0:0:0:0:0:0') {
9958 return '::'; // all addresses
9961 $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9962 if ($compressed !== $result) {
9963 return $compressed;
9966 $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9967 if ($compressed !== $result) {
9968 return $compressed;
9971 $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9972 if ($compressed !== $result) {
9973 return $compressed;
9976 return $result;
9979 // first get all things that look like IPv4 addresses
9980 $parts = array();
9981 if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9982 return null;
9984 unset($parts[0]);
9986 foreach ($parts as $key=>$match) {
9987 if ($match > 255) {
9988 return null;
9990 $parts[$key] = (int)$match; // normalise 0s
9993 return implode('.', $parts);
9997 * This function will make a complete copy of anything it's given,
9998 * regardless of whether it's an object or not.
10000 * @param mixed $thing Something you want cloned
10001 * @return mixed What ever it is you passed it
10003 function fullclone($thing) {
10004 return unserialize(serialize($thing));
10009 * This function expects to called during shutdown
10010 * should be set via register_shutdown_function()
10011 * in lib/setup.php .
10013 * @return void
10015 function moodle_request_shutdown() {
10016 global $CFG;
10018 // help apache server if possible
10019 $apachereleasemem = false;
10020 if (function_exists('apache_child_terminate') && function_exists('memory_get_usage')
10021 && ini_get_bool('child_terminate')) {
10023 $limit = (empty($CFG->apachemaxmem) ? 64*1024*1024 : $CFG->apachemaxmem); //64MB default
10024 if (memory_get_usage() > get_real_size($limit)) {
10025 $apachereleasemem = $limit;
10026 @apache_child_terminate();
10030 // deal with perf logging
10031 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
10032 if ($apachereleasemem) {
10033 error_log('Mem usage over '.$apachereleasemem.': marking Apache child for reaping.');
10035 if (defined('MDL_PERFTOLOG')) {
10036 $perf = get_performance_info();
10037 error_log("PERF: " . $perf['txt']);
10039 if (defined('MDL_PERFINC')) {
10040 $inc = get_included_files();
10041 $ts = 0;
10042 foreach($inc as $f) {
10043 if (preg_match(':^/:', $f)) {
10044 $fs = filesize($f);
10045 $ts += $fs;
10046 $hfs = display_size($fs);
10047 error_log(substr($f,strlen($CFG->dirroot)) . " size: $fs ($hfs)"
10048 , NULL, NULL, 0);
10049 } else {
10050 error_log($f , NULL, NULL, 0);
10053 if ($ts > 0 ) {
10054 $hts = display_size($ts);
10055 error_log("Total size of files included: $ts ($hts)");
10062 * If new messages are waiting for the current user, then insert
10063 * JavaScript to pop up the messaging window into the page
10065 * @global moodle_page $PAGE
10066 * @return void
10068 function message_popup_window() {
10069 global $USER, $DB, $PAGE, $CFG, $SITE;
10071 if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
10072 return;
10075 if (!isloggedin() || isguestuser()) {
10076 return;
10079 if (!isset($USER->message_lastpopup)) {
10080 $USER->message_lastpopup = 0;
10081 } else if ($USER->message_lastpopup > (time()-120)) {
10082 //dont run the query to check whether to display a popup if its been run in the last 2 minutes
10083 return;
10086 //a quick query to check whether the user has new messages
10087 $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
10088 if ($messagecount<1) {
10089 return;
10092 //got unread messages so now do another query that joins with the user table
10093 $messagesql = "SELECT m.id, m.smallmessage, m.fullmessageformat, m.notification, u.firstname, u.lastname
10094 FROM {message} m
10095 JOIN {message_working} mw ON m.id=mw.unreadmessageid
10096 JOIN {message_processors} p ON mw.processorid=p.id
10097 JOIN {user} u ON m.useridfrom=u.id
10098 WHERE m.useridto = :userid
10099 AND p.name='popup'";
10101 //if the user was last notified over an hour ago we can renotify them of old messages
10102 //so don't worry about when the new message was sent
10103 $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
10104 if (!$lastnotifiedlongago) {
10105 $messagesql .= 'AND m.timecreated > :lastpopuptime';
10108 $message_users = $DB->get_records_sql($messagesql, array('userid'=>$USER->id, 'lastpopuptime'=>$USER->message_lastpopup));
10110 //if we have new messages to notify the user about
10111 if (!empty($message_users)) {
10113 $strmessages = '';
10114 if (count($message_users)>1) {
10115 $strmessages = get_string('unreadnewmessages', 'message', count($message_users));
10116 } else {
10117 $message_users = reset($message_users);
10119 //show who the message is from if its not a notification
10120 if (!$message_users->notification) {
10121 $strmessages = get_string('unreadnewmessage', 'message', fullname($message_users) );
10124 //try to display the small version of the message
10125 $smallmessage = null;
10126 if (!empty($message_users->smallmessage)) {
10127 //display the first 200 chars of the message in the popup
10128 $smallmessage = null;
10129 if (textlib::strlen($message_users->smallmessage) > 200) {
10130 $smallmessage = textlib::substr($message_users->smallmessage,0,200).'...';
10131 } else {
10132 $smallmessage = $message_users->smallmessage;
10135 //prevent html symbols being displayed
10136 if ($message_users->fullmessageformat == FORMAT_HTML) {
10137 $smallmessage = html_to_text($smallmessage);
10138 } else {
10139 $smallmessage = s($smallmessage);
10141 } else if ($message_users->notification) {
10142 //its a notification with no smallmessage so just say they have a notification
10143 $smallmessage = get_string('unreadnewnotification', 'message');
10145 if (!empty($smallmessage)) {
10146 $strmessages .= '<div id="usermessage">'.s($smallmessage).'</div>';
10150 $strgomessage = get_string('gotomessages', 'message');
10151 $strstaymessage = get_string('ignore','admin');
10153 $url = $CFG->wwwroot.'/message/index.php';
10154 $content = html_writer::start_tag('div', array('id'=>'newmessageoverlay','class'=>'mdl-align')).
10155 html_writer::start_tag('div', array('id'=>'newmessagetext')).
10156 $strmessages.
10157 html_writer::end_tag('div').
10159 html_writer::start_tag('div', array('id'=>'newmessagelinks')).
10160 html_writer::link($url, $strgomessage, array('id'=>'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
10161 html_writer::link('', $strstaymessage, array('id'=>'notificationno')).
10162 html_writer::end_tag('div');
10163 html_writer::end_tag('div');
10165 $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
10167 $USER->message_lastpopup = time();
10172 * Used to make sure that $min <= $value <= $max
10174 * Make sure that value is between min, and max
10176 * @param int $min The minimum value
10177 * @param int $value The value to check
10178 * @param int $max The maximum value
10180 function bounded_number($min, $value, $max) {
10181 if($value < $min) {
10182 return $min;
10184 if($value > $max) {
10185 return $max;
10187 return $value;
10191 * Check if there is a nested array within the passed array
10193 * @param array $array
10194 * @return bool true if there is a nested array false otherwise
10196 function array_is_nested($array) {
10197 foreach ($array as $value) {
10198 if (is_array($value)) {
10199 return true;
10202 return false;
10206 * get_performance_info() pairs up with init_performance_info()
10207 * loaded in setup.php. Returns an array with 'html' and 'txt'
10208 * values ready for use, and each of the individual stats provided
10209 * separately as well.
10211 * @global object
10212 * @global object
10213 * @global object
10214 * @return array
10216 function get_performance_info() {
10217 global $CFG, $PERF, $DB, $PAGE;
10219 $info = array();
10220 $info['html'] = ''; // holds userfriendly HTML representation
10221 $info['txt'] = me() . ' '; // holds log-friendly representation
10223 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
10225 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
10226 $info['txt'] .= 'time: '.$info['realtime'].'s ';
10228 if (function_exists('memory_get_usage')) {
10229 $info['memory_total'] = memory_get_usage();
10230 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
10231 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
10232 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
10235 if (function_exists('memory_get_peak_usage')) {
10236 $info['memory_peak'] = memory_get_peak_usage();
10237 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
10238 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
10241 $inc = get_included_files();
10242 //error_log(print_r($inc,1));
10243 $info['includecount'] = count($inc);
10244 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
10245 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
10247 if (!empty($CFG->early_install_lang) or empty($PAGE)) {
10248 // We can not track more performance before installation or before PAGE init, sorry.
10249 return $info;
10252 $filtermanager = filter_manager::instance();
10253 if (method_exists($filtermanager, 'get_performance_summary')) {
10254 list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
10255 $info = array_merge($filterinfo, $info);
10256 foreach ($filterinfo as $key => $value) {
10257 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
10258 $info['txt'] .= "$key: $value ";
10262 $stringmanager = get_string_manager();
10263 if (method_exists($stringmanager, 'get_performance_summary')) {
10264 list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
10265 $info = array_merge($filterinfo, $info);
10266 foreach ($filterinfo as $key => $value) {
10267 $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
10268 $info['txt'] .= "$key: $value ";
10272 $jsmodules = $PAGE->requires->get_loaded_modules();
10273 if ($jsmodules) {
10274 $yuicount = 0;
10275 $othercount = 0;
10276 $details = '';
10277 foreach ($jsmodules as $module => $backtraces) {
10278 if (strpos($module, 'yui') === 0) {
10279 $yuicount += 1;
10280 } else {
10281 $othercount += 1;
10283 if (!empty($CFG->yuimoduledebug)) {
10284 // hidden feature for developers working on YUI module infrastructure
10285 $details .= "<div class='yui-module'><p>$module</p>";
10286 foreach ($backtraces as $backtrace) {
10287 $details .= "<div class='backtrace'>$backtrace</div>";
10289 $details .= '</div>';
10292 $info['html'] .= "<span class='includedyuimodules'>Included YUI modules: $yuicount</span> ";
10293 $info['txt'] .= "includedyuimodules: $yuicount ";
10294 $info['html'] .= "<span class='includedjsmodules'>Other JavaScript modules: $othercount</span> ";
10295 $info['txt'] .= "includedjsmodules: $othercount ";
10296 if ($details) {
10297 $info['html'] .= '<div id="yui-module-debug" class="notifytiny">'.$details.'</div>';
10301 if (!empty($PERF->logwrites)) {
10302 $info['logwrites'] = $PERF->logwrites;
10303 $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
10304 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
10307 $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
10308 $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
10309 $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
10311 if (function_exists('posix_times')) {
10312 $ptimes = posix_times();
10313 if (is_array($ptimes)) {
10314 foreach ($ptimes as $key => $val) {
10315 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
10317 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
10318 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
10322 // Grab the load average for the last minute
10323 // /proc will only work under some linux configurations
10324 // while uptime is there under MacOSX/Darwin and other unices
10325 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
10326 list($server_load) = explode(' ', $loadavg[0]);
10327 unset($loadavg);
10328 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
10329 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
10330 $server_load = $matches[1];
10331 } else {
10332 trigger_error('Could not parse uptime output!');
10335 if (!empty($server_load)) {
10336 $info['serverload'] = $server_load;
10337 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
10338 $info['txt'] .= "serverload: {$info['serverload']} ";
10341 // Display size of session if session started
10342 if (session_id()) {
10343 $info['sessionsize'] = display_size(strlen(session_encode()));
10344 $info['html'] .= '<span class="sessionsize">Session: ' . $info['sessionsize'] . '</span> ';
10345 $info['txt'] .= "Session: {$info['sessionsize']} ";
10348 if ($stats = cache_helper::get_stats()) {
10349 $html = '<span class="cachesused">';
10350 $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
10351 $text = 'Caches used (hits/misses/sets): ';
10352 $hits = 0;
10353 $misses = 0;
10354 $sets = 0;
10355 foreach ($stats as $definition => $stores) {
10356 $html .= '<span class="cache-definition-stats">';
10357 $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
10358 $text .= "$definition {";
10359 foreach ($stores as $store => $data) {
10360 $hits += $data['hits'];
10361 $misses += $data['misses'];
10362 $sets += $data['sets'];
10363 if ($data['hits'] == 0 and $data['misses'] > 0) {
10364 $cachestoreclass = 'nohits';
10365 } else if ($data['hits'] < $data['misses']) {
10366 $cachestoreclass = 'lowhits';
10367 } else {
10368 $cachestoreclass = 'hihits';
10370 $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
10371 $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
10373 $html .= '</span>';
10374 $text .= '} ';
10376 $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
10377 $html .= '</span> ';
10378 $info['cachesused'] = "$hits / $misses / $sets";
10379 $info['html'] .= $html;
10380 $info['txt'] .= $text.'. ';
10381 } else {
10382 $info['cachesused'] = '0 / 0 / 0';
10383 $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
10384 $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
10387 $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
10388 return $info;
10392 * @todo Document this function linux people
10394 function apd_get_profiling() {
10395 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
10399 * Delete directory or only its content
10401 * @param string $dir directory path
10402 * @param bool $content_only
10403 * @return bool success, true also if dir does not exist
10405 function remove_dir($dir, $content_only=false) {
10406 if (!file_exists($dir)) {
10407 // nothing to do
10408 return true;
10410 if (!$handle = opendir($dir)) {
10411 return false;
10413 $result = true;
10414 while (false!==($item = readdir($handle))) {
10415 if($item != '.' && $item != '..') {
10416 if(is_dir($dir.'/'.$item)) {
10417 $result = remove_dir($dir.'/'.$item) && $result;
10418 }else{
10419 $result = unlink($dir.'/'.$item) && $result;
10423 closedir($handle);
10424 if ($content_only) {
10425 clearstatcache(); // make sure file stat cache is properly invalidated
10426 return $result;
10428 $result = rmdir($dir); // if anything left the result will be false, no need for && $result
10429 clearstatcache(); // make sure file stat cache is properly invalidated
10430 return $result;
10434 * Detect if an object or a class contains a given property
10435 * will take an actual object or the name of a class
10437 * @param mix $obj Name of class or real object to test
10438 * @param string $property name of property to find
10439 * @return bool true if property exists
10441 function object_property_exists( $obj, $property ) {
10442 if (is_string( $obj )) {
10443 $properties = get_class_vars( $obj );
10445 else {
10446 $properties = get_object_vars( $obj );
10448 return array_key_exists( $property, $properties );
10452 * Converts an object into an associative array
10454 * This function converts an object into an associative array by iterating
10455 * over its public properties. Because this function uses the foreach
10456 * construct, Iterators are respected. It works recursively on arrays of objects.
10457 * Arrays and simple values are returned as is.
10459 * If class has magic properties, it can implement IteratorAggregate
10460 * and return all available properties in getIterator()
10462 * @param mixed $var
10463 * @return array
10465 function convert_to_array($var) {
10466 $result = array();
10468 // loop over elements/properties
10469 foreach ($var as $key => $value) {
10470 // recursively convert objects
10471 if (is_object($value) || is_array($value)) {
10472 $result[$key] = convert_to_array($value);
10473 } else {
10474 // simple values are untouched
10475 $result[$key] = $value;
10478 return $result;
10482 * Detect a custom script replacement in the data directory that will
10483 * replace an existing moodle script
10485 * @return string|bool full path name if a custom script exists, false if no custom script exists
10487 function custom_script_path() {
10488 global $CFG, $SCRIPT;
10490 if ($SCRIPT === null) {
10491 // Probably some weird external script
10492 return false;
10495 $scriptpath = $CFG->customscripts . $SCRIPT;
10497 // check the custom script exists
10498 if (file_exists($scriptpath) and is_file($scriptpath)) {
10499 return $scriptpath;
10500 } else {
10501 return false;
10506 * Returns whether or not the user object is a remote MNET user. This function
10507 * is in moodlelib because it does not rely on loading any of the MNET code.
10509 * @global object
10510 * @param object $user A valid user object
10511 * @return bool True if the user is from a remote Moodle.
10513 function is_mnet_remote_user($user) {
10514 global $CFG;
10516 if (!isset($CFG->mnet_localhost_id)) {
10517 include_once $CFG->dirroot . '/mnet/lib.php';
10518 $env = new mnet_environment();
10519 $env->init();
10520 unset($env);
10523 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
10527 * This function will search for browser prefereed languages, setting Moodle
10528 * to use the best one available if $SESSION->lang is undefined
10530 * @global object
10531 * @global object
10532 * @global object
10534 function setup_lang_from_browser() {
10536 global $CFG, $SESSION, $USER;
10538 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
10539 // Lang is defined in session or user profile, nothing to do
10540 return;
10543 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
10544 return;
10547 /// Extract and clean langs from headers
10548 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
10549 $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
10550 $rawlangs = explode(',', $rawlangs); // Convert to array
10551 $langs = array();
10553 $order = 1.0;
10554 foreach ($rawlangs as $lang) {
10555 if (strpos($lang, ';') === false) {
10556 $langs[(string)$order] = $lang;
10557 $order = $order-0.01;
10558 } else {
10559 $parts = explode(';', $lang);
10560 $pos = strpos($parts[1], '=');
10561 $langs[substr($parts[1], $pos+1)] = $parts[0];
10564 krsort($langs, SORT_NUMERIC);
10566 /// Look for such langs under standard locations
10567 foreach ($langs as $lang) {
10568 $lang = strtolower(clean_param($lang, PARAM_SAFEDIR)); // clean it properly for include
10569 if (get_string_manager()->translation_exists($lang, false)) {
10570 $SESSION->lang = $lang; /// Lang exists, set it in session
10571 break; /// We have finished. Go out
10574 return;
10578 * check if $url matches anything in proxybypass list
10580 * any errors just result in the proxy being used (least bad)
10582 * @global object
10583 * @param string $url url to check
10584 * @return boolean true if we should bypass the proxy
10586 function is_proxybypass( $url ) {
10587 global $CFG;
10589 // sanity check
10590 if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
10591 return false;
10594 // get the host part out of the url
10595 if (!$host = parse_url( $url, PHP_URL_HOST )) {
10596 return false;
10599 // get the possible bypass hosts into an array
10600 $matches = explode( ',', $CFG->proxybypass );
10602 // check for a match
10603 // (IPs need to match the left hand side and hosts the right of the url,
10604 // but we can recklessly check both as there can't be a false +ve)
10605 $bypass = false;
10606 foreach ($matches as $match) {
10607 $match = trim($match);
10609 // try for IP match (Left side)
10610 $lhs = substr($host,0,strlen($match));
10611 if (strcasecmp($match,$lhs)==0) {
10612 return true;
10615 // try for host match (Right side)
10616 $rhs = substr($host,-strlen($match));
10617 if (strcasecmp($match,$rhs)==0) {
10618 return true;
10622 // nothing matched.
10623 return false;
10627 ////////////////////////////////////////////////////////////////////////////////
10630 * Check if the passed navigation is of the new style
10632 * @param mixed $navigation
10633 * @return bool true for yes false for no
10635 function is_newnav($navigation) {
10636 if (is_array($navigation) && !empty($navigation['newnav'])) {
10637 return true;
10638 } else {
10639 return false;
10644 * Checks whether the given variable name is defined as a variable within the given object.
10646 * This will NOT work with stdClass objects, which have no class variables.
10648 * @param string $var The variable name
10649 * @param object $object The object to check
10650 * @return boolean
10652 function in_object_vars($var, $object) {
10653 $class_vars = get_class_vars(get_class($object));
10654 $class_vars = array_keys($class_vars);
10655 return in_array($var, $class_vars);
10659 * Returns an array without repeated objects.
10660 * This function is similar to array_unique, but for arrays that have objects as values
10662 * @param array $array
10663 * @param bool $keep_key_assoc
10664 * @return array
10666 function object_array_unique($array, $keep_key_assoc = true) {
10667 $duplicate_keys = array();
10668 $tmp = array();
10670 foreach ($array as $key=>$val) {
10671 // convert objects to arrays, in_array() does not support objects
10672 if (is_object($val)) {
10673 $val = (array)$val;
10676 if (!in_array($val, $tmp)) {
10677 $tmp[] = $val;
10678 } else {
10679 $duplicate_keys[] = $key;
10683 foreach ($duplicate_keys as $key) {
10684 unset($array[$key]);
10687 return $keep_key_assoc ? $array : array_values($array);
10691 * Is a userid the primary administrator?
10693 * @param int $userid int id of user to check
10694 * @return boolean
10696 function is_primary_admin($userid){
10697 $primaryadmin = get_admin();
10699 if($userid == $primaryadmin->id){
10700 return true;
10701 }else{
10702 return false;
10707 * Returns the site identifier
10709 * @global object
10710 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10712 function get_site_identifier() {
10713 global $CFG;
10714 // Check to see if it is missing. If so, initialise it.
10715 if (empty($CFG->siteidentifier)) {
10716 set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10718 // Return it.
10719 return $CFG->siteidentifier;
10723 * Check whether the given password has no more than the specified
10724 * number of consecutive identical characters.
10726 * @param string $password password to be checked against the password policy
10727 * @param integer $maxchars maximum number of consecutive identical characters
10729 function check_consecutive_identical_characters($password, $maxchars) {
10731 if ($maxchars < 1) {
10732 return true; // 0 is to disable this check
10734 if (strlen($password) <= $maxchars) {
10735 return true; // too short to fail this test
10738 $previouschar = '';
10739 $consecutivecount = 1;
10740 foreach (str_split($password) as $char) {
10741 if ($char != $previouschar) {
10742 $consecutivecount = 1;
10744 else {
10745 $consecutivecount++;
10746 if ($consecutivecount > $maxchars) {
10747 return false; // check failed already
10751 $previouschar = $char;
10754 return true;
10758 * helper function to do partial function binding
10759 * so we can use it for preg_replace_callback, for example
10760 * this works with php functions, user functions, static methods and class methods
10761 * it returns you a callback that you can pass on like so:
10763 * $callback = partial('somefunction', $arg1, $arg2);
10764 * or
10765 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10766 * or even
10767 * $obj = new someclass();
10768 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10770 * and then the arguments that are passed through at calltime are appended to the argument list.
10772 * @param mixed $function a php callback
10773 * $param mixed $arg1.. $argv arguments to partially bind with
10775 * @return callback
10777 function partial() {
10778 if (!class_exists('partial')) {
10779 class partial{
10780 var $values = array();
10781 var $func;
10783 function __construct($func, $args) {
10784 $this->values = $args;
10785 $this->func = $func;
10788 function method() {
10789 $args = func_get_args();
10790 return call_user_func_array($this->func, array_merge($this->values, $args));
10794 $args = func_get_args();
10795 $func = array_shift($args);
10796 $p = new partial($func, $args);
10797 return array($p, 'method');
10801 * helper function to load up and initialise the mnet environment
10802 * this must be called before you use mnet functions.
10804 * @return mnet_environment the equivalent of old $MNET global
10806 function get_mnet_environment() {
10807 global $CFG;
10808 require_once($CFG->dirroot . '/mnet/lib.php');
10809 static $instance = null;
10810 if (empty($instance)) {
10811 $instance = new mnet_environment();
10812 $instance->init();
10814 return $instance;
10818 * during xmlrpc server code execution, any code wishing to access
10819 * information about the remote peer must use this to get it.
10821 * @return mnet_remote_client the equivalent of old $MNET_REMOTE_CLIENT global
10823 function get_mnet_remote_client() {
10824 if (!defined('MNET_SERVER')) {
10825 debugging(get_string('notinxmlrpcserver', 'mnet'));
10826 return false;
10828 global $MNET_REMOTE_CLIENT;
10829 if (isset($MNET_REMOTE_CLIENT)) {
10830 return $MNET_REMOTE_CLIENT;
10832 return false;
10836 * during the xmlrpc server code execution, this will be called
10837 * to setup the object returned by {@see get_mnet_remote_client}
10839 * @param mnet_remote_client $client the client to set up
10841 function set_mnet_remote_client($client) {
10842 if (!defined('MNET_SERVER')) {
10843 throw new moodle_exception('notinxmlrpcserver', 'mnet');
10845 global $MNET_REMOTE_CLIENT;
10846 $MNET_REMOTE_CLIENT = $client;
10850 * return the jump url for a given remote user
10851 * this is used for rewriting forum post links in emails, etc
10853 * @param stdclass $user the user to get the idp url for
10855 function mnet_get_idp_jump_url($user) {
10856 global $CFG;
10858 static $mnetjumps = array();
10859 if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10860 $idp = mnet_get_peer_host($user->mnethostid);
10861 $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10862 $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10864 return $mnetjumps[$user->mnethostid];
10868 * Gets the homepage to use for the current user
10870 * @return int One of HOMEPAGE_*
10872 function get_home_page() {
10873 global $CFG;
10875 if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10876 if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10877 return HOMEPAGE_MY;
10878 } else {
10879 return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
10882 return HOMEPAGE_SITE;
10886 * Gets the name of a course to be displayed when showing a list of courses.
10887 * By default this is just $course->fullname but user can configure it. The
10888 * result of this function should be passed through print_string.
10889 * @param stdClass|course_in_list $course Moodle course object
10890 * @return string Display name of course (either fullname or short + fullname)
10892 function get_course_display_name_for_list($course) {
10893 global $CFG;
10894 if (!empty($CFG->courselistshortnames)) {
10895 if (!($course instanceof stdClass)) {
10896 $course = (object)convert_to_array($course);
10898 return get_string('courseextendednamedisplay', '', $course);
10899 } else {
10900 return $course->fullname;
10905 * The lang_string class
10907 * This special class is used to create an object representation of a string request.
10908 * It is special because processing doesn't occur until the object is first used.
10909 * The class was created especially to aid performance in areas where strings were
10910 * required to be generated but were not necessarily used.
10911 * As an example the admin tree when generated uses over 1500 strings, of which
10912 * normally only 1/3 are ever actually printed at any time.
10913 * The performance advantage is achieved by not actually processing strings that
10914 * arn't being used, as such reducing the processing required for the page.
10916 * How to use the lang_string class?
10917 * There are two methods of using the lang_string class, first through the
10918 * forth argument of the get_string function, and secondly directly.
10919 * The following are examples of both.
10920 * 1. Through get_string calls e.g.
10921 * $string = get_string($identifier, $component, $a, true);
10922 * $string = get_string('yes', 'moodle', null, true);
10923 * 2. Direct instantiation
10924 * $string = new lang_string($identifier, $component, $a, $lang);
10925 * $string = new lang_string('yes');
10927 * How do I use a lang_string object?
10928 * The lang_string object makes use of a magic __toString method so that you
10929 * are able to use the object exactly as you would use a string in most cases.
10930 * This means you are able to collect it into a variable and then directly
10931 * echo it, or concatenate it into another string, or similar.
10932 * The other thing you can do is manually get the string by calling the
10933 * lang_strings out method e.g.
10934 * $string = new lang_string('yes');
10935 * $string->out();
10936 * Also worth noting is that the out method can take one argument, $lang which
10937 * allows the developer to change the language on the fly.
10939 * When should I use a lang_string object?
10940 * The lang_string object is designed to be used in any situation where a
10941 * string may not be needed, but needs to be generated.
10942 * The admin tree is a good example of where lang_string objects should be
10943 * used.
10944 * A more practical example would be any class that requries strings that may
10945 * not be printed (after all classes get renderer by renderers and who knows
10946 * what they will do ;))
10948 * When should I not use a lang_string object?
10949 * Don't use lang_strings when you are going to use a string immediately.
10950 * There is no need as it will be processed immediately and there will be no
10951 * advantage, and in fact perhaps a negative hit as a class has to be
10952 * instantiated for a lang_string object, however get_string won't require
10953 * that.
10955 * Limitations:
10956 * 1. You cannot use a lang_string object as an array offset. Doing so will
10957 * result in PHP throwing an error. (You can use it as an object property!)
10959 * @package core
10960 * @category string
10961 * @copyright 2011 Sam Hemelryk
10962 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10964 class lang_string {
10966 /** @var string The strings identifier */
10967 protected $identifier;
10968 /** @var string The strings component. Default '' */
10969 protected $component = '';
10970 /** @var array|stdClass Any arguments required for the string. Default null */
10971 protected $a = null;
10972 /** @var string The language to use when processing the string. Default null */
10973 protected $lang = null;
10975 /** @var string The processed string (once processed) */
10976 protected $string = null;
10979 * A special boolean. If set to true then the object has been woken up and
10980 * cannot be regenerated. If this is set then $this->string MUST be used.
10981 * @var bool
10983 protected $forcedstring = false;
10986 * Constructs a lang_string object
10988 * This function should do as little processing as possible to ensure the best
10989 * performance for strings that won't be used.
10991 * @param string $identifier The strings identifier
10992 * @param string $component The strings component
10993 * @param stdClass|array $a Any arguments the string requires
10994 * @param string $lang The language to use when processing the string.
10996 public function __construct($identifier, $component = '', $a = null, $lang = null) {
10997 if (empty($component)) {
10998 $component = 'moodle';
11001 $this->identifier = $identifier;
11002 $this->component = $component;
11003 $this->lang = $lang;
11005 // We MUST duplicate $a to ensure that it if it changes by reference those
11006 // changes are not carried across.
11007 // To do this we always ensure $a or its properties/values are strings
11008 // and that any properties/values that arn't convertable are forgotten.
11009 if (!empty($a)) {
11010 if (is_scalar($a)) {
11011 $this->a = $a;
11012 } else if ($a instanceof lang_string) {
11013 $this->a = $a->out();
11014 } else if (is_object($a) or is_array($a)) {
11015 $a = (array)$a;
11016 $this->a = array();
11017 foreach ($a as $key => $value) {
11018 // Make sure conversion errors don't get displayed (results in '')
11019 if (is_array($value)) {
11020 $this->a[$key] = '';
11021 } else if (is_object($value)) {
11022 if (method_exists($value, '__toString')) {
11023 $this->a[$key] = $value->__toString();
11024 } else {
11025 $this->a[$key] = '';
11027 } else {
11028 $this->a[$key] = (string)$value;
11034 if (debugging(false, DEBUG_DEVELOPER)) {
11035 if (clean_param($this->identifier, PARAM_STRINGID) == '') {
11036 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
11038 if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
11039 throw new coding_exception('Invalid string compontent. Please check your string definition');
11041 if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
11042 debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
11048 * Processes the string.
11050 * This function actually processes the string, stores it in the string property
11051 * and then returns it.
11052 * You will notice that this function is VERY similar to the get_string method.
11053 * That is because it is pretty much doing the same thing.
11054 * However as this function is an upgrade it isn't as tolerant to backwards
11055 * compatability.
11057 * @return string
11059 protected function get_string() {
11060 global $CFG;
11062 // Check if we need to process the string
11063 if ($this->string === null) {
11064 // Check the quality of the identifier.
11065 if (debugging('', DEBUG_DEVELOPER) && clean_param($this->identifier, PARAM_STRINGID) === '') {
11066 throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
11069 // Process the string
11070 $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
11071 // Debugging feature lets you display string identifier and component
11072 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
11073 $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
11076 // Return the string
11077 return $this->string;
11081 * Returns the string
11083 * @param string $lang The langauge to use when processing the string
11084 * @return string
11086 public function out($lang = null) {
11087 if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
11088 if ($this->forcedstring) {
11089 debugging('lang_string objects that have been serialised and unserialised cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
11090 return $this->get_string();
11092 $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
11093 return $translatedstring->out();
11095 return $this->get_string();
11099 * Magic __toString method for printing a string
11101 * @return string
11103 public function __toString() {
11104 return $this->get_string();
11108 * Magic __set_state method used for var_export
11110 * @return string
11112 public function __set_state() {
11113 return $this->get_string();
11117 * Prepares the lang_string for sleep and stores only the forcedstring and
11118 * string properties... the string cannot be regenerated so we need to ensure
11119 * it is generated for this.
11121 * @return string
11123 public function __sleep() {
11124 $this->get_string();
11125 $this->forcedstring = true;
11126 return array('forcedstring', 'string', 'lang');