3 ///////////////////////////////////////////////////////////////////////////
5 // NOTICE OF COPYRIGHT //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
10 // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
22 // http://www.gnu.org/copyleft/gpl.html //
24 ///////////////////////////////////////////////////////////////////////////
27 * moodlelib.php - Moodle main library
29 * Main library file of miscellaneous general-purpose Moodle functions.
30 * Other main libraries:
31 * - weblib.php - functions that produce web output
32 * - datalib.php - functions that access the database
33 * @author Martin Dougiamas
35 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
39 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
42 * Used by some scripts to check they are being called by Moodle
44 define('MOODLE_INTERNAL', true);
46 /// Date and time constants ///
48 * Time constant - the number of seconds in a year
51 define('YEARSECS', 31536000);
54 * Time constant - the number of seconds in a week
56 define('WEEKSECS', 604800);
59 * Time constant - the number of seconds in a day
61 define('DAYSECS', 86400);
64 * Time constant - the number of seconds in an hour
66 define('HOURSECS', 3600);
69 * Time constant - the number of seconds in a minute
71 define('MINSECS', 60);
74 * Time constant - the number of minutes in a day
76 define('DAYMINS', 1440);
79 * Time constant - the number of minutes in an hour
81 define('HOURMINS', 60);
83 /// Parameter constants - every call to optional_param(), required_param() ///
84 /// or clean_param() should have a specified type of parameter. //////////////
87 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way;
88 * originally was 0, but changed because we need to detect unknown
89 * parameter types and swiched order in clean_param().
91 define('PARAM_RAW', 666);
94 * PARAM_CLEAN - obsoleted, please try to use more specific type of parameter.
95 * It was one of the first types, that is why it is abused so much ;-)
97 define('PARAM_CLEAN', 0x0001);
100 * PARAM_INT - integers only, use when expecting only numbers.
102 define('PARAM_INT', 0x0002);
105 * PARAM_INTEGER - an alias for PARAM_INT
107 define('PARAM_INTEGER', 0x0002);
110 * PARAM_NUMBER - a real/floating point number.
112 define('PARAM_NUMBER', 0x000a);
115 * PARAM_ALPHA - contains only english letters.
117 define('PARAM_ALPHA', 0x0004);
120 * PARAM_ACTION - an alias for PARAM_ALPHA, use for various actions in formas and urls
121 * @TODO: should we alias it to PARAM_ALPHANUM ?
123 define('PARAM_ACTION', 0x0004);
126 * PARAM_FORMAT - an alias for PARAM_ALPHA, use for names of plugins, formats, etc.
127 * @TODO: should we alias it to PARAM_ALPHANUM ?
129 define('PARAM_FORMAT', 0x0004);
132 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
134 define('PARAM_NOTAGS', 0x0008);
137 * PARAM_MULTILANG - alias of PARAM_TEXT.
139 define('PARAM_MULTILANG', 0x0009);
142 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
144 define('PARAM_TEXT', 0x0009);
147 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
149 define('PARAM_FILE', 0x0010);
152 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international alphanumeric with spaces
154 define('PARAM_TAG', 0x0011);
157 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
159 define('PARAM_TAGLIST', 0x0012);
162 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
163 * note: the leading slash is not removed, window drive letter is not allowed
165 define('PARAM_PATH', 0x0020);
168 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
170 define('PARAM_HOST', 0x0040);
173 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not acceppted but http://localhost.localdomain/ is ok.
175 define('PARAM_URL', 0x0080);
178 * 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!)
180 define('PARAM_LOCALURL', 0x0180);
183 * PARAM_CLEANFILE - safe file name, all dangerous and regional chars are removed,
184 * use when you want to store a new file submitted by students
186 define('PARAM_CLEANFILE',0x0200);
189 * PARAM_ALPHANUM - expected numbers and letters only.
191 define('PARAM_ALPHANUM', 0x0400);
194 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
196 define('PARAM_BOOL', 0x0800);
199 * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes
200 * note: do not forget to addslashes() before storing into database!
202 define('PARAM_CLEANHTML',0x1000);
205 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "/-_" allowed,
206 * suitable for include() and require()
207 * @TODO: should we rename this function to PARAM_SAFEDIRS??
209 define('PARAM_ALPHAEXT', 0x2000);
212 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
214 define('PARAM_SAFEDIR', 0x4000);
217 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
219 define('PARAM_SEQUENCE', 0x8000);
222 * PARAM_PEM - Privacy Enhanced Mail format
224 define('PARAM_PEM', 0x10000);
227 * PARAM_BASE64 - Base 64 encoded format
229 define('PARAM_BASE64', 0x20000);
234 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
236 define('PAGE_COURSE_VIEW', 'course-view');
239 /** no warnings at all */
240 define ('DEBUG_NONE', 0);
241 /** E_ERROR | E_PARSE */
242 define ('DEBUG_MINIMAL', 5);
243 /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
244 define ('DEBUG_NORMAL', 15);
245 /** E_ALL without E_STRICT and E_RECOVERABLE_ERROR for now */
246 define ('DEBUG_ALL', 2047);
247 /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
248 define ('DEBUG_DEVELOPER', 34815);
251 * Blog access level constant declaration
253 define ('BLOG_USER_LEVEL', 1);
254 define ('BLOG_GROUP_LEVEL', 2);
255 define ('BLOG_COURSE_LEVEL', 3);
256 define ('BLOG_SITE_LEVEL', 4);
257 define ('BLOG_GLOBAL_LEVEL', 5);
262 define('TAG_MAX_LENGTH', 50);
266 /// PARAMETER HANDLING ////////////////////////////////////////////////////
269 * Returns a particular value for the named variable, taken from
270 * POST or GET. If the parameter doesn't exist then an error is
271 * thrown because we require this variable.
273 * This function should be used to initialise all required values
274 * in a script that are based on parameters. Usually it will be
276 * $id = required_param('id');
278 * @param string $parname the name of the page parameter we want
279 * @param int $type expected type of parameter
282 function required_param($parname, $type=PARAM_CLEAN
) {
284 // detect_unchecked_vars addition
286 if (!empty($CFG->detect_unchecked_vars
)) {
287 global $UNCHECKED_VARS;
288 unset ($UNCHECKED_VARS->vars
[$parname]);
291 if (isset($_POST[$parname])) { // POST has precedence
292 $param = $_POST[$parname];
293 } else if (isset($_GET[$parname])) {
294 $param = $_GET[$parname];
296 error('A required parameter ('.$parname.') was missing');
299 return clean_param($param, $type);
303 * Returns a particular value for the named variable, taken from
304 * POST or GET, otherwise returning a given default.
306 * This function should be used to initialise all optional values
307 * in a script that are based on parameters. Usually it will be
309 * $name = optional_param('name', 'Fred');
311 * @param string $parname the name of the page parameter we want
312 * @param mixed $default the default value to return if nothing is found
313 * @param int $type expected type of parameter
316 function optional_param($parname, $default=NULL, $type=PARAM_CLEAN
) {
318 // detect_unchecked_vars addition
320 if (!empty($CFG->detect_unchecked_vars
)) {
321 global $UNCHECKED_VARS;
322 unset ($UNCHECKED_VARS->vars
[$parname]);
325 if (isset($_POST[$parname])) { // POST has precedence
326 $param = $_POST[$parname];
327 } else if (isset($_GET[$parname])) {
328 $param = $_GET[$parname];
333 return clean_param($param, $type);
337 * Used by {@link optional_param()} and {@link required_param()} to
338 * clean the variables and/or cast to specific types, based on
341 * $course->format = clean_param($course->format, PARAM_ALPHA);
342 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
348 * @uses PARAM_INTEGER
350 * @uses PARAM_ALPHANUM
352 * @uses PARAM_ALPHAEXT
354 * @uses PARAM_SAFEDIR
355 * @uses PARAM_CLEANFILE
360 * @uses PARAM_LOCALURL
361 * @uses PARAM_CLEANHTML
362 * @uses PARAM_SEQUENCE
363 * @param mixed $param the variable we are cleaning
364 * @param int $type expected format of param after cleaning.
367 function clean_param($param, $type) {
371 if (is_array($param)) { // Let's loop
373 foreach ($param as $key => $value) {
374 $newparam[$key] = clean_param($value, $type);
380 case PARAM_RAW
: // no cleaning at all
383 case PARAM_CLEAN
: // General HTML cleaning, try to use more specific type if possible
384 if (is_numeric($param)) {
387 $param = stripslashes($param); // Needed for kses to work fine
388 $param = clean_text($param); // Sweep for scripts, etc
389 return addslashes($param); // Restore original request parameter slashes
391 case PARAM_CLEANHTML
: // prepare html fragment for display, do not store it into db!!
392 $param = stripslashes($param); // Remove any slashes
393 $param = clean_text($param); // Sweep for scripts, etc
397 return (int)$param; // Convert to integer
400 return (float)$param; // Convert to integer
402 case PARAM_ALPHA
: // Remove everything not a-z
403 return eregi_replace('[^a-zA-Z]', '', $param);
405 case PARAM_ALPHANUM
: // Remove everything not a-zA-Z0-9
406 return eregi_replace('[^A-Za-z0-9]', '', $param);
408 case PARAM_ALPHAEXT
: // Remove everything not a-zA-Z/_-
409 return eregi_replace('[^a-zA-Z/_-]', '', $param);
411 case PARAM_SEQUENCE
: // Remove everything not 0-9,
412 return eregi_replace('[^0-9,]', '', $param);
414 case PARAM_BOOL
: // Convert to 1 or 0
415 $tempstr = strtolower($param);
416 if ($tempstr == 'on' or $tempstr == 'yes' ) {
418 } else if ($tempstr == 'off' or $tempstr == 'no') {
421 $param = empty($param) ?
0 : 1;
425 case PARAM_NOTAGS
: // Strip all tags
426 return strip_tags($param);
428 case PARAM_TEXT
: // leave only tags needed for multilang
429 return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN
);
431 case PARAM_SAFEDIR
: // Remove everything not a-zA-Z0-9_-
432 return eregi_replace('[^a-zA-Z0-9_-]', '', $param);
434 case PARAM_CLEANFILE
: // allow only safe characters
435 return clean_filename($param);
437 case PARAM_FILE
: // Strip all suspicious characters from filename
438 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':\\/]', '', $param);
439 $param = ereg_replace('\.\.+', '', $param);
445 case PARAM_PATH
: // Strip all suspicious characters from file path
446 $param = str_replace('\\\'', '\'', $param);
447 $param = str_replace('\\"', '"', $param);
448 $param = str_replace('\\', '/', $param);
449 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':]', '', $param);
450 $param = ereg_replace('\.\.+', '', $param);
451 $param = ereg_replace('//+', '/', $param);
452 return ereg_replace('/(\./)+', '/', $param);
454 case PARAM_HOST
: // allow FQDN or IPv4 dotted quad
455 preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
456 // match ipv4 dotted quad
457 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
458 // confirm values are ok
462 ||
$match[4] > 255 ) {
463 // hmmm, what kind of dotted quad is this?
466 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
467 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
468 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
470 // all is ok - $param is respected
477 case PARAM_URL
: // allow safe ftp, http, mailto urls
478 include_once($CFG->dirroot
. '/lib/validateurlsyntax.php');
479 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
480 // all is ok, param is respected
482 $param =''; // not really ok
486 case PARAM_LOCALURL
: // allow http absolute, root relative and relative URLs within wwwroot
487 $param = clean_param($param, PARAM_URL
);
488 if (!empty($param)) {
489 if (preg_match(':^/:', $param)) {
490 // root-relative, ok!
491 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot
, '/').'/i',$param)) {
492 // absolute, and matches our wwwroot
494 // relative - let's make sure there are no tricks
495 if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
505 $param = trim($param);
506 // PEM formatted strings may contain letters/numbers and the symbols
510 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
511 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
512 list($wholething, $body) = $matches;
513 unset($wholething, $matches);
514 $b64 = clean_param($body, PARAM_BASE64
);
516 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
524 if (!empty($param)) {
525 // PEM formatted strings may contain letters/numbers and the symbols
529 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
532 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY
);
533 // Each line of base64 encoded data must be 64 characters in
534 // length, except for the last line which may be less than (or
535 // equal to) 64 characters long.
536 for ($i=0, $j=count($lines); $i < $j; $i++
) {
538 if (64 < strlen($lines[$i])) {
544 if (64 != strlen($lines[$i])) {
548 return implode("\n",$lines);
554 //first fix whitespace
555 $param = preg_replace('/\s+/', ' ', $param);
556 //remove blacklisted ASCII ranges of chars - security FIRST - keep only ascii letters, numnbers and spaces
557 //the result should be safe to be used directly in html and SQL
558 $param = preg_replace("/[\\000-\\x1f\\x21-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]/", '', $param);
559 //now remove some unicode ranges we do not want
560 $param = preg_replace("/[\\x{80}-\\x{bf}\\x{d7}\\x{f7}]/u", '', $param);
562 $param = preg_replace('/ +/', ' ', $param);
563 $param = trim($param);
564 $textlib = textlib_get_instance();
565 $param = $textlib->substr($param, 0, TAG_MAX_LENGTH
);
566 //numeric tags not allowed
567 return is_numeric($param) ?
'' : $param;
570 $tags = explode(',', $param);
572 foreach ($tags as $tag) {
573 $res = clean_param($tag, PARAM_TAG
);
579 return implode(',', $result);
584 default: // throw error, switched parameters in optional_param or another serious problem
585 error("Unknown parameter type: $type");
592 * Set a key in global configuration
594 * Set a key/value pair in both this session's {@link $CFG} global variable
595 * and in the 'config' database table for future sessions.
597 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
598 * In that case it doesn't affect $CFG.
600 * @param string $name the key to set
601 * @param string $value the value to set (without magic quotes)
602 * @param string $plugin (optional) the plugin scope
606 function set_config($name, $value, $plugin=NULL) {
607 /// No need for get_config because they are usually always available in $CFG
611 if (empty($plugin)) {
612 $CFG->$name = $value; // So it's defined for this invocation at least
614 if (get_field('config', 'name', 'name', $name)) {
615 return set_field('config', 'value', addslashes($value), 'name', $name);
617 $config = new object();
618 $config->name
= $name;
619 $config->value
= addslashes($value);
620 return insert_record('config', $config);
622 } else { // plugin scope
623 if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
624 return set_field('config_plugins', 'value', addslashes($value), 'id', $id);
626 $config = new object();
627 $config->plugin
= addslashes($plugin);
628 $config->name
= $name;
629 $config->value
= addslashes($value);
630 return insert_record('config_plugins', $config);
636 * Get configuration values from the global config table
637 * or the config_plugins table.
639 * If called with no parameters it will do the right thing
640 * generating $CFG safely from the database without overwriting
643 * If called with 2 parameters it will return a $string single
644 * value or false of the value is not found.
646 * @param string $plugin
647 * @param string $name
649 * @return hash-like object or single value
652 function get_config($plugin=NULL, $name=NULL) {
656 if (!empty($name)) { // the user is asking for a specific value
657 if (!empty($plugin)) {
658 return get_field('config_plugins', 'value', 'plugin' , $plugin, 'name', $name);
660 return get_field('config', 'value', 'name', $name);
664 // the user is after a recordset
665 if (!empty($plugin)) {
666 if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
667 $configs = (array)$configs;
669 foreach ($configs as $config) {
670 $localcfg[$config->name
] = $config->value
;
672 return (object)$localcfg;
677 // this was originally in setup.php
678 if ($configs = get_records('config')) {
679 $localcfg = (array)$CFG;
680 foreach ($configs as $config) {
681 if (!isset($localcfg[$config->name
])) {
682 $localcfg[$config->name
] = $config->value
;
684 if ($localcfg[$config->name
] != $config->value
) {
685 // complain if the DB has a different
686 // value than config.php does
687 error_log("\$CFG->{$config->name} in config.php ({$localcfg[$config->name]}) overrides database setting ({$config->value})");
692 $localcfg = (object)$localcfg;
695 // preserve $CFG if DB returns nothing or error
703 * Removes a key from global configuration
705 * @param string $name the key to set
706 * @param string $plugin (optional) the plugin scope
710 function unset_config($name, $plugin=NULL) {
716 if (empty($plugin)) {
717 return delete_records('config', 'name', $name);
719 return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
726 * @param string $type
727 * @param int $changedsince
728 * @return records array
731 function get_cache_flags($type, $changedsince=NULL) {
733 $type = addslashes($type);
735 $sqlwhere = 'flagtype=\'' . $type . '\' AND expiry >= ' . time();
736 if ($changedsince !== NULL) {
737 $changedsince = (int)$changedsince;
738 $sqlwhere .= ' AND timemodified > ' . $changedsince;
741 if ($flags=get_records_select('cache_flags', $sqlwhere, '', 'name,value')) {
742 foreach ($flags as $flag) {
743 $cf[$flag->name
] = $flag->value
;
751 * Set a volatile flag
753 * @param string $type the "type" namespace for the key
754 * @param string $name the key to set
755 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
756 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
759 function set_cache_flag($type, $name, $value, $expiry=NULL) {
762 $timemodified = time();
763 if ($expiry===NULL ||
$expiry < $timemodified) {
764 $expiry = $timemodified +
24 * 60 * 60;
766 $expiry = (int)$expiry;
769 if ($value === NULL) {
770 return unset_cache_flag($type,$name);
773 $type = addslashes($type);
774 $name = addslashes($name);
775 if ($f = get_record('cache_flags', 'name', $name, 'flagtype', $type)) { // this is a potentail problem in DEBUG_DEVELOPER
776 if ($f->value
== $value and $f->expiry
== $expiry and $f->timemodified
== $timemodified) {
777 return true; //no need to update; helps rcache too
779 $f->value
= addslashes($value);
780 $f->expiry
= $expiry;
781 $f->timemodified
= $timemodified;
782 return update_record('cache_flags', $f);
785 $f->flagtype
= $type;
787 $f->value
= addslashes($value);
788 $f->expiry
= $expiry;
789 $f->timemodified
= $timemodified;
790 return (bool)insert_record('cache_flags', $f);
795 * Removes a single volatile flag
797 * @param string $type the "type" namespace for the key
798 * @param string $name the key to set
802 function unset_cache_flag($type, $name) {
804 return delete_records('cache_flags',
805 'name', addslashes($name),
806 'flagtype', addslashes($type));
810 * Garbage-collect volatile flags
813 function gc_cache_flags() {
814 return delete_records_select('cache_flags', 'expiry < ' . time());
818 * Refresh current $USER session global variable with all their current preferences.
821 function reload_user_preferences() {
826 $USER->preference
= array();
828 if (!isloggedin() or isguestuser()) {
829 // no pernament storage for not-logged-in user and guest
831 } else if ($preferences = get_records('user_preferences', 'userid', $USER->id
)) {
832 foreach ($preferences as $preference) {
833 $USER->preference
[$preference->name
] = $preference->value
;
841 * Sets a preference for the current user
842 * Optionally, can set a preference for a different user object
844 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
846 * @param string $name The key to set as preference for the specified user
847 * @param string $value The value to set forthe $name key in the specified user's record
848 * @param int $otheruserid A moodle user ID
851 function set_user_preference($name, $value, $otheruserid=NULL) {
855 if (!isset($USER->preference
)) {
856 reload_user_preferences();
865 if (empty($otheruserid)){
866 if (!isloggedin() or isguestuser()) {
871 if (isguestuser($otheruserid)) {
874 $userid = $otheruserid;
879 // no pernament storage for not-logged-in user and guest
881 } else if ($preference = get_record('user_preferences', 'userid', $userid, 'name', addslashes($name))) {
882 if ($preference->value
=== $value) {
885 if (!set_field('user_preferences', 'value', addslashes((string)$value), 'id', $preference->id
)) {
890 $preference = new object();
891 $preference->userid
= $userid;
892 $preference->name
= addslashes($name);
893 $preference->value
= addslashes((string)$value);
894 if (!insert_record('user_preferences', $preference)) {
899 // update value in USER session if needed
900 if ($userid == $USER->id
) {
901 $USER->preference
[$name] = (string)$value;
908 * Unsets a preference completely by deleting it from the database
909 * Optionally, can set a preference for a different user id
911 * @param string $name The key to unset as preference for the specified user
912 * @param int $otheruserid A moodle user ID
914 function unset_user_preference($name, $otheruserid=NULL) {
918 if (!isset($USER->preference
)) {
919 reload_user_preferences();
922 if (empty($otheruserid)){
925 $userid = $otheruserid;
928 //Delete the preference from $USER if needed
929 if ($userid == $USER->id
) {
930 unset($USER->preference
[$name]);
934 return delete_records('user_preferences', 'userid', $userid, 'name', addslashes($name));
939 * Sets a whole array of preferences for the current user
940 * @param array $prefarray An array of key/value pairs to be set
941 * @param int $otheruserid A moodle user ID
944 function set_user_preferences($prefarray, $otheruserid=NULL) {
946 if (!is_array($prefarray) or empty($prefarray)) {
951 foreach ($prefarray as $name => $value) {
952 // The order is important; test for return is done first
953 $return = (set_user_preference($name, $value, $otheruserid) && $return);
959 * If no arguments are supplied this function will return
960 * all of the current user preferences as an array.
961 * If a name is specified then this function
962 * attempts to return that particular preference value. If
963 * none is found, then the optional value $default is returned,
965 * @param string $name Name of the key to use in finding a preference value
966 * @param string $default Value to be returned if the $name key is not set in the user preferences
967 * @param int $otheruserid A moodle user ID
971 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
974 if (!isset($USER->preference
)) {
975 reload_user_preferences();
978 if (empty($otheruserid)){
981 $userid = $otheruserid;
984 if ($userid == $USER->id
) {
985 $preference = $USER->preference
;
988 $preference = array();
989 if ($prefdata = get_records('user_preferences', 'userid', $userid)) {
990 foreach ($prefdata as $pref) {
991 $preference[$pref->name
] = $pref->value
;
997 return $preference; // All values
999 } else if (array_key_exists($name, $preference)) {
1000 return $preference[$name]; // The single value
1003 return $default; // Default value (or NULL)
1008 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1011 * Given date parts in user time produce a GMT timestamp.
1013 * @param int $year The year part to create timestamp of
1014 * @param int $month The month part to create timestamp of
1015 * @param int $day The day part to create timestamp of
1016 * @param int $hour The hour part to create timestamp of
1017 * @param int $minute The minute part to create timestamp of
1018 * @param int $second The second part to create timestamp of
1019 * @param float $timezone ?
1020 * @param bool $applydst ?
1021 * @return int timestamp
1022 * @todo Finish documenting this function
1024 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1026 $timezone = get_user_timezone_offset($timezone);
1028 if (abs($timezone) > 13) {
1029 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1031 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1032 $time = usertime($time, $timezone);
1034 $time -= dst_offset_on($time);
1043 * Given an amount of time in seconds, returns string
1044 * formatted nicely as weeks, days, hours etc as needed
1050 * @param int $totalsecs ?
1051 * @param array $str ?
1054 function format_time($totalsecs, $str=NULL) {
1056 $totalsecs = abs($totalsecs);
1058 if (!$str) { // Create the str structure the slow way
1059 $str->day
= get_string('day');
1060 $str->days
= get_string('days');
1061 $str->hour
= get_string('hour');
1062 $str->hours
= get_string('hours');
1063 $str->min
= get_string('min');
1064 $str->mins
= get_string('mins');
1065 $str->sec
= get_string('sec');
1066 $str->secs
= get_string('secs');
1067 $str->year
= get_string('year');
1068 $str->years
= get_string('years');
1072 $years = floor($totalsecs/YEARSECS
);
1073 $remainder = $totalsecs - ($years*YEARSECS
);
1074 $days = floor($remainder/DAYSECS
);
1075 $remainder = $totalsecs - ($days*DAYSECS
);
1076 $hours = floor($remainder/HOURSECS
);
1077 $remainder = $remainder - ($hours*HOURSECS
);
1078 $mins = floor($remainder/MINSECS
);
1079 $secs = $remainder - ($mins*MINSECS
);
1081 $ss = ($secs == 1) ?
$str->sec
: $str->secs
;
1082 $sm = ($mins == 1) ?
$str->min
: $str->mins
;
1083 $sh = ($hours == 1) ?
$str->hour
: $str->hours
;
1084 $sd = ($days == 1) ?
$str->day
: $str->days
;
1085 $sy = ($years == 1) ?
$str->year
: $str->years
;
1093 if ($years) $oyears = $years .' '. $sy;
1094 if ($days) $odays = $days .' '. $sd;
1095 if ($hours) $ohours = $hours .' '. $sh;
1096 if ($mins) $omins = $mins .' '. $sm;
1097 if ($secs) $osecs = $secs .' '. $ss;
1099 if ($years) return trim($oyears .' '. $odays);
1100 if ($days) return trim($odays .' '. $ohours);
1101 if ($hours) return trim($ohours .' '. $omins);
1102 if ($mins) return trim($omins .' '. $osecs);
1103 if ($secs) return $osecs;
1104 return get_string('now');
1108 * Returns a formatted string that represents a date in user time
1109 * <b>WARNING: note that the format is for strftime(), not date().</b>
1110 * Because of a bug in most Windows time libraries, we can't use
1111 * the nicer %e, so we have to use %d which has leading zeroes.
1112 * A lot of the fuss in the function is just getting rid of these leading
1113 * zeroes as efficiently as possible.
1115 * If parameter fixday = true (default), then take off leading
1116 * zero from %d, else mantain it.
1119 * @param int $date timestamp in GMT
1120 * @param string $format strftime format
1121 * @param float $timezone
1122 * @param bool $fixday If true (default) then the leading
1123 * zero from %d is removed. If false then the leading zero is mantained.
1126 function userdate($date, $format='', $timezone=99, $fixday = true) {
1130 if (empty($format)) {
1131 $format = get_string('strftimedaydatetime');
1134 if (!empty($CFG->nofixday
)) { // Config.php can force %d not to be fixed.
1136 } else if ($fixday) {
1137 $formatnoday = str_replace('%d', 'DD', $format);
1138 $fixday = ($formatnoday != $format);
1141 $date +
= dst_offset_on($date);
1143 $timezone = get_user_timezone_offset($timezone);
1145 if (abs($timezone) > 13) { /// Server time
1147 $datestring = strftime($formatnoday, $date);
1148 $daystring = str_replace(' 0', '', strftime(' %d', $date));
1149 $datestring = str_replace('DD', $daystring, $datestring);
1151 $datestring = strftime($format, $date);
1154 $date +
= (int)($timezone * 3600);
1156 $datestring = gmstrftime($formatnoday, $date);
1157 $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
1158 $datestring = str_replace('DD', $daystring, $datestring);
1160 $datestring = gmstrftime($format, $date);
1164 /// If we are running under Windows convert from windows encoding to UTF-8
1165 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1167 if ($CFG->ostype
== 'WINDOWS') {
1168 if ($localewincharset = get_string('localewincharset')) {
1169 $textlib = textlib_get_instance();
1170 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1178 * Given a $time timestamp in GMT (seconds since epoch),
1179 * returns an array that represents the date in user time
1182 * @param int $time Timestamp in GMT
1183 * @param float $timezone ?
1184 * @return array An array that represents the date in user time
1185 * @todo Finish documenting this function
1187 function usergetdate($time, $timezone=99) {
1189 $timezone = get_user_timezone_offset($timezone);
1191 if (abs($timezone) > 13) { // Server time
1192 return getdate($time);
1195 // There is no gmgetdate so we use gmdate instead
1196 $time +
= dst_offset_on($time);
1197 $time +
= intval((float)$timezone * HOURSECS
);
1199 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
1202 $getdate['seconds'],
1203 $getdate['minutes'],
1210 $getdate['weekday'],
1212 ) = explode('_', $datestring);
1218 * Given a GMT timestamp (seconds since epoch), offsets it by
1219 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1222 * @param int $date Timestamp in GMT
1223 * @param float $timezone
1226 function usertime($date, $timezone=99) {
1228 $timezone = get_user_timezone_offset($timezone);
1230 if (abs($timezone) > 13) {
1233 return $date - (int)($timezone * HOURSECS
);
1237 * Given a time, return the GMT timestamp of the most recent midnight
1238 * for the current user.
1240 * @param int $date Timestamp in GMT
1241 * @param float $timezone ?
1244 function usergetmidnight($date, $timezone=99) {
1246 $timezone = get_user_timezone_offset($timezone);
1247 $userdate = usergetdate($date, $timezone);
1249 // Time of midnight of this user's day, in GMT
1250 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1255 * Returns a string that prints the user's timezone
1257 * @param float $timezone The user's timezone
1260 function usertimezone($timezone=99) {
1262 $tz = get_user_timezone($timezone);
1264 if (!is_float($tz)) {
1268 if(abs($tz) > 13) { // Server time
1269 return get_string('serverlocaltime');
1272 if($tz == intval($tz)) {
1273 // Don't show .0 for whole hours
1290 * Returns a float which represents the user's timezone difference from GMT in hours
1291 * Checks various settings and picks the most dominant of those which have a value
1295 * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
1298 function get_user_timezone_offset($tz = 99) {
1302 $tz = get_user_timezone($tz);
1304 if (is_float($tz)) {
1307 $tzrecord = get_timezone_record($tz);
1308 if (empty($tzrecord)) {
1311 return (float)$tzrecord->gmtoff
/ HOURMINS
;
1316 * Returns a float or a string which denotes the user's timezone
1317 * 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)
1318 * means that for this timezone there are also DST rules to be taken into account
1319 * Checks various settings and picks the most dominant of those which have a value
1323 * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
1326 function get_user_timezone($tz = 99) {
1331 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
1332 isset($USER->timezone
) ?
$USER->timezone
: 99,
1333 isset($CFG->timezone
) ?
$CFG->timezone
: 99,
1338 while(($tz == '' ||
$tz == 99) && $next = each($timezones)) {
1339 $tz = $next['value'];
1342 return is_numeric($tz) ?
(float) $tz : $tz;
1350 * @param string $timezonename ?
1353 function get_timezone_record($timezonename) {
1355 static $cache = NULL;
1357 if ($cache === NULL) {
1361 if (isset($cache[$timezonename])) {
1362 return $cache[$timezonename];
1365 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix
.'timezone
1366 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
1374 * @param ? $fromyear ?
1375 * @param ? $to_year ?
1378 function calculate_user_dst_table($from_year = NULL, $to_year = NULL) {
1379 global $CFG, $SESSION;
1381 $usertz = get_user_timezone();
1383 if (is_float($usertz)) {
1384 // Trivial timezone, no DST
1388 if (!empty($SESSION->dst_offsettz
) && $SESSION->dst_offsettz
!= $usertz) {
1389 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1390 unset($SESSION->dst_offsets
);
1391 unset($SESSION->dst_range
);
1394 if (!empty($SESSION->dst_offsets
) && empty($from_year) && empty($to_year)) {
1395 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1396 // This will be the return path most of the time, pretty light computationally
1400 // Reaching here means we either need to extend our table or create it from scratch
1402 // Remember which TZ we calculated these changes for
1403 $SESSION->dst_offsettz
= $usertz;
1405 if(empty($SESSION->dst_offsets
)) {
1406 // If we 're creating from scratch, put the two guard elements in there
1407 $SESSION->dst_offsets
= array(1 => NULL, 0 => NULL);
1409 if(empty($SESSION->dst_range
)) {
1410 // If creating from scratch
1411 $from = max((empty($from_year) ?
intval(date('Y')) - 3 : $from_year), 1971);
1412 $to = min((empty($to_year) ?
intval(date('Y')) +
3 : $to_year), 2035);
1414 // Fill in the array with the extra years we need to process
1415 $yearstoprocess = array();
1416 for($i = $from; $i <= $to; ++
$i) {
1417 $yearstoprocess[] = $i;
1420 // Take note of which years we have processed for future calls
1421 $SESSION->dst_range
= array($from, $to);
1424 // If needing to extend the table, do the same
1425 $yearstoprocess = array();
1427 $from = max((empty($from_year) ?
$SESSION->dst_range
[0] : $from_year), 1971);
1428 $to = min((empty($to_year) ?
$SESSION->dst_range
[1] : $to_year), 2035);
1430 if($from < $SESSION->dst_range
[0]) {
1431 // Take note of which years we need to process and then note that we have processed them for future calls
1432 for($i = $from; $i < $SESSION->dst_range
[0]; ++
$i) {
1433 $yearstoprocess[] = $i;
1435 $SESSION->dst_range
[0] = $from;
1437 if($to > $SESSION->dst_range
[1]) {
1438 // Take note of which years we need to process and then note that we have processed them for future calls
1439 for($i = $SESSION->dst_range
[1] +
1; $i <= $to; ++
$i) {
1440 $yearstoprocess[] = $i;
1442 $SESSION->dst_range
[1] = $to;
1446 if(empty($yearstoprocess)) {
1447 // This means that there was a call requesting a SMALLER range than we have already calculated
1451 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1452 // Also, the array is sorted in descending timestamp order!
1455 $presetrecords = get_records('timezone', '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');
1456 if(empty($presetrecords)) {
1460 // Remove ending guard (first element of the array)
1461 reset($SESSION->dst_offsets
);
1462 unset($SESSION->dst_offsets
[key($SESSION->dst_offsets
)]);
1464 // Add all required change timestamps
1465 foreach($yearstoprocess as $y) {
1466 // Find the record which is in effect for the year $y
1467 foreach($presetrecords as $year => $preset) {
1473 $changes = dst_changes_for_year($y, $preset);
1475 if($changes === NULL) {
1478 if($changes['dst'] != 0) {
1479 $SESSION->dst_offsets
[$changes['dst']] = $preset->dstoff
* MINSECS
;
1481 if($changes['std'] != 0) {
1482 $SESSION->dst_offsets
[$changes['std']] = 0;
1486 // Put in a guard element at the top
1487 $maxtimestamp = max(array_keys($SESSION->dst_offsets
));
1488 $SESSION->dst_offsets
[($maxtimestamp + DAYSECS
)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1491 krsort($SESSION->dst_offsets
);
1496 function dst_changes_for_year($year, $timezone) {
1498 if($timezone->dst_startday
== 0 && $timezone->dst_weekday
== 0 && $timezone->std_startday
== 0 && $timezone->std_weekday
== 0) {
1502 $monthdaydst = find_day_in_month($timezone->dst_startday
, $timezone->dst_weekday
, $timezone->dst_month
, $year);
1503 $monthdaystd = find_day_in_month($timezone->std_startday
, $timezone->std_weekday
, $timezone->std_month
, $year);
1505 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time
);
1506 list($std_hour, $std_min) = explode(':', $timezone->std_time
);
1508 $timedst = make_timestamp($year, $timezone->dst_month
, $monthdaydst, 0, 0, 0, 99, false);
1509 $timestd = make_timestamp($year, $timezone->std_month
, $monthdaystd, 0, 0, 0, 99, false);
1511 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1512 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1513 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1515 $timedst +
= $dst_hour * HOURSECS +
$dst_min * MINSECS
;
1516 $timestd +
= $std_hour * HOURSECS +
$std_min * MINSECS
;
1518 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1521 // $time must NOT be compensated at all, it has to be a pure timestamp
1522 function dst_offset_on($time) {
1525 if(!calculate_user_dst_table() ||
empty($SESSION->dst_offsets
)) {
1529 reset($SESSION->dst_offsets
);
1530 while(list($from, $offset) = each($SESSION->dst_offsets
)) {
1531 if($from <= $time) {
1536 // This is the normal return path
1537 if($offset !== NULL) {
1541 // Reaching this point means we haven't calculated far enough, do it now:
1542 // Calculate extra DST changes if needed and recurse. The recursion always
1543 // moves toward the stopping condition, so will always end.
1546 // We need a year smaller than $SESSION->dst_range[0]
1547 if($SESSION->dst_range
[0] == 1971) {
1550 calculate_user_dst_table($SESSION->dst_range
[0] - 5, NULL);
1551 return dst_offset_on($time);
1554 // We need a year larger than $SESSION->dst_range[1]
1555 if($SESSION->dst_range
[1] == 2035) {
1558 calculate_user_dst_table(NULL, $SESSION->dst_range
[1] +
5);
1559 return dst_offset_on($time);
1563 function find_day_in_month($startday, $weekday, $month, $year) {
1565 $daysinmonth = days_in_month($month, $year);
1567 if($weekday == -1) {
1568 // Don't care about weekday, so return:
1569 // abs($startday) if $startday != -1
1570 // $daysinmonth otherwise
1571 return ($startday == -1) ?
$daysinmonth : abs($startday);
1574 // From now on we 're looking for a specific weekday
1576 // Give "end of month" its actual value, since we know it
1577 if($startday == -1) {
1578 $startday = -1 * $daysinmonth;
1581 // Starting from day $startday, the sign is the direction
1585 $startday = abs($startday);
1586 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1588 // This is the last such weekday of the month
1589 $lastinmonth = $daysinmonth +
$weekday - $lastmonthweekday;
1590 if($lastinmonth > $daysinmonth) {
1594 // Find the first such weekday <= $startday
1595 while($lastinmonth > $startday) {
1599 return $lastinmonth;
1604 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
1606 $diff = $weekday - $indexweekday;
1611 // This is the first such weekday of the month equal to or after $startday
1612 $firstfromindex = $startday +
$diff;
1614 return $firstfromindex;
1620 * Calculate the number of days in a given month
1622 * @param int $month The month whose day count is sought
1623 * @param int $year The year of the month whose day count is sought
1626 function days_in_month($month, $year) {
1627 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1631 * Calculate the position in the week of a specific calendar day
1633 * @param int $day The day of the date whose position in the week is sought
1634 * @param int $month The month of the date whose position in the week is sought
1635 * @param int $year The year of the date whose position in the week is sought
1638 function dayofweek($day, $month, $year) {
1639 // I wonder if this is any different from
1640 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1641 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1644 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
1647 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1648 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1649 * sesskey string if $USER exists, or boolean false if not.
1654 function sesskey() {
1661 if (empty($USER->sesskey
)) {
1662 $USER->sesskey
= random_string(10);
1665 return $USER->sesskey
;
1670 * For security purposes, this function will check that the currently
1671 * given sesskey (passed as a parameter to the script or this function)
1672 * matches that of the current user.
1674 * @param string $sesskey optionally provided sesskey
1677 function confirm_sesskey($sesskey=NULL) {
1680 if (!empty($USER->ignoresesskey
) ||
!empty($CFG->ignoresesskey
)) {
1684 if (empty($sesskey)) {
1685 $sesskey = required_param('sesskey', PARAM_RAW
); // Check script parameters
1688 if (!isset($USER->sesskey
)) {
1692 return ($USER->sesskey
=== $sesskey);
1696 * Setup all global $CFG course variables, set locale and also themes
1697 * This function can be used on pages that do not require login instead of require_login()
1699 * @param mixed $courseorid id of the course or course object
1701 function course_setup($courseorid=0) {
1702 global $COURSE, $CFG, $SITE;
1704 /// Redefine global $COURSE if needed
1705 if (empty($courseorid)) {
1706 // no change in global $COURSE - for backwards compatibiltiy
1707 // if require_rogin() used after require_login($courseid);
1708 } else if (is_object($courseorid)) {
1709 $COURSE = clone($courseorid);
1711 global $course; // used here only to prevent repeated fetching from DB - may be removed later
1712 if (!empty($course->id
) and $course->id
== SITEID
) {
1713 $COURSE = clone($SITE);
1714 } else if (!empty($course->id
) and $course->id
== $courseorid) {
1715 $COURSE = clone($course);
1717 if (!$COURSE = get_record('course', 'id', $courseorid)) {
1718 error('Invalid course ID');
1723 /// set locale and themes
1730 * This function checks that the current user is logged in and has the
1731 * required privileges
1733 * This function checks that the current user is logged in, and optionally
1734 * whether they are allowed to be in a particular course and view a particular
1736 * If they are not logged in, then it redirects them to the site login unless
1737 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
1738 * case they are automatically logged in as guests.
1739 * If $courseid is given and the user is not enrolled in that course then the
1740 * user is redirected to the course enrolment page.
1741 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1742 * in the course then the user is redirected to the course home page.
1750 * @param mixed $courseorid id of the course or course object
1751 * @param bool $autologinguest
1752 * @param object $cm course module object
1754 function require_login($courseorid=0, $autologinguest=true, $cm=null) {
1756 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
1758 /// setup global $COURSE, themes, language and locale
1759 course_setup($courseorid);
1761 /// If the user is not even logged in yet then make sure they are
1762 if (!isloggedin()) {
1763 //NOTE: $USER->site check was obsoleted by session test cookie,
1764 // $USER->confirmed test is in login/index.php
1765 $SESSION->wantsurl
= $FULLME;
1766 if (!empty($_SERVER['HTTP_REFERER'])) {
1767 $SESSION->fromurl
= $_SERVER['HTTP_REFERER'];
1769 if ($autologinguest and !empty($CFG->guestloginbutton
) and !empty($CFG->autologinguests
) and ($COURSE->id
== SITEID
or $COURSE->guest
) ) {
1770 $loginguest = '?loginguest=true';
1774 if (empty($CFG->loginhttps
) or $loginguest) { //do not require https for guest logins
1775 redirect($CFG->wwwroot
.'/login/index.php'. $loginguest);
1777 $wwwroot = str_replace('http:','https:', $CFG->wwwroot
);
1778 redirect($wwwroot .'/login/index.php');
1783 /// loginas as redirection if needed
1784 if ($COURSE->id
!= SITEID
and !empty($USER->realuser
)) {
1785 if ($USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
1786 if ($USER->loginascontext
->instanceid
!= $COURSE->id
) {
1787 print_error('loginasonecourse', '', $CFG->wwwroot
.'/course/view.php?id='.$USER->loginascontext
->instanceid
);
1793 /// check whether the user should be changing password (but only if it is REALLY them)
1794 if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser
)) {
1795 $userauth = get_auth_plugin($USER->auth
);
1796 if ($userauth->can_change_password()) {
1797 $SESSION->wantsurl
= $FULLME;
1798 if ($changeurl = $userauth->change_password_url()) {
1799 //use plugin custom url
1800 redirect($changeurl);
1802 //use moodle internal method
1803 if (empty($CFG->loginhttps
)) {
1804 redirect($CFG->wwwroot
.'/login/change_password.php');
1806 $wwwroot = str_replace('http:','https:', $CFG->wwwroot
);
1807 redirect($wwwroot .'/login/change_password.php');
1811 error(get_string('nopasswordchangeforced', 'auth'));
1815 /// Check that the user account is properly set up
1816 if (user_not_fully_set_up($USER)) {
1817 $SESSION->wantsurl
= $FULLME;
1818 redirect($CFG->wwwroot
.'/user/edit.php?id='. $USER->id
.'&course='. SITEID
);
1821 /// Make sure current IP matches the one for this session (if required)
1822 if (!empty($CFG->tracksessionip
)) {
1823 if ($USER->sessionIP
!= md5(getremoteaddr())) {
1824 error(get_string('sessionipnomatch', 'error'));
1828 /// Make sure the USER has a sesskey set up. Used for checking script parameters.
1831 // Check that the user has agreed to a site policy if there is one
1832 if (!empty($CFG->sitepolicy
)) {
1833 if (!$USER->policyagreed
) {
1834 $SESSION->wantsurl
= $FULLME;
1835 redirect($CFG->wwwroot
.'/user/policy.php');
1839 // Fetch the system context, we are going to use it a lot.
1840 $sysctx = get_context_instance(CONTEXT_SYSTEM
);
1842 /// If the site is currently under maintenance, then print a message
1843 if (!has_capability('moodle/site:config', $sysctx)) {
1844 if (file_exists($CFG->dataroot
.'/'.SITEID
.'/maintenance.html')) {
1845 print_maintenance_message();
1850 /// groupmembersonly access control
1851 if (!empty($CFG->enablegroupings
) and $cm and $cm->groupmembersonly
and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE
, $cm->id
))) {
1852 if (isguestuser() or !groups_has_membership($cm)) {
1853 error(get_string('groupmembersonlyerror', 'group'), $CFG->wwwroot
.'/course/view.php?id='.$cm->course
);
1857 // Fetch the course context, and prefetch its child contexts
1858 if (!isset($COURSE->context
)) {
1859 if ( ! $COURSE->context
= get_context_instance(CONTEXT_COURSE
, $COURSE->id
) ) {
1860 print_error('nocontext');
1863 if ($COURSE->id
== SITEID
) {
1864 /// Eliminate hidden site activities straight away
1865 if (!empty($cm) && !$cm->visible
1866 && !has_capability('moodle/course:viewhiddenactivities', $COURSE->context
)) {
1867 redirect($CFG->wwwroot
, get_string('activityiscurrentlyhidden'));
1873 /// Check if the user can be in a particular course
1874 if (empty($USER->access
['rsw'][$COURSE->context
->path
])) {
1876 // Spaghetti logic construct
1878 // - able to view course?
1879 // - able to view category?
1880 // => if either is missing, course is hidden from this user
1882 // It's carefully ordered so we run the cheap checks first, and the
1883 // more costly checks last...
1885 if (! (($COURSE->visible ||
has_capability('moodle/course:viewhiddencourses', $COURSE->context
))
1886 && (course_parent_visible($COURSE)) ||
has_capability('moodle/course:viewhiddencourses',
1887 get_context_instance(CONTEXT_COURSECAT
,
1888 $COURSE->category
)))) {
1889 print_header_simple();
1890 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
1894 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1896 if ($USER->username
!= 'guest' and !has_capability('moodle/course:view', $COURSE->context
)) {
1897 if ($COURSE->guest
== 1) {
1898 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
1899 $USER->access
= load_temp_role($COURSE->context
, $CFG->guestroleid
, $USER->access
);
1903 /// If the user is a guest then treat them according to the course policy about guests
1905 if (has_capability('moodle/legacy:guest', $COURSE->context
, NULL, false)) {
1906 switch ($COURSE->guest
) { /// Check course policy about guest access
1908 case 1: /// Guests always allowed
1909 if (!has_capability('moodle/course:view', $COURSE->context
)) { // Prohibited by capability
1910 print_header_simple();
1911 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)), "$CFG->wwwroot/login/index.php");
1913 if (!empty($cm) and !$cm->visible
) { // Not allowed to see module, send to course page
1914 redirect($CFG->wwwroot
.'/course/view.php?id='.$cm->course
,
1915 get_string('activityiscurrentlyhidden'));
1918 return; // User is allowed to see this course
1922 case 2: /// Guests allowed with key
1923 if (!empty($USER->enrolkey
[$COURSE->id
])) { // Set by enrol/manual/enrol.php
1926 // otherwise drop through to logic below (--> enrol.php)
1929 default: /// Guests not allowed
1930 $strloggedinasguest = get_string('loggedinasguest');
1931 print_header_simple('', '',
1932 build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc'))));
1933 if (empty($USER->access
['rsw'][$COURSE->context
->path
])) { // Normal guest
1934 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)), "$CFG->wwwroot/login/index.php");
1936 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)));
1937 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id
).'</div>';
1938 print_footer($COURSE);
1944 /// For non-guests, check if they have course view access
1946 } else if (has_capability('moodle/course:view', $COURSE->context
)) {
1947 if (!empty($USER->realuser
)) { // Make sure the REAL person can also access this course
1948 if (!has_capability('moodle/course:view', $COURSE->context
, $USER->realuser
)) {
1949 print_header_simple();
1950 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot
.'/');
1954 /// Make sure they can read this activity too, if specified
1956 if (!empty($cm) and !$cm->visible
and !has_capability('moodle/course:viewhiddenactivities', $COURSE->context
)) {
1957 redirect($CFG->wwwroot
.'/course/view.php?id='.$cm->course
, get_string('activityiscurrentlyhidden'));
1959 return; // User is allowed to see this course
1964 /// Currently not enrolled in the course, so see if they want to enrol
1965 $SESSION->wantsurl
= $FULLME;
1966 redirect($CFG->wwwroot
.'/course/enrol.php?id='. $COURSE->id
);
1974 * This function just makes sure a user is logged out.
1979 function require_logout() {
1981 global $USER, $CFG, $SESSION;
1984 add_to_log(SITEID
, "user", "logout", "view.php?id=$USER->id&course=".SITEID
, $USER->id
, 0, $USER->id
);
1986 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
1987 foreach($authsequence as $authname) {
1988 $authplugin = get_auth_plugin($authname);
1989 $authplugin->prelogout_hook();
1993 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
1994 // This method is just to try to avoid silly warnings from PHP 4.3.0
1995 session_unregister("USER");
1996 session_unregister("SESSION");
1999 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
2000 $file = $line = null;
2001 if (headers_sent($file, $line)) {
2002 error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__
);
2003 error_log('Headers were already sent in file: '.$file.' on line '.$line);
2005 setcookie('MoodleSessionTest'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
2008 unset($_SESSION['USER']);
2009 unset($_SESSION['SESSION']);
2017 * This is a weaker version of {@link require_login()} which only requires login
2018 * when called from within a course rather than the site page, unless
2019 * the forcelogin option is turned on.
2022 * @param mixed $courseorid The course object or id in question
2023 * @param bool $autologinguest Allow autologin guests if that is wanted
2024 * @param object $cm Course activity module if known
2026 function require_course_login($courseorid, $autologinguest=true, $cm=null) {
2028 if (!empty($CFG->forcelogin
)) {
2029 // login required for both SITE and courses
2030 require_login($courseorid, $autologinguest, $cm);
2032 } else if (!empty($cm) and !$cm->visible
) {
2033 // always login for hidden activities
2034 require_login($courseorid, $autologinguest, $cm);
2036 } else if ((is_object($courseorid) and $courseorid->id
== SITEID
)
2037 or (!is_object($courseorid) and $courseorid == SITEID
)) {
2038 //login for SITE not required
2042 // course login always required
2043 require_login($courseorid, $autologinguest, $cm);
2048 * Require key login. Function terminates with error if key not found or incorrect.
2049 * @param string $script unique script identifier
2050 * @param int $instance optional instance id
2052 function require_user_key_login($script, $instance=null) {
2053 global $nomoodlecookie, $USER, $SESSION, $CFG;
2055 if (empty($nomoodlecookie)) {
2056 error('Incorrect use of require_key_login() - session cookies must be disabled!');
2060 @session_write_close
();
2062 $keyvalue = required_param('key', PARAM_ALPHANUM
);
2064 if (!$key = get_record('user_private_key', 'script', $script, 'value', $keyvalue, 'instance', $instance)) {
2065 error('Incorrect key');
2068 if (!empty($key->validuntil
) and $key->validuntil
< time()) {
2069 error('Expired key');
2072 if ($key->iprestriction
) {
2073 $remoteaddr = getremoteaddr();
2074 if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction
)) {
2075 error('Client IP address mismatch');
2079 if (!$user = get_record('user', 'id', $key->userid
)) {
2080 error('Incorrect user record');
2083 /// emulate normal session
2084 $SESSION = new object();
2087 /// note we are not using normal login
2088 if (!defined('USER_KEY_LOGIN')) {
2089 define('USER_KEY_LOGIN', true);
2092 load_all_capabilities();
2094 /// return isntance id - it might be empty
2095 return $key->instance
;
2099 * Creates a new private user access key.
2100 * @param string $script unique target identifier
2101 * @param int $userid
2102 * @param instance $int optional instance id
2103 * @param string $iprestriction optional ip restricted access
2104 * @param timestamp $validuntil key valid only until given data
2105 * @return string access key value
2107 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2108 $key = new object();
2109 $key->script
= $script;
2110 $key->userid
= $userid;
2111 $key->instance
= $instance;
2112 $key->iprestriction
= $iprestriction;
2113 $key->validuntil
= $validuntil;
2114 $key->timecreated
= time();
2116 $key->value
= md5($userid.'_'.time().random_string(40)); // something long and unique
2117 while (record_exists('user_private_key', 'value', $key->value
)) {
2119 $key->value
= md5($userid.'_'.time().random_string(40));
2122 if (!insert_record('user_private_key', $key)) {
2123 error('Can not insert new key');
2130 * Modify the user table by setting the currently logged in user's
2131 * last login to now.
2136 function update_user_login_times() {
2139 $user = new object();
2140 $USER->lastlogin
= $user->lastlogin
= $USER->currentlogin
;
2141 $USER->currentlogin
= $user->lastaccess
= $user->currentlogin
= time();
2143 $user->id
= $USER->id
;
2145 return update_record('user', $user);
2149 * Determines if a user has completed setting up their account.
2151 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
2154 function user_not_fully_set_up($user) {
2155 return ($user->username
!= 'guest' and (empty($user->firstname
) or empty($user->lastname
) or empty($user->email
) or over_bounce_threshold($user)));
2158 function over_bounce_threshold($user) {
2162 if (empty($CFG->handlebounces
)) {
2165 // set sensible defaults
2166 if (empty($CFG->minbounces
)) {
2167 $CFG->minbounces
= 10;
2169 if (empty($CFG->bounceratio
)) {
2170 $CFG->bounceratio
= .20;
2174 if ($bounce = get_record('user_preferences','userid',$user->id
,'name','email_bounce_count')) {
2175 $bouncecount = $bounce->value
;
2177 if ($send = get_record('user_preferences','userid',$user->id
,'name','email_send_count')) {
2178 $sendcount = $send->value
;
2180 return ($bouncecount >= $CFG->minbounces
&& $bouncecount/$sendcount >= $CFG->bounceratio
);
2184 * @param $user - object containing an id
2185 * @param $reset - will reset the count to 0
2187 function set_send_count($user,$reset=false) {
2188 if ($pref = get_record('user_preferences','userid',$user->id
,'name','email_send_count')) {
2189 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
2190 update_record('user_preferences',$pref);
2192 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2194 $pref->name
= 'email_send_count';
2196 $pref->userid
= $user->id
;
2197 insert_record('user_preferences',$pref, false);
2202 * @param $user - object containing an id
2203 * @param $reset - will reset the count to 0
2205 function set_bounce_count($user,$reset=false) {
2206 if ($pref = get_record('user_preferences','userid',$user->id
,'name','email_bounce_count')) {
2207 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
2208 update_record('user_preferences',$pref);
2210 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2212 $pref->name
= 'email_bounce_count';
2214 $pref->userid
= $user->id
;
2215 insert_record('user_preferences',$pref, false);
2220 * Keeps track of login attempts
2224 function update_login_count() {
2230 if (empty($SESSION->logincount
)) {
2231 $SESSION->logincount
= 1;
2233 $SESSION->logincount++
;
2236 if ($SESSION->logincount
> $max_logins) {
2237 unset($SESSION->wantsurl
);
2238 error(get_string('errortoomanylogins'));
2243 * Resets login attempts
2247 function reset_login_count() {
2250 $SESSION->logincount
= 0;
2253 function sync_metacourses() {
2257 if (!$courses = get_records('course', 'metacourse', 1)) {
2261 foreach ($courses as $course) {
2262 sync_metacourse($course);
2267 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
2269 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
2271 function sync_metacourse($course) {
2274 // Check the course is valid.
2275 if (!is_object($course)) {
2276 if (!$course = get_record('course', 'id', $course)) {
2277 return false; // invalid course id
2281 // Check that we actually have a metacourse.
2282 if (empty($course->metacourse
)) {
2286 // Get a list of roles that should not be synced.
2287 if (!empty($CFG->nonmetacoursesyncroleids
)) {
2288 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids
. ') AND';
2290 $roleexclusions = '';
2293 // Get the context of the metacourse.
2294 $context = get_context_instance(CONTEXT_COURSE
, $course->id
); // SITEID can not be a metacourse
2296 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
2297 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
2298 $managers = array_keys($users);
2300 $managers = array();
2303 // Get assignments of a user to a role that exist in a child course, but
2304 // not in the meta coure. That is, get a list of the assignments that need to be made.
2305 if (!$assignments = get_records_sql("
2307 ra.id, ra.roleid, ra.userid
2309 {$CFG->prefix}role_assignments ra,
2310 {$CFG->prefix}context con,
2311 {$CFG->prefix}course_meta cm
2313 ra.contextid = con.id AND
2314 con.contextlevel = " . CONTEXT_COURSE
. " AND
2315 con.instanceid = cm.child_course AND
2316 cm.parent_course = {$course->id} AND
2320 {$CFG->prefix}role_assignments ra2
2322 ra2.userid = ra.userid AND
2323 ra2.roleid = ra.roleid AND
2324 ra2.contextid = {$context->id}
2327 $assignments = array();
2330 // Get assignments of a user to a role that exist in the meta course, but
2331 // not in any child courses. That is, get a list of the unassignments that need to be made.
2332 if (!$unassignments = get_records_sql("
2334 ra.id, ra.roleid, ra.userid
2336 {$CFG->prefix}role_assignments ra
2338 ra.contextid = {$context->id} AND
2342 {$CFG->prefix}role_assignments ra2,
2343 {$CFG->prefix}context con2,
2344 {$CFG->prefix}course_meta cm
2346 ra2.userid = ra.userid AND
2347 ra2.roleid = ra.roleid AND
2348 ra2.contextid = con2.id AND
2349 con2.contextlevel = " . CONTEXT_COURSE
. " AND
2350 con2.instanceid = cm.child_course AND
2351 cm.parent_course = {$course->id}
2354 $unassignments = array();
2359 // Make the unassignments, if they are not managers.
2360 foreach ($unassignments as $unassignment) {
2361 if (!in_array($unassignment->userid
, $managers)) {
2362 $success = role_unassign($unassignment->roleid
, $unassignment->userid
, 0, $context->id
) && $success;
2366 // Make the assignments.
2367 foreach ($assignments as $assignment) {
2368 $success = role_assign($assignment->roleid
, $assignment->userid
, 0, $context->id
) && $success;
2373 // TODO: finish timeend and timestart
2374 // maybe we could rely on cron job to do the cleaning from time to time
2378 * Adds a record to the metacourse table and calls sync_metacoures
2380 function add_to_metacourse ($metacourseid, $courseid) {
2382 if (!$metacourse = get_record("course","id",$metacourseid)) {
2386 if (!$course = get_record("course","id",$courseid)) {
2390 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
2391 $rec = new object();
2392 $rec->parent_course
= $metacourseid;
2393 $rec->child_course
= $courseid;
2394 if (!insert_record('course_meta',$rec)) {
2397 return sync_metacourse($metacourseid);
2404 * Removes the record from the metacourse table and calls sync_metacourse
2406 function remove_from_metacourse($metacourseid, $courseid) {
2408 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
2409 return sync_metacourse($metacourseid);
2416 * Determines if a user is currently logged in
2421 function isloggedin() {
2424 return (!empty($USER->id
));
2428 * Determines if a user is logged in as real guest user with username 'guest'.
2429 * This function is similar to original isguest() in 1.6 and earlier.
2430 * Current isguest() is deprecated - do not use it anymore.
2432 * @param $user mixed user object or id, $USER if not specified
2433 * @return bool true if user is the real guest user, false if not logged in or other user
2435 function isguestuser($user=NULL) {
2437 if ($user === NULL) {
2439 } else if (is_numeric($user)) {
2440 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2443 if (empty($user->id
)) {
2444 return false; // not logged in, can not be guest
2447 return ($user->username
== 'guest');
2451 * Determines if the currently logged in user is in editing mode.
2452 * Note: originally this function had $userid parameter - it was not usable anyway
2454 * @uses $USER, $PAGE
2457 function isediting() {
2458 global $USER, $PAGE;
2460 if (empty($USER->editing
)) {
2462 } elseif (is_object($PAGE) && method_exists($PAGE,'user_allowed_editing')) {
2463 return $PAGE->user_allowed_editing();
2465 return true;//false;
2469 * Determines if the logged in user is currently moving an activity
2472 * @param int $courseid The id of the course being tested
2475 function ismoving($courseid) {
2478 if (!empty($USER->activitycopy
)) {
2479 return ($USER->activitycopycourse
== $courseid);
2485 * Given an object containing firstname and lastname
2486 * values, this function returns a string with the
2487 * full name of the person.
2488 * The result may depend on system settings
2489 * or language. 'override' will force both names
2490 * to be used even if system settings specify one.
2494 * @param object $user A {@link $USER} object to get full name of
2495 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
2497 function fullname($user, $override=false) {
2499 global $CFG, $SESSION;
2501 if (!isset($user->firstname
) and !isset($user->lastname
)) {
2506 if (!empty($CFG->forcefirstname
)) {
2507 $user->firstname
= $CFG->forcefirstname
;
2509 if (!empty($CFG->forcelastname
)) {
2510 $user->lastname
= $CFG->forcelastname
;
2514 if (!empty($SESSION->fullnamedisplay
)) {
2515 $CFG->fullnamedisplay
= $SESSION->fullnamedisplay
;
2518 if ($CFG->fullnamedisplay
== 'firstname lastname') {
2519 return $user->firstname
.' '. $user->lastname
;
2521 } else if ($CFG->fullnamedisplay
== 'lastname firstname') {
2522 return $user->lastname
.' '. $user->firstname
;
2524 } else if ($CFG->fullnamedisplay
== 'firstname') {
2526 return get_string('fullnamedisplay', '', $user);
2528 return $user->firstname
;
2532 return get_string('fullnamedisplay', '', $user);
2536 * Sets a moodle cookie with an encrypted string
2541 * @param string $thing The string to encrypt and place in a cookie
2543 function set_moodle_cookie($thing) {
2546 if ($thing == 'guest') { // Ignore guest account
2550 $cookiename = 'MOODLEID_'.$CFG->sessioncookie
;
2553 $seconds = DAYSECS
*$days;
2555 setCookie($cookiename, '', time() - HOURSECS
, $CFG->sessioncookiepath
);
2556 setCookie($cookiename, rc4encrypt($thing), time()+
$seconds, $CFG->sessioncookiepath
);
2560 * Gets a moodle cookie with an encrypted string
2565 function get_moodle_cookie() {
2568 $cookiename = 'MOODLEID_'.$CFG->sessioncookie
;
2570 if (empty($_COOKIE[$cookiename])) {
2573 $thing = rc4decrypt($_COOKIE[$cookiename]);
2574 return ($thing == 'guest') ?
'': $thing; // Ignore guest account
2579 * Returns whether a given authentication plugin exists.
2582 * @param string $auth Form of authentication to check for. Defaults to the
2583 * global setting in {@link $CFG}.
2584 * @return boolean Whether the plugin is available.
2586 function exists_auth_plugin($auth) {
2589 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2590 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2596 * Checks if a given plugin is in the list of enabled authentication plugins.
2598 * @param string $auth Authentication plugin.
2599 * @return boolean Whether the plugin is enabled.
2601 function is_enabled_auth($auth) {
2606 $enabled = get_enabled_auth_plugins();
2608 return in_array($auth, $enabled);
2612 * Returns an authentication plugin instance.
2615 * @param string $auth name of authentication plugin
2616 * @return object An instance of the required authentication plugin.
2618 function get_auth_plugin($auth) {
2621 // check the plugin exists first
2622 if (! exists_auth_plugin($auth)) {
2623 error("Authentication plugin '$auth' not found.");
2626 // return auth plugin instance
2627 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2628 $class = "auth_plugin_$auth";
2633 * Returns array of active auth plugins.
2635 * @param bool $fix fix $CFG->auth if needed
2638 function get_enabled_auth_plugins($fix=false) {
2641 $default = array('manual', 'nologin');
2643 if (empty($CFG->auth
)) {
2646 $auths = explode(',', $CFG->auth
);
2650 $auths = array_unique($auths);
2651 foreach($auths as $k=>$authname) {
2652 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
2656 $newconfig = implode(',', $auths);
2657 if (!isset($CFG->auth
) or $newconfig != $CFG->auth
) {
2658 set_config('auth', $newconfig);
2662 return (array_merge($default, $auths));
2666 * Returns true if an internal authentication method is being used.
2667 * if method not specified then, global default is assumed
2670 * @param string $auth Form of authentication required
2673 function is_internal_auth($auth) {
2674 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2675 return $authplugin->is_internal();
2679 * Returns an array of user fields
2683 * @return array User field/column names
2685 function get_user_fieldnames() {
2689 $fieldarray = $db->MetaColumnNames($CFG->prefix
.'user');
2690 unset($fieldarray['ID']);
2696 * Creates the default "guest" user. Used both from
2697 * admin/index.php and login/index.php
2698 * @return mixed user object created or boolean false if the creation has failed
2700 function create_guest_record() {
2704 $guest = new stdClass();
2705 $guest->auth
= 'manual';
2706 $guest->username
= 'guest';
2707 $guest->password
= hash_internal_user_password('guest');
2708 $guest->firstname
= addslashes(get_string('guestuser'));
2709 $guest->lastname
= ' ';
2710 $guest->email
= 'root@localhost';
2711 $guest->description
= addslashes(get_string('guestuserinfo'));
2712 $guest->mnethostid
= $CFG->mnet_localhost_id
;
2713 $guest->confirmed
= 1;
2714 $guest->lang
= $CFG->lang
;
2715 $guest->timemodified
= time();
2717 if (! $guest->id
= insert_record("user", $guest)) {
2725 * Creates a bare-bones user record
2728 * @param string $username New user's username to add to record
2729 * @param string $password New user's password to add to record
2730 * @param string $auth Form of authentication required
2731 * @return object A {@link $USER} object
2732 * @todo Outline auth types and provide code example
2734 function create_user_record($username, $password, $auth='manual') {
2737 //just in case check text case
2738 $username = trim(moodle_strtolower($username));
2740 $authplugin = get_auth_plugin($auth);
2742 if ($newinfo = $authplugin->get_userinfo($username)) {
2743 $newinfo = truncate_userinfo($newinfo);
2744 foreach ($newinfo as $key => $value){
2745 $newuser->$key = addslashes($value);
2749 if (!empty($newuser->email
)) {
2750 if (email_is_not_allowed($newuser->email
)) {
2751 unset($newuser->email
);
2755 $newuser->auth
= $auth;
2756 $newuser->username
= $username;
2759 // user CFG lang for user if $newuser->lang is empty
2760 // or $user->lang is not an installed language
2761 $sitelangs = array_keys(get_list_of_languages());
2762 if (empty($newuser->lang
) ||
!in_array($newuser->lang
, $sitelangs)) {
2763 $newuser -> lang
= $CFG->lang
;
2765 $newuser->confirmed
= 1;
2766 $newuser->lastip
= getremoteaddr();
2767 $newuser->timemodified
= time();
2768 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
2770 if (insert_record('user', $newuser)) {
2771 $user = get_complete_user_data('username', $newuser->username
);
2772 if(!empty($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'})){
2773 set_user_preference('auth_forcepasswordchange', 1, $user->id
);
2775 update_internal_user_password($user, $password);
2782 * Will update a local user record from an external source
2785 * @param string $username New user's username to add to record
2786 * @return user A {@link $USER} object
2788 function update_user_record($username, $authplugin) {
2789 $username = trim(moodle_strtolower($username)); /// just in case check text case
2791 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2792 $userauth = get_auth_plugin($oldinfo->auth
);
2794 if ($newinfo = $userauth->get_userinfo($username)) {
2795 $newinfo = truncate_userinfo($newinfo);
2796 foreach ($newinfo as $key => $value){
2797 $confkey = 'field_updatelocal_' . $key;
2798 if (!empty($userauth->config
->$confkey) and $userauth->config
->$confkey === 'onlogin') {
2799 $value = addslashes(stripslashes($value)); // Just in case
2800 set_field('user', $key, $value, 'username', $username)
2801 or error_log("Error updating $key for $username");
2806 return get_complete_user_data('username', $username);
2809 function truncate_userinfo($info) {
2810 /// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2811 /// which may have large fields
2813 // define the limits
2823 'institution' => 40,
2831 // apply where needed
2832 foreach (array_keys($info) as $key) {
2833 if (!empty($limit[$key])) {
2834 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
2842 * Marks user deleted in internal user database and notifies the auth plugin.
2843 * Also unenrols user from all roles and does other cleanup.
2844 * @param object $user Userobject before delete (without system magic quotes)
2845 * @return boolean success
2847 function delete_user($user) {
2849 require_once($CFG->libdir
.'/grouplib.php');
2850 require_once($CFG->libdir
.'/gradelib.php');
2854 // delete all grades - backup is kept in grade_grades_history table
2855 if ($grades = grade_grade
::fetch_all(array('userid'=>$user->id
))) {
2856 foreach ($grades as $grade) {
2857 $grade->delete('userdelete');
2861 // remove from all groups
2862 delete_records('groups_members', 'userid', $user->id
);
2864 // unenrol from all roles in all contexts
2865 role_unassign(0, $user->id
); // this might be slow but it is really needed - modules might do some extra cleanup!
2867 // now do a final accesslib cleanup - removes all role assingments in user context and context itself
2868 delete_context(CONTEXT_USER
, $user->id
);
2870 // mark internal user record as "deleted"
2871 $updateuser = new object();
2872 $updateuser->id
= $user->id
;
2873 $updateuser->deleted
= 1;
2874 $updateuser->username
= addslashes("$user->email.".time()); // Remember it just in case
2875 $updateuser->email
= ''; // Clear this field to free it up
2876 $updateuser->idnumber
= ''; // Clear this field to free it up
2877 $updateuser->timemodified
= time();
2879 if (update_record('user', $updateuser)) {
2881 // notify auth plugin - do not block the delete even when plugin fails
2882 $authplugin = get_auth_plugin($user->auth
);
2883 $authplugin->user_delete($user);
2893 * Retrieve the guest user object
2896 * @return user A {@link $USER} object
2898 function guest_user() {
2901 if ($newuser = get_record('user', 'username', 'guest', 'mnethostid', $CFG->mnet_localhost_id
)) {
2902 $newuser->confirmed
= 1;
2903 $newuser->lang
= $CFG->lang
;
2904 $newuser->lastip
= getremoteaddr();
2911 * Given a username and password, this function looks them
2912 * up using the currently selected authentication mechanism,
2913 * and if the authentication is successful, it returns a
2914 * valid $user object from the 'user' table.
2916 * Uses auth_ functions from the currently active auth module
2919 * @param string $username User's username (with system magic quotes)
2920 * @param string $password User's password (with system magic quotes)
2921 * @return user|flase A {@link $USER} object or false if error
2923 function authenticate_user_login($username, $password) {
2927 $authsenabled = get_enabled_auth_plugins();
2929 if ($user = get_complete_user_data('username', $username)) {
2930 $auth = empty($user->auth
) ?
'manual' : $user->auth
; // use manual if auth not set
2931 if ($auth=='nologin' or !is_enabled_auth($auth)) {
2932 add_to_log(0, 'login', 'error', 'index.php', $username);
2933 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2936 if (!empty($user->deleted
)) {
2937 add_to_log(0, 'login', 'error', 'index.php', $username);
2938 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2941 $auths = array($auth);
2944 $auths = $authsenabled;
2945 $user = new object();
2946 $user->id
= 0; // User does not exist
2949 foreach ($auths as $auth) {
2950 $authplugin = get_auth_plugin($auth);
2952 // on auth fail fall through to the next plugin
2953 if (!$authplugin->user_login($username, $password)) {
2957 // successful authentication
2958 if ($user->id
) { // User already exists in database
2959 if (empty($user->auth
)) { // For some reason auth isn't set yet
2960 set_field('user', 'auth', $auth, 'username', $username);
2961 $user->auth
= $auth;
2964 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
2966 if (!$authplugin->is_internal()) { // update user record from external DB
2967 $user = update_user_record($username, get_auth_plugin($user->auth
));
2970 // if user not found, create him
2971 $user = create_user_record($username, $password, $auth);
2974 $authplugin->sync_roles($user);
2976 foreach ($authsenabled as $hau) {
2977 $hauth = get_auth_plugin($hau);
2978 $hauth->user_authenticated_hook($user, $username, $password);
2981 /// Log in to a second system if necessary
2982 /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
2983 if (!empty($CFG->sso
)) {
2984 include_once($CFG->dirroot
.'/sso/'. $CFG->sso
.'/lib.php');
2985 if (function_exists('sso_user_login')) {
2986 if (!sso_user_login($username, $password)) { // Perform the signon process
2987 notify('Second sign-on failed');
2996 // failed if all the plugins have failed
2997 add_to_log(0, 'login', 'error', 'index.php', $username);
2998 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3003 * Compare password against hash stored in internal user table.
3004 * If necessary it also updates the stored hash to new format.
3006 * @param object user
3007 * @param string plain text password
3008 * @return bool is password valid?
3010 function validate_internal_user_password(&$user, $password) {
3013 if (!isset($CFG->passwordsaltmain
)) {
3014 $CFG->passwordsaltmain
= '';
3019 // get password original encoding in case it was not updated to unicode yet
3020 $textlib = textlib_get_instance();
3021 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
3023 if ($user->password
== md5($password.$CFG->passwordsaltmain
) or $user->password
== md5($password)
3024 or $user->password
== md5($convpassword.$CFG->passwordsaltmain
) or $user->password
== md5($convpassword)) {
3027 for ($i=1; $i<=20; $i++
) { //20 alternative salts should be enough, right?
3028 $alt = 'passwordsaltalt'.$i;
3029 if (!empty($CFG->$alt)) {
3030 if ($user->password
== md5($password.$CFG->$alt) or $user->password
== md5($convpassword.$CFG->$alt)) {
3039 // force update of password hash using latest main password salt and encoding if needed
3040 update_internal_user_password($user, $password);
3047 * Calculate hashed value from password using current hash mechanism.
3049 * @param string password
3050 * @return string password hash
3052 function hash_internal_user_password($password) {
3055 if (isset($CFG->passwordsaltmain
)) {
3056 return md5($password.$CFG->passwordsaltmain
);
3058 return md5($password);
3063 * Update pssword hash in user object.
3065 * @param object user
3066 * @param string plain text password
3067 * @param bool store changes also in db, default true
3068 * @return true if hash changed
3070 function update_internal_user_password(&$user, $password) {
3073 $authplugin = get_auth_plugin($user->auth
);
3074 if (!empty($authplugin->config
->preventpassindb
)) {
3075 $hashedpassword = 'not cached';
3077 $hashedpassword = hash_internal_user_password($password);
3080 return set_field('user', 'password', $hashedpassword, 'id', $user->id
);
3084 * Get a complete user record, which includes all the info
3085 * in the user record
3086 * Intended for setting as $USER session variable
3090 * @param string $field The user field to be checked for a given value.
3091 * @param string $value The value to match for $field.
3092 * @return user A {@link $USER} object.
3094 function get_complete_user_data($field, $value, $mnethostid=null) {
3098 if (!$field ||
!$value) {
3102 /// Build the WHERE clause for an SQL query
3104 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
3106 if (is_null($mnethostid)) {
3107 // if null, we restrict to local users
3108 // ** testing for local user can be done with
3109 // mnethostid = $CFG->mnet_localhost_id
3112 // but the first one is FAST with our indexes
3113 $mnethostid = $CFG->mnet_localhost_id
;
3115 $mnethostid = (int)$mnethostid;
3116 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
3118 /// Get all the basic user data
3120 if (! $user = get_record_select('user', $constraints)) {
3124 /// Get various settings and preferences
3126 if ($displays = get_records('course_display', 'userid', $user->id
)) {
3127 foreach ($displays as $display) {
3128 $user->display
[$display->course
] = $display->display
;
3132 $user->preference
= get_user_preferences(null, null, $user->id
);
3134 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id
)) {
3135 foreach ($lastaccesses as $lastaccess) {
3136 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
3140 $sql = "SELECT g.id, g.courseid
3141 FROM {$CFG->prefix}groups g, {$CFG->prefix}groups_members gm
3142 WHERE gm.groupid=g.id AND gm.userid={$user->id}";
3144 // this is a special hack to speedup calendar display
3145 $user->groupmember
= array();
3146 if ($groups = get_records_sql($sql)) {
3147 foreach ($groups as $group) {
3148 if (!array_key_exists($group->courseid
, $user->groupmember
)) {
3149 $user->groupmember
[$group->courseid
] = array();
3151 $user->groupmember
[$group->courseid
][$group->id
] = $group->id
;
3155 /// Add the custom profile fields to the user record
3156 include_once($CFG->dirroot
.'/user/profile/lib.php');
3157 $customfields = (array)profile_user_record($user->id
);
3158 foreach ($customfields as $cname=>$cvalue) {
3159 if (!isset($user->$cname)) { // Don't overwrite any standard fields
3160 $user->$cname = $cvalue;
3164 /// Rewrite some variables if necessary
3165 if (!empty($user->description
)) {
3166 $user->description
= true; // No need to cart all of it around
3168 if ($user->username
== 'guest') {
3169 $user->lang
= $CFG->lang
; // Guest language always same as site
3170 $user->firstname
= get_string('guestuser'); // Name always in current language
3171 $user->lastname
= ' ';
3174 $user->sesskey
= random_string(10);
3175 $user->sessionIP
= md5(getremoteaddr()); // Store the current IP in the session
3182 * @param string $password the password to be checked agains the password policy
3183 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
3184 * @return bool true if the password is valid according to the policy. false otherwise.
3186 function check_password_policy($password, &$errmsg) {
3189 if (empty($CFG->passwordpolicy
)) {
3193 $textlib = textlib_get_instance();
3195 if ($textlib->strlen($password) < $CFG->minpasswordlength
) {
3196 $errmsg = get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength
);
3198 } else if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits
) {
3199 $errmsg = get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits
);
3201 } else if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower
) {
3202 $errmsg = get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower
);
3204 } else if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper
) {
3205 $errmsg = get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper
);
3207 } else if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum
) {
3208 $errmsg = get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
);
3210 } else if ($password == 'admin' or $password == 'password') {
3211 $errmsg = get_string('unsafepassword');
3214 if ($errmsg == '') {
3223 * When logging in, this function is run to set certain preferences
3224 * for the current SESSION
3226 function set_login_session_preferences() {
3227 global $SESSION, $CFG;
3229 $SESSION->justloggedin
= true;
3231 unset($SESSION->lang
);
3233 // Restore the calendar filters, if saved
3234 if (intval(get_user_preferences('calendar_persistflt', 0))) {
3235 include_once($CFG->dirroot
.'/calendar/lib.php');
3236 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
3242 * Delete a course, including all related data from the database,
3243 * and any associated files from the moodledata folder.
3245 * @param int $courseid The id of the course to delete.
3246 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3247 * @return bool true if all the removals succeeded. false if there were any failures. If this
3248 * method returns false, some of the removals will probably have succeeded, and others
3249 * failed, but you have no way of knowing which.
3251 function delete_course($courseid, $showfeedback = true) {
3253 require_once($CFG->libdir
.'/gradelib.php');
3256 // frontpage course can not be deleted!!
3257 if ($courseid == SITEID
) {
3261 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
3263 if (!remove_course_contents($courseid, $showfeedback)) {
3264 if ($showfeedback) {
3265 notify("An error occurred while deleting some of the course contents.");
3270 remove_course_grades($courseid, $showfeedback);
3271 remove_grade_letters($context, $showfeedback);
3273 if (!delete_records("course", "id", $courseid)) {
3274 if ($showfeedback) {
3275 notify("An error occurred while deleting the main course record.");
3280 /// Delete all roles and overiddes in the course context
3281 if (!delete_context(CONTEXT_COURSE
, $courseid)) {
3282 if ($showfeedback) {
3283 notify("An error occurred while deleting the main course context.");
3288 if (!fulldelete($CFG->dataroot
.'/'.$courseid)) {
3289 if ($showfeedback) {
3290 notify("An error occurred while deleting the course files.");
3299 * Clear a course out completely, deleting all content
3300 * but don't delete the course itself
3303 * @param int $courseid The id of the course that is being deleted
3304 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3305 * @return bool true if all the removals succeeded. false if there were any failures. If this
3306 * method returns false, some of the removals will probably have succeeded, and others
3307 * failed, but you have no way of knowing which.
3309 function remove_course_contents($courseid, $showfeedback=true) {
3312 include_once($CFG->libdir
.'/questionlib.php');
3316 if (! $course = get_record('course', 'id', $courseid)) {
3317 error('Course ID was incorrect (can\'t find it)');
3320 $strdeleted = get_string('deleted');
3322 /// First delete every instance of every module
3324 if ($allmods = get_records('modules') ) {
3325 foreach ($allmods as $mod) {
3326 $modname = $mod->name
;
3327 $modfile = $CFG->dirroot
.'/mod/'. $modname .'/lib.php';
3328 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
3329 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
3331 if (file_exists($modfile)) {
3332 include_once($modfile);
3333 if (function_exists($moddelete)) {
3334 if ($instances = get_records($modname, 'course', $course->id
)) {
3335 foreach ($instances as $instance) {
3336 if ($cm = get_coursemodule_from_instance($modname, $instance->id
, $course->id
)) {
3337 /// Delete activity context questions and question categories
3338 question_delete_activity($cm, $showfeedback);
3340 if ($moddelete($instance->id
)) {
3344 notify('Could not delete '. $modname .' instance '. $instance->id
.' ('. format_string($instance->name
) .')');
3348 // delete cm and its context in correct order
3349 delete_records('course_modules', 'id', $cm->id
);
3350 delete_context(CONTEXT_MODULE
, $cm->id
);
3355 notify('Function '. $moddelete() .'doesn\'t exist!');
3359 if (function_exists($moddeletecourse)) {
3360 $moddeletecourse($course, $showfeedback);
3363 if ($showfeedback) {
3364 notify($strdeleted .' '. $count .' x '. $modname);
3368 error('No modules are installed!');
3371 /// Give local code a chance to delete its references to this course.
3372 require_once('locallib.php');
3373 notify_local_delete_course($courseid, $showfeedback);
3375 /// Delete course blocks
3377 if ($blocks = get_records_sql("SELECT *
3378 FROM {$CFG->prefix}block_instance
3379 WHERE pagetype = '".PAGE_COURSE_VIEW
."'
3380 AND pageid = $course->id")) {
3381 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW
, 'pageid', $course->id
)) {
3382 if ($showfeedback) {
3383 notify($strdeleted .' block_instance');
3386 require_once($CFG->libdir
.'/blocklib.php');
3387 foreach ($blocks as $block) { /// Delete any associated contexts for this block
3389 delete_context(CONTEXT_BLOCK
, $block->id
);
3392 // Get the block object and call instance_delete()
3393 if (!$record = blocks_get_record($block->blockid
)) {
3397 if (!$obj = block_instance($record->name
, $block)) {
3401 // Return value ignored, in core mods this does not do anything, but just in case
3402 // third party blocks might have stuff to clean up
3403 // we execute this anyway
3404 $obj->instance_delete();
3412 /// Delete any groups, removing members and grouping/course links first.
3413 require_once($CFG->dirroot
.'/group/lib.php');
3414 groups_delete_groupings($courseid, true);
3415 groups_delete_groups($courseid, true);
3417 /// Delete all related records in other tables that may have a courseid
3418 /// This array stores the tables that need to be cleared, as
3419 /// table_name => column_name that contains the course id.
3421 $tablestoclear = array(
3422 'event' => 'courseid', // Delete events
3423 'log' => 'course', // Delete logs
3424 'course_sections' => 'course', // Delete any course stuff
3425 'course_modules' => 'course',
3426 'backup_courses' => 'courseid', // Delete scheduled backup stuff
3427 'user_lastaccess' => 'courseid',
3428 'backup_log' => 'courseid'
3430 foreach ($tablestoclear as $table => $col) {
3431 if (delete_records($table, $col, $course->id
)) {
3432 if ($showfeedback) {
3433 notify($strdeleted . ' ' . $table);
3441 /// Clean up metacourse stuff
3443 if ($course->metacourse
) {
3444 delete_records("course_meta","parent_course",$course->id
);
3445 sync_metacourse($course->id
); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
3446 if ($showfeedback) {
3447 notify("$strdeleted course_meta");
3450 if ($parents = get_records("course_meta","child_course",$course->id
)) {
3451 foreach ($parents as $parent) {
3452 remove_from_metacourse($parent->parent_course
,$parent->child_course
); // this will do the unenrolments as well.
3454 if ($showfeedback) {
3455 notify("$strdeleted course_meta");
3460 /// Delete questions and question categories
3461 question_delete_course($course, $showfeedback);
3468 * This function will empty a course of USER data as much as
3469 /// possible. It will retain the activities and the structure
3475 * @param object $data an object containing all the boolean settings and courseid
3476 * @param bool $showfeedback if false then do it all silently
3478 * @todo Finish documenting this function
3480 function reset_course_userdata($data, $showfeedback=true) {
3482 global $CFG, $USER, $SESSION;
3483 require_once($CFG->dirroot
.'/group/lib.php');
3487 $strdeleted = get_string('deleted');
3489 // Look in every instance of every module for data to delete
3491 if ($allmods = get_records('modules') ) {
3492 foreach ($allmods as $mod) {
3493 $modname = $mod->name
;
3494 $modfile = $CFG->dirroot
.'/mod/'. $modname .'/lib.php';
3495 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3496 if (file_exists($modfile)) {
3497 @include_once
($modfile);
3498 if (function_exists($moddeleteuserdata)) {
3499 $moddeleteuserdata($data, $showfeedback);
3504 error('No modules are installed!');
3507 // Delete other stuff
3508 $context = get_context_instance(CONTEXT_COURSE
, $data->courseid
);
3510 if (!empty($data->reset_students
) or !empty($data->reset_teachers
)) {
3511 $teachers = array_keys(get_users_by_capability($context, 'moodle/course:update'));
3512 $participants = array_keys(get_users_by_capability($context, 'moodle/course:view'));
3513 $students = array_diff($participants, $teachers);
3515 if (!empty($data->reset_students
)) {
3516 foreach ($students as $studentid) {
3517 role_unassign(0, $studentid, 0, $context->id
);
3519 if ($showfeedback) {
3520 notify($strdeleted .' '.get_string('students'), 'notifysuccess');
3523 /// Delete group members (but keep the groups)
3524 $result = groups_delete_group_members($data->courseid
, $showfeedback) && $result;
3527 if (!empty($data->reset_teachers
)) {
3528 foreach ($teachers as $teacherid) {
3529 role_unassign(0, $teacherid, 0, $context->id
);
3531 if ($showfeedback) {
3532 notify($strdeleted .' '.get_string('teachers'), 'notifysuccess');
3537 if (!empty($data->reset_groups
)) {
3538 $result = groups_delete_groupings($data->courseid
, $showfeedback) && $result;
3539 $result = groups_delete_groups($data->courseid
, $showfeedback) && $result;
3542 if (!empty($data->reset_events
)) {
3543 if (delete_records('event', 'courseid', $data->courseid
)) {
3544 if ($showfeedback) {
3545 notify($strdeleted .' event', 'notifysuccess');
3552 if (!empty($data->reset_logs
)) {
3553 if (delete_records('log', 'course', $data->courseid
)) {
3554 if ($showfeedback) {
3555 notify($strdeleted .' log', 'notifysuccess');
3562 // deletes all role assignments, and local override,
3563 // these have no courseid in table and needs separate process
3564 delete_records('role_capabilities', 'contextid', $context->id
);
3566 // force accessinfo refresh for users visiting this context...
3567 mark_context_dirty($context->path
);
3572 function generate_email_processing_address($modid,$modargs) {
3575 if (empty($CFG->siteidentifier
)) { // Unique site identification code
3576 set_config('siteidentifier', random_string(32));
3579 $header = $CFG->mailprefix
. substr(base64_encode(pack('C',$modid)),0,2).$modargs;
3580 return $header . substr(md5($header.$CFG->siteidentifier
),0,16).'@'.$CFG->maildomain
;
3584 function moodle_process_email($modargs,$body) {
3585 // the first char should be an unencoded letter. We'll take this as an action
3586 switch ($modargs{0}) {
3587 case 'B': { // bounce
3588 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
3589 if ($user = get_record_select("user","id=$userid","id,email")) {
3590 // check the half md5 of their email
3591 $md5check = substr(md5($user->email
),0,16);
3592 if ($md5check == substr($modargs, -16)) {
3593 set_bounce_count($user);
3595 // else maybe they've already changed it?
3599 // maybe more later?
3603 /// CORRESPONDENCE ////////////////////////////////////////////////
3606 * Send an email to a specified user
3611 * @param user $user A {@link $USER} object
3612 * @param user $from A {@link $USER} object
3613 * @param string $subject plain text subject line of the email
3614 * @param string $messagetext plain text version of the message
3615 * @param string $messagehtml complete html version of the message (optional)
3616 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
3617 * @param string $attachname the name of the file (extension indicates MIME)
3618 * @param bool $usetrueaddress determines whether $from email address should
3619 * be sent out. Will be overruled by user profile setting for maildisplay
3620 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3621 * was blocked by user and "false" if there was another sort of error.
3623 function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='') {
3625 global $CFG, $FULLME;
3627 include_once($CFG->libdir
.'/phpmailer/class.phpmailer.php');
3629 /// We are going to use textlib services here
3630 $textlib = textlib_get_instance();
3636 // skip mail to suspended users
3637 if (isset($user->auth
) && $user->auth
=='nologin') {
3641 if (!empty($user->emailstop
)) {
3645 if (over_bounce_threshold($user)) {
3646 error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
3650 $mail = new phpmailer
;
3652 $mail->Version
= 'Moodle '. $CFG->version
; // mailer version
3653 $mail->PluginDir
= $CFG->libdir
.'/phpmailer/'; // plugin directory (eg smtp plugin)
3655 $mail->CharSet
= 'UTF-8';
3657 if ($CFG->smtphosts
== 'qmail') {
3658 $mail->IsQmail(); // use Qmail system
3660 } else if (empty($CFG->smtphosts
)) {
3661 $mail->IsMail(); // use PHP mail() = sendmail
3664 $mail->IsSMTP(); // use SMTP directly
3665 if (!empty($CFG->debugsmtp
)) {
3666 echo '<pre>' . "\n";
3667 $mail->SMTPDebug
= true;
3669 $mail->Host
= $CFG->smtphosts
; // specify main and backup servers
3671 if ($CFG->smtpuser
) { // Use SMTP authentication
3672 $mail->SMTPAuth
= true;
3673 $mail->Username
= $CFG->smtpuser
;
3674 $mail->Password
= $CFG->smtppass
;
3678 $supportuser = generate_email_supportuser();
3681 // make up an email address for handling bounces
3682 if (!empty($CFG->handlebounces
)) {
3683 $modargs = 'B'.base64_encode(pack('V',$user->id
)).substr(md5($user->email
),0,16);
3684 $mail->Sender
= generate_email_processing_address(0,$modargs);
3686 $mail->Sender
= $supportuser->email
;
3689 if (is_string($from)) { // So we can pass whatever we want if there is need
3690 $mail->From
= $CFG->noreplyaddress
;
3691 $mail->FromName
= $from;
3692 } else if ($usetrueaddress and $from->maildisplay
) {
3693 $mail->From
= $from->email
;
3694 $mail->FromName
= fullname($from);
3696 $mail->From
= $CFG->noreplyaddress
;
3697 $mail->FromName
= fullname($from);
3698 if (empty($replyto)) {
3699 $mail->AddReplyTo($CFG->noreplyaddress
,get_string('noreplyname'));
3703 if (!empty($replyto)) {
3704 $mail->AddReplyTo($replyto,$replytoname);
3707 $mail->Subject
= substr(stripslashes($subject), 0, 900);
3709 $mail->AddAddress($user->email
, fullname($user) );
3711 $mail->WordWrap
= 79; // set word wrap
3713 if (!empty($from->customheaders
)) { // Add custom headers
3714 if (is_array($from->customheaders
)) {
3715 foreach ($from->customheaders
as $customheader) {
3716 $mail->AddCustomHeader($customheader);
3719 $mail->AddCustomHeader($from->customheaders
);
3723 if (!empty($from->priority
)) {
3724 $mail->Priority
= $from->priority
;
3727 if ($messagehtml && $user->mailformat
== 1) { // Don't ever send HTML to users who don't want it
3728 $mail->IsHTML(true);
3729 $mail->Encoding
= 'quoted-printable'; // Encoding to use
3730 $mail->Body
= $messagehtml;
3731 $mail->AltBody
= "\n$messagetext\n";
3733 $mail->IsHTML(false);
3734 $mail->Body
= "\n$messagetext\n";
3737 if ($attachment && $attachname) {
3738 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
3739 $mail->AddAddress($supportuser->email
, fullname($supportuser, true) );
3740 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
3742 require_once($CFG->libdir
.'/filelib.php');
3743 $mimetype = mimeinfo('type', $attachname);
3744 $mail->AddAttachment($CFG->dataroot
.'/'. $attachment, $attachname, 'base64', $mimetype);
3750 /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
3751 /// encoding to the specified one
3752 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
3753 /// Set it to site mail charset
3754 $charset = $CFG->sitemailcharset
;
3755 /// Overwrite it with the user mail charset
3756 if (!empty($CFG->allowusermailcharset
)) {
3757 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
3758 $charset = $useremailcharset;
3761 /// If it has changed, convert all the necessary strings
3762 $charsets = get_list_of_charsets();
3763 unset($charsets['UTF-8']);
3764 if (in_array($charset, $charsets)) {
3765 /// Save the new mail charset
3766 $mail->CharSet
= $charset;
3767 /// And convert some strings
3768 $mail->FromName
= $textlib->convert($mail->FromName
, 'utf-8', $mail->CharSet
); //From Name
3769 foreach ($mail->ReplyTo
as $key => $rt) { //ReplyTo Names
3770 $mail->ReplyTo
[$key][1] = $textlib->convert($rt, 'utf-8', $mail->CharSet
);
3772 $mail->Subject
= $textlib->convert($mail->Subject
, 'utf-8', $mail->CharSet
); //Subject
3773 foreach ($mail->to
as $key => $to) {
3774 $mail->to
[$key][1] = $textlib->convert($to, 'utf-8', $mail->CharSet
); //To Names
3776 $mail->Body
= $textlib->convert($mail->Body
, 'utf-8', $mail->CharSet
); //Body
3777 $mail->AltBody
= $textlib->convert($mail->AltBody
, 'utf-8', $mail->CharSet
); //Subject
3781 if ($mail->Send()) {
3782 set_send_count($user);
3783 $mail->IsSMTP(); // use SMTP directly
3784 if (!empty($CFG->debugsmtp
)) {
3789 mtrace('ERROR: '. $mail->ErrorInfo
);
3790 add_to_log(SITEID
, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo
);
3791 if (!empty($CFG->debugsmtp
)) {
3799 * Generate a signoff for emails based on support settings
3802 function generate_email_signoff() {
3806 if (!empty($CFG->supportname
)) {
3807 $signoff .= $CFG->supportname
."\n";
3809 if (!empty($CFG->supportemail
)) {
3810 $signoff .= $CFG->supportemail
."\n";
3812 if (!empty($CFG->supportpage
)) {
3813 $signoff .= $CFG->supportpage
."\n";
3819 * Generate a fake user for emails based on support settings
3822 function generate_email_supportuser() {
3826 static $supportuser;
3828 if (!empty($supportuser)) {
3829 return $supportuser;
3832 $supportuser = new object;
3833 $supportuser->email
= $CFG->supportemail ?
$CFG->supportemail
: $CFG->noreplyaddress
;
3834 $supportuser->firstname
= $CFG->supportname ?
$CFG->supportname
: get_string('noreplyname');
3835 $supportuser->lastname
= '';
3836 $supportuser->maildisplay
= true;
3838 return $supportuser;
3843 * Sets specified user's password and send the new password to the user via email.
3846 * @param user $user A {@link $USER} object
3847 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
3848 * was blocked by user and "false" if there was another sort of error.
3850 function setnew_password_and_mail($user) {
3856 $supportuser = generate_email_supportuser();
3858 $newpassword = generate_password();
3860 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id
) ) {
3861 trigger_error('Could not set user password!');
3866 $a->firstname
= fullname($user, true);
3867 $a->sitename
= format_string($site->fullname
);
3868 $a->username
= $user->username
;
3869 $a->newpassword
= $newpassword;
3870 $a->link
= $CFG->wwwroot
.'/login/';
3871 $a->signoff
= generate_email_signoff();
3873 $message = get_string('newusernewpasswordtext', '', $a);
3875 $subject = format_string($site->fullname
) .': '. get_string('newusernewpasswordsubj');
3877 return email_to_user($user, $supportuser, $subject, $message);
3882 * Resets specified user's password and send the new password to the user via email.
3885 * @param user $user A {@link $USER} object
3886 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3887 * was blocked by user and "false" if there was another sort of error.
3889 function reset_password_and_mail($user) {
3894 $supportuser = generate_email_supportuser();
3896 $userauth = get_auth_plugin($user->auth
);
3897 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth
)) {
3898 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
3902 $newpassword = generate_password();
3904 if (!$userauth->user_update_password(addslashes_recursive($user), addslashes($newpassword))) {
3905 error("Could not set user password!");
3909 $a->firstname
= $user->firstname
;
3910 $a->sitename
= format_string($site->fullname
);
3911 $a->username
= $user->username
;
3912 $a->newpassword
= $newpassword;
3913 $a->link
= $CFG->httpswwwroot
.'/login/change_password.php';
3914 $a->signoff
= generate_email_signoff();
3916 $message = get_string('newpasswordtext', '', $a);
3918 $subject = format_string($site->fullname
) .': '. get_string('changedpassword');
3920 return email_to_user($user, $supportuser, $subject, $message);
3925 * Send email to specified user with confirmation text and activation link.
3928 * @param user $user A {@link $USER} object
3929 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3930 * was blocked by user and "false" if there was another sort of error.
3932 function send_confirmation_email($user) {
3937 $supportuser = generate_email_supportuser();
3939 $data = new object();
3940 $data->firstname
= fullname($user);
3941 $data->sitename
= format_string($site->fullname
);
3942 $data->admin
= generate_email_signoff();
3944 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname
));
3946 $data->link
= $CFG->wwwroot
.'/login/confirm.php?data='. $user->secret
.'/'. urlencode($user->username
);
3947 $message = get_string('emailconfirmation', '', $data);
3948 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
3950 $user->mailformat
= 1; // Always send HTML version as well
3952 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
3957 * send_password_change_confirmation_email.
3960 * @param user $user A {@link $USER} object
3961 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3962 * was blocked by user and "false" if there was another sort of error.
3964 function send_password_change_confirmation_email($user) {
3969 $supportuser = generate_email_supportuser();
3971 $data = new object();
3972 $data->firstname
= $user->firstname
;
3973 $data->sitename
= format_string($site->fullname
);
3974 $data->link
= $CFG->httpswwwroot
.'/login/forgot_password.php?p='. $user->secret
.'&s='. urlencode($user->username
);
3975 $data->admin
= generate_email_signoff();
3977 $message = get_string('emailpasswordconfirmation', '', $data);
3978 $subject = get_string('emailpasswordconfirmationsubject', '', format_string($site->fullname
));
3980 return email_to_user($user, $supportuser, $subject, $message);
3985 * send_password_change_info.
3988 * @param user $user A {@link $USER} object
3989 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3990 * was blocked by user and "false" if there was another sort of error.
3992 function send_password_change_info($user) {
3997 $supportuser = generate_email_supportuser();
3998 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
4000 $data = new object();
4001 $data->firstname
= $user->firstname
;
4002 $data->sitename
= format_string($site->fullname
);
4003 $data->admin
= generate_email_signoff();
4005 $userauth = get_auth_plugin($user->auth
);
4007 if (!is_enabled_auth($user->auth
) or $user->auth
== 'nologin') {
4008 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
4009 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
4010 return email_to_user($user, $supportuser, $subject, $message);
4013 if ($userauth->can_change_password() and $userauth->change_password_url()) {
4014 // we have some external url for password changing
4015 $data->link
.= $userauth->change_password_url();
4018 //no way to change password, sorry
4022 if (!empty($data->link
) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id
)) {
4023 $message = get_string('emailpasswordchangeinfo', '', $data);
4024 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
4026 $message = get_string('emailpasswordchangeinfofail', '', $data);
4027 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
4030 return email_to_user($user, $supportuser, $subject, $message);
4035 * Check that an email is allowed. It returns an error message if there
4039 * @param string $email Content of email
4040 * @return string|false
4042 function email_is_not_allowed($email) {
4046 if (!empty($CFG->allowemailaddresses
)) {
4047 $allowed = explode(' ', $CFG->allowemailaddresses
);
4048 foreach ($allowed as $allowedpattern) {
4049 $allowedpattern = trim($allowedpattern);
4050 if (!$allowedpattern) {
4053 if (strpos($allowedpattern, '.') === 0) {
4054 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
4055 // subdomains are in a form ".example.com" - matches "xxx@anything.example.com"
4059 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) { // Match! (bug 5250)
4063 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
4065 } else if (!empty($CFG->denyemailaddresses
)) {
4066 $denied = explode(' ', $CFG->denyemailaddresses
);
4067 foreach ($denied as $deniedpattern) {
4068 $deniedpattern = trim($deniedpattern);
4069 if (!$deniedpattern) {
4072 if (strpos($deniedpattern, '.') === 0) {
4073 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
4074 // subdomains are in a form ".example.com" - matches "xxx@anything.example.com"
4075 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
4078 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) { // Match! (bug 5250)
4079 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
4087 function email_welcome_message_to_user($course, $user=NULL) {
4091 if (!isloggedin()) {
4097 if (!empty($course->welcomemessage
)) {
4098 $subject = get_string('welcometocourse', '', format_string($course->fullname
));
4100 $a->coursename
= $course->fullname
;
4101 $a->profileurl
= "$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id";
4102 //$message = get_string("welcometocoursetext", "", $a);
4103 $message = $course->welcomemessage
;
4105 if (! $teacher = get_teacher($course->id
)) {
4106 $teacher = get_admin();
4108 email_to_user($user, $teacher, $subject, $message);
4112 /// FILE HANDLING /////////////////////////////////////////////
4116 * Makes an upload directory for a particular module.
4119 * @param int $courseid The id of the course in question - maps to id field of 'course' table.
4120 * @return string|false Returns full path to directory if successful, false if not
4122 function make_mod_upload_directory($courseid) {
4125 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata
)) {
4129 $strreadme = get_string('readme');
4131 if (file_exists($CFG->dirroot
.'/lang/'. $CFG->lang
.'/docs/module_files.txt')) {
4132 copy($CFG->dirroot
.'/lang/'. $CFG->lang
.'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
4134 copy($CFG->dirroot
.'/lang/en_utf8/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
4140 * Makes a directory for a particular user.
4143 * @param int $userid The id of the user in question - maps to id field of 'user' table.
4144 * @param bool $test Whether we are only testing the return value (do not create the directory)
4145 * @return string|false Returns full path to directory if successful, false if not
4147 function make_user_directory($userid, $test=false) {
4150 if (is_bool($userid) ||
$userid < 0 ||
!ereg('^[0-9]{1,10}$', $userid) ||
$userid > 2147483647) {
4152 notify("Given userid was not a valid integer! (" . gettype($userid) . " $userid)");
4157 // Generate a two-level path for the userid. First level groups them by slices of 1000 users, second level is userid
4158 $level1 = floor($userid / 1000) * 1000;
4160 $userdir = "user/$level1/$userid";
4162 return $CFG->dataroot
. '/' . $userdir;
4164 return make_upload_directory($userdir);
4169 * Returns an array of full paths to user directories, indexed by their userids.
4171 * @param bool $only_non_empty Only return directories that contain files
4172 * @param bool $legacy Search for user directories in legacy location (dataroot/users/userid) instead of (dataroot/user/section/userid)
4173 * @return array An associative array: userid=>array(basedir => $basedir, userfolder => $userfolder)
4175 function get_user_directories($only_non_empty=true, $legacy=false) {
4178 $rootdir = $CFG->dataroot
."/user";
4181 $rootdir = $CFG->dataroot
."/users";
4185 //Check if directory exists
4186 if (check_dir_exists($rootdir, true)) {
4188 if ($userlist = get_directory_list($rootdir, '', true, true, false)) {
4189 foreach ($userlist as $userid) {
4190 $dirlist[$userid] = array('basedir' => $rootdir, 'userfolder' => $userid);
4193 notify("no directories found under $rootdir");
4196 if ($grouplist =get_directory_list($rootdir, '', true, true, false)) { // directories will be in the form 0, 1000, 2000 etc...
4197 foreach ($grouplist as $group) {
4198 if ($userlist = get_directory_list("$rootdir/$group", '', true, true, false)) {
4199 foreach ($userlist as $userid) {
4200 $dirlist[$userid] = array('basedir' => $rootdir, 'userfolder' => $group . '/' . $userid);
4207 notify("$rootdir does not exist!");
4214 * Returns current name of file on disk if it exists.
4216 * @param string $newfile File to be verified
4217 * @return string Current name of file on disk if true
4219 function valid_uploaded_file($newfile) {
4220 if (empty($newfile)) {
4223 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
4224 return $newfile['tmp_name'];
4231 * Returns the maximum size for uploading files.
4233 * There are seven possible upload limits:
4234 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
4235 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
4236 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
4237 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
4238 * 5. by the Moodle admin in $CFG->maxbytes
4239 * 6. by the teacher in the current course $course->maxbytes
4240 * 7. by the teacher for the current module, eg $assignment->maxbytes
4242 * These last two are passed to this function as arguments (in bytes).
4243 * Anything defined as 0 is ignored.
4244 * The smallest of all the non-zero numbers is returned.
4246 * @param int $sizebytes ?
4247 * @param int $coursebytes Current course $course->maxbytes (in bytes)
4248 * @param int $modulebytes Current module ->maxbytes (in bytes)
4249 * @return int The maximum size for uploading files.
4250 * @todo Finish documenting this function
4252 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4254 if (! $filesize = ini_get('upload_max_filesize')) {
4257 $minimumsize = get_real_size($filesize);
4259 if ($postsize = ini_get('post_max_size')) {
4260 $postsize = get_real_size($postsize);
4261 if ($postsize < $minimumsize) {
4262 $minimumsize = $postsize;
4266 if ($sitebytes and $sitebytes < $minimumsize) {
4267 $minimumsize = $sitebytes;
4270 if ($coursebytes and $coursebytes < $minimumsize) {
4271 $minimumsize = $coursebytes;
4274 if ($modulebytes and $modulebytes < $minimumsize) {
4275 $minimumsize = $modulebytes;
4278 return $minimumsize;
4282 * Related to {@link get_max_upload_file_size()} - this function returns an
4283 * array of possible sizes in an array, translated to the
4286 * @uses SORT_NUMERIC
4287 * @param int $sizebytes ?
4288 * @param int $coursebytes Current course $course->maxbytes (in bytes)
4289 * @param int $modulebytes Current module ->maxbytes (in bytes)
4291 * @todo Finish documenting this function
4293 function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4296 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
4300 $filesize[$maxsize] = display_size($maxsize);
4302 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
4303 5242880, 10485760, 20971520, 52428800, 104857600);
4305 // Allow maxbytes to be selected if it falls outside the above boundaries
4306 if( isset($CFG->maxbytes
) && !in_array($CFG->maxbytes
, $sizelist) ){
4307 $sizelist[] = $CFG->maxbytes
;
4310 foreach ($sizelist as $sizebytes) {
4311 if ($sizebytes < $maxsize) {
4312 $filesize[$sizebytes] = display_size($sizebytes);
4316 krsort($filesize, SORT_NUMERIC
);
4322 * If there has been an error uploading a file, print the appropriate error message
4323 * Numerical constants used as constant definitions not added until PHP version 4.2.0
4325 * $filearray is a 1-dimensional sub-array of the $_FILES array
4326 * eg $filearray = $_FILES['userfile1']
4327 * If left empty then the first element of the $_FILES array will be used
4330 * @param array $filearray A 1-dimensional sub-array of the $_FILES array
4331 * @param bool $returnerror If true then a string error message will be returned. Otherwise the user will be notified of the error in a notify() call.
4332 * @return bool|string
4334 function print_file_upload_error($filearray = '', $returnerror = false) {
4336 if ($filearray == '' or !isset($filearray['error'])) {
4338 if (empty($_FILES)) return false;
4340 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
4341 $filearray = array_shift($files); /// use first element of array
4344 switch ($filearray['error']) {
4346 case 0: // UPLOAD_ERR_OK
4347 if ($filearray['size'] > 0) {
4348 $errmessage = get_string('uploadproblem', $filearray['name']);
4350 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
4354 case 1: // UPLOAD_ERR_INI_SIZE
4355 $errmessage = get_string('uploadserverlimit');
4358 case 2: // UPLOAD_ERR_FORM_SIZE
4359 $errmessage = get_string('uploadformlimit');
4362 case 3: // UPLOAD_ERR_PARTIAL
4363 $errmessage = get_string('uploadpartialfile');
4366 case 4: // UPLOAD_ERR_NO_FILE
4367 $errmessage = get_string('uploadnofilefound');
4371 $errmessage = get_string('uploadproblem', $filearray['name']);
4377 notify($errmessage);
4384 * handy function to loop through an array of files and resolve any filename conflicts
4385 * both in the array of filenames and for what is already on disk.
4386 * not really compatible with the similar function in uploadlib.php
4387 * but this could be used for files/index.php for moving files around.
4390 function resolve_filename_collisions($destination,$files,$format='%s_%d.%s') {
4391 foreach ($files as $k => $f) {
4392 if (check_potential_filename($destination,$f,$files)) {
4393 $bits = explode('.', $f);
4394 for ($i = 1; true; $i++
) {
4395 $try = sprintf($format, $bits[0], $i, $bits[1]);
4396 if (!check_potential_filename($destination,$try,$files)) {
4407 * @used by resolve_filename_collisions
4409 function check_potential_filename($destination,$filename,$files) {
4410 if (file_exists($destination.'/'.$filename)) {
4413 if (count(array_keys($files,$filename)) > 1) {
4421 * Returns an array with all the filenames in
4422 * all subdirectories, relative to the given rootdir.
4423 * If excludefile is defined, then that file/directory is ignored
4424 * If getdirs is true, then (sub)directories are included in the output
4425 * If getfiles is true, then files are included in the output
4426 * (at least one of these must be true!)
4428 * @param string $rootdir ?
4429 * @param string $excludefile If defined then the specified file/directory is ignored
4430 * @param bool $descend ?
4431 * @param bool $getdirs If true then (sub)directories are included in the output
4432 * @param bool $getfiles If true then files are included in the output
4433 * @return array An array with all the filenames in
4434 * all subdirectories, relative to the given rootdir
4435 * @todo Finish documenting this function. Add examples of $excludefile usage.
4437 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
4441 if (!$getdirs and !$getfiles) { // Nothing to show
4445 if (!is_dir($rootdir)) { // Must be a directory
4449 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
4453 if (!is_array($excludefiles)) {
4454 $excludefiles = array($excludefiles);
4457 while (false !== ($file = readdir($dir))) {
4458 $firstchar = substr($file, 0, 1);
4459 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
4462 $fullfile = $rootdir .'/'. $file;
4463 if (filetype($fullfile) == 'dir') {
4468 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
4469 foreach ($subdirs as $subdir) {
4470 $dirs[] = $file .'/'. $subdir;
4473 } else if ($getfiles) {
4486 * Adds up all the files in a directory and works out the size.
4488 * @param string $rootdir ?
4489 * @param string $excludefile ?
4491 * @todo Finish documenting this function
4493 function get_directory_size($rootdir, $excludefile='') {
4497 // do it this way if we can, it's much faster
4498 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
4499 $command = trim($CFG->pathtodu
).' -sk --apparent-size '.escapeshellarg($rootdir);
4502 exec($command,$output,$return);
4503 if (is_array($output)) {
4504 return get_real_size(intval($output[0]).'k'); // we told it to return k.
4508 if (!is_dir($rootdir)) { // Must be a directory
4512 if (!$dir = @opendir
($rootdir)) { // Can't open it for some reason
4518 while (false !== ($file = readdir($dir))) {
4519 $firstchar = substr($file, 0, 1);
4520 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
4523 $fullfile = $rootdir .'/'. $file;
4524 if (filetype($fullfile) == 'dir') {
4525 $size +
= get_directory_size($fullfile, $excludefile);
4527 $size +
= filesize($fullfile);
4536 * Converts bytes into display form
4538 * @param string $size ?
4540 * @staticvar string $gb Localized string for size in gigabytes
4541 * @staticvar string $mb Localized string for size in megabytes
4542 * @staticvar string $kb Localized string for size in kilobytes
4543 * @staticvar string $b Localized string for size in bytes
4544 * @todo Finish documenting this function. Verify return type.
4546 function display_size($size) {
4548 static $gb, $mb, $kb, $b;
4551 $gb = get_string('sizegb');
4552 $mb = get_string('sizemb');
4553 $kb = get_string('sizekb');
4554 $b = get_string('sizeb');
4557 if ($size >= 1073741824) {
4558 $size = round($size / 1073741824 * 10) / 10 . $gb;
4559 } else if ($size >= 1048576) {
4560 $size = round($size / 1048576 * 10) / 10 . $mb;
4561 } else if ($size >= 1024) {
4562 $size = round($size / 1024 * 10) / 10 . $kb;
4564 $size = $size .' '. $b;
4570 * Cleans a given filename by removing suspicious or troublesome characters
4571 * Only these are allowed: alphanumeric _ - .
4572 * Unicode characters can be enabled by setting $CFG->unicodecleanfilename = true in config.php
4574 * WARNING: unicode characters may not be compatible with zip compression in backup/restore,
4575 * because native zip binaries do weird character conversions. Use PHP zipping instead.
4577 * @param string $string file name
4578 * @return string cleaned file name
4580 function clean_filename($string) {
4582 if (empty($CFG->unicodecleanfilename
)) {
4583 $textlib = textlib_get_instance();
4584 $string = $textlib->specialtoascii($string);
4585 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
4587 //clean only ascii range
4588 $string = preg_replace("/[\\000-\\x2c\\x2f\\x3a-\\x40\\x5b-\\x5e\\x60\\x7b-\\177]/s", '_', $string);
4590 $string = preg_replace("/_+/", '_', $string);
4591 $string = preg_replace("/\.\.+/", '.', $string);
4596 /// STRING TRANSLATION ////////////////////////////////////////
4599 * Returns the code for the current language
4606 function current_language() {
4607 global $CFG, $USER, $SESSION, $COURSE;
4609 if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) { // Course language can override all other settings for this page
4610 $return = $COURSE->lang
;
4612 } else if (!empty($SESSION->lang
)) { // Session language can override other settings
4613 $return = $SESSION->lang
;
4615 } else if (!empty($USER->lang
)) {
4616 $return = $USER->lang
;
4619 $return = $CFG->lang
;
4622 if ($return == 'en') {
4623 $return = 'en_utf8';
4630 * Prints out a translated string.
4632 * Prints out a translated string using the return value from the {@link get_string()} function.
4634 * Example usage of this function when the string is in the moodle.php file:<br/>
4637 * print_string('wordforstudent');
4641 * Example usage of this function when the string is not in the moodle.php file:<br/>
4644 * print_string('typecourse', 'calendar');
4648 * @param string $identifier The key identifier for the localized string
4649 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4650 * @param mixed $a An object, string or number that can be used
4651 * within translation strings
4653 function print_string($identifier, $module='', $a=NULL) {
4654 echo get_string($identifier, $module, $a);
4658 * fix up the optional data in get_string()/print_string() etc
4659 * ensure possible sprintf() format characters are escaped correctly
4660 * needs to handle arbitrary strings and objects
4661 * @param mixed $a An object, string or number that can be used
4662 * @return mixed the supplied parameter 'cleaned'
4664 function clean_getstring_data( $a ) {
4665 if (is_string($a)) {
4666 return str_replace( '%','%%',$a );
4668 elseif (is_object($a)) {
4669 $a_vars = get_object_vars( $a );
4670 $new_a_vars = array();
4671 foreach ($a_vars as $fname => $a_var) {
4672 $new_a_vars[$fname] = clean_getstring_data( $a_var );
4674 return (object)$new_a_vars;
4682 * @return array places to look for lang strings based on the prefix to the
4683 * module name. For example qtype_ in question/type. Used by get_string and
4686 function places_to_search_for_lang_strings() {
4690 '__exceptions' => array('moodle', 'langconfig'),
4691 'assignment_' => array('mod/assignment/type'),
4692 'auth_' => array('auth'),
4693 'block_' => array('blocks'),
4694 'datafield_' => array('mod/data/field'),
4695 'datapreset_' => array('mod/data/preset'),
4696 'enrol_' => array('enrol'),
4697 'format_' => array('course/format'),
4698 'qtype_' => array('question/type'),
4699 'report_' => array($CFG->admin
.'/report', 'course/report', 'mod/quiz/report'),
4700 'resource_' => array('mod/resource/type'),
4701 'gradereport_' => array('grade/report'),
4702 'gradeimport_' => array('grade/import'),
4703 'gradeexport_' => array('grade/export'),
4709 * Returns a localized string.
4711 * Returns the translated string specified by $identifier as
4712 * for $module. Uses the same format files as STphp.
4713 * $a is an object, string or number that can be used
4714 * within translation strings
4716 * eg "hello \$a->firstname \$a->lastname"
4719 * If you would like to directly echo the localized string use
4720 * the function {@link print_string()}
4722 * Example usage of this function involves finding the string you would
4723 * like a local equivalent of and using its identifier and module information
4724 * to retrive it.<br/>
4725 * If you open moodle/lang/en/moodle.php and look near line 1031
4726 * you will find a string to prompt a user for their word for student
4728 * $string['wordforstudent'] = 'Your word for Student';
4730 * So if you want to display the string 'Your word for student'
4731 * in any language that supports it on your site
4732 * you just need to use the identifier 'wordforstudent'
4734 * $mystring = '<strong>'. get_string('wordforstudent') .'</strong>';
4737 * If the string you want is in another file you'd take a slightly
4738 * different approach. Looking in moodle/lang/en/calendar.php you find
4741 * $string['typecourse'] = 'Course event';
4743 * If you want to display the string "Course event" in any language
4744 * supported you would use the identifier 'typecourse' and the module 'calendar'
4745 * (because it is in the file calendar.php):
4747 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
4750 * As a last resort, should the identifier fail to map to a string
4751 * the returned string will be [[ $identifier ]]
4754 * @param string $identifier The key identifier for the localized string
4755 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4756 * @param mixed $a An object, string or number that can be used
4757 * within translation strings
4758 * @param array $extralocations An array of strings with other locations to look for string files
4759 * @return string The localized string.
4761 function get_string($identifier, $module='', $a=NULL, $extralocations=NULL) {
4765 /// originally these special strings were stored in moodle.php now we are only in langconfig.php
4766 $langconfigstrs = array('alphabet', 'backupnameformat', 'decsep', 'firstdayofweek', 'listsep', 'locale',
4767 'localewin', 'localewincharset', 'oldcharset',
4768 'parentlanguage', 'strftimedate', 'strftimedateshort', 'strftimedatetime',
4769 'strftimedaydate', 'strftimedaydatetime', 'strftimedayshort', 'strftimedaytime',
4770 'strftimemonthyear', 'strftimerecent', 'strftimerecentfull', 'strftimetime',
4771 'thischarset', 'thisdirection', 'thislanguage');
4773 $filetocheck = 'langconfig.php';
4774 $defaultlang = 'en_utf8';
4775 if (in_array($identifier, $langconfigstrs)) {
4776 $module = 'langconfig'; //This strings are under langconfig.php for 1.6 lang packs
4779 $lang = current_language();
4781 if ($module == '') {
4785 // if $a happens to have % in it, double it so sprintf() doesn't break
4787 $a = clean_getstring_data( $a );
4790 /// Define the two or three major locations of language strings for this module
4791 $locations = array();
4793 if (!empty($extralocations)) { // Calling code has a good idea where to look
4794 if (is_array($extralocations)) {
4795 $locations +
= $extralocations;
4796 } else if (is_string($extralocations)) {
4797 $locations[] = $extralocations;
4799 debugging('Bad lang path provided');
4803 if (isset($CFG->running_installer
)) {
4804 $module = 'installer';
4805 $filetocheck = 'installer.php';
4806 $locations[] = $CFG->dirroot
.'/install/lang/';
4807 $locations[] = $CFG->dataroot
.'/lang/';
4808 $locations[] = $CFG->dirroot
.'/lang/';
4809 $defaultlang = 'en_utf8';
4811 $locations[] = $CFG->dataroot
.'/lang/';
4812 $locations[] = $CFG->dirroot
.'/lang/';
4815 /// Add extra places to look for strings for particular plugin types.
4816 $rules = places_to_search_for_lang_strings();
4817 $exceptions = $rules['__exceptions'];
4818 unset($rules['__exceptions']);
4820 if (!in_array($module, $exceptions)) {
4821 $dividerpos = strpos($module, '_');
4822 if ($dividerpos === false) {
4826 $type = substr($module, 0, $dividerpos +
1);
4827 $plugin = substr($module, $dividerpos +
1);
4829 if (!empty($rules[$type])) {
4830 foreach ($rules[$type] as $location) {
4831 $locations[] = $CFG->dirroot
. "/$location/$plugin/lang/";
4836 /// First check all the normal locations for the string in the current language
4838 foreach ($locations as $location) {
4839 $locallangfile = $location.$lang.'_local'.'/'.$module.'.php'; //first, see if there's a local file
4840 if (file_exists($locallangfile)) {
4841 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4843 return $resultstring;
4846 //if local directory not found, or particular string does not exist in local direcotry
4847 $langfile = $location.$lang.'/'.$module.'.php';
4848 if (file_exists($langfile)) {
4849 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4851 return $resultstring;
4856 /// If the preferred language was English (utf8) we can abort now
4857 /// saving some checks beacuse it's the only "root" lang
4858 if ($lang == 'en_utf8') {
4859 return '[['. $identifier .']]';
4862 /// Is a parent language defined? If so, try to find this string in a parent language file
4864 foreach ($locations as $location) {
4865 $langfile = $location.$lang.'/'.$filetocheck;
4866 if (file_exists($langfile)) {
4867 if ($result = get_string_from_file('parentlanguage', $langfile, "\$parentlang")) {
4869 if (!empty($parentlang)) { // found it!
4871 //first, see if there's a local file for parent
4872 $locallangfile = $location.$parentlang.'_local'.'/'.$module.'.php';
4873 if (file_exists($locallangfile)) {
4874 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4876 return $resultstring;
4880 //if local directory not found, or particular string does not exist in local direcotry
4881 $langfile = $location.$parentlang.'/'.$module.'.php';
4882 if (file_exists($langfile)) {
4883 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4885 return $resultstring;
4893 /// Our only remaining option is to try English
4895 foreach ($locations as $location) {
4896 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4897 if (file_exists($locallangfile)) {
4898 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4900 return $resultstring;
4904 //if local_en not found, or string not found in local_en
4905 $langfile = $location.$defaultlang.'/'.$module.'.php';
4907 if (file_exists($langfile)) {
4908 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4910 return $resultstring;
4915 /// And, because under 1.6 en is defined as en_utf8 child, me must try
4916 /// if it hasn't been queried before.
4917 if ($defaultlang == 'en') {
4918 $defaultlang = 'en_utf8';
4919 foreach ($locations as $location) {
4920 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4921 if (file_exists($locallangfile)) {
4922 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4924 return $resultstring;
4928 //if local_en not found, or string not found in local_en
4929 $langfile = $location.$defaultlang.'/'.$module.'.php';
4931 if (file_exists($langfile)) {
4932 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4934 return $resultstring;
4940 return '[['.$identifier.']]'; // Last resort
4944 * This function is only used from {@link get_string()}.
4946 * @internal Only used from get_string, not meant to be public API
4947 * @param string $identifier ?
4948 * @param string $langfile ?
4949 * @param string $destination ?
4950 * @return string|false ?
4951 * @staticvar array $strings Localized strings
4953 * @todo Finish documenting this function.
4955 function get_string_from_file($identifier, $langfile, $destination) {
4957 static $strings; // Keep the strings cached in memory.
4959 if (empty($strings[$langfile])) {
4961 include ($langfile);
4962 $strings[$langfile] = $string;
4964 $string = &$strings[$langfile];
4967 if (!isset ($string[$identifier])) {
4971 return $destination .'= sprintf("'. $string[$identifier] .'");';
4975 * Converts an array of strings to their localized value.
4977 * @param array $array An array of strings
4978 * @param string $module The language module that these strings can be found in.
4981 function get_strings($array, $module='') {
4984 foreach ($array as $item) {
4985 $string->$item = get_string($item, $module);
4991 * Returns a list of language codes and their full names
4992 * hides the _local files from everyone.
4993 * @param bool refreshcache force refreshing of lang cache
4994 * @param bool returnall ignore langlist, return all languages available
4995 * @return array An associative array with contents in the form of LanguageCode => LanguageName
4997 function get_list_of_languages($refreshcache=false, $returnall=false) {
5001 $languages = array();
5003 $filetocheck = 'langconfig.php';
5005 if (!$refreshcache && !$returnall && !empty($CFG->langcache
) && file_exists($CFG->dataroot
.'/cache/languages')) {
5006 /// read available langs from cache
5008 $lines = file($CFG->dataroot
.'/cache/languages');
5009 foreach ($lines as $line) {
5010 $line = trim($line);
5011 if (preg_match('/^(\w+)\s+(.+)/', $line, $matches)) {
5012 $languages[$matches[1]] = $matches[2];
5015 unset($lines); unset($line); unset($matches);
5019 if (!$returnall && !empty($CFG->langlist
)) {
5020 /// return only languages allowed in langlist admin setting
5022 $langlist = explode(',', $CFG->langlist
);
5023 // fix short lang names first - non existing langs are skipped anyway...
5024 foreach ($langlist as $lang) {
5025 if (strpos($lang, '_utf8') === false) {
5026 $langlist[] = $lang.'_utf8';
5029 // find existing langs from langlist
5030 foreach ($langlist as $lang) {
5031 $lang = trim($lang); //Just trim spaces to be a bit more permissive
5032 if (strstr($lang, '_local')!==false) {
5035 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
5036 $shortlang = substr($lang, 0, -5);
5040 /// Search under dirroot/lang
5041 if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck)) {
5042 include($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck);
5043 if (!empty($string['thislanguage'])) {
5044 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
5048 /// And moodledata/lang
5049 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck)) {
5050 include($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck);
5051 if (!empty($string['thislanguage'])) {
5052 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
5059 /// return all languages available in system
5060 /// Fetch langs from moodle/lang directory
5061 $langdirs = get_list_of_plugins('lang');
5062 /// Fetch langs from moodledata/lang directory
5063 $langdirs2 = get_list_of_plugins('lang', '', $CFG->dataroot
);
5064 /// Merge both lists of langs
5065 $langdirs = array_merge($langdirs, $langdirs2);
5068 /// Get some info from each lang (first from moodledata, then from moodle)
5069 foreach ($langdirs as $lang) {
5070 if (strstr($lang, '_local')!==false) {
5073 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
5074 $shortlang = substr($lang, 0, -5);
5078 /// Search under moodledata/lang
5079 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck)) {
5080 include($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck);
5081 if (!empty($string['thislanguage'])) {
5082 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
5086 /// And dirroot/lang
5087 if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck)) {
5088 include($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck);
5089 if (!empty($string['thislanguage'])) {
5090 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
5097 if ($refreshcache && !empty($CFG->langcache
)) {
5099 // we have a list of all langs only, just delete old cache
5100 @unlink
($CFG->dataroot
.'/cache/languages');
5103 // store the list of allowed languages
5104 if ($file = fopen($CFG->dataroot
.'/cache/languages', 'w')) {
5105 foreach ($languages as $key => $value) {
5106 fwrite($file, "$key $value\n");
5117 * Returns a list of charset codes. It's hardcoded, so they should be added manually
5118 * (cheking that such charset is supported by the texlib library!)
5120 * @return array And associative array with contents in the form of charset => charset
5122 function get_list_of_charsets() {
5125 'EUC-JP' => 'EUC-JP',
5126 'ISO-2022-JP'=> 'ISO-2022-JP',
5127 'ISO-8859-1' => 'ISO-8859-1',
5128 'SHIFT-JIS' => 'SHIFT-JIS',
5129 'GB2312' => 'GB2312',
5130 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
5131 'UTF-8' => 'UTF-8');
5139 * Returns a list of country names in the current language
5145 function get_list_of_countries() {
5148 $lang = current_language();
5150 if (!file_exists($CFG->dirroot
.'/lang/'. $lang .'/countries.php') &&
5151 !file_exists($CFG->dataroot
.'/lang/'. $lang .'/countries.php')) {
5152 if ($parentlang = get_string('parentlanguage')) {
5153 if (file_exists($CFG->dirroot
.'/lang/'. $parentlang .'/countries.php') ||
5154 file_exists($CFG->dataroot
.'/lang/'. $parentlang .'/countries.php')) {
5155 $lang = $parentlang;
5157 $lang = 'en_utf8'; // countries.php must exist in this pack
5160 $lang = 'en_utf8'; // countries.php must exist in this pack
5164 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/countries.php')) {
5165 include($CFG->dataroot
.'/lang/'. $lang .'/countries.php');
5166 } else if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/countries.php')) {
5167 include($CFG->dirroot
.'/lang/'. $lang .'/countries.php');
5170 if (!empty($string)) {
5178 * Returns a list of valid and compatible themes
5183 function get_list_of_themes() {
5189 if (!empty($CFG->themelist
)) { // use admin's list of themes
5190 $themelist = explode(',', $CFG->themelist
);
5192 $themelist = get_list_of_plugins("theme");
5195 foreach ($themelist as $key => $theme) {
5196 if (!file_exists("$CFG->themedir/$theme/config.php")) { // bad folder
5199 $THEME = new object(); // Note this is not the global one!! :-)
5200 include("$CFG->themedir/$theme/config.php");
5201 if (!isset($THEME->sheets
)) { // Not a valid 1.5 theme
5204 $themes[$theme] = $theme;
5213 * Returns a list of picture names in the current or specified language
5218 function get_list_of_pixnames($lang = '') {
5222 $lang = current_language();
5227 $path = $CFG->dirroot
.'/lang/en_utf8/pix.php'; // always exists
5229 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'_local/pix.php')) {
5230 $path = $CFG->dataroot
.'/lang/'. $lang .'_local/pix.php';
5232 } else if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/pix.php')) {
5233 $path = $CFG->dirroot
.'/lang/'. $lang .'/pix.php';
5235 } else if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/pix.php')) {
5236 $path = $CFG->dataroot
.'/lang/'. $lang .'/pix.php';
5238 } else if ($parentlang = get_string('parentlanguage') and $parentlang != '[[parentlanguage]]') {
5239 return get_list_of_pixnames($parentlang); //return pixnames from parent language instead
5248 * Returns a list of timezones in the current language
5253 function get_list_of_timezones() {
5258 if (!empty($timezones)) { // This function has been called recently
5262 $timezones = array();
5264 if ($rawtimezones = get_records_sql('SELECT MAX(id), name FROM '.$CFG->prefix
.'timezone GROUP BY name')) {
5265 foreach($rawtimezones as $timezone) {
5266 if (!empty($timezone->name
)) {
5267 $timezones[$timezone->name
] = get_string(strtolower($timezone->name
), 'timezones');
5268 if (substr($timezones[$timezone->name
], 0, 1) == '[') { // No translation found
5269 $timezones[$timezone->name
] = $timezone->name
;
5277 for ($i = -13; $i <= 13; $i +
= .5) {
5280 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
5281 } else if ($i > 0) {
5282 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
5284 $timezones[sprintf("%.1f", $i)] = $tzstring;
5292 * Returns a list of currencies in the current language
5298 function get_list_of_currencies() {
5301 $lang = current_language();
5303 if (!file_exists($CFG->dataroot
.'/lang/'. $lang .'/currencies.php')) {
5304 if ($parentlang = get_string('parentlanguage')) {
5305 if (file_exists($CFG->dataroot
.'/lang/'. $parentlang .'/currencies.php')) {
5306 $lang = $parentlang;
5308 $lang = 'en_utf8'; // currencies.php must exist in this pack
5311 $lang = 'en_utf8'; // currencies.php must exist in this pack
5315 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/currencies.php')) {
5316 include_once($CFG->dataroot
.'/lang/'. $lang .'/currencies.php');
5317 } else { //if en_utf8 is not installed in dataroot
5318 include_once($CFG->dirroot
.'/lang/'. $lang .'/currencies.php');
5321 if (!empty($string)) {
5331 * Can include a given document file (depends on second
5332 * parameter) or just return info about it.
5335 * @param string $file ?
5336 * @param bool $include ?
5338 * @todo Finish documenting this function
5340 function document_file($file, $include=true) {
5343 $file = clean_filename($file);
5349 $langs = array(current_language(), get_string('parentlanguage'), 'en');
5351 foreach ($langs as $lang) {
5352 $info = new object();
5353 $info->filepath
= $CFG->dirroot
.'/lang/'. $lang .'/docs/'. $file;
5354 $info->urlpath
= $CFG->wwwroot
.'/lang/'. $lang .'/docs/'. $file;
5356 if (file_exists($info->filepath
)) {
5358 include($info->filepath
);
5367 /// ENCRYPTION ////////////////////////////////////////////////
5372 * @param string $data ?
5374 * @todo Finish documenting this function
5376 function rc4encrypt($data) {
5377 $password = 'nfgjeingjk';
5378 return endecrypt($password, $data, '');
5384 * @param string $data ?
5386 * @todo Finish documenting this function
5388 function rc4decrypt($data) {
5389 $password = 'nfgjeingjk';
5390 return endecrypt($password, $data, 'de');
5394 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
5396 * @param string $pwd ?
5397 * @param string $data ?
5398 * @param string $case ?
5400 * @todo Finish documenting this function
5402 function endecrypt ($pwd, $data, $case) {
5404 if ($case == 'de') {
5405 $data = urldecode($data);
5413 $pwd_length = strlen($pwd);
5415 for ($i = 0; $i <= 255; $i++
) {
5416 $key[$i] = ord(substr($pwd, ($i %
$pwd_length), 1));
5422 for ($i = 0; $i <= 255; $i++
) {
5423 $x = ($x +
$box[$i] +
$key[$i]) %
256;
5424 $temp_swap = $box[$i];
5425 $box[$i] = $box[$x];
5426 $box[$x] = $temp_swap;
5438 for ($i = 0; $i < strlen($data); $i++
) {
5439 $a = ($a +
1) %
256;
5440 $j = ($j +
$box[$a]) %
256;
5442 $box[$a] = $box[$j];
5444 $k = $box[(($box[$a] +
$box[$j]) %
256)];
5445 $cipherby = ord(substr($data, $i, 1)) ^
$k;
5446 $cipher .= chr($cipherby);
5449 if ($case == 'de') {
5450 $cipher = urldecode(urlencode($cipher));
5452 $cipher = urlencode($cipher);
5459 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
5463 * Call this function to add an event to the calendar table
5464 * and to call any calendar plugins
5467 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field. The object event should include the following:
5469 * <li><b>$event->name</b> - Name for the event
5470 * <li><b>$event->description</b> - Description of the event (defaults to '')
5471 * <li><b>$event->format</b> - Format for the description (using formatting types defined at the top of weblib.php)
5472 * <li><b>$event->courseid</b> - The id of the course this event belongs to (0 = all courses)
5473 * <li><b>$event->groupid</b> - The id of the group this event belongs to (0 = no group)
5474 * <li><b>$event->userid</b> - The id of the user this event belongs to (0 = no user)
5475 * <li><b>$event->modulename</b> - Name of the module that creates this event
5476 * <li><b>$event->instance</b> - Instance of the module that owns this event
5477 * <li><b>$event->eventtype</b> - The type info together with the module info could
5478 * be used by calendar plugins to decide how to display event
5479 * <li><b>$event->timestart</b>- Timestamp for start of event
5480 * <li><b>$event->timeduration</b> - Duration (defaults to zero)
5481 * <li><b>$event->visible</b> - 0 if the event should be hidden (e.g. because the activity that created it is hidden)
5483 * @return int The id number of the resulting record
5485 function add_event($event) {
5489 $event->timemodified
= time();
5491 if (!$event->id
= insert_record('event', $event)) {
5495 if (!empty($CFG->calendar
)) { // call the add_event function of the selected calendar
5496 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5497 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5498 $calendar_add_event = $CFG->calendar
.'_add_event';
5499 if (function_exists($calendar_add_event)) {
5500 $calendar_add_event($event);
5509 * Call this function to update an event in the calendar table
5510 * the event will be identified by the id field of the $event object.
5513 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5516 function update_event($event) {
5520 $event->timemodified
= time();
5522 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
5523 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5524 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5525 $calendar_update_event = $CFG->calendar
.'_update_event';
5526 if (function_exists($calendar_update_event)) {
5527 $calendar_update_event($event);
5531 return update_record('event', $event);
5535 * Call this function to delete the event with id $id from calendar table.
5538 * @param int $id The id of an event from the 'calendar' table.
5539 * @return array An associative array with the results from the SQL call.
5540 * @todo Verify return type
5542 function delete_event($id) {
5546 if (!empty($CFG->calendar
)) { // call the delete_event function of the selected calendar
5547 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5548 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5549 $calendar_delete_event = $CFG->calendar
.'_delete_event';
5550 if (function_exists($calendar_delete_event)) {
5551 $calendar_delete_event($id);
5555 return delete_records('event', 'id', $id);
5559 * Call this function to hide an event in the calendar table
5560 * the event will be identified by the id field of the $event object.
5563 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5564 * @return array An associative array with the results from the SQL call.
5565 * @todo Verify return type
5567 function hide_event($event) {
5570 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
5571 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5572 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5573 $calendar_hide_event = $CFG->calendar
.'_hide_event';
5574 if (function_exists($calendar_hide_event)) {
5575 $calendar_hide_event($event);
5579 return set_field('event', 'visible', 0, 'id', $event->id
);
5583 * Call this function to unhide an event in the calendar table
5584 * the event will be identified by the id field of the $event object.
5587 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5588 * @return array An associative array with the results from the SQL call.
5589 * @todo Verify return type
5591 function show_event($event) {
5594 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
5595 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5596 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5597 $calendar_show_event = $CFG->calendar
.'_show_event';
5598 if (function_exists($calendar_show_event)) {
5599 $calendar_show_event($event);
5603 return set_field('event', 'visible', 1, 'id', $event->id
);
5607 /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
5610 * Lists plugin directories within some directory
5613 * @param string $plugin dir under we'll look for plugins (defaults to 'mod')
5614 * @param string $exclude dir name to exclude from the list (defaults to none)
5615 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
5616 * @return array of plugins found under the requested parameters
5618 function get_list_of_plugins($plugin='mod', $exclude='', $basedir='') {
5624 if (empty($basedir)) {
5626 # This switch allows us to use the appropiate theme directory - and potentialy alternatives for other plugins
5629 $basedir = $CFG->themedir
;
5633 $basedir = $CFG->dirroot
.'/'. $plugin;
5637 $basedir = $basedir .'/'. $plugin;
5640 if (file_exists($basedir) && filetype($basedir) == 'dir') {
5641 $dirhandle = opendir($basedir);
5642 while (false !== ($dir = readdir($dirhandle))) {
5643 $firstchar = substr($dir, 0, 1);
5644 if ($firstchar == '.' or $dir == 'CVS' or $dir == '_vti_cnf' or $dir == $exclude) {
5647 if (filetype($basedir .'/'. $dir) != 'dir') {
5652 closedir($dirhandle);
5661 * Returns true if the current version of PHP is greater that the specified one.
5663 * @param string $version The version of php being tested.
5666 function check_php_version($version='4.1.0') {
5667 return (version_compare(phpversion(), $version) >= 0);
5672 * Checks to see if is a browser matches the specified
5673 * brand and is equal or better version.
5676 * @param string $brand The browser identifier being tested
5677 * @param int $version The version of the browser
5678 * @return bool true if the given version is below that of the detected browser
5680 function check_browser_version($brand='MSIE', $version=5.5) {
5681 if (empty($_SERVER['HTTP_USER_AGENT'])) {
5685 $agent = $_SERVER['HTTP_USER_AGENT'];
5689 case 'Camino': /// Mozilla Firefox browsers
5691 if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
5692 if (version_compare($match[1], $version) >= 0) {
5699 case 'Firefox': /// Mozilla Firefox browsers
5701 if (preg_match("/Firefox\/([0-9\.]+)/i", $agent, $match)) {
5702 if (version_compare($match[1], $version) >= 0) {
5709 case 'Gecko': /// Gecko based browsers
5711 if (substr_count($agent, 'Camino')) {
5712 // MacOS X Camino support
5713 $version = 20041110;
5716 // the proper string - Gecko/CCYYMMDD Vendor/Version
5717 // Faster version and work-a-round No IDN problem.
5718 if (preg_match("/Gecko\/([0-9]+)/i", $agent, $match)) {
5719 if ($match[1] > $version) {
5726 case 'MSIE': /// Internet Explorer
5728 if (strpos($agent, 'Opera')) { // Reject Opera
5731 $string = explode(';', $agent);
5732 if (!isset($string[1])) {
5735 $string = explode(' ', trim($string[1]));
5736 if (!isset($string[0]) and !isset($string[1])) {
5739 if ($string[0] == $brand and (float)$string[1] >= $version ) {
5744 case 'Opera': /// Opera
5746 if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
5747 if (version_compare($match[1], $version) >= 0) {
5753 case 'Safari': /// Safari
5754 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SimbianOS
5755 if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
5757 } elseif (strpos($agent, 'Shiira')) { // Reject Shiira
5759 } elseif (strpos($agent, 'SimbianOS')) { // Reject SimbianOS
5763 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
5764 if (version_compare($match[1], $version) >= 0) {
5777 * This function makes the return value of ini_get consistent if you are
5778 * setting server directives through the .htaccess file in apache.
5779 * Current behavior for value set from php.ini On = 1, Off = [blank]
5780 * Current behavior for value set from .htaccess On = On, Off = Off
5781 * Contributed by jdell @ unr.edu
5783 * @param string $ini_get_arg ?
5785 * @todo Finish documenting this function
5787 function ini_get_bool($ini_get_arg) {
5788 $temp = ini_get($ini_get_arg);
5790 if ($temp == '1' or strtolower($temp) == 'on') {
5797 * Compatibility stub to provide backward compatibility
5799 * Determines if the HTML editor is enabled.
5800 * @deprecated Use {@link can_use_html_editor()} instead.
5802 function can_use_richtext_editor() {
5803 return can_use_html_editor();
5807 * Determines if the HTML editor is enabled.
5809 * This depends on site and user
5810 * settings, as well as the current browser being used.
5812 * @return string|false Returns false if editor is not being used, otherwise
5813 * returns 'MSIE' or 'Gecko'.
5815 function can_use_html_editor() {
5818 if (!empty($USER->htmleditor
) and !empty($CFG->htmleditor
)) {
5819 if (check_browser_version('MSIE', 5.5)) {
5821 } else if (check_browser_version('Gecko', 20030516)) {
5829 * Hack to find out the GD version by parsing phpinfo output
5831 * @return int GD version (1, 2, or 0)
5833 function check_gd_version() {
5836 if (function_exists('gd_info')){
5837 $gd_info = gd_info();
5838 if (substr_count($gd_info['GD Version'], '2.')) {
5840 } else if (substr_count($gd_info['GD Version'], '1.')) {
5847 $phpinfo = ob_get_contents();
5850 $phpinfo = explode("\n", $phpinfo);
5853 foreach ($phpinfo as $text) {
5854 $parts = explode('</td>', $text);
5855 foreach ($parts as $key => $val) {
5856 $parts[$key] = trim(strip_tags($val));
5858 if ($parts[0] == 'GD Version') {
5859 if (substr_count($parts[1], '2.0')) {
5862 $gdversion = intval($parts[1]);
5867 return $gdversion; // 1, 2 or 0
5871 * Determine if moodle installation requires update
5873 * Checks version numbers of main code and all modules to see
5874 * if there are any mismatches
5879 function moodle_needs_upgrading() {
5883 include_once($CFG->dirroot
.'/version.php'); # defines $version and upgrades
5884 if ($CFG->version
) {
5885 if ($version > $CFG->version
) {
5888 if ($mods = get_list_of_plugins('mod')) {
5889 foreach ($mods as $mod) {
5890 $fullmod = $CFG->dirroot
.'/mod/'. $mod;
5891 $module = new object();
5892 if (!is_readable($fullmod .'/version.php')) {
5893 notify('Module "'. $mod .'" is not readable - check permissions');
5896 include_once($fullmod .'/version.php'); # defines $module with version etc
5897 if ($currmodule = get_record('modules', 'name', $mod)) {
5898 if ($module->version
> $currmodule->version
) {
5911 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
5914 * Notify admin users or admin user of any failed logins (since last notification).
5916 * Note that this function must be only executed from the cron script
5917 * It uses the cache_flags system to store temporary records, deleting them
5918 * by name before finishing
5924 function notify_login_failures() {
5927 switch ($CFG->notifyloginfailures
) {
5929 $recip = array(get_admin());
5932 $recip = get_admins();
5936 if (empty($CFG->lastnotifyfailure
)) {
5937 $CFG->lastnotifyfailure
=0;
5940 // we need to deal with the threshold stuff first.
5941 if (empty($CFG->notifyloginthreshold
)) {
5942 $CFG->notifyloginthreshold
= 10; // default to something sensible.
5945 /// Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
5946 /// and insert them into the cache_flags temp table
5947 $iprs = get_recordset_sql("SELECT ip, count(*)
5948 FROM {$CFG->prefix}log
5949 WHERE module = 'login'
5950 AND action = 'error'
5951 AND time > $CFG->lastnotifyfailure
5953 HAVING count(*) >= $CFG->notifyloginthreshold");
5954 while ($iprec = rs_fetch_next_record($iprs)) {
5955 if (!empty($iprec->ip
)) {
5956 set_cache_flag('login_failure_by_ip', $iprec->ip
, '1', 0);
5961 /// Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
5962 /// and insert them into the cache_flags temp table
5963 $infors = get_recordset_sql("SELECT info, count(*)
5964 FROM {$CFG->prefix}log
5965 WHERE module = 'login'
5966 AND action = 'error'
5967 AND time > $CFG->lastnotifyfailure
5969 HAVING count(*) >= $CFG->notifyloginthreshold");
5970 while ($inforec = rs_fetch_next_record($infors)) {
5971 if (!empty($inforec->info
)) {
5972 set_cache_flag('login_failure_by_info', $inforec->info
, '1', 0);
5977 /// Now, select all the login error logged records belonging to the ips and infos
5978 /// since lastnotifyfailure, that we have stored in the cache_flags table
5979 $logsrs = get_recordset_sql("SELECT l.*, u.firstname, u.lastname
5980 FROM {$CFG->prefix}log l
5981 JOIN {$CFG->prefix}cache_flags cf ON (l.ip = cf.name)
5982 LEFT JOIN {$CFG->prefix}user u ON (l.userid = u.id)
5983 WHERE l.module = 'login'
5984 AND l.action = 'error'
5985 AND l.time > $CFG->lastnotifyfailure
5986 AND cf.flagtype = 'login_failure_by_ip'
5988 SELECT l.*, u.firstname, u.lastname
5989 FROM {$CFG->prefix}log l
5990 JOIN {$CFG->prefix}cache_flags cf ON (l.info = cf.name)
5991 LEFT JOIN {$CFG->prefix}user u ON (l.userid = u.id)
5992 WHERE l.module = 'login'
5993 AND l.action = 'error'
5994 AND l.time > $CFG->lastnotifyfailure
5995 AND cf.flagtype = 'login_failure_by_info'
5996 ORDER BY time DESC");
5998 /// Init some variables
6001 /// Iterate over the logs recordset
6002 while ($log = rs_fetch_next_record($logsrs)) {
6003 $log->time
= userdate($log->time
);
6004 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
6009 /// If we haven't run in the last hour and
6010 /// we have something useful to report and we
6011 /// are actually supposed to be reporting to somebody
6012 if ((time() - HOURSECS
) > $CFG->lastnotifyfailure
&& $count > 0 && is_array($recip) && count($recip) > 0) {
6014 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname
));
6015 /// Calculate the complete body of notification (start + messages + end)
6016 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot
) .
6017 (($CFG->lastnotifyfailure
!= 0) ?
'('.userdate($CFG->lastnotifyfailure
).')' : '')."\n\n" .
6019 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot
)."\n\n";
6021 /// For each destination, send mail
6022 foreach ($recip as $admin) {
6023 mtrace('Emailing '. $admin->username
.' about '. $count .' failed login attempts');
6024 email_to_user($admin,get_admin(), $subject, $body);
6027 /// Update lastnotifyfailure with current time
6028 set_config('lastnotifyfailure', time());
6031 /// Finally, delete all the temp records we have created in cache_flags
6032 delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
6039 * @param string $locale ?
6040 * @todo Finish documenting this function
6042 function moodle_setlocale($locale='') {
6046 static $currentlocale = ''; // last locale caching
6048 $oldlocale = $currentlocale;
6050 /// Fetch the correct locale based on ostype
6051 if($CFG->ostype
== 'WINDOWS') {
6052 $stringtofetch = 'localewin';
6054 $stringtofetch = 'locale';
6057 /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
6058 if (!empty($locale)) {
6059 $currentlocale = $locale;
6060 } else if (!empty($CFG->locale
)) { // override locale for all language packs
6061 $currentlocale = $CFG->locale
;
6063 $currentlocale = get_string($stringtofetch);
6066 /// do nothing if locale already set up
6067 if ($oldlocale == $currentlocale) {
6071 /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
6072 /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
6073 /// Some day, numeric, monetary and other categories should be set too, I think. :-/
6075 /// Get current values
6076 $monetary= setlocale (LC_MONETARY
, 0);
6077 $numeric = setlocale (LC_NUMERIC
, 0);
6078 $ctype = setlocale (LC_CTYPE
, 0);
6079 if ($CFG->ostype
!= 'WINDOWS') {
6080 $messages= setlocale (LC_MESSAGES
, 0);
6082 /// Set locale to all
6083 setlocale (LC_ALL
, $currentlocale);
6085 setlocale (LC_MONETARY
, $monetary);
6086 setlocale (LC_NUMERIC
, $numeric);
6087 if ($CFG->ostype
!= 'WINDOWS') {
6088 setlocale (LC_MESSAGES
, $messages);
6090 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
6091 setlocale (LC_CTYPE
, $ctype);
6096 * Converts string to lowercase using most compatible function available.
6098 * @param string $string The string to convert to all lowercase characters.
6099 * @param string $encoding The encoding on the string.
6101 * @todo Add examples of calling this function with/without encoding types
6102 * @deprecated Use textlib->strtolower($text) instead.
6104 function moodle_strtolower ($string, $encoding='') {
6106 //If not specified use utf8
6107 if (empty($encoding)) {
6108 $encoding = 'UTF-8';
6111 $textlib = textlib_get_instance();
6113 return $textlib->strtolower($string, $encoding);
6117 * Count words in a string.
6119 * Words are defined as things between whitespace.
6121 * @param string $string The text to be searched for words.
6122 * @return int The count of words in the specified string
6124 function count_words($string) {
6125 $string = strip_tags($string);
6126 return count(preg_split("/\w\b/", $string)) - 1;
6129 /** Count letters in a string.
6131 * Letters are defined as chars not in tags and different from whitespace.
6133 * @param string $string The text to be searched for letters.
6134 * @return int The count of letters in the specified text.
6136 function count_letters($string) {
6137 /// Loading the textlib singleton instance. We are going to need it.
6138 $textlib = textlib_get_instance();
6140 $string = strip_tags($string); // Tags are out now
6141 $string = ereg_replace('[[:space:]]*','',$string); //Whitespace are out now
6143 return $textlib->strlen($string);
6147 * Generate and return a random string of the specified length.
6149 * @param int $length The length of the string to be created.
6152 function random_string ($length=15) {
6153 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
6154 $pool .= 'abcdefghijklmnopqrstuvwxyz';
6155 $pool .= '0123456789';
6156 $poollen = strlen($pool);
6157 mt_srand ((double) microtime() * 1000000);
6159 for ($i = 0; $i < $length; $i++
) {
6160 $string .= substr($pool, (mt_rand()%
($poollen)), 1);
6166 * Given some text (which may contain HTML) and an ideal length,
6167 * this function truncates the text neatly on a word boundary if possible
6169 function shorten_text($text, $ideal=30) {
6176 $length = strlen($text);
6181 if ($length <= $ideal) {
6185 for ($i=0; $i<$length; $i++
) {
6198 if ($char == '.' or $char == ' ') {
6201 } else if (ord($char) >= 0xE0) { // Chinese/Japanese/Korean text
6202 $truncate = $i; // can be truncated at any UTF-8
6203 break 2; // character boundary.
6211 if ($count > $ideal) {
6221 $ellipse = ($truncate < $length) ?
'...' : '';
6223 return substr($text, 0, $truncate).$ellipse;
6228 * Given dates in seconds, how many weeks is the date from startdate
6229 * The first week is 1, the second 2 etc ...
6232 * @param ? $startdate ?
6233 * @param ? $thedate ?
6235 * @todo Finish documenting this function
6237 function getweek ($startdate, $thedate) {
6238 if ($thedate < $startdate) { // error
6242 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
6246 * returns a randomly generated password of length $maxlen. inspired by
6247 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3}
6249 * @param int $maxlength The maximum size of the password being generated.
6252 function generate_password($maxlen=10) {
6255 $fillers = '1234567890!$-+';
6256 $wordlist = file($CFG->wordlist
);
6258 srand((double) microtime() * 1000000);
6259 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
6260 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
6261 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
6263 return substr($word1 . $filler1 . $word2, 0, $maxlen);
6267 * Given a float, prints it nicely.
6268 * Localized floats must not be used in calculations!
6270 * @param float $flaot The float to print
6271 * @param int $places The number of decimal places to print.
6272 * @param bool $localized use localized decimal separator
6273 * @return string locale float
6275 function format_float($float, $decimalpoints=1, $localized=true) {
6276 if (is_null($float)) {
6280 return number_format($float, $decimalpoints, get_string('decsep'), '');
6282 return number_format($float, $decimalpoints, '.', '');
6287 * Converts locale specific floating point/comma number back to standard PHP float value
6288 * Do NOT try to do any math operations before this conversion on any user submitted floats!
6290 * @param string $locale_float locale aware float representation
6292 function unformat_float($locale_float) {
6293 $locale_float = trim($locale_float);
6295 if ($locale_float == '') {
6299 $locale_float = str_replace(' ', '', $locale_float); // no spaces - those might be used as thousand separators
6301 return (float)str_replace(get_string('decsep'), '.', $locale_float);
6305 * Given a simple array, this shuffles it up just like shuffle()
6306 * Unlike PHP's shuffle() this function works on any machine.
6308 * @param array $array The array to be rearranged
6311 function swapshuffle($array) {
6313 srand ((double) microtime() * 10000000);
6314 $last = count($array) - 1;
6315 for ($i=0;$i<=$last;$i++
) {
6316 $from = rand(0,$last);
6318 $array[$i] = $array[$from];
6319 $array[$from] = $curr;
6325 * Like {@link swapshuffle()}, but works on associative arrays
6327 * @param array $array The associative array to be rearranged
6330 function swapshuffle_assoc($array) {
6333 $newkeys = swapshuffle(array_keys($array));
6334 foreach ($newkeys as $newkey) {
6335 $newarray[$newkey] = $array[$newkey];
6341 * Given an arbitrary array, and a number of draws,
6342 * this function returns an array with that amount
6343 * of items. The indexes are retained.
6345 * @param array $array ?
6348 * @todo Finish documenting this function
6350 function draw_rand_array($array, $draws) {
6351 srand ((double) microtime() * 10000000);
6355 $last = count($array);
6357 if ($draws > $last) {
6361 while ($draws > 0) {
6364 $keys = array_keys($array);
6365 $rand = rand(0, $last);
6367 $return[$keys[$rand]] = $array[$keys[$rand]];
6368 unset($array[$keys[$rand]]);
6379 * @param string $a ?
6380 * @param string $b ?
6382 * @todo Finish documenting this function
6384 function microtime_diff($a, $b) {
6385 list($a_dec, $a_sec) = explode(' ', $a);
6386 list($b_dec, $b_sec) = explode(' ', $b);
6387 return $b_sec - $a_sec +
$b_dec - $a_dec;
6391 * Given a list (eg a,b,c,d,e) this function returns
6392 * an array of 1->a, 2->b, 3->c etc
6394 * @param array $list ?
6395 * @param string $separator ?
6396 * @todo Finish documenting this function
6398 function make_menu_from_list($list, $separator=',') {
6400 $array = array_reverse(explode($separator, $list), true);
6401 foreach ($array as $key => $item) {
6402 $outarray[$key+
1] = trim($item);
6408 * Creates an array that represents all the current grades that
6409 * can be chosen using the given grading type. Negative numbers
6410 * are scales, zero is no grade, and positive numbers are maximum
6413 * @param int $gradingtype ?
6415 * @todo Finish documenting this function
6417 function make_grades_menu($gradingtype) {
6419 if ($gradingtype < 0) {
6420 if ($scale = get_record('scale', 'id', - $gradingtype)) {
6421 return make_menu_from_list($scale->scale
);
6423 } else if ($gradingtype > 0) {
6424 for ($i=$gradingtype; $i>=0; $i--) {
6425 $grades[$i] = $i .' / '. $gradingtype;
6433 * This function returns the nummber of activities
6434 * using scaleid in a courseid
6436 * @param int $courseid ?
6437 * @param int $scaleid ?
6439 * @todo Finish documenting this function
6441 function course_scale_used($courseid, $scaleid) {
6447 if (!empty($scaleid)) {
6448 if ($cms = get_course_mods($courseid)) {
6449 foreach ($cms as $cm) {
6450 //Check cm->name/lib.php exists
6451 if (file_exists($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php')) {
6452 include_once($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php');
6453 $function_name = $cm->modname
.'_scale_used';
6454 if (function_exists($function_name)) {
6455 if ($function_name($cm->instance
,$scaleid)) {
6463 // check if any course grade item makes use of the scale
6464 $return +
= count_records('grade_items', 'courseid', $courseid, 'scaleid', $scaleid);
6470 * This function returns the nummber of activities
6471 * using scaleid in the entire site
6473 * @param int $scaleid ?
6475 * @todo Finish documenting this function. Is return type correct?
6477 function site_scale_used($scaleid,&$courses) {
6483 if (!is_array($courses) ||
count($courses) == 0) {
6484 $courses = get_courses("all",false,"c.id,c.shortname");
6487 if (!empty($scaleid)) {
6488 if (is_array($courses) && count($courses) > 0) {
6489 foreach ($courses as $course) {
6490 $return +
= course_scale_used($course->id
,$scaleid);
6498 * make_unique_id_code
6500 * @param string $extra ?
6502 * @todo Finish documenting this function
6504 function make_unique_id_code($extra='') {
6506 $hostname = 'unknownhost';
6507 if (!empty($_SERVER['HTTP_HOST'])) {
6508 $hostname = $_SERVER['HTTP_HOST'];
6509 } else if (!empty($_ENV['HTTP_HOST'])) {
6510 $hostname = $_ENV['HTTP_HOST'];
6511 } else if (!empty($_SERVER['SERVER_NAME'])) {
6512 $hostname = $_SERVER['SERVER_NAME'];
6513 } else if (!empty($_ENV['SERVER_NAME'])) {
6514 $hostname = $_ENV['SERVER_NAME'];
6517 $date = gmdate("ymdHis");
6519 $random = random_string(6);
6522 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
6524 return $hostname .'+'. $date .'+'. $random;
6530 * Function to check the passed address is within the passed subnet
6532 * The parameter is a comma separated string of subnet definitions.
6533 * Subnet strings can be in one of three formats:
6534 * 1: xxx.xxx.xxx.xxx/xx
6536 * 3: xxx.xxx.xxx.xxx-xxx //a range of IP addresses in the last group.
6537 * Code for type 1 modified from user posted comments by mediator at
6538 * {@link http://au.php.net/manual/en/function.ip2long.php}
6540 * @param string $addr The address you are checking
6541 * @param string $subnetstr The string of subnet addresses
6544 function address_in_subnet($addr, $subnetstr) {
6546 $subnets = explode(',', $subnetstr);
6548 $addr = trim($addr);
6550 foreach ($subnets as $subnet) {
6551 $subnet = trim($subnet);
6552 if (strpos($subnet, '/') !== false) { /// type 1
6553 list($ip, $mask) = explode('/', $subnet);
6554 $mask = 0xffffffff << (32 - $mask);
6555 $found = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
6556 } else if (strpos($subnet, '-') !== false) {/// type 3
6557 $subnetparts = explode('.', $subnet);
6558 $addrparts = explode('.', $addr);
6559 $subnetrange = explode('-', array_pop($subnetparts));
6560 if (count($subnetrange) == 2) {
6561 $lastaddrpart = array_pop($addrparts);
6562 $found = ($subnetparts == $addrparts &&
6563 $subnetrange[0] <= $lastaddrpart && $lastaddrpart <= $subnetrange[1]);
6566 $found = (strpos($addr, $subnet) === 0);
6577 * This function sets the $HTTPSPAGEREQUIRED global
6578 * (used in some parts of moodle to change some links)
6579 * and calculate the proper wwwroot to be used
6581 * By using this function properly, we can ensure 100% https-ized pages
6582 * at our entire discretion (login, forgot_password, change_password)
6584 function httpsrequired() {
6586 global $CFG, $HTTPSPAGEREQUIRED;
6588 if (!empty($CFG->loginhttps
)) {
6589 $HTTPSPAGEREQUIRED = true;
6590 $CFG->httpswwwroot
= str_replace('http:', 'https:', $CFG->wwwroot
);
6591 $CFG->httpsthemewww
= str_replace('http:', 'https:', $CFG->themewww
);
6593 // change theme URLs to https
6597 $CFG->httpswwwroot
= $CFG->wwwroot
;
6598 $CFG->httpsthemewww
= $CFG->themewww
;
6603 * For outputting debugging info
6606 * @param string $string ?
6607 * @param string $eol ?
6608 * @todo Finish documenting this function
6610 function mtrace($string, $eol="\n", $sleep=0) {
6612 if (defined('STDOUT')) {
6613 fwrite(STDOUT
, $string.$eol);
6615 echo $string . $eol;
6620 //delay to keep message on user's screen in case of subsequent redirect
6626 //Replace 1 or more slashes or backslashes to 1 slash
6627 function cleardoubleslashes ($path) {
6628 return preg_replace('/(\/|\\\){1,}/','/',$path);
6631 function zip_files ($originalfiles, $destination) {
6632 //Zip an array of files/dirs to a destination zip file
6633 //Both parameters must be FULL paths to the files/dirs
6637 //Extract everything from destination
6638 $path_parts = pathinfo(cleardoubleslashes($destination));
6639 $destpath = $path_parts["dirname"]; //The path of the zip file
6640 $destfilename = $path_parts["basename"]; //The name of the zip file
6641 $extension = $path_parts["extension"]; //The extension of the file
6644 if (empty($destfilename)) {
6648 //If no extension, add it
6649 if (empty($extension)) {
6651 $destfilename = $destfilename.'.'.$extension;
6654 //Check destination path exists
6655 if (!is_dir($destpath)) {
6659 //Check destination path is writable. TODO!!
6661 //Clean destination filename
6662 $destfilename = clean_filename($destfilename);
6664 //Now check and prepare every file
6668 foreach ($originalfiles as $file) { //Iterate over each file
6669 //Check for every file
6670 $tempfile = cleardoubleslashes($file); // no doubleslashes!
6671 //Calculate the base path for all files if it isn't set
6672 if ($origpath === NULL) {
6673 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
6675 //See if the file is readable
6676 if (!is_readable($tempfile)) { //Is readable
6679 //See if the file/dir is in the same directory than the rest
6680 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
6683 //Add the file to the array
6684 $files[] = $tempfile;
6687 //Everything is ready:
6688 // -$origpath is the path where ALL the files to be compressed reside (dir).
6689 // -$destpath is the destination path where the zip file will go (dir).
6690 // -$files is an array of files/dirs to compress (fullpath)
6691 // -$destfilename is the name of the zip file (without path)
6693 //print_object($files); //Debug
6695 if (empty($CFG->zip
)) { // Use built-in php-based zip function
6697 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6698 //rewrite filenames because the old method with PCLZIP_OPT_REMOVE_PATH does not work under win32
6699 $zipfiles = array();
6700 $start = strlen($origpath)+
1;
6701 foreach($files as $file) {
6703 $tf[PCLZIP_ATT_FILE_NAME
] = $file;
6704 $tf[PCLZIP_ATT_FILE_NEW_FULL_NAME
] = substr($file, $start);
6707 //create the archive
6708 $archive = new PclZip(cleardoubleslashes("$destpath/$destfilename"));
6709 if (($list = $archive->create($zipfiles) == 0)) {
6710 notice($archive->errorInfo(true));
6714 } else { // Use external zip program
6717 foreach ($files as $filetozip) {
6718 $filestozip .= escapeshellarg(basename($filetozip));
6721 //Construct the command
6722 $separator = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
' &' : ' ;';
6723 $command = 'cd '.escapeshellarg($origpath).$separator.
6724 escapeshellarg($CFG->zip
).' -r '.
6725 escapeshellarg(cleardoubleslashes("$destpath/$destfilename")).' '.$filestozip;
6726 //All converted to backslashes in WIN
6727 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6728 $command = str_replace('/','\\',$command);
6735 function unzip_file ($zipfile, $destination = '', $showstatus = true) {
6736 //Unzip one zip file to a destination dir
6737 //Both parameters must be FULL paths
6738 //If destination isn't specified, it will be the
6739 //SAME directory where the zip file resides.
6743 //Extract everything from zipfile
6744 $path_parts = pathinfo(cleardoubleslashes($zipfile));
6745 $zippath = $path_parts["dirname"]; //The path of the zip file
6746 $zipfilename = $path_parts["basename"]; //The name of the zip file
6747 $extension = $path_parts["extension"]; //The extension of the file
6750 if (empty($zipfilename)) {
6754 //If no extension, error
6755 if (empty($extension)) {
6760 $zipfile = cleardoubleslashes($zipfile);
6762 //Check zipfile exists
6763 if (!file_exists($zipfile)) {
6767 //If no destination, passed let's go with the same directory
6768 if (empty($destination)) {
6769 $destination = $zippath;
6772 //Clear $destination
6773 $destpath = rtrim(cleardoubleslashes($destination), "/");
6775 //Check destination path exists
6776 if (!is_dir($destpath)) {
6780 //Check destination path is writable. TODO!!
6782 //Everything is ready:
6783 // -$zippath is the path where the zip file resides (dir)
6784 // -$zipfilename is the name of the zip file (without path)
6785 // -$destpath is the destination path where the zip file will uncompressed (dir)
6789 if (empty($CFG->unzip
)) { // Use built-in php-based unzip function
6791 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6792 $archive = new PclZip(cleardoubleslashes("$zippath/$zipfilename"));
6793 if (!$list = $archive->extract(PCLZIP_OPT_PATH
, $destpath,
6794 PCLZIP_CB_PRE_EXTRACT
, 'unzip_cleanfilename',
6795 PCLZIP_OPT_EXTRACT_DIR_RESTRICTION
, $destpath)) {
6796 notice($archive->errorInfo(true));
6800 } else { // Use external unzip program
6802 $separator = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
' &' : ' ;';
6803 $redirection = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
'' : ' 2>&1';
6805 $command = 'cd '.escapeshellarg($zippath).$separator.
6806 escapeshellarg($CFG->unzip
).' -o '.
6807 escapeshellarg(cleardoubleslashes("$zippath/$zipfilename")).' -d '.
6808 escapeshellarg($destpath).$redirection;
6809 //All converted to backslashes in WIN
6810 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6811 $command = str_replace('/','\\',$command);
6813 Exec($command,$list);
6816 //Display some info about the unzip execution
6818 unzip_show_status($list,$destpath);
6824 function unzip_cleanfilename ($p_event, &$p_header) {
6825 //This function is used as callback in unzip_file() function
6826 //to clean illegal characters for given platform and to prevent directory traversal.
6827 //Produces the same result as info-zip unzip.
6828 $p_header['filename'] = ereg_replace('[[:cntrl:]]', '', $p_header['filename']); //strip control chars first!
6829 $p_header['filename'] = ereg_replace('\.\.+', '', $p_header['filename']); //directory traversal protection
6830 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6831 $p_header['filename'] = ereg_replace('[:*"?<>|]', '_', $p_header['filename']); //replace illegal chars
6832 $p_header['filename'] = ereg_replace('^([a-zA-Z])_', '\1:', $p_header['filename']); //repair drive letter
6834 //Add filtering for other systems here
6835 // BSD: none (tested)
6839 $p_header['filename'] = cleardoubleslashes($p_header['filename']); //normalize the slashes/backslashes
6843 function unzip_show_status ($list,$removepath) {
6844 //This function shows the results of the unzip execution
6845 //depending of the value of the $CFG->zip, results will be
6846 //text or an array of files.
6850 if (empty($CFG->unzip
)) { // Use built-in php-based zip function
6851 $strname = get_string("name");
6852 $strsize = get_string("size");
6853 $strmodified = get_string("modified");
6854 $strstatus = get_string("status");
6855 echo "<table width=\"640\">";
6856 echo "<tr><th class=\"header\" scope=\"col\">$strname</th>";
6857 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strsize</th>";
6858 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strmodified</th>";
6859 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strstatus</th></tr>";
6860 foreach ($list as $item) {
6862 $item['filename'] = str_replace(cleardoubleslashes($removepath).'/', "", $item['filename']);
6863 print_cell("left", s($item['filename']));
6864 if (! $item['folder']) {
6865 print_cell("right", display_size($item['size']));
6867 echo "<td> </td>";
6869 $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
6870 print_cell("right", $filedate);
6871 print_cell("right", $item['status']);
6876 } else { // Use external zip program
6877 print_simple_box_start("center");
6879 foreach ($list as $item) {
6880 echo s(str_replace(cleardoubleslashes($removepath.'/'), '', $item)).'<br />';
6883 print_simple_box_end();
6888 * Returns most reliable client address
6890 * @return string The remote IP address
6892 function getremoteaddr() {
6893 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
6894 return cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
6896 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
6897 return cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
6899 if (!empty($_SERVER['REMOTE_ADDR'])) {
6900 return cleanremoteaddr($_SERVER['REMOTE_ADDR']);
6906 * Cleans a remote address ready to put into the log table
6908 function cleanremoteaddr($addr) {
6909 $originaladdr = $addr;
6911 // first get all things that look like IP addresses.
6912 if (!preg_match_all('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/',$addr,$matches,PREG_SET_ORDER
)) {
6915 $goodmatches = array();
6916 $lanmatches = array();
6917 foreach ($matches as $match) {
6919 // check to make sure it's not an internal address.
6920 // the following are reserved for private lans...
6921 // 10.0.0.0 - 10.255.255.255
6922 // 172.16.0.0 - 172.31.255.255
6923 // 192.168.0.0 - 192.168.255.255
6924 // 169.254.0.0 -169.254.255.255
6925 $bits = explode('.',$match[0]);
6926 if (count($bits) != 4) {
6927 // weird, preg match shouldn't give us it.
6930 if (($bits[0] == 10)
6931 ||
($bits[0] == 172 && $bits[1] >= 16 && $bits[1] <= 31)
6932 ||
($bits[0] == 192 && $bits[1] == 168)
6933 ||
($bits[0] == 169 && $bits[1] == 254)) {
6934 $lanmatches[] = $match[0];
6938 $goodmatches[] = $match[0];
6940 if (!count($goodmatches)) {
6941 // perhaps we have a lan match, it's probably better to return that.
6942 if (!count($lanmatches)) {
6945 return array_pop($lanmatches);
6948 if (count($goodmatches) == 1) {
6949 return $goodmatches[0];
6951 error_log("NOTICE: cleanremoteaddr gives us something funny: $originaladdr had ".count($goodmatches)." matches");
6952 // we need to return something, so
6953 return array_pop($goodmatches);
6957 * file_put_contents is only supported by php 5.0 and higher
6958 * so if it is not predefined, define it here
6960 * @param $file full path of the file to write
6961 * @param $contents contents to be sent
6962 * @return number of bytes written (false on error)
6964 if(!function_exists('file_put_contents')) {
6965 function file_put_contents($file, $contents) {
6967 if ($f = fopen($file, 'w')) {
6968 $result = fwrite($f, $contents);
6976 * The clone keyword is only supported from PHP 5 onwards.
6977 * The behaviour of $obj2 = $obj1 differs fundamentally
6978 * between PHP 4 and PHP 5. In PHP 4 a copy of $obj1 was
6979 * created, in PHP 5 $obj1 is referenced. To create a copy
6980 * in PHP 5 the clone keyword was introduced. This function
6981 * simulates this behaviour for PHP < 5.0.0.
6982 * See also: http://mjtsai.com/blog/2004/07/15/php-5-object-references/
6984 * Modified 2005-09-29 by Eloy (from Julian Sedding proposal)
6985 * Found a better implementation (more checks and possibilities) from PEAR:
6986 * http://cvs.php.net/co.php/pear/PHP_Compat/Compat/Function/clone.php
6988 * @param object $obj
6991 if(!check_php_version('5.0.0')) {
6992 // the eval is needed to prevent PHP 5 from getting a parse error!
6994 function clone($obj) {
6996 if (!is_object($obj)) {
6997 user_error(\'clone() __clone method called on non-object\', E_USER_WARNING);
7001 /// Use serialize/unserialize trick to deep copy the object
7002 $obj = unserialize(serialize($obj));
7004 /// If there is a __clone method call it on the "new" class
7005 if (method_exists($obj, \'__clone\')) {
7012 // Supply the PHP5 function scandir() to older versions.
7013 function scandir($directory) {
7015 if ($dh = opendir($directory)) {
7016 while (($file = readdir($dh)) !== false) {
7024 // Supply the PHP5 function array_combine() to older versions.
7025 function array_combine($keys, $values) {
7026 if (!is_array($keys) || !is_array($values) || count($keys) != count($values)) {
7031 foreach ($keys as $key) {
7032 $result[$key] = current($values);
7041 * This function will make a complete copy of anything it's given,
7042 * regardless of whether it's an object or not.
7043 * @param mixed $thing
7046 function fullclone($thing) {
7047 return unserialize(serialize($thing));
7052 * This function expects to called during shutdown
7053 * should be set via register_shutdown_function()
7054 * in lib/setup.php .
7056 * Right now we do it only if we are under apache, to
7057 * make sure apache children that hog too much mem are
7061 function moodle_request_shutdown() {
7065 // initially, we are only ever called under apache
7066 // but check just in case
7067 if (function_exists('apache_child_terminate')
7068 && function_exists('memory_get_usage')
7069 && ini_get_bool('child_terminate')) {
7070 if (empty($CFG->apachemaxmem
)) {
7071 $CFG->apachemaxmem
= 25000000; // default 25MiB
7073 if (memory_get_usage() > (int)$CFG->apachemaxmem
) {
7074 trigger_error('Mem usage over $CFG->apachemaxmem: marking child for reaping.');
7075 @apache_child_terminate
();
7078 if (defined('MDL_PERF') ||
(!empty($CFG->perfdebug
) and $CFG->perfdebug
> 7)) {
7079 if (defined('MDL_PERFTOLOG')) {
7080 $perf = get_performance_info();
7081 error_log("PERF: " . $perf['txt']);
7083 if (defined('MDL_PERFINC')) {
7084 $inc = get_included_files();
7086 foreach($inc as $f) {
7087 if (preg_match(':^/:', $f)) {
7090 $hfs = display_size($fs);
7091 error_log(substr($f,strlen($CFG->dirroot
)) . " size: $fs ($hfs)"
7094 error_log($f , NULL, NULL, 0);
7098 $hts = display_size($ts);
7099 error_log("Total size of files included: $ts ($hts)");
7106 * If new messages are waiting for the current user, then return
7107 * Javascript code to create a popup window
7109 * @return string Javascript code
7111 function message_popup_window() {
7114 $popuplimit = 30; // Minimum seconds between popups
7116 if (!defined('MESSAGE_WINDOW')) {
7117 if (isset($USER->id
) and !isguestuser()) {
7118 if (!isset($USER->message_lastpopup
)) {
7119 $USER->message_lastpopup
= 0;
7121 if ((time() - $USER->message_lastpopup
) > $popuplimit) { /// It's been long enough
7122 if (get_user_preferences('message_showmessagewindow', 1) == 1) {
7123 if (count_records_select('message', 'useridto = \''.$USER->id
.'\' AND timecreated > \''.$USER->message_lastpopup
.'\'')) {
7124 $USER->message_lastpopup
= time();
7125 return '<script type="text/javascript">'."\n//<![CDATA[\n openpopup('/message/index.php', 'message',
7126 'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500', 0);\n//]]>\n</script>";
7136 // Used to make sure that $min <= $value <= $max
7137 function bounded_number($min, $value, $max) {
7147 function array_is_nested($array) {
7148 foreach ($array as $value) {
7149 if (is_array($value)) {
7157 *** get_performance_info() pairs up with init_performance_info()
7158 *** loaded in setup.php. Returns an array with 'html' and 'txt'
7159 *** values ready for use, and each of the individual stats provided
7160 *** separately as well.
7163 function get_performance_info() {
7164 global $CFG, $PERF, $rcache;
7167 $info['html'] = ''; // holds userfriendly HTML representation
7168 $info['txt'] = me() . ' '; // holds log-friendly representation
7170 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
7172 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
7173 $info['txt'] .= 'time: '.$info['realtime'].'s ';
7175 if (function_exists('memory_get_usage')) {
7176 $info['memory_total'] = memory_get_usage();
7177 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
7178 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
7179 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
7182 $inc = get_included_files();
7183 //error_log(print_r($inc,1));
7184 $info['includecount'] = count($inc);
7185 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
7186 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
7188 if (!empty($PERF->dbqueries
)) {
7189 $info['dbqueries'] = $PERF->dbqueries
;
7190 $info['html'] .= '<span class="dbqueries">DB queries '.$info['dbqueries'].'</span> ';
7191 $info['txt'] .= 'dbqueries: '.$info['dbqueries'].' ';
7194 if (!empty($PERF->logwrites
)) {
7195 $info['logwrites'] = $PERF->logwrites
;
7196 $info['html'] .= '<span class="logwrites">Log writes '.$info['logwrites'].'</span> ';
7197 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
7200 if (!empty($PERF->profiling
) && $PERF->profiling
) {
7201 require_once($CFG->dirroot
.'/lib/profilerlib.php');
7202 $info['html'] .= '<span class="profilinginfo">'.Profiler
::get_profiling(array('-R')).'</span>';
7205 if (function_exists('posix_times')) {
7206 $ptimes = posix_times();
7207 if (is_array($ptimes)) {
7208 foreach ($ptimes as $key => $val) {
7209 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
7211 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
7212 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
7216 // Grab the load average for the last minute
7217 // /proc will only work under some linux configurations
7218 // while uptime is there under MacOSX/Darwin and other unices
7219 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
7220 list($server_load) = explode(' ', $loadavg[0]);
7222 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
7223 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
7224 $server_load = $matches[1];
7226 trigger_error('Could not parse uptime output!');
7229 if (!empty($server_load)) {
7230 $info['serverload'] = $server_load;
7231 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
7232 $info['txt'] .= "serverload: {$info['serverload']} ";
7235 if (isset($rcache->hits
) && isset($rcache->misses
)) {
7236 $info['rcachehits'] = $rcache->hits
;
7237 $info['rcachemisses'] = $rcache->misses
;
7238 $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
7239 "{$rcache->hits}/{$rcache->misses}</span> ";
7240 $info['txt'] .= 'rcache: '.
7241 "{$rcache->hits}/{$rcache->misses} ";
7243 $info['html'] = '<div class="performanceinfo">'.$info['html'].'</div>';
7247 function apd_get_profiling() {
7248 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
7251 function remove_dir($dir, $content_only=false) {
7252 // if content_only=true then delete all but
7253 // the directory itself
7255 $handle = opendir($dir);
7256 while (false!==($item = readdir($handle))) {
7257 if($item != '.' && $item != '..') {
7258 if(is_dir($dir.'/'.$item)) {
7259 remove_dir($dir.'/'.$item);
7261 unlink($dir.'/'.$item);
7266 if ($content_only) {
7273 * Function to check if a directory exists and optionally create it.
7275 * @param string absolute directory path
7276 * @param boolean create directory if does not exist
7277 * @param boolean create directory recursively
7279 * @return boolean true if directory exists or created
7281 function check_dir_exists($dir, $create=false, $recursive=false) {
7293 // PHP 5.0 has recursive mkdir parameter, but 4.x does not :-(
7294 $dir = str_replace('\\', '/', $dir); //windows compatibility
7295 $dirs = explode('/', $dir);
7296 $dir = array_shift($dirs).'/'; //skip root or drive letter
7297 foreach ($dirs as $part) {
7302 if (!is_dir($dir)) {
7303 if (!mkdir($dir, $CFG->directorypermissions
)) {
7310 $status = mkdir($dir, $CFG->directorypermissions
);
7317 function report_session_error() {
7318 global $CFG, $FULLME;
7320 if (empty($CFG->lang
)) {
7323 // Set up default theme and locale
7327 //clear session cookies
7328 setcookie('MoodleSession'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
7329 setcookie('MoodleSessionTest'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
7330 //increment database error counters
7331 if (isset($CFG->session_error_counter
)) {
7332 set_config('session_error_counter', 1 +
$CFG->session_error_counter
);
7334 set_config('session_error_counter', 1);
7336 redirect($FULLME, get_string('sessionerroruser2', 'error'), 5);
7341 * Detect if an object or a class contains a given property
7342 * will take an actual object or the name of a class
7343 * @param mix $obj Name of class or real object to test
7344 * @param string $property name of property to find
7345 * @return bool true if property exists
7347 function object_property_exists( $obj, $property ) {
7348 if (is_string( $obj )) {
7349 $properties = get_class_vars( $obj );
7352 $properties = get_object_vars( $obj );
7354 return array_key_exists( $property, $properties );
7359 * Detect a custom script replacement in the data directory that will
7360 * replace an existing moodle script
7361 * @param string $urlpath path to the original script
7362 * @return string full path name if a custom script exists
7363 * @return bool false if no custom script exists
7365 function custom_script_path($urlpath='') {
7368 // set default $urlpath, if necessary
7369 if (empty($urlpath)) {
7370 $urlpath = qualified_me(); // e.g. http://www.this-server.com/moodle/this-script.php
7373 // $urlpath is invalid if it is empty or does not start with the Moodle wwwroot
7374 if (empty($urlpath) or (strpos($urlpath, $CFG->wwwroot
) === false )) {
7378 // replace wwwroot with the path to the customscripts folder and clean path
7379 $scriptpath = $CFG->customscripts
. clean_param(substr($urlpath, strlen($CFG->wwwroot
)), PARAM_PATH
);
7381 // remove the query string, if any
7382 if (($strpos = strpos($scriptpath, '?')) !== false) {
7383 $scriptpath = substr($scriptpath, 0, $strpos);
7386 // remove trailing slashes, if any
7387 $scriptpath = rtrim($scriptpath, '/\\');
7389 // append index.php, if necessary
7390 if (is_dir($scriptpath)) {
7391 $scriptpath .= '/index.php';
7394 // check the custom script exists
7395 if (file_exists($scriptpath)) {
7403 * Wrapper function to load necessary editor scripts
7404 * to $CFG->editorsrc array. Params can be coursei id
7405 * or associative array('courseid' => value, 'name' => 'editorname').
7407 * @param mixed $args Courseid or associative array.
7409 function loadeditor($args) {
7411 include($CFG->libdir
.'/editorlib.php');
7412 return editorObject
::loadeditor($args);
7416 * Returns whether or not the user object is a remote MNET user. This function
7417 * is in moodlelib because it does not rely on loading any of the MNET code.
7419 * @param object $user A valid user object
7420 * @return bool True if the user is from a remote Moodle.
7422 function is_mnet_remote_user($user) {
7425 if (!isset($CFG->mnet_localhost_id
)) {
7426 include_once $CFG->dirroot
. '/mnet/lib.php';
7427 $env = new mnet_environment();
7432 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
7436 * Checks if a given plugin is in the list of enabled enrolment plugins.
7438 * @param string $auth Enrolment plugin.
7439 * @return boolean Whether the plugin is enabled.
7441 function is_enabled_enrol($enrol='') {
7444 // use the global default if not specified
7446 $enrol = $CFG->enrol
;
7448 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled
));
7452 * This function will search for browser prefereed languages, setting Moodle
7453 * to use the best one available if $SESSION->lang is undefined
7455 function setup_lang_from_browser() {
7457 global $CFG, $SESSION, $USER;
7459 if (!empty($SESSION->lang
) or !empty($USER->lang
)) {
7460 // Lang is defined in session or user profile, nothing to do
7464 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
7468 /// Extract and clean langs from headers
7469 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
7470 $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
7471 $rawlangs = explode(',', $rawlangs); // Convert to array
7475 foreach ($rawlangs as $lang) {
7476 if (strpos($lang, ';') === false) {
7477 $langs[(string)$order] = $lang;
7478 $order = $order-0.01;
7480 $parts = explode(';', $lang);
7481 $pos = strpos($parts[1], '=');
7482 $langs[substr($parts[1], $pos+
1)] = $parts[0];
7485 krsort($langs, SORT_NUMERIC
);
7487 $langlist = get_list_of_languages();
7489 /// Look for such langs under standard locations
7490 foreach ($langs as $lang) {
7491 $lang = strtolower(clean_param($lang.'_utf8', PARAM_SAFEDIR
)); // clean it properly for include
7492 if (!array_key_exists($lang, $langlist)) {
7493 continue; // language not allowed, try next one
7495 if (file_exists($CFG->dataroot
.'/lang/'. $lang) or file_exists($CFG->dirroot
.'/lang/'. $lang)) {
7496 $SESSION->lang
= $lang; /// Lang exists, set it in session
7497 break; /// We have finished. Go out
7504 ////////////////////////////////////////////////////////////////////////////////
7506 function is_newnav($navigation) {
7507 if (is_array($navigation) && !empty($navigation['newnav'])) {
7515 * Checks whether the given variable name is defined as a variable within the given object.
7516 * @note This will NOT work with stdClass objects, which have no class variables.
7517 * @param string $var The variable name
7518 * @param object $object The object to check
7521 function in_object_vars($var, $object) {
7522 $class_vars = get_class_vars(get_class($object));
7523 $class_vars = array_keys($class_vars);
7524 return in_array($var, $class_vars);
7528 * Returns an array without repeated objects.
7529 * This function is similar to array_unique, but for arrays that have objects as values
7531 * @param unknown_type $array
7532 * @param unknown_type $keep_key_assoc
7535 function object_array_unique($array, $keep_key_assoc = true) {
7536 $duplicate_keys = array();
7539 foreach ($array as $key=>$val) {
7540 // convert objects to arrays, in_array() does not support objects
7541 if (is_object($val)) {
7545 if (!in_array($val, $tmp)) {
7548 $duplicate_keys[] = $key;
7552 foreach ($duplicate_keys as $key) {
7553 unset($array[$key]);
7556 return $keep_key_assoc ?
$array : array_values($array);
7559 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: