3 ///////////////////////////////////////////////////////////////////////////
5 // NOTICE OF COPYRIGHT //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
10 // Copyright (C) 1999-2004 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);
49 define('NOGROUPS', 0);
54 define('SEPARATEGROUPS', 1);
59 define('VISIBLEGROUPS', 2);
61 /// Date and time constants ///
63 * Time constant - the number of seconds in a year
66 define('YEARSECS', 31536000);
69 * Time constant - the number of seconds in a week
71 define('WEEKSECS', 604800);
74 * Time constant - the number of seconds in a day
76 define('DAYSECS', 86400);
79 * Time constant - the number of seconds in an hour
81 define('HOURSECS', 3600);
84 * Time constant - the number of seconds in a minute
86 define('MINSECS', 60);
89 * Time constant - the number of minutes in a day
91 define('DAYMINS', 1440);
94 * Time constant - the number of minutes in an hour
96 define('HOURMINS', 60);
98 /// Parameter constants - every call to optional_param(), required_param() ///
99 /// or clean_param() should have a specified type of parameter. //////////////
102 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way;
103 * originally was 0, but changed because we need to detect unknown
104 * parameter types and swiched order in clean_param().
106 define('PARAM_RAW', 666);
109 * PARAM_CLEAN - obsoleted, please try to use more specific type of parameter.
110 * It was one of the first types, that is why it is abused so much ;-)
112 define('PARAM_CLEAN', 0x0001);
115 * PARAM_INT - integers only, use when expecting only numbers.
117 define('PARAM_INT', 0x0002);
120 * PARAM_INTEGER - an alias for PARAM_INT
122 define('PARAM_INTEGER', 0x0002);
125 * PARAM_NUMBER - a real/floating point number.
127 define('PARAM_NUMBER', 0x000a);
130 * PARAM_ALPHA - contains only english letters.
132 define('PARAM_ALPHA', 0x0004);
135 * PARAM_ACTION - an alias for PARAM_ALPHA, use for various actions in formas and urls
136 * @TODO: should we alias it to PARAM_ALPHANUM ?
138 define('PARAM_ACTION', 0x0004);
141 * PARAM_FORMAT - an alias for PARAM_ALPHA, use for names of plugins, formats, etc.
142 * @TODO: should we alias it to PARAM_ALPHANUM ?
144 define('PARAM_FORMAT', 0x0004);
147 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
149 define('PARAM_NOTAGS', 0x0008);
152 * PARAM_MULTILANG - alias of PARAM_TEXT.
154 define('PARAM_MULTILANG', 0x0009);
157 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
159 define('PARAM_TEXT', 0x0009);
162 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
164 define('PARAM_FILE', 0x0010);
167 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
168 * note: the leading slash is not removed, window drive letter is not allowed
170 define('PARAM_PATH', 0x0020);
173 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
175 define('PARAM_HOST', 0x0040);
178 * PARAM_URL - expected properly formatted URL.
180 define('PARAM_URL', 0x0080);
183 * 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!)
185 define('PARAM_LOCALURL', 0x0180);
188 * PARAM_CLEANFILE - safe file name, all dangerous and regional chars are removed,
189 * use when you want to store a new file submitted by students
191 define('PARAM_CLEANFILE',0x0200);
194 * PARAM_ALPHANUM - expected numbers and letters only.
196 define('PARAM_ALPHANUM', 0x0400);
199 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
201 define('PARAM_BOOL', 0x0800);
204 * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes
205 * note: do not forget to addslashes() before storing into database!
207 define('PARAM_CLEANHTML',0x1000);
210 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "/-_" allowed,
211 * suitable for include() and require()
212 * @TODO: should we rename this function to PARAM_SAFEDIRS??
214 define('PARAM_ALPHAEXT', 0x2000);
217 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
219 define('PARAM_SAFEDIR', 0x4000);
222 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
224 define('PARAM_SEQUENCE', 0x8000);
227 * PARAM_PEM - Privacy Enhanced Mail format
229 define('PARAM_PEM', 0x10000);
232 * PARAM_BASE64 - Base 64 encoded format
234 define('PARAM_BASE64', 0x20000);
239 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
241 define('PAGE_COURSE_VIEW', 'course-view');
244 /** no warnings at all */
245 define ('DEBUG_NONE', 0);
246 /** E_ERROR | E_PARSE */
247 define ('DEBUG_MINIMAL', 5);
248 /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
249 define ('DEBUG_NORMAL', 15);
250 /** E_ALL without E_STRICT and E_RECOVERABLE_ERROR for now */
251 define ('DEBUG_ALL', 2047);
252 /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL |Â 32768) */
253 define ('DEBUG_DEVELOPER', 34815);
256 * Blog access level constant declaration
258 define ('BLOG_USER_LEVEL', 1);
259 define ('BLOG_GROUP_LEVEL', 2);
260 define ('BLOG_COURSE_LEVEL', 3);
261 define ('BLOG_SITE_LEVEL', 4);
262 define ('BLOG_GLOBAL_LEVEL', 5);
265 * Authentication - error codes for user confirm
267 define('AUTH_CONFIRM_FAIL', 0);
268 define('AUTH_CONFIRM_OK', 1);
269 define('AUTH_CONFIRM_ALREADY', 2);
270 define('AUTH_CONFIRM_ERROR', 3);
274 /// PARAMETER HANDLING ////////////////////////////////////////////////////
277 * Returns a particular value for the named variable, taken from
278 * POST or GET. If the parameter doesn't exist then an error is
279 * thrown because we require this variable.
281 * This function should be used to initialise all required values
282 * in a script that are based on parameters. Usually it will be
284 * $id = required_param('id');
286 * @param string $parname the name of the page parameter we want
287 * @param int $type expected type of parameter
290 function required_param($parname, $type=PARAM_CLEAN
) {
292 // detect_unchecked_vars addition
294 if (!empty($CFG->detect_unchecked_vars
)) {
295 global $UNCHECKED_VARS;
296 unset ($UNCHECKED_VARS->vars
[$parname]);
299 if (isset($_POST[$parname])) { // POST has precedence
300 $param = $_POST[$parname];
301 } else if (isset($_GET[$parname])) {
302 $param = $_GET[$parname];
304 error('A required parameter ('.$parname.') was missing');
307 return clean_param($param, $type);
311 * Returns a particular value for the named variable, taken from
312 * POST or GET, otherwise returning a given default.
314 * This function should be used to initialise all optional values
315 * in a script that are based on parameters. Usually it will be
317 * $name = optional_param('name', 'Fred');
319 * @param string $parname the name of the page parameter we want
320 * @param mixed $default the default value to return if nothing is found
321 * @param int $type expected type of parameter
324 function optional_param($parname, $default=NULL, $type=PARAM_CLEAN
) {
326 // detect_unchecked_vars addition
328 if (!empty($CFG->detect_unchecked_vars
)) {
329 global $UNCHECKED_VARS;
330 unset ($UNCHECKED_VARS->vars
[$parname]);
333 if (isset($_POST[$parname])) { // POST has precedence
334 $param = $_POST[$parname];
335 } else if (isset($_GET[$parname])) {
336 $param = $_GET[$parname];
341 return clean_param($param, $type);
345 * Used by {@link optional_param()} and {@link required_param()} to
346 * clean the variables and/or cast to specific types, based on
349 * $course->format = clean_param($course->format, PARAM_ALPHA);
350 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
356 * @uses PARAM_INTEGER
358 * @uses PARAM_ALPHANUM
360 * @uses PARAM_ALPHAEXT
362 * @uses PARAM_SAFEDIR
363 * @uses PARAM_CLEANFILE
368 * @uses PARAM_LOCALURL
369 * @uses PARAM_CLEANHTML
370 * @uses PARAM_SEQUENCE
371 * @param mixed $param the variable we are cleaning
372 * @param int $type expected format of param after cleaning.
375 function clean_param($param, $type) {
379 if (is_array($param)) { // Let's loop
381 foreach ($param as $key => $value) {
382 $newparam[$key] = clean_param($value, $type);
388 case PARAM_RAW
: // no cleaning at all
391 case PARAM_CLEAN
: // General HTML cleaning, try to use more specific type if possible
392 if (is_numeric($param)) {
395 $param = stripslashes($param); // Needed for kses to work fine
396 $param = clean_text($param); // Sweep for scripts, etc
397 return addslashes($param); // Restore original request parameter slashes
399 case PARAM_CLEANHTML
: // prepare html fragment for display, do not store it into db!!
400 $param = stripslashes($param); // Remove any slashes
401 $param = clean_text($param); // Sweep for scripts, etc
405 return (int)$param; // Convert to integer
408 return (float)$param; // Convert to integer
410 case PARAM_ALPHA
: // Remove everything not a-z
411 return eregi_replace('[^a-zA-Z]', '', $param);
413 case PARAM_ALPHANUM
: // Remove everything not a-zA-Z0-9
414 return eregi_replace('[^A-Za-z0-9]', '', $param);
416 case PARAM_ALPHAEXT
: // Remove everything not a-zA-Z/_-
417 return eregi_replace('[^a-zA-Z/_-]', '', $param);
419 case PARAM_SEQUENCE
: // Remove everything not 0-9,
420 return eregi_replace('[^0-9,]', '', $param);
422 case PARAM_BOOL
: // Convert to 1 or 0
423 $tempstr = strtolower($param);
424 if ($tempstr == 'on' or $tempstr == 'yes' ) {
426 } else if ($tempstr == 'off' or $tempstr == 'no') {
429 $param = empty($param) ?
0 : 1;
433 case PARAM_NOTAGS
: // Strip all tags
434 return strip_tags($param);
436 case PARAM_TEXT
: // leave only tags needed for multilang
437 return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN
);
439 case PARAM_SAFEDIR
: // Remove everything not a-zA-Z0-9_-
440 return eregi_replace('[^a-zA-Z0-9_-]', '', $param);
442 case PARAM_CLEANFILE
: // allow only safe characters
443 return clean_filename($param);
445 case PARAM_FILE
: // Strip all suspicious characters from filename
446 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':\\/]', '', $param);
447 $param = ereg_replace('\.\.+', '', $param);
453 case PARAM_PATH
: // Strip all suspicious characters from file path
454 $param = str_replace('\\\'', '\'', $param);
455 $param = str_replace('\\"', '"', $param);
456 $param = str_replace('\\', '/', $param);
457 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':]', '', $param);
458 $param = ereg_replace('\.\.+', '', $param);
459 $param = ereg_replace('//+', '/', $param);
460 return ereg_replace('/(\./)+', '/', $param);
462 case PARAM_HOST
: // allow FQDN or IPv4 dotted quad
463 preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
464 // match ipv4 dotted quad
465 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
466 // confirm values are ok
470 ||
$match[4] > 255 ) {
471 // hmmm, what kind of dotted quad is this?
474 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
475 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
476 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
478 // all is ok - $param is respected
485 case PARAM_URL
: // allow safe ftp, http, mailto urls
486 include_once($CFG->dirroot
. '/lib/validateurlsyntax.php');
487 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
488 // all is ok, param is respected
490 $param =''; // not really ok
494 case PARAM_LOCALURL
: // allow http absolute, root relative and relative URLs within wwwroot
495 clean_param($param, PARAM_URL
);
496 if (!empty($param)) {
497 if (preg_match(':^/:', $param)) {
498 // root-relative, ok!
499 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot
, '/').'/i',$param)) {
500 // absolute, and matches our wwwroot
502 // relative - let's make sure there are no tricks
503 if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
512 $param = trim($param);
513 // PEM formatted strings may contain letters/numbers and the symbols
517 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
518 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
519 list($wholething, $body) = $matches;
520 unset($wholething, $matches);
521 $b64 = clean_param($body, PARAM_BASE64
);
523 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
530 if (!empty($param)) {
531 // PEM formatted strings may contain letters/numbers and the symbols
535 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
538 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY
);
539 // Each line of base64 encoded data must be 64 characters in
540 // length, except for the last line which may be less than (or
541 // equal to) 64 characters long.
542 for ($i=0, $j=count($lines); $i < $j; $i++
) {
544 if (64 < strlen($lines[$i])) {
550 if (64 != strlen($lines[$i])) {
554 return implode("\n",$lines);
558 default: // throw error, switched parameters in optional_param or another serious problem
559 error("Unknown parameter type: $type");
566 * Set a key in global configuration
568 * Set a key/value pair in both this session's {@link $CFG} global variable
569 * and in the 'config' database table for future sessions.
571 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
572 * In that case it doesn't affect $CFG.
574 * @param string $name the key to set
575 * @param string $value the value to set (without magic quotes)
576 * @param string $plugin (optional) the plugin scope
580 function set_config($name, $value, $plugin=NULL) {
581 /// No need for get_config because they are usually always available in $CFG
585 if (empty($plugin)) {
586 $CFG->$name = $value; // So it's defined for this invocation at least
588 if (get_field('config', 'name', 'name', $name)) {
589 return set_field('config', 'value', addslashes($value), 'name', $name);
591 $config = new object();
592 $config->name
= $name;
593 $config->value
= addslashes($value);
594 return insert_record('config', $config);
596 } else { // plugin scope
597 if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
598 return set_field('config_plugins', 'value', addslashes($value), 'id', $id);
600 $config = new object();
601 $config->plugin
= addslashes($plugin);
602 $config->name
= $name;
603 $config->value
= addslashes($value);
604 return insert_record('config_plugins', $config);
610 * Get configuration values from the global config table
611 * or the config_plugins table.
613 * If called with no parameters it will do the right thing
614 * generating $CFG safely from the database without overwriting
617 * If called with 2 parameters it will return a $string single
618 * value or false of the value is not found.
620 * @param string $plugin
621 * @param string $name
623 * @return hash-like object or single value
626 function get_config($plugin=NULL, $name=NULL) {
630 if (!empty($name)) { // the user is asking for a specific value
631 if (!empty($plugin)) {
632 return get_field('config_plugins', 'value', 'plugin' , $plugin, 'name', $name);
634 return get_field('config', 'value', 'name', $name);
638 // the user is after a recordset
639 if (!empty($plugin)) {
640 if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
641 $configs = (array)$configs;
643 foreach ($configs as $config) {
644 $localcfg[$config->name
] = $config->value
;
646 return (object)$localcfg;
651 // this was originally in setup.php
652 if ($configs = get_records('config')) {
653 $localcfg = (array)$CFG;
654 foreach ($configs as $config) {
655 if (!isset($localcfg[$config->name
])) {
656 $localcfg[$config->name
] = $config->value
;
658 if ($localcfg[$config->name
] != $config->value
) {
659 // complain if the DB has a different
660 // value than config.php does
661 error_log("\$CFG->{$config->name} in config.php ({$localcfg[$config->name]}) overrides database setting ({$config->value})");
666 $localcfg = (object)$localcfg;
669 // preserve $CFG if DB returns nothing or error
677 * Removes a key from global configuration
679 * @param string $name the key to set
680 * @param string $plugin (optional) the plugin scope
684 function unset_config($name, $plugin=NULL) {
690 if (empty($plugin)) {
691 return delete_records('config', 'name', $name);
693 return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
699 * Refresh current $USER session global variable with all their current preferences.
702 function reload_user_preferences() {
707 $USER->preference
= array();
709 if (!isloggedin() or isguestuser()) {
710 // no pernament storage for not-logged-in user and guest
712 } else if ($preferences = get_records('user_preferences', 'userid', $USER->id
)) {
713 foreach ($preferences as $preference) {
714 $USER->preference
[$preference->name
] = $preference->value
;
722 * Sets a preference for the current user
723 * Optionally, can set a preference for a different user object
725 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
727 * @param string $name The key to set as preference for the specified user
728 * @param string $value The value to set forthe $name key in the specified user's record
729 * @param int $otheruserid A moodle user ID
732 function set_user_preference($name, $value, $otheruserid=NULL) {
736 if (!isset($USER->preference
)) {
737 reload_user_preferences();
746 if (empty($otheruserid)){
747 if (!isloggedin() or isguestuser()) {
752 if (isguestuser($otheruserid)) {
755 $userid = $otheruserid;
760 // no pernament storage for not-logged-in user and guest
762 } else if ($preference = get_record('user_preferences', 'userid', $userid, 'name', addslashes($name))) {
763 if (!set_field('user_preferences', 'value', addslashes((string)$value), 'id', $preference->id
)) {
768 $preference = new object();
769 $preference->userid
= $userid;
770 $preference->name
= addslashes($name);
771 $preference->value
= addslashes((string)$value);
772 if (!insert_record('user_preferences', $preference)) {
777 // update value in USER session if needed
778 if ($userid == $USER->id
) {
779 $USER->preference
[$name] = (string)$value;
786 * Unsets a preference completely by deleting it from the database
787 * Optionally, can set a preference for a different user id
789 * @param string $name The key to unset as preference for the specified user
790 * @param int $otheruserid A moodle user ID
792 function unset_user_preference($name, $otheruserid=NULL) {
796 if (!isset($USER->preference
)) {
797 reload_user_preferences();
800 if (empty($otheruserid)){
803 $userid = $otheruserid;
806 //Delete the preference from $USER if needed
807 if ($userid == $USER->id
) {
808 unset($USER->preference
[$name]);
812 return delete_records('user_preferences', 'userid', $userid, 'name', addslashes($name));
817 * Sets a whole array of preferences for the current user
818 * @param array $prefarray An array of key/value pairs to be set
819 * @param int $otheruserid A moodle user ID
822 function set_user_preferences($prefarray, $otheruserid=NULL) {
824 if (!is_array($prefarray) or empty($prefarray)) {
829 foreach ($prefarray as $name => $value) {
830 // The order is important; test for return is done first
831 $return = (set_user_preference($name, $value, $otheruserid) && $return);
837 * If no arguments are supplied this function will return
838 * all of the current user preferences as an array.
839 * If a name is specified then this function
840 * attempts to return that particular preference value. If
841 * none is found, then the optional value $default is returned,
843 * @param string $name Name of the key to use in finding a preference value
844 * @param string $default Value to be returned if the $name key is not set in the user preferences
845 * @param int $otheruserid A moodle user ID
849 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
852 if (!isset($USER->preference
)) {
853 reload_user_preferences();
856 if (empty($otheruserid)){
859 $userid = $otheruserid;
862 if ($userid == $USER->id
) {
863 $preference = $USER->preference
;
866 $preference = array();
867 if ($prefdata = get_records('user_preferences', 'userid', $userid)) {
868 foreach ($prefdata as $pref) {
869 $preference[$pref->name
] = $pref->value
;
875 return $preference; // All values
877 } else if (array_key_exists($name, $preference)) {
878 return $preference[$name]; // The single value
881 return $default; // Default value (or NULL)
886 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
889 * Given date parts in user time produce a GMT timestamp.
891 * @param int $year The year part to create timestamp of
892 * @param int $month The month part to create timestamp of
893 * @param int $day The day part to create timestamp of
894 * @param int $hour The hour part to create timestamp of
895 * @param int $minute The minute part to create timestamp of
896 * @param int $second The second part to create timestamp of
897 * @param float $timezone ?
898 * @param bool $applydst ?
899 * @return int timestamp
900 * @todo Finish documenting this function
902 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
904 $timezone = get_user_timezone_offset($timezone);
906 if (abs($timezone) > 13) {
907 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
909 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
910 $time = usertime($time, $timezone);
912 $time -= dst_offset_on($time);
921 * Given an amount of time in seconds, returns string
922 * formatted nicely as weeks, days, hours etc as needed
928 * @param int $totalsecs ?
929 * @param array $str ?
932 function format_time($totalsecs, $str=NULL) {
934 $totalsecs = abs($totalsecs);
936 if (!$str) { // Create the str structure the slow way
937 $str->day
= get_string('day');
938 $str->days
= get_string('days');
939 $str->hour
= get_string('hour');
940 $str->hours
= get_string('hours');
941 $str->min
= get_string('min');
942 $str->mins
= get_string('mins');
943 $str->sec
= get_string('sec');
944 $str->secs
= get_string('secs');
945 $str->year
= get_string('year');
946 $str->years
= get_string('years');
950 $years = floor($totalsecs/YEARSECS
);
951 $remainder = $totalsecs - ($years*YEARSECS
);
952 $days = floor($remainder/DAYSECS
);
953 $remainder = $totalsecs - ($days*DAYSECS
);
954 $hours = floor($remainder/HOURSECS
);
955 $remainder = $remainder - ($hours*HOURSECS
);
956 $mins = floor($remainder/MINSECS
);
957 $secs = $remainder - ($mins*MINSECS
);
959 $ss = ($secs == 1) ?
$str->sec
: $str->secs
;
960 $sm = ($mins == 1) ?
$str->min
: $str->mins
;
961 $sh = ($hours == 1) ?
$str->hour
: $str->hours
;
962 $sd = ($days == 1) ?
$str->day
: $str->days
;
963 $sy = ($years == 1) ?
$str->year
: $str->years
;
971 if ($years) $oyears = $years .' '. $sy;
972 if ($days) $odays = $days .' '. $sd;
973 if ($hours) $ohours = $hours .' '. $sh;
974 if ($mins) $omins = $mins .' '. $sm;
975 if ($secs) $osecs = $secs .' '. $ss;
977 if ($years) return $oyears .' '. $odays;
978 if ($days) return $odays .' '. $ohours;
979 if ($hours) return $ohours .' '. $omins;
980 if ($mins) return $omins .' '. $osecs;
981 if ($secs) return $osecs;
982 return get_string('now');
986 * Returns a formatted string that represents a date in user time
987 * <b>WARNING: note that the format is for strftime(), not date().</b>
988 * Because of a bug in most Windows time libraries, we can't use
989 * the nicer %e, so we have to use %d which has leading zeroes.
990 * A lot of the fuss in the function is just getting rid of these leading
991 * zeroes as efficiently as possible.
993 * If parameter fixday = true (default), then take off leading
994 * zero from %d, else mantain it.
997 * @param int $date timestamp in GMT
998 * @param string $format strftime format
999 * @param float $timezone
1000 * @param bool $fixday If true (default) then the leading
1001 * zero from %d is removed. If false then the leading zero is mantained.
1004 function userdate($date, $format='', $timezone=99, $fixday = true) {
1008 static $strftimedaydatetime;
1010 if ($format == '') {
1011 if (empty($strftimedaydatetime)) {
1012 $strftimedaydatetime = get_string('strftimedaydatetime');
1014 $format = $strftimedaydatetime;
1017 if (!empty($CFG->nofixday
)) { // Config.php can force %d not to be fixed.
1019 } else if ($fixday) {
1020 $formatnoday = str_replace('%d', 'DD', $format);
1021 $fixday = ($formatnoday != $format);
1024 $date +
= dst_offset_on($date);
1026 $timezone = get_user_timezone_offset($timezone);
1028 if (abs($timezone) > 13) { /// Server time
1030 $datestring = strftime($formatnoday, $date);
1031 $daystring = str_replace(' 0', '', strftime(' %d', $date));
1032 $datestring = str_replace('DD', $daystring, $datestring);
1034 $datestring = strftime($format, $date);
1037 $date +
= (int)($timezone * 3600);
1039 $datestring = gmstrftime($formatnoday, $date);
1040 $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
1041 $datestring = str_replace('DD', $daystring, $datestring);
1043 $datestring = gmstrftime($format, $date);
1047 /// If we are running under Windows convert from windows encoding to UTF-8
1048 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1050 if ($CFG->ostype
== 'WINDOWS') {
1051 if ($localewincharset = get_string('localewincharset')) {
1052 $textlib = textlib_get_instance();
1053 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1061 * Given a $time timestamp in GMT (seconds since epoch),
1062 * returns an array that represents the date in user time
1065 * @param int $time Timestamp in GMT
1066 * @param float $timezone ?
1067 * @return array An array that represents the date in user time
1068 * @todo Finish documenting this function
1070 function usergetdate($time, $timezone=99) {
1072 $timezone = get_user_timezone_offset($timezone);
1074 if (abs($timezone) > 13) { // Server time
1075 return getdate($time);
1078 // There is no gmgetdate so we use gmdate instead
1079 $time +
= dst_offset_on($time);
1080 $time +
= intval((float)$timezone * HOURSECS
);
1082 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
1085 $getdate['seconds'],
1086 $getdate['minutes'],
1093 $getdate['weekday'],
1095 ) = explode('_', $datestring);
1101 * Given a GMT timestamp (seconds since epoch), offsets it by
1102 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1105 * @param int $date Timestamp in GMT
1106 * @param float $timezone
1109 function usertime($date, $timezone=99) {
1111 $timezone = get_user_timezone_offset($timezone);
1113 if (abs($timezone) > 13) {
1116 return $date - (int)($timezone * HOURSECS
);
1120 * Given a time, return the GMT timestamp of the most recent midnight
1121 * for the current user.
1123 * @param int $date Timestamp in GMT
1124 * @param float $timezone ?
1127 function usergetmidnight($date, $timezone=99) {
1129 $timezone = get_user_timezone_offset($timezone);
1130 $userdate = usergetdate($date, $timezone);
1132 // Time of midnight of this user's day, in GMT
1133 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1138 * Returns a string that prints the user's timezone
1140 * @param float $timezone The user's timezone
1143 function usertimezone($timezone=99) {
1145 $tz = get_user_timezone($timezone);
1147 if (!is_float($tz)) {
1151 if(abs($tz) > 13) { // Server time
1152 return get_string('serverlocaltime');
1155 if($tz == intval($tz)) {
1156 // Don't show .0 for whole hours
1173 * Returns a float which represents the user's timezone difference from GMT in hours
1174 * Checks various settings and picks the most dominant of those which have a value
1178 * @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
1181 function get_user_timezone_offset($tz = 99) {
1185 $tz = get_user_timezone($tz);
1187 if (is_float($tz)) {
1190 $tzrecord = get_timezone_record($tz);
1191 if (empty($tzrecord)) {
1194 return (float)$tzrecord->gmtoff
/ HOURMINS
;
1199 * Returns a float or a string which denotes the user's timezone
1200 * 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)
1201 * means that for this timezone there are also DST rules to be taken into account
1202 * Checks various settings and picks the most dominant of those which have a value
1206 * @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
1209 function get_user_timezone($tz = 99) {
1214 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
1215 isset($USER->timezone
) ?
$USER->timezone
: 99,
1216 isset($CFG->timezone
) ?
$CFG->timezone
: 99,
1221 while(($tz == '' ||
$tz == 99) && $next = each($timezones)) {
1222 $tz = $next['value'];
1225 return is_numeric($tz) ?
(float) $tz : $tz;
1233 * @param string $timezonename ?
1236 function get_timezone_record($timezonename) {
1238 static $cache = NULL;
1240 if ($cache === NULL) {
1244 if (isset($cache[$timezonename])) {
1245 return $cache[$timezonename];
1248 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix
.'timezone
1249 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
1257 * @param ? $fromyear ?
1258 * @param ? $to_year ?
1261 function calculate_user_dst_table($from_year = NULL, $to_year = NULL) {
1262 global $CFG, $SESSION;
1264 $usertz = get_user_timezone();
1266 if (is_float($usertz)) {
1267 // Trivial timezone, no DST
1271 if (!empty($SESSION->dst_offsettz
) && $SESSION->dst_offsettz
!= $usertz) {
1272 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1273 unset($SESSION->dst_offsets
);
1274 unset($SESSION->dst_range
);
1277 if (!empty($SESSION->dst_offsets
) && empty($from_year) && empty($to_year)) {
1278 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1279 // This will be the return path most of the time, pretty light computationally
1283 // Reaching here means we either need to extend our table or create it from scratch
1285 // Remember which TZ we calculated these changes for
1286 $SESSION->dst_offsettz
= $usertz;
1288 if(empty($SESSION->dst_offsets
)) {
1289 // If we 're creating from scratch, put the two guard elements in there
1290 $SESSION->dst_offsets
= array(1 => NULL, 0 => NULL);
1292 if(empty($SESSION->dst_range
)) {
1293 // If creating from scratch
1294 $from = max((empty($from_year) ?
intval(date('Y')) - 3 : $from_year), 1971);
1295 $to = min((empty($to_year) ?
intval(date('Y')) +
3 : $to_year), 2035);
1297 // Fill in the array with the extra years we need to process
1298 $yearstoprocess = array();
1299 for($i = $from; $i <= $to; ++
$i) {
1300 $yearstoprocess[] = $i;
1303 // Take note of which years we have processed for future calls
1304 $SESSION->dst_range
= array($from, $to);
1307 // If needing to extend the table, do the same
1308 $yearstoprocess = array();
1310 $from = max((empty($from_year) ?
$SESSION->dst_range
[0] : $from_year), 1971);
1311 $to = min((empty($to_year) ?
$SESSION->dst_range
[1] : $to_year), 2035);
1313 if($from < $SESSION->dst_range
[0]) {
1314 // Take note of which years we need to process and then note that we have processed them for future calls
1315 for($i = $from; $i < $SESSION->dst_range
[0]; ++
$i) {
1316 $yearstoprocess[] = $i;
1318 $SESSION->dst_range
[0] = $from;
1320 if($to > $SESSION->dst_range
[1]) {
1321 // Take note of which years we need to process and then note that we have processed them for future calls
1322 for($i = $SESSION->dst_range
[1] +
1; $i <= $to; ++
$i) {
1323 $yearstoprocess[] = $i;
1325 $SESSION->dst_range
[1] = $to;
1329 if(empty($yearstoprocess)) {
1330 // This means that there was a call requesting a SMALLER range than we have already calculated
1334 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1335 // Also, the array is sorted in descending timestamp order!
1338 $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');
1339 if(empty($presetrecords)) {
1343 // Remove ending guard (first element of the array)
1344 reset($SESSION->dst_offsets
);
1345 unset($SESSION->dst_offsets
[key($SESSION->dst_offsets
)]);
1347 // Add all required change timestamps
1348 foreach($yearstoprocess as $y) {
1349 // Find the record which is in effect for the year $y
1350 foreach($presetrecords as $year => $preset) {
1356 $changes = dst_changes_for_year($y, $preset);
1358 if($changes === NULL) {
1361 if($changes['dst'] != 0) {
1362 $SESSION->dst_offsets
[$changes['dst']] = $preset->dstoff
* MINSECS
;
1364 if($changes['std'] != 0) {
1365 $SESSION->dst_offsets
[$changes['std']] = 0;
1369 // Put in a guard element at the top
1370 $maxtimestamp = max(array_keys($SESSION->dst_offsets
));
1371 $SESSION->dst_offsets
[($maxtimestamp + DAYSECS
)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1374 krsort($SESSION->dst_offsets
);
1379 function dst_changes_for_year($year, $timezone) {
1381 if($timezone->dst_startday
== 0 && $timezone->dst_weekday
== 0 && $timezone->std_startday
== 0 && $timezone->std_weekday
== 0) {
1385 $monthdaydst = find_day_in_month($timezone->dst_startday
, $timezone->dst_weekday
, $timezone->dst_month
, $year);
1386 $monthdaystd = find_day_in_month($timezone->std_startday
, $timezone->std_weekday
, $timezone->std_month
, $year);
1388 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time
);
1389 list($std_hour, $std_min) = explode(':', $timezone->std_time
);
1391 $timedst = make_timestamp($year, $timezone->dst_month
, $monthdaydst, 0, 0, 0, 99, false);
1392 $timestd = make_timestamp($year, $timezone->std_month
, $monthdaystd, 0, 0, 0, 99, false);
1394 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1395 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1396 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1398 $timedst +
= $dst_hour * HOURSECS +
$dst_min * MINSECS
;
1399 $timestd +
= $std_hour * HOURSECS +
$std_min * MINSECS
;
1401 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1404 // $time must NOT be compensated at all, it has to be a pure timestamp
1405 function dst_offset_on($time) {
1408 if(!calculate_user_dst_table() ||
empty($SESSION->dst_offsets
)) {
1412 reset($SESSION->dst_offsets
);
1413 while(list($from, $offset) = each($SESSION->dst_offsets
)) {
1414 if($from <= $time) {
1419 // This is the normal return path
1420 if($offset !== NULL) {
1424 // Reaching this point means we haven't calculated far enough, do it now:
1425 // Calculate extra DST changes if needed and recurse. The recursion always
1426 // moves toward the stopping condition, so will always end.
1429 // We need a year smaller than $SESSION->dst_range[0]
1430 if($SESSION->dst_range
[0] == 1971) {
1433 calculate_user_dst_table($SESSION->dst_range
[0] - 5, NULL);
1434 return dst_offset_on($time);
1437 // We need a year larger than $SESSION->dst_range[1]
1438 if($SESSION->dst_range
[1] == 2035) {
1441 calculate_user_dst_table(NULL, $SESSION->dst_range
[1] +
5);
1442 return dst_offset_on($time);
1446 function find_day_in_month($startday, $weekday, $month, $year) {
1448 $daysinmonth = days_in_month($month, $year);
1450 if($weekday == -1) {
1451 // Don't care about weekday, so return:
1452 // abs($startday) if $startday != -1
1453 // $daysinmonth otherwise
1454 return ($startday == -1) ?
$daysinmonth : abs($startday);
1457 // From now on we 're looking for a specific weekday
1459 // Give "end of month" its actual value, since we know it
1460 if($startday == -1) {
1461 $startday = -1 * $daysinmonth;
1464 // Starting from day $startday, the sign is the direction
1468 $startday = abs($startday);
1469 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1471 // This is the last such weekday of the month
1472 $lastinmonth = $daysinmonth +
$weekday - $lastmonthweekday;
1473 if($lastinmonth > $daysinmonth) {
1477 // Find the first such weekday <= $startday
1478 while($lastinmonth > $startday) {
1482 return $lastinmonth;
1487 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
1489 $diff = $weekday - $indexweekday;
1494 // This is the first such weekday of the month equal to or after $startday
1495 $firstfromindex = $startday +
$diff;
1497 return $firstfromindex;
1503 * Calculate the number of days in a given month
1505 * @param int $month The month whose day count is sought
1506 * @param int $year The year of the month whose day count is sought
1509 function days_in_month($month, $year) {
1510 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1514 * Calculate the position in the week of a specific calendar day
1516 * @param int $day The day of the date whose position in the week is sought
1517 * @param int $month The month of the date whose position in the week is sought
1518 * @param int $year The year of the date whose position in the week is sought
1521 function dayofweek($day, $month, $year) {
1522 // I wonder if this is any different from
1523 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1524 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1527 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
1530 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1531 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1532 * sesskey string if $USER exists, or boolean false if not.
1537 function sesskey() {
1544 if (empty($USER->sesskey
)) {
1545 $USER->sesskey
= random_string(10);
1548 return $USER->sesskey
;
1553 * For security purposes, this function will check that the currently
1554 * given sesskey (passed as a parameter to the script or this function)
1555 * matches that of the current user.
1557 * @param string $sesskey optionally provided sesskey
1560 function confirm_sesskey($sesskey=NULL) {
1563 if (!empty($USER->ignoresesskey
) ||
!empty($CFG->ignoresesskey
)) {
1567 if (empty($sesskey)) {
1568 $sesskey = required_param('sesskey', PARAM_RAW
); // Check script parameters
1571 if (!isset($USER->sesskey
)) {
1575 return ($USER->sesskey
=== $sesskey);
1579 * Setup all global $CFG course variables, set locale and also themes
1580 * This function can be used on pages that do not require login instead of require_login()
1582 * @param mixed $courseorid id of the course or course object
1584 function course_setup($courseorid=0) {
1585 global $COURSE, $CFG, $SITE, $USER;
1587 /// Redefine global $COURSE if needed
1588 if (empty($courseorid)) {
1589 // no change in global $COURSE - for backwards compatibiltiy
1590 // if require_rogin() used after require_login($courseid);
1591 } else if (is_object($courseorid)) {
1592 $COURSE = clone($courseorid);
1594 global $course; // used here only to prevent repeated fetching from DB - may be removed later
1595 if (!empty($course->id
) and $course->id
== SITEID
) {
1596 $COURSE = clone($SITE);
1597 } else if (!empty($course->id
) and $course->id
== $courseorid) {
1598 $COURSE = clone($course);
1600 if (!$COURSE = get_record('course', 'id', $courseorid)) {
1601 error('Invalid course ID');
1606 /// set locale and themes
1613 * This function checks that the current user is logged in and has the
1614 * required privileges
1616 * This function checks that the current user is logged in, and optionally
1617 * whether they are allowed to be in a particular course and view a particular
1619 * If they are not logged in, then it redirects them to the site login unless
1620 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
1621 * case they are automatically logged in as guests.
1622 * If $courseid is given and the user is not enrolled in that course then the
1623 * user is redirected to the course enrolment page.
1624 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1625 * in the course then the user is redirected to the course home page.
1633 * @param mixed $courseorid id of the course or course object
1634 * @param bool $autologinguest
1635 * @param object $cm course module object
1637 function require_login($courseorid=0, $autologinguest=true, $cm=null) {
1639 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
1641 /// setup global $COURSE, themes, language and locale
1642 course_setup($courseorid);
1644 /// If the user is not even logged in yet then make sure they are
1645 if (!isloggedin()) {
1646 //NOTE: $USER->site check was obsoleted by session test cookie,
1647 // $USER->confirmed test is in login/index.php
1648 $SESSION->wantsurl
= $FULLME;
1649 if (!empty($_SERVER['HTTP_REFERER'])) {
1650 $SESSION->fromurl
= $_SERVER['HTTP_REFERER'];
1652 if ($autologinguest and !empty($CFG->autologinguests
) and ($COURSE->id
== SITEID
or $COURSE->guest
) ) {
1653 $loginguest = '?loginguest=true';
1657 if (empty($CFG->loginhttps
) or $autologinguest) { //do not require https for guest logins
1658 redirect($CFG->wwwroot
.'/login/index.php'. $loginguest);
1660 $wwwroot = str_replace('http:','https:', $CFG->wwwroot
);
1661 redirect($wwwroot .'/login/index.php');
1666 /// check whether the user should be changing password (but only if it is REALLY them)
1667 $userauth = get_auth_plugin($USER->auth
);
1668 if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser
)) {
1669 if ($userauth->can_change_password()) {
1670 $SESSION->wantsurl
= $FULLME;
1671 if (method_exists($userauth, 'change_password_url') and $userauth->change_password_url()) {
1672 //use plugin custom url
1673 redirect($userauth->change_password_url());
1675 //use moodle internal method
1676 if (empty($CFG->loginhttps
)) {
1677 redirect($CFG->wwwroot
.'/login/change_password.php');
1679 $wwwroot = str_replace('http:','https:', $CFG->wwwroot
);
1680 redirect($wwwroot .'/login/change_password.php');
1684 error(get_strin('nopasswordchangeforced', 'auth'));
1688 /// Check that the user account is properly set up
1689 if (user_not_fully_set_up($USER)) {
1690 $SESSION->wantsurl
= $FULLME;
1691 redirect($CFG->wwwroot
.'/user/edit.php?id='. $USER->id
.'&course='. SITEID
);
1694 /// Make sure current IP matches the one for this session (if required)
1695 if (!empty($CFG->tracksessionip
)) {
1696 if ($USER->sessionIP
!= md5(getremoteaddr())) {
1697 error(get_string('sessionipnomatch', 'error'));
1701 /// Make sure the USER has a sesskey set up. Used for checking script parameters.
1704 // Check that the user has agreed to a site policy if there is one
1705 if (!empty($CFG->sitepolicy
)) {
1706 if (!$USER->policyagreed
) {
1707 $SESSION->wantsurl
= $FULLME;
1708 redirect($CFG->wwwroot
.'/user/policy.php');
1712 /// If the site is currently under maintenance, then print a message
1713 if (!has_capability('moodle/site:config',get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
1714 if (file_exists($CFG->dataroot
.'/'.SITEID
.'/maintenance.html')) {
1715 print_maintenance_message();
1721 if ($COURSE->id
== SITEID
) {
1722 /// We can eliminate hidden site activities straight away
1723 if (!empty($cm) && !$cm->visible
and !has_capability('moodle/course:viewhiddenactivities',
1724 get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
1725 redirect($CFG->wwwroot
, get_string('activityiscurrentlyhidden'));
1730 /// Check if the user can be in a particular course
1731 if (!$context = get_context_instance(CONTEXT_COURSE
, $COURSE->id
)) {
1732 print_error('nocontext');
1735 if (empty($USER->switchrole
[$context->id
]) &&
1736 !($COURSE->visible
&& course_parent_visible($COURSE)) &&
1737 !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $COURSE->id
)) ){
1738 print_header_simple();
1739 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
1742 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1744 if ($USER->username
!= 'guest' and !has_capability('moodle/course:view', $context)) {
1745 if ($COURSE->guest
== 1) {
1746 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
1747 has_capability('clearcache'); // Must clear cache
1748 $guestcaps = get_role_context_caps($CFG->guestroleid
, $context);
1749 $USER->capabilities
= merge_role_caps($USER->capabilities
, $guestcaps);
1753 /// If the user is a guest then treat them according to the course policy about guests
1755 if (has_capability('moodle/legacy:guest', $context, NULL, false)) {
1756 switch ($COURSE->guest
) { /// Check course policy about guest access
1758 case 1: /// Guests always allowed
1759 if (!has_capability('moodle/course:view', $context)) { // Prohibited by capability
1760 print_header_simple();
1761 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)), "$CFG->wwwroot/login/index.php");
1763 if (!empty($cm) and !$cm->visible
) { // Not allowed to see module, send to course page
1764 redirect($CFG->wwwroot
.'/course/view.php?id='.$cm->course
,
1765 get_string('activityiscurrentlyhidden'));
1768 return; // User is allowed to see this course
1772 case 2: /// Guests allowed with key
1773 if (!empty($USER->enrolkey
[$COURSE->id
])) { // Set by enrol/manual/enrol.php
1776 // otherwise drop through to logic below (--> enrol.php)
1779 default: /// Guests not allowed
1780 print_header_simple('', '', get_string('loggedinasguest'));
1781 if (empty($USER->switchrole
[$context->id
])) { // Normal guest
1782 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)), "$CFG->wwwroot/login/index.php");
1784 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)));
1785 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id
).'</div>';
1786 print_footer($COURSE);
1792 /// For non-guests, check if they have course view access
1794 } else if (has_capability('moodle/course:view', $context)) {
1795 if (!empty($USER->realuser
)) { // Make sure the REAL person can also access this course
1796 if (!has_capability('moodle/course:view', $context, $USER->realuser
)) {
1797 print_header_simple();
1798 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot
.'/');
1802 /// Make sure they can read this activity too, if specified
1804 if (!empty($cm) and !$cm->visible
and !has_capability('moodle/course:viewhiddenactivities', $context)) {
1805 redirect($CFG->wwwroot
.'/course/view.php?id='.$cm->course
, get_string('activityiscurrentlyhidden'));
1807 return; // User is allowed to see this course
1812 /// Currently not enrolled in the course, so see if they want to enrol
1813 $SESSION->wantsurl
= $FULLME;
1814 redirect($CFG->wwwroot
.'/course/enrol.php?id='. $COURSE->id
);
1822 * This function just makes sure a user is logged out.
1827 function require_logout() {
1829 global $USER, $CFG, $SESSION;
1831 if (isset($USER) and isset($USER->id
)) {
1832 add_to_log(SITEID
, "user", "logout", "view.php?id=$USER->id&course=".SITEID
, $USER->id
, 0, $USER->id
);
1834 if ($USER->auth
== 'cas' && !empty($CFG->cas_enabled
)) {
1835 require($CFG->dirroot
.'/auth/cas/logout.php');
1838 if (extension_loaded('openssl')) {
1839 require($CFG->dirroot
.'/auth/mnet/auth.php');
1840 $authplugin = new auth_plugin_mnet();
1841 $authplugin->logout();
1845 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
1846 // This method is just to try to avoid silly warnings from PHP 4.3.0
1847 session_unregister("USER");
1848 session_unregister("SESSION");
1851 setcookie('MoodleSessionTest'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
1852 unset($_SESSION['USER']);
1853 unset($_SESSION['SESSION']);
1861 * This is a weaker version of {@link require_login()} which only requires login
1862 * when called from within a course rather than the site page, unless
1863 * the forcelogin option is turned on.
1866 * @param mixed $courseorid The course object or id in question
1867 * @param bool $autologinguest Allow autologin guests if that is wanted
1868 * @param object $cm Course activity module if known
1870 function require_course_login($courseorid, $autologinguest=true, $cm=null) {
1872 if (!empty($CFG->forcelogin
)) {
1873 // login required for both SITE and courses
1874 require_login($courseorid, $autologinguest, $cm);
1875 } else if ((is_object($courseorid) and $courseorid->id
== SITEID
)
1876 or (!is_object($courseorid) and $courseorid == SITEID
)) {
1877 //login for SITE not required
1879 // course login always required
1880 require_login($courseorid, $autologinguest, $cm);
1885 * Modify the user table by setting the currently logged in user's
1886 * last login to now.
1891 function update_user_login_times() {
1894 $user = new object();
1895 $USER->lastlogin
= $user->lastlogin
= $USER->currentlogin
;
1896 $USER->currentlogin
= $user->lastaccess
= $user->currentlogin
= time();
1898 $user->id
= $USER->id
;
1900 return update_record('user', $user);
1904 * Determines if a user has completed setting up their account.
1906 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
1909 function user_not_fully_set_up($user) {
1910 return ($user->username
!= 'guest' and (empty($user->firstname
) or empty($user->lastname
) or empty($user->email
) or over_bounce_threshold($user)));
1913 function over_bounce_threshold($user) {
1917 if (empty($CFG->handlebounces
)) {
1920 // set sensible defaults
1921 if (empty($CFG->minbounces
)) {
1922 $CFG->minbounces
= 10;
1924 if (empty($CFG->bounceratio
)) {
1925 $CFG->bounceratio
= .20;
1929 if ($bounce = get_record('user_preferences','userid',$user->id
,'name','email_bounce_count')) {
1930 $bouncecount = $bounce->value
;
1932 if ($send = get_record('user_preferences','userid',$user->id
,'name','email_send_count')) {
1933 $sendcount = $send->value
;
1935 return ($bouncecount >= $CFG->minbounces
&& $bouncecount/$sendcount >= $CFG->bounceratio
);
1939 * @param $user - object containing an id
1940 * @param $reset - will reset the count to 0
1942 function set_send_count($user,$reset=false) {
1943 if ($pref = get_record('user_preferences','userid',$user->id
,'name','email_send_count')) {
1944 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
1945 update_record('user_preferences',$pref);
1947 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1949 $pref->name
= 'email_send_count';
1951 $pref->userid
= $user->id
;
1952 insert_record('user_preferences',$pref, false);
1957 * @param $user - object containing an id
1958 * @param $reset - will reset the count to 0
1960 function set_bounce_count($user,$reset=false) {
1961 if ($pref = get_record('user_preferences','userid',$user->id
,'name','email_bounce_count')) {
1962 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
1963 update_record('user_preferences',$pref);
1965 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1967 $pref->name
= 'email_bounce_count';
1969 $pref->userid
= $user->id
;
1970 insert_record('user_preferences',$pref, false);
1975 * Keeps track of login attempts
1979 function update_login_count() {
1985 if (empty($SESSION->logincount
)) {
1986 $SESSION->logincount
= 1;
1988 $SESSION->logincount++
;
1991 if ($SESSION->logincount
> $max_logins) {
1992 unset($SESSION->wantsurl
);
1993 error(get_string('errortoomanylogins'));
1998 * Resets login attempts
2002 function reset_login_count() {
2005 $SESSION->logincount
= 0;
2008 function sync_metacourses() {
2012 if (!$courses = get_records('course', 'metacourse', 1)) {
2016 foreach ($courses as $course) {
2017 sync_metacourse($course);
2022 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
2024 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
2026 function sync_metacourse($course) {
2029 // Check the course is valid.
2030 if (!is_object($course)) {
2031 if (!$course = get_record('course', 'id', $course)) {
2032 return false; // invalid course id
2036 // Check that we actually have a metacourse.
2037 if (empty($course->metacourse
)) {
2041 // Get a list of roles that should not be synced.
2042 if ($CFG->nonmetacoursesyncroleids
) {
2043 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids
. ') AND';
2045 $roleexclusions = '';
2048 // Get the context of the metacourse.
2049 $context = get_context_instance(CONTEXT_COURSE
, $course->id
); // SITEID can not be a metacourse
2051 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
2052 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
2053 $managers = array_keys($users);
2055 $managers = array();
2058 // Get assignments of a user to a role that exist in a child course, but
2059 // not in the meta coure. That is, get a list of the assignments that need to be made.
2060 if (!$assignments = get_records_sql("
2062 ra.id, ra.roleid, ra.userid
2064 {$CFG->prefix}role_assignments ra,
2065 {$CFG->prefix}context con,
2066 {$CFG->prefix}course_meta cm
2068 ra.contextid = con.id AND
2069 con.contextlevel = " . CONTEXT_COURSE
. " AND
2070 con.instanceid = cm.child_course AND
2071 cm.parent_course = {$course->id} AND
2075 {$CFG->prefix}role_assignments ra2
2077 ra2.userid = ra.userid AND
2078 ra2.roleid = ra.roleid AND
2079 ra2.contextid = {$context->id}
2082 $assignments = array();
2085 // Get assignments of a user to a role that exist in the meta course, but
2086 // not in any child courses. That is, get a list of the unassignments that need to be made.
2087 if (!$unassignments = get_records_sql("
2089 ra.id, ra.roleid, ra.userid
2091 {$CFG->prefix}role_assignments ra
2093 ra.contextid = {$context->id} AND
2097 {$CFG->prefix}role_assignments ra2,
2098 {$CFG->prefix}context con2,
2099 {$CFG->prefix}course_meta cm
2101 ra2.userid = ra.userid AND
2102 ra2.roleid = ra.roleid AND
2103 ra2.contextid = con2.id AND
2104 con2.contextlevel = " . CONTEXT_COURSE
. " AND
2105 con2.instanceid = cm.child_course AND
2106 cm.parent_course = {$course->id}
2109 $unassignments = array();
2114 // Make the unassignments, if they are not managers.
2115 foreach ($unassignments as $unassignment) {
2116 if (!in_array($unassignment->userid
, $managers)) {
2117 $success = role_unassign($unassignment->roleid
, $unassignment->userid
, 0, $context->id
) && $success;
2121 // Make the assignments.
2122 foreach ($assignments as $assignment) {
2123 $success = role_assign($assignment->roleid
, $assignment->userid
, 0, $context->id
) && $success;
2128 // TODO: finish timeend and timestart
2129 // maybe we could rely on cron job to do the cleaning from time to time
2133 * Adds a record to the metacourse table and calls sync_metacoures
2135 function add_to_metacourse ($metacourseid, $courseid) {
2137 if (!$metacourse = get_record("course","id",$metacourseid)) {
2141 if (!$course = get_record("course","id",$courseid)) {
2145 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
2146 $rec = new object();
2147 $rec->parent_course
= $metacourseid;
2148 $rec->child_course
= $courseid;
2149 if (!insert_record('course_meta',$rec)) {
2152 return sync_metacourse($metacourseid);
2159 * Removes the record from the metacourse table and calls sync_metacourse
2161 function remove_from_metacourse($metacourseid, $courseid) {
2163 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
2164 return sync_metacourse($metacourseid);
2171 * Determines if a user is currently logged in
2176 function isloggedin() {
2179 return (!empty($USER->id
));
2183 * Determines if a user is logged in as real guest user with username 'guest'.
2184 * This function is similar to original isguest() in 1.6 and earlier.
2185 * Current isguest() is deprecated - do not use it anymore.
2187 * @param $user mixed user object or id, $USER if not specified
2188 * @return bool true if user is the real guest user, false if not logged in or other user
2190 function isguestuser($user=NULL) {
2192 if ($user === NULL) {
2194 } else if (is_numeric($user)) {
2195 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2198 if (empty($user->id
)) {
2199 return false; // not logged in, can not be guest
2202 return ($user->username
== 'guest');
2206 * Determines if the currently logged in user is in editing mode
2209 * @param int $courseid The id of the course being tested
2210 * @param user $user A {@link $USER} object. If null then the currently logged in user is used.
2213 function isediting($courseid, $user=NULL) {
2218 if (empty($user->editing
)) {
2223 $coursecontext = get_context_instance(CONTEXT_COURSE
, $courseid);
2225 if (has_capability('moodle/course:manageactivities', $coursecontext) ||
2226 has_capability('moodle/site:manageblocks', $coursecontext)) {
2229 // loop through all child context, see if user has moodle/course:manageactivities or moodle/site:manageblocks
2230 if ($children = get_child_contexts($coursecontext)) {
2231 foreach ($children as $child) {
2232 $childcontext = get_record('context', 'id', $child);
2233 if (has_capability('moodle/course:manageactivities', $childcontext) ||
2234 has_capability('moodle/site:manageblocks', $childcontext)) {
2242 return ($user->editing
&& $capcheck);
2243 //return ($user->editing and has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $courseid)));
2247 * Determines if the logged in user is currently moving an activity
2250 * @param int $courseid The id of the course being tested
2253 function ismoving($courseid) {
2256 if (!empty($USER->activitycopy
)) {
2257 return ($USER->activitycopycourse
== $courseid);
2263 * Given an object containing firstname and lastname
2264 * values, this function returns a string with the
2265 * full name of the person.
2266 * The result may depend on system settings
2267 * or language. 'override' will force both names
2268 * to be used even if system settings specify one.
2272 * @param object $user A {@link $USER} object to get full name of
2273 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
2275 function fullname($user, $override=false) {
2277 global $CFG, $SESSION;
2279 if (!isset($user->firstname
) and !isset($user->lastname
)) {
2284 if (!empty($CFG->forcefirstname
)) {
2285 $user->firstname
= $CFG->forcefirstname
;
2287 if (!empty($CFG->forcelastname
)) {
2288 $user->lastname
= $CFG->forcelastname
;
2292 if (!empty($SESSION->fullnamedisplay
)) {
2293 $CFG->fullnamedisplay
= $SESSION->fullnamedisplay
;
2296 if ($CFG->fullnamedisplay
== 'firstname lastname') {
2297 return $user->firstname
.' '. $user->lastname
;
2299 } else if ($CFG->fullnamedisplay
== 'lastname firstname') {
2300 return $user->lastname
.' '. $user->firstname
;
2302 } else if ($CFG->fullnamedisplay
== 'firstname') {
2304 return get_string('fullnamedisplay', '', $user);
2306 return $user->firstname
;
2310 return get_string('fullnamedisplay', '', $user);
2314 * Sets a moodle cookie with an encrypted string
2319 * @param string $thing The string to encrypt and place in a cookie
2321 function set_moodle_cookie($thing) {
2324 if ($thing == 'guest') { // Ignore guest account
2328 $cookiename = 'MOODLEID_'.$CFG->sessioncookie
;
2331 $seconds = DAYSECS
*$days;
2333 setCookie($cookiename, '', time() - HOURSECS
, '/');
2334 setCookie($cookiename, rc4encrypt($thing), time()+
$seconds, '/');
2338 * Gets a moodle cookie with an encrypted string
2343 function get_moodle_cookie() {
2346 $cookiename = 'MOODLEID_'.$CFG->sessioncookie
;
2348 if (empty($_COOKIE[$cookiename])) {
2351 $thing = rc4decrypt($_COOKIE[$cookiename]);
2352 return ($thing == 'guest') ?
'': $thing; // Ignore guest account
2357 * Returns whether a given authentication plugin exists.
2360 * @param string $auth Form of authentication to check for. Defaults to the
2361 * global setting in {@link $CFG}.
2362 * @return boolean Whether the plugin is available.
2364 function exists_auth_plugin($auth) {
2367 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2368 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2374 * Checks if a given plugin is in the list of enabled authentication plugins.
2376 * @param string $auth Authentication plugin.
2377 * @return boolean Whether the plugin is enabled.
2379 function is_enabled_auth($auth) {
2384 } else if ($auth == 'manual') {
2388 return in_array($auth, explode(',', $CFG->auth
));
2392 * Returns an authentication plugin instance.
2395 * @param string $auth name of authentication plugin
2396 * @return object An instance of the required authentication plugin.
2398 function get_auth_plugin($auth) {
2401 // check the plugin exists first
2402 if (! exists_auth_plugin($auth)) {
2403 error("Authentication plugin '$auth' not found.");
2406 // return auth plugin instance
2407 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2408 $class = "auth_plugin_$auth";
2413 * Returns true if an internal authentication method is being used.
2414 * if method not specified then, global default is assumed
2417 * @param string $auth Form of authentication required
2420 function is_internal_auth($auth) {
2421 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2422 return $authplugin->is_internal();
2426 * Returns an array of user fields
2430 * @return array User field/column names
2432 function get_user_fieldnames() {
2436 $fieldarray = $db->MetaColumnNames($CFG->prefix
.'user');
2437 unset($fieldarray['ID']);
2443 * Creates a bare-bones user record
2446 * @param string $username New user's username to add to record
2447 * @param string $password New user's password to add to record
2448 * @param string $auth Form of authentication required
2449 * @return object A {@link $USER} object
2450 * @todo Outline auth types and provide code example
2452 function create_user_record($username, $password, $auth='') {
2455 //just in case check text case
2456 $username = trim(moodle_strtolower($username));
2458 $authplugin = get_auth_plugin($auth);
2460 if (method_exists($authplugin, 'get_userinfo')) {
2461 if ($newinfo = $authplugin->get_userinfo($username)) {
2462 $newinfo = truncate_userinfo($newinfo);
2463 foreach ($newinfo as $key => $value){
2464 $newuser->$key = addslashes($value);
2469 if (!empty($newuser->email
)) {
2470 if (email_is_not_allowed($newuser->email
)) {
2471 unset($newuser->email
);
2475 $newuser->auth
= (empty($auth)) ?
'manual' : $auth;
2476 $newuser->username
= $username;
2479 // user CFG lang for user if $newuser->lang is empty
2480 // or $user->lang is not an installed language
2481 $sitelangs = array_keys(get_list_of_languages());
2482 if (empty($newuser->lang
) ||
!in_array($newuser->lang
, $sitelangs)) {
2483 $newuser -> lang
= $CFG->lang
;
2485 $newuser->confirmed
= 1;
2486 $newuser->lastip
= getremoteaddr();
2487 $newuser->timemodified
= time();
2488 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
2490 if (insert_record('user', $newuser)) {
2491 $user = get_complete_user_data('username', $newuser->username
);
2492 if($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'}){
2493 set_user_preference('auth_forcepasswordchange', 1, $user->id
);
2495 update_internal_user_password($user, $password);
2502 * Will update a local user record from an external source
2505 * @param string $username New user's username to add to record
2506 * @return user A {@link $USER} object
2508 function update_user_record($username, $authplugin) {
2509 if (method_exists($authplugin, 'get_userinfo')) {
2510 $username = trim(moodle_strtolower($username)); /// just in case check text case
2512 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2513 $userauth = get_auth_plugin($oldinfo->auth
);
2515 if ($newinfo = $authplugin->get_userinfo($username)) {
2516 $newinfo = truncate_userinfo($newinfo);
2517 foreach ($newinfo as $key => $value){
2518 $confkey = 'field_updatelocal_' . $key;
2519 if (!empty($userauth->config
->$confkey) and $userauth->config
->$confkey === 'onlogin') {
2520 $value = addslashes(stripslashes($value)); // Just in case
2521 set_field('user', $key, $value, 'username', $username)
2522 or error_log("Error updating $key for $username");
2527 return get_complete_user_data('username', $username);
2530 function truncate_userinfo($info) {
2531 /// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2532 /// which may have large fields
2534 // define the limits
2544 'institution' => 40,
2552 // apply where needed
2553 foreach (array_keys($info) as $key) {
2554 if (!empty($limit[$key])) {
2555 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
2563 * Retrieve the guest user object
2566 * @return user A {@link $USER} object
2568 function guest_user() {
2571 if ($newuser = get_record('user', 'username', 'guest')) {
2572 $newuser->confirmed
= 1;
2573 $newuser->lang
= $CFG->lang
;
2574 $newuser->lastip
= getremoteaddr();
2581 * Given a username and password, this function looks them
2582 * up using the currently selected authentication mechanism,
2583 * and if the authentication is successful, it returns a
2584 * valid $user object from the 'user' table.
2586 * Uses auth_ functions from the currently active auth module
2589 * @param string $username User's username
2590 * @param string $password User's password
2591 * @return user|flase A {@link $USER} object or false if error
2593 function authenticate_user_login($username, $password) {
2597 if (empty($CFG->auth
)) {
2598 $authsenabled = array('manual');
2600 $authsenabled = explode(',', 'manual,'.$CFG->auth
);
2603 if ($user = get_complete_user_data('username', $username)) {
2604 $auth = empty($user->auth
) ?
'manual' : $user->auth
; // use manual if auth not set
2605 if ($auth=='nologin' or !is_enabled_auth($auth)) {
2606 add_to_log(0, 'login', 'error', 'index.php', $username);
2607 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2610 if (!empty($user->deleted
)) {
2611 add_to_log(0, 'login', 'error', 'index.php', $username);
2612 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2615 $auths = array($auth);
2618 $auths = $authsenabled;
2619 $user = new object();
2620 $user->id
= 0; // User does not exist
2623 foreach ($auths as $auth) {
2624 $authplugin = get_auth_plugin($auth);
2626 // on auth fail fall through to the next plugin
2627 if (!$authplugin->user_login($username, $password)) {
2631 // successful authentication
2632 if ($user->id
) { // User already exists in database
2633 if (empty($user->auth
)) { // For some reason auth isn't set yet
2634 set_field('user', 'auth', $auth, 'username', $username);
2635 $user->auth
= $auth;
2638 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
2640 if (!$authplugin->is_internal()) { // update user record from external DB
2641 $user = update_user_record($username, get_auth_plugin($user->auth
));
2644 // if user not found, create him
2645 $user = create_user_record($username, $password, $auth);
2648 if (method_exists($authplugin, 'iscreator')) {
2649 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2650 if ($creatorroles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW
)) {
2651 $creatorrole = array_shift($creatorroles); // We can only use one, let's use the first one
2652 // Check if the user is a creator
2653 if ($authplugin->iscreator($username)) { // Following calls will not create duplicates
2654 role_assign($creatorrole->id
, $user->id
, 0, $sitecontext->id
, 0, 0, 0, $auth);
2656 role_unassign($creatorrole->id
, $user->id
, 0, $sitecontext->id
);
2661 /// Log in to a second system if necessary
2662 if (!empty($CFG->sso
)) {
2663 include_once($CFG->dirroot
.'/sso/'. $CFG->sso
.'/lib.php');
2664 if (function_exists('sso_user_login')) {
2665 if (!sso_user_login($username, $password)) { // Perform the signon process
2666 notify('Second sign-on failed');
2675 // failed if all the plugins have failed
2676 add_to_log(0, 'login', 'error', 'index.php', $username);
2677 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2682 * Compare password against hash stored in internal user table.
2683 * If necessary it also updates the stored hash to new format.
2685 * @param object user
2686 * @param string plain text password
2687 * @return bool is password valid?
2689 function validate_internal_user_password(&$user, $password) {
2692 if (!isset($CFG->passwordsaltmain
)) {
2693 $CFG->passwordsaltmain
= '';
2698 // get password original encoding in case it was not updated to unicode yet
2699 $textlib = textlib_get_instance();
2700 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
2702 if ($user->password
== md5($password.$CFG->passwordsaltmain
) or $user->password
== md5($password)
2703 or $user->password
== md5($convpassword.$CFG->passwordsaltmain
) or $user->password
== md5($convpassword)) {
2706 for ($i=1; $i<=20; $i++
) { //20 alternative salts should be enough, right?
2707 $alt = 'passwordsaltalt'.$i;
2708 if (!empty($CFG->$alt)) {
2709 if ($user->password
== md5($password.$CFG->$alt) or $user->password
== md5($convpassword.$CFG->$alt)) {
2718 // force update of password hash using latest main password salt and encoding if needed
2719 update_internal_user_password($user, $password);
2726 * Calculate hashed value from password using current hash mechanism.
2728 * @param string password
2729 * @return string password hash
2731 function hash_internal_user_password($password) {
2734 if (isset($CFG->passwordsaltmain
)) {
2735 return md5($password.$CFG->passwordsaltmain
);
2737 return md5($password);
2742 * Update pssword hash in user object.
2744 * @param object user
2745 * @param string plain text password
2746 * @param bool store changes also in db, default true
2747 * @return true if hash changed
2749 function update_internal_user_password(&$user, $password) {
2752 $authplugin = get_auth_plugin($user->auth
);
2753 if (!empty($authplugin->config
->preventpassindb
)) {
2754 $hashedpassword = 'not cached';
2756 $hashedpassword = hash_internal_user_password($password);
2759 return set_field('user', 'password', $hashedpassword, 'id', $user->id
);
2763 * Get a complete user record, which includes all the info
2764 * in the user record
2765 * Intended for setting as $USER session variable
2769 * @param string $field The user field to be checked for a given value.
2770 * @param string $value The value to match for $field.
2771 * @return user A {@link $USER} object.
2773 function get_complete_user_data($field, $value, $mnethostid=null) {
2777 if (!$field ||
!$value) {
2781 /// Build the WHERE clause for an SQL query
2783 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
2785 if (null === $mnethostid) {
2786 $constraints .= ' AND auth != \'mnet\'';
2787 } elseif (is_numeric($mnethostid)) {
2788 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
2790 error_log('Call to get_complete_user_data for $field='.$field.', $value = '.$value.', with invalid $mnethostid: '. $mnethostid);
2791 print_error('invalidhostlogin','mnet', $CFG->wwwroot
.'/login/index.php');
2795 /// Get all the basic user data
2797 if (! $user = get_record_select('user', $constraints)) {
2801 /// Get various settings and preferences
2803 if ($displays = get_records('course_display', 'userid', $user->id
)) {
2804 foreach ($displays as $display) {
2805 $user->display
[$display->course
] = $display->display
;
2809 $user->preference
= get_user_preferences(null, null, $user->id
);
2811 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id
)) {
2812 foreach ($lastaccesses as $lastaccess) {
2813 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
2817 if ($groupids = groups_get_all_groups_for_user($user->id
)) { //TODO:check.
2818 foreach ($groupids as $groupid) {
2819 $courseid = groups_get_course($groupid);
2820 //change this to 2D array so we can put multiple groups in a course
2821 $user->groupmember
[$courseid][] = $groupid;
2825 /// Rewrite some variables if necessary
2826 if (!empty($user->description
)) {
2827 $user->description
= true; // No need to cart all of it around
2829 if ($user->username
== 'guest') {
2830 $user->lang
= $CFG->lang
; // Guest language always same as site
2831 $user->firstname
= get_string('guestuser'); // Name always in current language
2832 $user->lastname
= ' ';
2835 $user->sesskey
= random_string(10);
2836 $user->sessionIP
= md5(getremoteaddr()); // Store the current IP in the session
2844 * When logging in, this function is run to set certain preferences
2845 * for the current SESSION
2847 function set_login_session_preferences() {
2848 global $SESSION, $CFG;
2850 $SESSION->justloggedin
= true;
2852 unset($SESSION->lang
);
2854 // Restore the calendar filters, if saved
2855 if (intval(get_user_preferences('calendar_persistflt', 0))) {
2856 include_once($CFG->dirroot
.'/calendar/lib.php');
2857 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
2863 * Delete a course, including all related data from the database,
2864 * and any associated files from the moodledata folder.
2866 * @param int $courseid The id of the course to delete.
2867 * @param bool $showfeedback Whether to display notifications of each action the function performs.
2868 * @return bool true if all the removals succeeded. false if there were any failures. If this
2869 * method returns false, some of the removals will probably have succeeded, and others
2870 * failed, but you have no way of knowing which.
2872 function delete_course($courseid, $showfeedback = true) {
2876 if (!remove_course_contents($courseid, $showfeedback)) {
2877 if ($showfeedback) {
2878 notify("An error occurred while deleting some of the course contents.");
2883 if (!delete_records("course", "id", $courseid)) {
2884 if ($showfeedback) {
2885 notify("An error occurred while deleting the main course record.");
2890 if (!delete_records('context', 'contextlevel', CONTEXT_COURSE
, 'instanceid', $courseid)) {
2891 if ($showfeedback) {
2892 notify("An error occurred while deleting the main context record.");
2897 if (!fulldelete($CFG->dataroot
.'/'.$courseid)) {
2898 if ($showfeedback) {
2899 notify("An error occurred while deleting the course files.");
2908 * Clear a course out completely, deleting all content
2909 * but don't delete the course itself
2912 * @param int $courseid The id of the course that is being deleted
2913 * @param bool $showfeedback Whether to display notifications of each action the function performs.
2914 * @return bool true if all the removals succeeded. false if there were any failures. If this
2915 * method returns false, some of the removals will probably have succeeded, and others
2916 * failed, but you have no way of knowing which.
2918 function remove_course_contents($courseid, $showfeedback=true) {
2924 if (! $course = get_record('course', 'id', $courseid)) {
2925 error('Course ID was incorrect (can\'t find it)');
2928 $strdeleted = get_string('deleted');
2930 /// First delete every instance of every module
2932 if ($allmods = get_records('modules') ) {
2933 foreach ($allmods as $mod) {
2934 $modname = $mod->name
;
2935 $modfile = $CFG->dirroot
.'/mod/'. $modname .'/lib.php';
2936 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
2937 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
2939 if (file_exists($modfile)) {
2940 include_once($modfile);
2941 if (function_exists($moddelete)) {
2942 if ($instances = get_records($modname, 'course', $course->id
)) {
2943 foreach ($instances as $instance) {
2944 if ($cm = get_coursemodule_from_instance($modname, $instance->id
, $course->id
)) {
2945 delete_context(CONTEXT_MODULE
, $cm->id
);
2947 if ($moddelete($instance->id
)) {
2951 notify('Could not delete '. $modname .' instance '. $instance->id
.' ('. format_string($instance->name
) .')');
2957 notify('Function '. $moddelete() .'doesn\'t exist!');
2961 if (function_exists($moddeletecourse)) {
2962 $moddeletecourse($course, $showfeedback);
2965 if ($showfeedback) {
2966 notify($strdeleted .' '. $count .' x '. $modname);
2970 error('No modules are installed!');
2973 /// Give local code a chance to delete its references to this course.
2974 require_once('locallib.php');
2975 notify_local_delete_course($courseid, $showfeedback);
2977 /// Delete course blocks
2979 if ($blocks = get_records_sql("SELECT *
2980 FROM {$CFG->prefix}block_instance
2981 WHERE pagetype = '".PAGE_COURSE_VIEW
."'
2982 AND pageid = $course->id")) {
2983 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW
, 'pageid', $course->id
)) {
2984 if ($showfeedback) {
2985 notify($strdeleted .' block_instance');
2987 foreach ($blocks as $block) { /// Delete any associated contexts for this block
2988 delete_context(CONTEXT_BLOCK
, $block->id
);
2995 /// Delete any groups, removing members and grouping/course links first.
2996 //TODO: If groups or groupings are to be shared between courses, think again!
2997 if ($groupids = groups_get_groups($course->id
)) {
2998 foreach ($groupids as $groupid) {
2999 if (groups_remove_all_members($groupid)) {
3000 if ($showfeedback) {
3001 notify($strdeleted .' groups_members');
3006 /// Delete any associated context for this group ??
3007 delete_context(CONTEXT_GROUP
, $groupid);
3009 if (groups_delete_group($groupid)) {
3010 if ($showfeedback) {
3011 notify($strdeleted .' groups');
3018 /// Delete any groupings.
3019 $result = groups_delete_all_groupings($course->id
);
3020 if ($result && $showfeedback) {
3021 notify($strdeleted .' groupings');
3024 /// Delete all related records in other tables that may have a courseid
3025 /// This array stores the tables that need to be cleared, as
3026 /// table_name => column_name that contains the course id.
3028 $tablestoclear = array(
3029 'event' => 'courseid', // Delete events
3030 'log' => 'course', // Delete logs
3031 'course_sections' => 'course', // Delete any course stuff
3032 'course_modules' => 'course',
3033 'grade_category' => 'courseid', // Delete gradebook stuff
3034 'grade_exceptions' => 'courseid',
3035 'grade_item' => 'courseid',
3036 'grade_letter' => 'courseid',
3037 'grade_preferences' => 'courseid',
3038 'backup_courses' => 'courseid', // Delete scheduled backup stuff
3039 'backup_log' => 'courseid'
3041 foreach ($tablestoclear as $table => $col) {
3042 if (delete_records($table, $col, $course->id
)) {
3043 if ($showfeedback) {
3044 notify($strdeleted . ' ' . $table);
3052 /// Clean up metacourse stuff
3054 if ($course->metacourse
) {
3055 delete_records("course_meta","parent_course",$course->id
);
3056 sync_metacourse($course->id
); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
3057 if ($showfeedback) {
3058 notify("$strdeleted course_meta");
3061 if ($parents = get_records("course_meta","child_course",$course->id
)) {
3062 foreach ($parents as $parent) {
3063 remove_from_metacourse($parent->parent_course
,$parent->child_course
); // this will do the unenrolments as well.
3065 if ($showfeedback) {
3066 notify("$strdeleted course_meta");
3071 /// Delete questions and question categories
3072 include_once($CFG->libdir
.'/questionlib.php');
3073 question_delete_course($course, $showfeedback);
3075 /// Delete all roles and overiddes in the course context (but keep the course context)
3076 if ($courseid != SITEID
) {
3077 delete_context(CONTEXT_COURSE
, $course->id
);
3085 * This function will empty a course of USER data as much as
3086 /// possible. It will retain the activities and the structure
3092 * @param object $data an object containing all the boolean settings and courseid
3093 * @param bool $showfeedback if false then do it all silently
3095 * @todo Finish documenting this function
3097 function reset_course_userdata($data, $showfeedback=true) {
3099 global $CFG, $USER, $SESSION;
3103 $strdeleted = get_string('deleted');
3105 // Look in every instance of every module for data to delete
3107 if ($allmods = get_records('modules') ) {
3108 foreach ($allmods as $mod) {
3109 $modname = $mod->name
;
3110 $modfile = $CFG->dirroot
.'/mod/'. $modname .'/lib.php';
3111 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3112 if (file_exists($modfile)) {
3113 @include_once
($modfile);
3114 if (function_exists($moddeleteuserdata)) {
3115 $moddeleteuserdata($data, $showfeedback);
3120 error('No modules are installed!');
3123 // Delete other stuff
3124 $coursecontext = get_context_instance(CONTEXT_COURSE
, $data->courseid
);
3126 if (!empty($data->reset_students
) or !empty($data->reset_teachers
)) {
3127 $teachers = array_keys(get_users_by_capability($coursecontext, 'moodle/course:update'));
3128 $participants = array_keys(get_users_by_capability($coursecontext, 'moodle/course:view'));
3129 $students = array_diff($participants, $teachers);
3131 if (!empty($data->reset_students
)) {
3132 foreach ($students as $studentid) {
3133 role_unassign(0, $studentid, 0, $coursecontext->id
);
3135 if ($showfeedback) {
3136 notify($strdeleted .' '.get_string('students'), 'notifysuccess');
3139 /// Delete group members (but keep the groups) TODO:check.
3140 if ($groupids = groups_get_groups($data->courseid
)) {
3141 foreach ($groupids as $groupid) {
3142 if (groups_remove_all_group_members($groupid)) {
3143 if ($showfeedback) {
3144 notify($strdeleted .' groups_members', 'notifysuccess');
3153 if (!empty($data->reset_teachers
)) {
3154 foreach ($teachers as $teacherid) {
3155 role_unassign(0, $teacherid, 0, $coursecontext->id
);
3157 if ($showfeedback) {
3158 notify($strdeleted .' '.get_string('teachers'), 'notifysuccess');
3163 if (!empty($data->reset_groups
)) {
3164 if ($groupids = groups_get_groups($data->courseid
)) {
3165 foreach ($groupids as $groupid) {
3166 if (groups_delete_group($groupid)) {
3167 if ($showfeedback) {
3168 notify($strdeleted .' groups', 'notifysuccess');
3177 if (!empty($data->reset_events
)) {
3178 if (delete_records('event', 'courseid', $data->courseid
)) {
3179 if ($showfeedback) {
3180 notify($strdeleted .' event', 'notifysuccess');
3187 if (!empty($data->reset_logs
)) {
3188 if (delete_records('log', 'course', $data->courseid
)) {
3189 if ($showfeedback) {
3190 notify($strdeleted .' log', 'notifysuccess');
3197 // deletes all role assignments, and local override, these have no courseid in table and needs separate process
3198 $context = get_context_instance(CONTEXT_COURSE
, $data->courseid
);
3199 delete_records('role_capabilities', 'contextid', $context->id
);
3205 require_once($CFG->dirroot
.'/group/lib.php');
3206 /*TODO: functions moved to /group/lib/legacylib.php
3216 function generate_email_processing_address($modid,$modargs) {
3219 if (empty($CFG->siteidentifier
)) { // Unique site identification code
3220 set_config('siteidentifier', random_string(32));
3223 $header = $CFG->mailprefix
. substr(base64_encode(pack('C',$modid)),0,2).$modargs;
3224 return $header . substr(md5($header.$CFG->siteidentifier
),0,16).'@'.$CFG->maildomain
;
3228 function moodle_process_email($modargs,$body) {
3229 // the first char should be an unencoded letter. We'll take this as an action
3230 switch ($modargs{0}) {
3231 case 'B': { // bounce
3232 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
3233 if ($user = get_record_select("user","id=$userid","id,email")) {
3234 // check the half md5 of their email
3235 $md5check = substr(md5($user->email
),0,16);
3236 if ($md5check == substr($modargs, -16)) {
3237 set_bounce_count($user);
3239 // else maybe they've already changed it?
3243 // maybe more later?
3247 /// CORRESPONDENCE ////////////////////////////////////////////////
3250 * Send an email to a specified user
3255 * @param user $user A {@link $USER} object
3256 * @param user $from A {@link $USER} object
3257 * @param string $subject plain text subject line of the email
3258 * @param string $messagetext plain text version of the message
3259 * @param string $messagehtml complete html version of the message (optional)
3260 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
3261 * @param string $attachname the name of the file (extension indicates MIME)
3262 * @param bool $usetrueaddress determines whether $from email address should
3263 * be sent out. Will be overruled by user profile setting for maildisplay
3264 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3265 * was blocked by user and "false" if there was another sort of error.
3267 function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='') {
3269 global $CFG, $FULLME;
3271 include_once($CFG->libdir
.'/phpmailer/class.phpmailer.php');
3273 /// We are going to use textlib services here
3274 $textlib = textlib_get_instance();
3280 // skip mail to suspended users
3281 if (isset($user->auth
) && $user->auth
=='nologin') {
3285 if (!empty($user->emailstop
)) {
3289 if (over_bounce_threshold($user)) {
3290 error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
3294 $mail = new phpmailer
;
3296 $mail->Version
= 'Moodle '. $CFG->version
; // mailer version
3297 $mail->PluginDir
= $CFG->libdir
.'/phpmailer/'; // plugin directory (eg smtp plugin)
3299 $mail->CharSet
= 'UTF-8';
3301 if ($CFG->smtphosts
== 'qmail') {
3302 $mail->IsQmail(); // use Qmail system
3304 } else if (empty($CFG->smtphosts
)) {
3305 $mail->IsMail(); // use PHP mail() = sendmail
3308 $mail->IsSMTP(); // use SMTP directly
3309 if (!empty($CFG->debugsmtp
)) {
3310 echo '<pre>' . "\n";
3311 $mail->SMTPDebug
= true;
3313 $mail->Host
= $CFG->smtphosts
; // specify main and backup servers
3315 if ($CFG->smtpuser
) { // Use SMTP authentication
3316 $mail->SMTPAuth
= true;
3317 $mail->Username
= $CFG->smtpuser
;
3318 $mail->Password
= $CFG->smtppass
;
3322 $adminuser = get_admin();
3324 // make up an email address for handling bounces
3325 if (!empty($CFG->handlebounces
)) {
3326 $modargs = 'B'.base64_encode(pack('V',$user->id
)).substr(md5($user->email
),0,16);
3327 $mail->Sender
= generate_email_processing_address(0,$modargs);
3330 $mail->Sender
= $adminuser->email
;
3333 if (is_string($from)) { // So we can pass whatever we want if there is need
3334 $mail->From
= $CFG->noreplyaddress
;
3335 $mail->FromName
= $from;
3336 } else if ($usetrueaddress and $from->maildisplay
) {
3337 $mail->From
= $from->email
;
3338 $mail->FromName
= fullname($from);
3340 $mail->From
= $CFG->noreplyaddress
;
3341 $mail->FromName
= fullname($from);
3342 if (empty($replyto)) {
3343 $mail->AddReplyTo($CFG->noreplyaddress
,get_string('noreplyname'));
3347 if (!empty($replyto)) {
3348 $mail->AddReplyTo($replyto,$replytoname);
3351 $mail->Subject
= substr(stripslashes($subject), 0, 900);
3353 $mail->AddAddress($user->email
, fullname($user) );
3355 $mail->WordWrap
= 79; // set word wrap
3357 if (!empty($from->customheaders
)) { // Add custom headers
3358 if (is_array($from->customheaders
)) {
3359 foreach ($from->customheaders
as $customheader) {
3360 $mail->AddCustomHeader($customheader);
3363 $mail->AddCustomHeader($from->customheaders
);
3367 if (!empty($from->priority
)) {
3368 $mail->Priority
= $from->priority
;
3371 if ($messagehtml && $user->mailformat
== 1) { // Don't ever send HTML to users who don't want it
3372 $mail->IsHTML(true);
3373 $mail->Encoding
= 'quoted-printable'; // Encoding to use
3374 $mail->Body
= $messagehtml;
3375 $mail->AltBody
= "\n$messagetext\n";
3377 $mail->IsHTML(false);
3378 $mail->Body
= "\n$messagetext\n";
3381 if ($attachment && $attachname) {
3382 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
3383 $mail->AddAddress($adminuser->email
, fullname($adminuser) );
3384 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
3386 require_once($CFG->libdir
.'/filelib.php');
3387 $mimetype = mimeinfo('type', $attachname);
3388 $mail->AddAttachment($CFG->dataroot
.'/'. $attachment, $attachname, 'base64', $mimetype);
3394 /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
3395 /// encoding to the specified one
3396 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
3397 /// Set it to site mail charset
3398 $charset = $CFG->sitemailcharset
;
3399 /// Overwrite it with the user mail charset
3400 if (!empty($CFG->allowusermailcharset
)) {
3401 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
3402 $charset = $useremailcharset;
3405 /// If it has changed, convert all the necessary strings
3406 $charsets = get_list_of_charsets();
3407 unset($charsets['UTF-8']);
3408 if (in_array($charset, $charsets)) {
3409 /// Save the new mail charset
3410 $mail->CharSet
= $charset;
3411 /// And convert some strings
3412 $mail->FromName
= $textlib->convert($mail->FromName
, 'utf-8', $mail->CharSet
); //From Name
3413 foreach ($mail->ReplyTo
as $key => $rt) { //ReplyTo Names
3414 $mail->ReplyTo
[$key][1] = $textlib->convert($rt, 'utf-8', $mail->CharSet
);
3416 $mail->Subject
= $textlib->convert($mail->Subject
, 'utf-8', $mail->CharSet
); //Subject
3417 foreach ($mail->to
as $key => $to) {
3418 $mail->to
[$key][1] = $textlib->convert($to, 'utf-8', $mail->CharSet
); //To Names
3420 $mail->Body
= $textlib->convert($mail->Body
, 'utf-8', $mail->CharSet
); //Body
3421 $mail->AltBody
= $textlib->convert($mail->AltBody
, 'utf-8', $mail->CharSet
); //Subject
3425 if ($mail->Send()) {
3426 set_send_count($user);
3427 $mail->IsSMTP(); // use SMTP directly
3428 if (!empty($CFG->debugsmtp
)) {
3433 mtrace('ERROR: '. $mail->ErrorInfo
);
3434 add_to_log(SITEID
, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo
);
3435 if (!empty($CFG->debugsmtp
)) {
3443 * Sets specified user's password and send the new password to the user via email.
3446 * @param user $user A {@link $USER} object
3447 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
3448 * was blocked by user and "false" if there was another sort of error.
3450 function setnew_password_and_mail($user) {
3455 $from = get_admin();
3457 $newpassword = generate_password();
3459 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id
) ) {
3460 trigger_error('Could not set user password!');
3465 $a->firstname
= $user->firstname
;
3466 $a->sitename
= $site->fullname
;
3467 $a->username
= $user->username
;
3468 $a->newpassword
= $newpassword;
3469 $a->link
= $CFG->wwwroot
.'/login/';
3470 $a->signoff
= fullname($from, true).' ('. $from->email
.')';
3472 $message = get_string('newusernewpasswordtext', '', $a);
3474 $subject = $site->fullname
.': '. get_string('newusernewpasswordsubj');
3476 return email_to_user($user, $from, $subject, $message);
3481 * Resets specified user's password and send the new password to the user via email.
3484 * @param user $user A {@link $USER} object
3485 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3486 * was blocked by user and "false" if there was another sort of error.
3488 function reset_password_and_mail($user) {
3493 $from = get_admin();
3495 $userauth = get_auth_plugin($user->auth
);
3496 if (!$userauth->can_reset_password()) {
3497 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
3501 $newpassword = generate_password();
3503 if (!$userauth->user_update_password(addslashes_recursive($user), addslashes($newpassword))) {
3504 error("Could not set user password!");
3508 $a->firstname
= $user->firstname
;
3509 $a->sitename
= $site->fullname
;
3510 $a->username
= $user->username
;
3511 $a->newpassword
= $newpassword;
3512 $a->link
= $CFG->httpswwwroot
.'/login/change_password.php';
3513 $a->signoff
= fullname($from, true).' ('. $from->email
.')';
3515 $message = get_string('newpasswordtext', '', $a);
3517 $subject = $site->fullname
.': '. get_string('changedpassword');
3519 return email_to_user($user, $from, $subject, $message);
3524 * Send email to specified user with confirmation text and activation link.
3527 * @param user $user A {@link $USER} object
3528 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3529 * was blocked by user and "false" if there was another sort of error.
3531 function send_confirmation_email($user) {
3536 $from = get_admin();
3538 $data = new object();
3539 $data->firstname
= fullname($user);
3540 $data->sitename
= $site->fullname
;
3541 $data->admin
= fullname($from) .' ('. $from->email
.')';
3543 $subject = get_string('emailconfirmationsubject', '', $site->fullname
);
3545 $data->link
= $CFG->wwwroot
.'/login/confirm.php?data='. $user->secret
.'/'. $user->username
;
3546 $message = get_string('emailconfirmation', '', $data);
3547 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
3549 $user->mailformat
= 1; // Always send HTML version as well
3551 return email_to_user($user, $from, $subject, $message, $messagehtml);
3556 * send_password_change_confirmation_email.
3559 * @param user $user A {@link $USER} object
3560 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3561 * was blocked by user and "false" if there was another sort of error.
3563 function send_password_change_confirmation_email($user) {
3568 $from = get_admin();
3570 $data = new object();
3571 $data->firstname
= $user->firstname
;
3572 $data->sitename
= $site->fullname
;
3573 $data->link
= $CFG->httpswwwroot
.'/login/forgot_password.php?p='. $user->secret
.'&s='. $user->username
;
3574 $data->admin
= fullname($from).' ('. $from->email
.')';
3576 $message = get_string('emailpasswordconfirmation', '', $data);
3577 $subject = get_string('emailpasswordconfirmationsubject', '', $site->fullname
);
3579 return email_to_user($user, $from, $subject, $message);
3584 * send_password_change_info.
3587 * @param user $user A {@link $USER} object
3588 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3589 * was blocked by user and "false" if there was another sort of error.
3591 function send_password_change_info($user) {
3596 $from = get_admin();
3598 $data = new object();
3599 $data->firstname
= $user->firstname
;
3600 $data->sitename
= $site->fullname
;
3601 $data->admin
= fullname($from).' ('. $from->email
.')';
3603 $userauth = get_auth_plugin($user->auth
);
3604 if ($userauth->can_change_password() and method_exists($userauth, 'change_password_url') and $userauth->change_password_url()) {
3605 // we have some external url for password cahnging
3606 $data->link
.= $userauth->change_password_url();
3609 //no way to change password, sorry
3613 if (!empty($data->link
)) {
3614 $message = get_string('emailpasswordchangeinfo', '', $data);
3615 $subject = get_string('emailpasswordchangeinfosubject', '', $site->fullname
);
3617 $message = get_string('emailpasswordchangeinfofail', '', $data);
3618 $subject = get_string('emailpasswordchangeinfosubject', '', $site->fullname
);
3621 return email_to_user($user, $from, $subject, $message);
3626 * Check that an email is allowed. It returns an error message if there
3630 * @param string $email Content of email
3631 * @return string|false
3633 function email_is_not_allowed($email) {
3637 if (!empty($CFG->allowemailaddresses
)) {
3638 $allowed = explode(' ', $CFG->allowemailaddresses
);
3639 foreach ($allowed as $allowedpattern) {
3640 $allowedpattern = trim($allowedpattern);
3641 if (!$allowedpattern) {
3644 if (strpos(strrev($email), strrev($allowedpattern)) === 0) { // Match! (bug 5250)
3648 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
3650 } else if (!empty($CFG->denyemailaddresses
)) {
3651 $denied = explode(' ', $CFG->denyemailaddresses
);
3652 foreach ($denied as $deniedpattern) {
3653 $deniedpattern = trim($deniedpattern);
3654 if (!$deniedpattern) {
3657 if (strpos(strrev($email), strrev($deniedpattern)) === 0) { // Match! (bug 5250)
3658 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
3666 function email_welcome_message_to_user($course, $user=NULL) {
3670 if (!isloggedin()) {
3676 if (!empty($course->welcomemessage
)) {
3677 $subject = get_string('welcometocourse', '', format_string($course->fullname
));
3679 $a->coursename
= $course->fullname
;
3680 $a->profileurl
= "$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id";
3681 //$message = get_string("welcometocoursetext", "", $a);
3682 $message = $course->welcomemessage
;
3684 if (! $teacher = get_teacher($course->id
)) {
3685 $teacher = get_admin();
3687 email_to_user($user, $teacher, $subject, $message);
3691 /// FILE HANDLING /////////////////////////////////////////////
3695 * Makes an upload directory for a particular module.
3698 * @param int $courseid The id of the course in question - maps to id field of 'course' table.
3699 * @return string|false Returns full path to directory if successful, false if not
3701 function make_mod_upload_directory($courseid) {
3704 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata
)) {
3708 $strreadme = get_string('readme');
3710 if (file_exists($CFG->dirroot
.'/lang/'. $CFG->lang
.'/docs/module_files.txt')) {
3711 copy($CFG->dirroot
.'/lang/'. $CFG->lang
.'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
3713 copy($CFG->dirroot
.'/lang/en_utf8/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
3719 * Returns current name of file on disk if it exists.
3721 * @param string $newfile File to be verified
3722 * @return string Current name of file on disk if true
3724 function valid_uploaded_file($newfile) {
3725 if (empty($newfile)) {
3728 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
3729 return $newfile['tmp_name'];
3736 * Returns the maximum size for uploading files.
3738 * There are seven possible upload limits:
3739 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
3740 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
3741 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
3742 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
3743 * 5. by the Moodle admin in $CFG->maxbytes
3744 * 6. by the teacher in the current course $course->maxbytes
3745 * 7. by the teacher for the current module, eg $assignment->maxbytes
3747 * These last two are passed to this function as arguments (in bytes).
3748 * Anything defined as 0 is ignored.
3749 * The smallest of all the non-zero numbers is returned.
3751 * @param int $sizebytes ?
3752 * @param int $coursebytes Current course $course->maxbytes (in bytes)
3753 * @param int $modulebytes Current module ->maxbytes (in bytes)
3754 * @return int The maximum size for uploading files.
3755 * @todo Finish documenting this function
3757 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
3759 if (! $filesize = ini_get('upload_max_filesize')) {
3762 $minimumsize = get_real_size($filesize);
3764 if ($postsize = ini_get('post_max_size')) {
3765 $postsize = get_real_size($postsize);
3766 if ($postsize < $minimumsize) {
3767 $minimumsize = $postsize;
3771 if ($sitebytes and $sitebytes < $minimumsize) {
3772 $minimumsize = $sitebytes;
3775 if ($coursebytes and $coursebytes < $minimumsize) {
3776 $minimumsize = $coursebytes;
3779 if ($modulebytes and $modulebytes < $minimumsize) {
3780 $minimumsize = $modulebytes;
3783 return $minimumsize;
3787 * Related to {@link get_max_upload_file_size()} - this function returns an
3788 * array of possible sizes in an array, translated to the
3791 * @uses SORT_NUMERIC
3792 * @param int $sizebytes ?
3793 * @param int $coursebytes Current course $course->maxbytes (in bytes)
3794 * @param int $modulebytes Current module ->maxbytes (in bytes)
3796 * @todo Finish documenting this function
3798 function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
3800 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
3804 $filesize[$maxsize] = display_size($maxsize);
3806 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
3807 5242880, 10485760, 20971520, 52428800, 104857600);
3809 foreach ($sizelist as $sizebytes) {
3810 if ($sizebytes < $maxsize) {
3811 $filesize[$sizebytes] = display_size($sizebytes);
3815 krsort($filesize, SORT_NUMERIC
);
3821 * If there has been an error uploading a file, print the appropriate error message
3822 * Numerical constants used as constant definitions not added until PHP version 4.2.0
3824 * $filearray is a 1-dimensional sub-array of the $_FILES array
3825 * eg $filearray = $_FILES['userfile1']
3826 * If left empty then the first element of the $_FILES array will be used
3829 * @param array $filearray A 1-dimensional sub-array of the $_FILES array
3830 * @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.
3831 * @return bool|string
3833 function print_file_upload_error($filearray = '', $returnerror = false) {
3835 if ($filearray == '' or !isset($filearray['error'])) {
3837 if (empty($_FILES)) return false;
3839 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
3840 $filearray = array_shift($files); /// use first element of array
3843 switch ($filearray['error']) {
3845 case 0: // UPLOAD_ERR_OK
3846 if ($filearray['size'] > 0) {
3847 $errmessage = get_string('uploadproblem', $filearray['name']);
3849 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
3853 case 1: // UPLOAD_ERR_INI_SIZE
3854 $errmessage = get_string('uploadserverlimit');
3857 case 2: // UPLOAD_ERR_FORM_SIZE
3858 $errmessage = get_string('uploadformlimit');
3861 case 3: // UPLOAD_ERR_PARTIAL
3862 $errmessage = get_string('uploadpartialfile');
3865 case 4: // UPLOAD_ERR_NO_FILE
3866 $errmessage = get_string('uploadnofilefound');
3870 $errmessage = get_string('uploadproblem', $filearray['name']);
3876 notify($errmessage);
3883 * handy function to loop through an array of files and resolve any filename conflicts
3884 * both in the array of filenames and for what is already on disk.
3885 * not really compatible with the similar function in uploadlib.php
3886 * but this could be used for files/index.php for moving files around.
3889 function resolve_filename_collisions($destination,$files,$format='%s_%d.%s') {
3890 foreach ($files as $k => $f) {
3891 if (check_potential_filename($destination,$f,$files)) {
3892 $bits = explode('.', $f);
3893 for ($i = 1; true; $i++
) {
3894 $try = sprintf($format, $bits[0], $i, $bits[1]);
3895 if (!check_potential_filename($destination,$try,$files)) {
3906 * @used by resolve_filename_collisions
3908 function check_potential_filename($destination,$filename,$files) {
3909 if (file_exists($destination.'/'.$filename)) {
3912 if (count(array_keys($files,$filename)) > 1) {
3920 * Returns an array with all the filenames in
3921 * all subdirectories, relative to the given rootdir.
3922 * If excludefile is defined, then that file/directory is ignored
3923 * If getdirs is true, then (sub)directories are included in the output
3924 * If getfiles is true, then files are included in the output
3925 * (at least one of these must be true!)
3927 * @param string $rootdir ?
3928 * @param string $excludefile If defined then the specified file/directory is ignored
3929 * @param bool $descend ?
3930 * @param bool $getdirs If true then (sub)directories are included in the output
3931 * @param bool $getfiles If true then files are included in the output
3932 * @return array An array with all the filenames in
3933 * all subdirectories, relative to the given rootdir
3934 * @todo Finish documenting this function. Add examples of $excludefile usage.
3936 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
3940 if (!$getdirs and !$getfiles) { // Nothing to show
3944 if (!is_dir($rootdir)) { // Must be a directory
3948 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
3952 if (!is_array($excludefiles)) {
3953 $excludefiles = array($excludefiles);
3956 while (false !== ($file = readdir($dir))) {
3957 $firstchar = substr($file, 0, 1);
3958 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
3961 $fullfile = $rootdir .'/'. $file;
3962 if (filetype($fullfile) == 'dir') {
3967 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
3968 foreach ($subdirs as $subdir) {
3969 $dirs[] = $file .'/'. $subdir;
3972 } else if ($getfiles) {
3985 * Adds up all the files in a directory and works out the size.
3987 * @param string $rootdir ?
3988 * @param string $excludefile ?
3990 * @todo Finish documenting this function
3992 function get_directory_size($rootdir, $excludefile='') {
3996 // do it this way if we can, it's much faster
3997 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
3998 $command = trim($CFG->pathtodu
).' -sk --apparent-size '.escapeshellarg($rootdir);
4001 exec($command,$output,$return);
4002 if (is_array($output)) {
4003 return get_real_size(intval($output[0]).'k'); // we told it to return k.
4007 if (!is_dir($rootdir)) { // Must be a directory
4011 if (!$dir = @opendir
($rootdir)) { // Can't open it for some reason
4017 while (false !== ($file = readdir($dir))) {
4018 $firstchar = substr($file, 0, 1);
4019 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
4022 $fullfile = $rootdir .'/'. $file;
4023 if (filetype($fullfile) == 'dir') {
4024 $size +
= get_directory_size($fullfile, $excludefile);
4026 $size +
= filesize($fullfile);
4035 * Converts bytes into display form
4037 * @param string $size ?
4039 * @staticvar string $gb Localized string for size in gigabytes
4040 * @staticvar string $mb Localized string for size in megabytes
4041 * @staticvar string $kb Localized string for size in kilobytes
4042 * @staticvar string $b Localized string for size in bytes
4043 * @todo Finish documenting this function. Verify return type.
4045 function display_size($size) {
4047 static $gb, $mb, $kb, $b;
4050 $gb = get_string('sizegb');
4051 $mb = get_string('sizemb');
4052 $kb = get_string('sizekb');
4053 $b = get_string('sizeb');
4056 if ($size >= 1073741824) {
4057 $size = round($size / 1073741824 * 10) / 10 . $gb;
4058 } else if ($size >= 1048576) {
4059 $size = round($size / 1048576 * 10) / 10 . $mb;
4060 } else if ($size >= 1024) {
4061 $size = round($size / 1024 * 10) / 10 . $kb;
4063 $size = $size .' '. $b;
4069 * Cleans a given filename by removing suspicious or troublesome characters
4070 * Only these are allowed: alphanumeric _ - .
4071 * Unicode characters can be enabled by setting $CFG->unicodecleanfilename = true in config.php
4073 * WARNING: unicode characters may not be compatible with zip compression in backup/restore,
4074 * because native zip binaries do weird character conversions. Use PHP zipping instead.
4076 * @param string $string file name
4077 * @return string cleaned file name
4079 function clean_filename($string) {
4081 if (empty($CFG->unicodecleanfilename
)) {
4082 $textlib = textlib_get_instance();
4083 $string = $textlib->specialtoascii($string);
4084 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
4086 //clean only ascii range
4087 $string = preg_replace("/[\\000-\\x2c\\x2f\\x3a-\\x40\\x5b-\\x5e\\x60\\x7b-\\177]/s", '_', $string);
4089 $string = preg_replace("/_+/", '_', $string);
4090 $string = preg_replace("/\.\.+/", '.', $string);
4095 /// STRING TRANSLATION ////////////////////////////////////////
4098 * Returns the code for the current language
4105 function current_language() {
4106 global $CFG, $USER, $SESSION, $COURSE;
4108 if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) { // Course language can override all other settings for this page
4109 $return = $COURSE->lang
;
4111 } else if (!empty($SESSION->lang
)) { // Session language can override other settings
4112 $return = $SESSION->lang
;
4114 } else if (!empty($USER->lang
)) {
4115 $return = $USER->lang
;
4118 $return = $CFG->lang
;
4121 if ($return == 'en') {
4122 $return = 'en_utf8';
4129 * Prints out a translated string.
4131 * Prints out a translated string using the return value from the {@link get_string()} function.
4133 * Example usage of this function when the string is in the moodle.php file:<br/>
4136 * print_string('wordforstudent');
4140 * Example usage of this function when the string is not in the moodle.php file:<br/>
4143 * print_string('typecourse', 'calendar');
4147 * @param string $identifier The key identifier for the localized string
4148 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4149 * @param mixed $a An object, string or number that can be used
4150 * within translation strings
4152 function print_string($identifier, $module='', $a=NULL) {
4153 echo get_string($identifier, $module, $a);
4157 * fix up the optional data in get_string()/print_string() etc
4158 * ensure possible sprintf() format characters are escaped correctly
4159 * needs to handle arbitrary strings and objects
4160 * @param mixed $a An object, string or number that can be used
4161 * @return mixed the supplied parameter 'cleaned'
4163 function clean_getstring_data( $a ) {
4164 if (is_string($a)) {
4165 return str_replace( '%','%%',$a );
4167 elseif (is_object($a)) {
4168 $a_vars = get_object_vars( $a );
4169 $new_a_vars = array();
4170 foreach ($a_vars as $fname => $a_var) {
4171 $new_a_vars[$fname] = clean_getstring_data( $a_var );
4173 return (object)$new_a_vars;
4181 * Returns a localized string.
4183 * Returns the translated string specified by $identifier as
4184 * for $module. Uses the same format files as STphp.
4185 * $a is an object, string or number that can be used
4186 * within translation strings
4188 * eg "hello \$a->firstname \$a->lastname"
4191 * If you would like to directly echo the localized string use
4192 * the function {@link print_string()}
4194 * Example usage of this function involves finding the string you would
4195 * like a local equivalent of and using its identifier and module information
4196 * to retrive it.<br/>
4197 * If you open moodle/lang/en/moodle.php and look near line 1031
4198 * you will find a string to prompt a user for their word for student
4200 * $string['wordforstudent'] = 'Your word for Student';
4202 * So if you want to display the string 'Your word for student'
4203 * in any language that supports it on your site
4204 * you just need to use the identifier 'wordforstudent'
4206 * $mystring = '<strong>'. get_string('wordforstudent') .'</strong>';
4209 * If the string you want is in another file you'd take a slightly
4210 * different approach. Looking in moodle/lang/en/calendar.php you find
4213 * $string['typecourse'] = 'Course event';
4215 * If you want to display the string "Course event" in any language
4216 * supported you would use the identifier 'typecourse' and the module 'calendar'
4217 * (because it is in the file calendar.php):
4219 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
4222 * As a last resort, should the identifier fail to map to a string
4223 * the returned string will be [[ $identifier ]]
4226 * @param string $identifier The key identifier for the localized string
4227 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4228 * @param mixed $a An object, string or number that can be used
4229 * within translation strings
4230 * @param array $extralocations An array of strings with other locations to look for string files
4231 * @return string The localized string.
4233 function get_string($identifier, $module='', $a=NULL, $extralocations=NULL) {
4237 /// originally these special strings were stored in moodle.php now we are only in langconfig.php
4238 $langconfigstrs = array('alphabet', 'backupnameformat', 'firstdayofweek', 'locale',
4239 'localewin', 'localewincharset', 'oldcharset',
4240 'parentlanguage', 'strftimedate', 'strftimedateshort', 'strftimedatetime',
4241 'strftimedaydate', 'strftimedaydatetime', 'strftimedayshort', 'strftimedaytime',
4242 'strftimemonthyear', 'strftimerecent', 'strftimerecentfull', 'strftimetime',
4243 'thischarset', 'thisdirection', 'thislanguage');
4245 $filetocheck = 'langconfig.php';
4246 $defaultlang = 'en_utf8';
4247 if (in_array($identifier, $langconfigstrs)) {
4248 $module = 'langconfig'; //This strings are under langconfig.php for 1.6 lang packs
4251 $lang = current_language();
4253 if ($module == '') {
4257 // if $a happens to have % in it, double it so sprintf() doesn't break
4259 $a = clean_getstring_data( $a );
4262 /// Define the two or three major locations of language strings for this module
4263 $locations = array();
4265 if (!empty($extralocations)) { // Calling code has a good idea where to look
4266 if (is_array($extralocations)) {
4267 $locations +
= $extralocations;
4268 } else if (is_string($extralocations)) {
4269 $locations[] = $extralocations;
4271 debugging('Bad lang path provided');
4275 if (isset($CFG->running_installer
)) {
4276 $module = 'installer';
4277 $filetocheck = 'installer.php';
4278 $locations +
= array( $CFG->dirroot
.'/install/lang/', $CFG->dataroot
.'/lang/', $CFG->dirroot
.'/lang/' );
4279 $defaultlang = 'en_utf8';
4281 $locations +
= array( $CFG->dataroot
.'/lang/', $CFG->dirroot
.'/lang/' );
4284 /// Add extra places to look for strings for particular plugin types.
4285 if ($module != 'moodle' && $module != 'langconfig') {
4286 if (strpos($module, 'block_') === 0) { // It's a block lang file
4287 $locations[] = $CFG->dirroot
.'/blocks/'.substr($module, 6).'/lang/';
4288 } else if (strpos($module, 'report_') === 0) { // It's a report lang file
4289 $locations[] = $CFG->dirroot
.'/'.$CFG->admin
.'/report/'.substr($module, 7).'/lang/';
4290 $locations[] = $CFG->dirroot
.'/course/report/'.substr($module, 7).'/lang/';
4291 $locations[] = $CFG->dirroot
.'/mod/quiz/report/'.substr($module, 7).'/lang/';
4292 } else if (strpos($module, 'resource_') === 0) { // It's a resource module file
4293 $locations[] = $CFG->dirroot
.'/mod/resource/type/'.substr($module, 9).'/lang/';
4294 } else if (strpos($module, 'assignment_') === 0) { // It's an assignment module file
4295 $locations[] = $CFG->dirroot
.'/mod/assignment/type/'.substr($module, 11).'/lang/';
4296 } else if (strpos($module, 'enrol_') === 0) { // It's an enrolment plugin
4297 $locations[] = $CFG->dirroot
.'/enrol/'.substr($module, 6).'/lang/';
4298 } else if (strpos($module, 'auth_') === 0) { // It's an auth plugin
4299 $locations[] = $CFG->dirroot
.'/auth/'.substr($module, 5).'/lang/';
4300 } else if (strpos($module, 'format_') === 0) { // Course format
4301 $locations[] = $CFG->dirroot
.'/course/format/'.substr($module,7).'/lang/';
4302 } else if (strpos($module, 'qtype_') === 0) { // It's a question type
4303 $locations[] = $CFG->dirroot
.'/question/type/'.substr($module, 6).'/lang/';
4304 } else { // It's a normal activity
4305 $locations[] = $CFG->dirroot
.'/mod/'.$module.'/lang/';
4309 /// First check all the normal locations for the string in the current language
4311 foreach ($locations as $location) {
4312 $locallangfile = $location.$lang.'_local'.'/'.$module.'.php'; //first, see if there's a local file
4313 if (file_exists($locallangfile)) {
4314 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4316 return $resultstring;
4319 //if local directory not found, or particular string does not exist in local direcotry
4320 $langfile = $location.$lang.'/'.$module.'.php';
4321 if (file_exists($langfile)) {
4322 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4324 return $resultstring;
4329 /// If the preferred language was English (utf8) we can abort now
4330 /// saving some checks beacuse it's the only "root" lang
4331 if ($lang == 'en_utf8') {
4332 return '[['. $identifier .']]';
4335 /// Is a parent language defined? If so, try to find this string in a parent language file
4337 foreach ($locations as $location) {
4338 $langfile = $location.$lang.'/'.$filetocheck;
4339 if (file_exists($langfile)) {
4340 if ($result = get_string_from_file('parentlanguage', $langfile, "\$parentlang")) {
4342 if (!empty($parentlang)) { // found it!
4344 //first, see if there's a local file for parent
4345 $locallangfile = $location.$parentlang.'_local'.'/'.$module.'.php';
4346 if (file_exists($locallangfile)) {
4347 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4349 return $resultstring;
4353 //if local directory not found, or particular string does not exist in local direcotry
4354 $langfile = $location.$parentlang.'/'.$module.'.php';
4355 if (file_exists($langfile)) {
4356 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4358 return $resultstring;
4366 /// Our only remaining option is to try English
4368 foreach ($locations as $location) {
4369 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4370 if (file_exists($locallangfile)) {
4371 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4373 return $resultstring;
4377 //if local_en not found, or string not found in local_en
4378 $langfile = $location.$defaultlang.'/'.$module.'.php';
4380 if (file_exists($langfile)) {
4381 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4383 return $resultstring;
4388 /// And, because under 1.6 en is defined as en_utf8 child, me must try
4389 /// if it hasn't been queried before.
4390 if ($defaultlang == 'en') {
4391 $defaultlang = 'en_utf8';
4392 foreach ($locations as $location) {
4393 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4394 if (file_exists($locallangfile)) {
4395 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4397 return $resultstring;
4401 //if local_en not found, or string not found in local_en
4402 $langfile = $location.$defaultlang.'/'.$module.'.php';
4404 if (file_exists($langfile)) {
4405 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4407 return $resultstring;
4413 return '[['.$identifier.']]'; // Last resort
4417 * This function is only used from {@link get_string()}.
4419 * @internal Only used from get_string, not meant to be public API
4420 * @param string $identifier ?
4421 * @param string $langfile ?
4422 * @param string $destination ?
4423 * @return string|false ?
4424 * @staticvar array $strings Localized strings
4426 * @todo Finish documenting this function.
4428 function get_string_from_file($identifier, $langfile, $destination) {
4430 static $strings; // Keep the strings cached in memory.
4432 if (empty($strings[$langfile])) {
4434 include ($langfile);
4435 $strings[$langfile] = $string;
4437 $string = &$strings[$langfile];
4440 if (!isset ($string[$identifier])) {
4444 return $destination .'= sprintf("'. $string[$identifier] .'");';
4448 * Converts an array of strings to their localized value.
4450 * @param array $array An array of strings
4451 * @param string $module The language module that these strings can be found in.
4454 function get_strings($array, $module='') {
4457 foreach ($array as $item) {
4458 $string->$item = get_string($item, $module);
4464 * Returns a list of language codes and their full names
4465 * hides the _local files from everyone.
4467 * @return array An associative array with contents in the form of LanguageCode => LanguageName
4469 function get_list_of_languages() {
4473 $languages = array();
4475 $filetocheck = 'langconfig.php';
4477 if ( (!defined('FULLME') || FULLME
!== 'cron')
4478 && !empty($CFG->langcache
) && file_exists($CFG->dataroot
.'/cache/languages')) {
4481 $lines = file($CFG->dataroot
.'/cache/languages');
4482 foreach ($lines as $line) {
4483 $line = trim($line);
4484 if (preg_match('/^(\w+)\s+(.+)/', $line, $matches)) {
4485 $languages[$matches[1]] = $matches[2];
4488 unset($lines); unset($line); unset($matches);
4492 if (!empty($CFG->langlist
)) { // use admin's list of languages
4494 $langlist = explode(',', $CFG->langlist
);
4495 foreach ($langlist as $lang) {
4496 $lang = trim($lang); //Just trim spaces to be a bit more permissive
4497 if (strstr($lang, '_local')!==false) {
4500 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4501 $shortlang = substr($lang, 0, -5);
4505 /// Search under dirroot/lang
4506 if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4507 include($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck);
4508 if (!empty($string['thislanguage'])) {
4509 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4513 /// And moodledata/lang
4514 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4515 include($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck);
4516 if (!empty($string['thislanguage'])) {
4517 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4523 /// Fetch langs from moodle/lang directory
4524 $langdirs = get_list_of_plugins('lang');
4525 /// Fetch langs from moodledata/lang directory
4526 $langdirs2 = get_list_of_plugins('lang', '', $CFG->dataroot
);
4527 /// Merge both lists of langs
4528 $langdirs = array_merge($langdirs, $langdirs2);
4531 /// Get some info from each lang (first from moodledata, then from moodle)
4532 foreach ($langdirs as $lang) {
4533 if (strstr($lang, '_local')!==false) {
4536 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4537 $shortlang = substr($lang, 0, -5);
4541 /// Search under moodledata/lang
4542 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4543 include($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck);
4544 if (!empty($string['thislanguage'])) {
4545 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4549 /// And dirroot/lang
4550 if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4551 include($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck);
4552 if (!empty($string['thislanguage'])) {
4553 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4560 if ( defined('FULLME') && FULLME
=== 'cron' && !empty($CFG->langcache
)) {
4561 if ($file = fopen($CFG->dataroot
.'/cache/languages', 'w')) {
4562 foreach ($languages as $key => $value) {
4563 fwrite($file, "$key $value\n");
4573 * Returns a list of charset codes. It's hardcoded, so they should be added manually
4574 * (cheking that such charset is supported by the texlib library!)
4576 * @return array And associative array with contents in the form of charset => charset
4578 function get_list_of_charsets() {
4581 'EUC-JP' => 'EUC-JP',
4582 'ISO-2022-JP'=> 'ISO-2022-JP',
4583 'ISO-8859-1' => 'ISO-8859-1',
4584 'SHIFT-JIS' => 'SHIFT-JIS',
4585 'GB2312' => 'GB2312',
4586 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
4587 'UTF-8' => 'UTF-8');
4595 * Returns a list of country names in the current language
4601 function get_list_of_countries() {
4604 $lang = current_language();
4606 if (!file_exists($CFG->dirroot
.'/lang/'. $lang .'/countries.php') &&
4607 !file_exists($CFG->dataroot
.'/lang/'. $lang .'/countries.php')) {
4608 if ($parentlang = get_string('parentlanguage')) {
4609 if (file_exists($CFG->dirroot
.'/lang/'. $parentlang .'/countries.php') ||
4610 file_exists($CFG->dataroot
.'/lang/'. $parentlang .'/countries.php')) {
4611 $lang = $parentlang;
4613 $lang = 'en_utf8'; // countries.php must exist in this pack
4616 $lang = 'en_utf8'; // countries.php must exist in this pack
4620 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/countries.php')) {
4621 include($CFG->dataroot
.'/lang/'. $lang .'/countries.php');
4622 } else if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/countries.php')) {
4623 include($CFG->dirroot
.'/lang/'. $lang .'/countries.php');
4626 if (!empty($string)) {
4634 * Returns a list of valid and compatible themes
4639 function get_list_of_themes() {
4645 if (!empty($CFG->themelist
)) { // use admin's list of themes
4646 $themelist = explode(',', $CFG->themelist
);
4648 $themelist = get_list_of_plugins("theme");
4651 foreach ($themelist as $key => $theme) {
4652 if (!file_exists("$CFG->themedir/$theme/config.php")) { // bad folder
4655 $THEME = new object(); // Note this is not the global one!! :-)
4656 include("$CFG->themedir/$theme/config.php");
4657 if (!isset($THEME->sheets
)) { // Not a valid 1.5 theme
4660 $themes[$theme] = $theme;
4669 * Returns a list of picture names in the current or specified language
4674 function get_list_of_pixnames($lang = '') {
4678 $lang = current_language();
4683 $path = $CFG->dirroot
.'/lang/en_utf8/pix.php'; // always exists
4685 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'_local/pix.php')) {
4686 $path = $CFG->dataroot
.'/lang/'. $lang .'_local/pix.php';
4688 } else if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/pix.php')) {
4689 $path = $CFG->dirroot
.'/lang/'. $lang .'/pix.php';
4691 } else if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/pix.php')) {
4692 $path = $CFG->dataroot
.'/lang/'. $lang .'/pix.php';
4694 } else if ($parentlang = get_string('parentlanguage') and $parentlang != '[[parentlanguage]]') {
4695 return get_list_of_pixnames($parentlang); //return pixnames from parent language instead
4704 * Returns a list of timezones in the current language
4709 function get_list_of_timezones() {
4712 $timezones = array();
4714 if ($rawtimezones = get_records_sql('SELECT MAX(id), name FROM '.$CFG->prefix
.'timezone GROUP BY name')) {
4715 foreach($rawtimezones as $timezone) {
4716 if (!empty($timezone->name
)) {
4717 $timezones[$timezone->name
] = get_string(strtolower($timezone->name
), 'timezones');
4718 if (substr($timezones[$timezone->name
], 0, 1) == '[') { // No translation found
4719 $timezones[$timezone->name
] = $timezone->name
;
4727 for ($i = -13; $i <= 13; $i +
= .5) {
4730 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
4731 } else if ($i > 0) {
4732 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
4734 $timezones[sprintf("%.1f", $i)] = $tzstring;
4742 * Returns a list of currencies in the current language
4748 function get_list_of_currencies() {
4751 $lang = current_language();
4753 if (!file_exists($CFG->dataroot
.'/lang/'. $lang .'/currencies.php')) {
4754 if ($parentlang = get_string('parentlanguage')) {
4755 if (file_exists($CFG->dataroot
.'/lang/'. $parentlang .'/currencies.php')) {
4756 $lang = $parentlang;
4758 $lang = 'en_utf8'; // currencies.php must exist in this pack
4761 $lang = 'en_utf8'; // currencies.php must exist in this pack
4765 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/currencies.php')) {
4766 include_once($CFG->dataroot
.'/lang/'. $lang .'/currencies.php');
4767 } else { //if en_utf8 is not installed in dataroot
4768 include_once($CFG->dirroot
.'/lang/'. $lang .'/currencies.php');
4771 if (!empty($string)) {
4781 * Can include a given document file (depends on second
4782 * parameter) or just return info about it.
4785 * @param string $file ?
4786 * @param bool $include ?
4788 * @todo Finish documenting this function
4790 function document_file($file, $include=true) {
4793 $file = clean_filename($file);
4799 $langs = array(current_language(), get_string('parentlanguage'), 'en');
4801 foreach ($langs as $lang) {
4802 $info = new object();
4803 $info->filepath
= $CFG->dirroot
.'/lang/'. $lang .'/docs/'. $file;
4804 $info->urlpath
= $CFG->wwwroot
.'/lang/'. $lang .'/docs/'. $file;
4806 if (file_exists($info->filepath
)) {
4808 include($info->filepath
);
4817 /// ENCRYPTION ////////////////////////////////////////////////
4822 * @param string $data ?
4824 * @todo Finish documenting this function
4826 function rc4encrypt($data) {
4827 $password = 'nfgjeingjk';
4828 return endecrypt($password, $data, '');
4834 * @param string $data ?
4836 * @todo Finish documenting this function
4838 function rc4decrypt($data) {
4839 $password = 'nfgjeingjk';
4840 return endecrypt($password, $data, 'de');
4844 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
4846 * @param string $pwd ?
4847 * @param string $data ?
4848 * @param string $case ?
4850 * @todo Finish documenting this function
4852 function endecrypt ($pwd, $data, $case) {
4854 if ($case == 'de') {
4855 $data = urldecode($data);
4863 $pwd_length = strlen($pwd);
4865 for ($i = 0; $i <= 255; $i++
) {
4866 $key[$i] = ord(substr($pwd, ($i %
$pwd_length), 1));
4872 for ($i = 0; $i <= 255; $i++
) {
4873 $x = ($x +
$box[$i] +
$key[$i]) %
256;
4874 $temp_swap = $box[$i];
4875 $box[$i] = $box[$x];
4876 $box[$x] = $temp_swap;
4888 for ($i = 0; $i < strlen($data); $i++
) {
4889 $a = ($a +
1) %
256;
4890 $j = ($j +
$box[$a]) %
256;
4892 $box[$a] = $box[$j];
4894 $k = $box[(($box[$a] +
$box[$j]) %
256)];
4895 $cipherby = ord(substr($data, $i, 1)) ^
$k;
4896 $cipher .= chr($cipherby);
4899 if ($case == 'de') {
4900 $cipher = urldecode(urlencode($cipher));
4902 $cipher = urlencode($cipher);
4909 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
4913 * Call this function to add an event to the calendar table
4914 * and to call any calendar plugins
4917 * @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:
4919 * <li><b>$event->name</b> - Name for the event
4920 * <li><b>$event->description</b> - Description of the event (defaults to '')
4921 * <li><b>$event->format</b> - Format for the description (using formatting types defined at the top of weblib.php)
4922 * <li><b>$event->courseid</b> - The id of the course this event belongs to (0 = all courses)
4923 * <li><b>$event->groupid</b> - The id of the group this event belongs to (0 = no group)
4924 * <li><b>$event->userid</b> - The id of the user this event belongs to (0 = no user)
4925 * <li><b>$event->modulename</b> - Name of the module that creates this event
4926 * <li><b>$event->instance</b> - Instance of the module that owns this event
4927 * <li><b>$event->eventtype</b> - The type info together with the module info could
4928 * be used by calendar plugins to decide how to display event
4929 * <li><b>$event->timestart</b>- Timestamp for start of event
4930 * <li><b>$event->timeduration</b> - Duration (defaults to zero)
4931 * <li><b>$event->visible</b> - 0 if the event should be hidden (e.g. because the activity that created it is hidden)
4933 * @return int The id number of the resulting record
4935 function add_event($event) {
4939 $event->timemodified
= time();
4941 if (!$event->id
= insert_record('event', $event)) {
4945 if (!empty($CFG->calendar
)) { // call the add_event function of the selected calendar
4946 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
4947 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
4948 $calendar_add_event = $CFG->calendar
.'_add_event';
4949 if (function_exists($calendar_add_event)) {
4950 $calendar_add_event($event);
4959 * Call this function to update an event in the calendar table
4960 * the event will be identified by the id field of the $event object.
4963 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
4966 function update_event($event) {
4970 $event->timemodified
= time();
4972 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
4973 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
4974 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
4975 $calendar_update_event = $CFG->calendar
.'_update_event';
4976 if (function_exists($calendar_update_event)) {
4977 $calendar_update_event($event);
4981 return update_record('event', $event);
4985 * Call this function to delete the event with id $id from calendar table.
4988 * @param int $id The id of an event from the 'calendar' table.
4989 * @return array An associative array with the results from the SQL call.
4990 * @todo Verify return type
4992 function delete_event($id) {
4996 if (!empty($CFG->calendar
)) { // call the delete_event function of the selected calendar
4997 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
4998 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
4999 $calendar_delete_event = $CFG->calendar
.'_delete_event';
5000 if (function_exists($calendar_delete_event)) {
5001 $calendar_delete_event($id);
5005 return delete_records('event', 'id', $id);
5009 * Call this function to hide an event in the calendar table
5010 * the event will be identified by the id field of the $event object.
5013 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5014 * @return array An associative array with the results from the SQL call.
5015 * @todo Verify return type
5017 function hide_event($event) {
5020 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
5021 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5022 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5023 $calendar_hide_event = $CFG->calendar
.'_hide_event';
5024 if (function_exists($calendar_hide_event)) {
5025 $calendar_hide_event($event);
5029 return set_field('event', 'visible', 0, 'id', $event->id
);
5033 * Call this function to unhide an event in the calendar table
5034 * the event will be identified by the id field of the $event object.
5037 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5038 * @return array An associative array with the results from the SQL call.
5039 * @todo Verify return type
5041 function show_event($event) {
5044 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
5045 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5046 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5047 $calendar_show_event = $CFG->calendar
.'_show_event';
5048 if (function_exists($calendar_show_event)) {
5049 $calendar_show_event($event);
5053 return set_field('event', 'visible', 1, 'id', $event->id
);
5057 /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
5060 * Lists plugin directories within some directory
5063 * @param string $plugin dir under we'll look for plugins (defaults to 'mod')
5064 * @param string $exclude dir name to exclude from the list (defaults to none)
5065 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
5066 * @return array of plugins found under the requested parameters
5068 function get_list_of_plugins($plugin='mod', $exclude='', $basedir='') {
5074 if (empty($basedir)) {
5076 # This switch allows us to use the appropiate theme directory - and potentialy alternatives for other plugins
5079 $basedir = $CFG->themedir
;
5083 $basedir = $CFG->dirroot
.'/'. $plugin;
5087 $basedir = $basedir .'/'. $plugin;
5090 if (file_exists($basedir) && filetype($basedir) == 'dir') {
5091 $dirhandle = opendir($basedir);
5092 while (false !== ($dir = readdir($dirhandle))) {
5093 $firstchar = substr($dir, 0, 1);
5094 if ($firstchar == '.' or $dir == 'CVS' or $dir == '_vti_cnf' or $dir == $exclude) {
5097 if (filetype($basedir .'/'. $dir) != 'dir') {
5102 closedir($dirhandle);
5111 * Returns true if the current version of PHP is greater that the specified one.
5113 * @param string $version The version of php being tested.
5116 function check_php_version($version='4.1.0') {
5117 return (version_compare(phpversion(), $version) >= 0);
5122 * Checks to see if is a browser matches the specified
5123 * brand and is equal or better version.
5126 * @param string $brand The browser identifier being tested
5127 * @param int $version The version of the browser
5128 * @return bool true if the given version is below that of the detected browser
5130 function check_browser_version($brand='MSIE', $version=5.5) {
5131 if (empty($_SERVER['HTTP_USER_AGENT'])) {
5135 $agent = $_SERVER['HTTP_USER_AGENT'];
5139 case 'Camino': /// Mozilla Firefox browsers
5141 if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
5142 if (version_compare($match[1], $version) >= 0) {
5149 case 'Firefox': /// Mozilla Firefox browsers
5151 if (preg_match("/Firefox\/([0-9\.]+)/i", $agent, $match)) {
5152 if (version_compare($match[1], $version) >= 0) {
5159 case 'Gecko': /// Gecko based browsers
5161 if (substr_count($agent, 'Camino')) {
5162 // MacOS X Camino support
5163 $version = 20041110;
5166 // the proper string - Gecko/CCYYMMDD Vendor/Version
5167 // Faster version and work-a-round No IDN problem.
5168 if (preg_match("/Gecko\/([0-9]+)/i", $agent, $match)) {
5169 if ($match[1] > $version) {
5176 case 'MSIE': /// Internet Explorer
5178 if (strpos($agent, 'Opera')) { // Reject Opera
5181 $string = explode(';', $agent);
5182 if (!isset($string[1])) {
5185 $string = explode(' ', trim($string[1]));
5186 if (!isset($string[0]) and !isset($string[1])) {
5189 if ($string[0] == $brand and (float)$string[1] >= $version ) {
5194 case 'Opera': /// Opera
5196 if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
5197 if (version_compare($match[1], $version) >= 0) {
5203 case 'Safari': /// Safari
5204 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SimbianOS
5205 if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
5207 } elseif (strpos($agent, 'Shiira')) { // Reject Shiira
5209 } elseif (strpos($agent, 'SimbianOS')) { // Reject SimbianOS
5213 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
5214 if (version_compare($match[1], $version) >= 0) {
5227 * This function makes the return value of ini_get consistent if you are
5228 * setting server directives through the .htaccess file in apache.
5229 * Current behavior for value set from php.ini On = 1, Off = [blank]
5230 * Current behavior for value set from .htaccess On = On, Off = Off
5231 * Contributed by jdell @ unr.edu
5233 * @param string $ini_get_arg ?
5235 * @todo Finish documenting this function
5237 function ini_get_bool($ini_get_arg) {
5238 $temp = ini_get($ini_get_arg);
5240 if ($temp == '1' or strtolower($temp) == 'on') {
5247 * Compatibility stub to provide backward compatibility
5249 * Determines if the HTML editor is enabled.
5250 * @deprecated Use {@link can_use_html_editor()} instead.
5252 function can_use_richtext_editor() {
5253 return can_use_html_editor();
5257 * Determines if the HTML editor is enabled.
5259 * This depends on site and user
5260 * settings, as well as the current browser being used.
5262 * @return string|false Returns false if editor is not being used, otherwise
5263 * returns 'MSIE' or 'Gecko'.
5265 function can_use_html_editor() {
5268 if (!empty($USER->htmleditor
) and !empty($CFG->htmleditor
)) {
5269 if (check_browser_version('MSIE', 5.5)) {
5271 } else if (check_browser_version('Gecko', 20030516)) {
5279 * Hack to find out the GD version by parsing phpinfo output
5281 * @return int GD version (1, 2, or 0)
5283 function check_gd_version() {
5286 if (function_exists('gd_info')){
5287 $gd_info = gd_info();
5288 if (substr_count($gd_info['GD Version'], '2.')) {
5290 } else if (substr_count($gd_info['GD Version'], '1.')) {
5297 $phpinfo = ob_get_contents();
5300 $phpinfo = explode("\n", $phpinfo);
5303 foreach ($phpinfo as $text) {
5304 $parts = explode('</td>', $text);
5305 foreach ($parts as $key => $val) {
5306 $parts[$key] = trim(strip_tags($val));
5308 if ($parts[0] == 'GD Version') {
5309 if (substr_count($parts[1], '2.0')) {
5312 $gdversion = intval($parts[1]);
5317 return $gdversion; // 1, 2 or 0
5321 * Determine if moodle installation requires update
5323 * Checks version numbers of main code and all modules to see
5324 * if there are any mismatches
5329 function moodle_needs_upgrading() {
5333 include_once($CFG->dirroot
.'/version.php'); # defines $version and upgrades
5334 if ($CFG->version
) {
5335 if ($version > $CFG->version
) {
5338 if ($mods = get_list_of_plugins('mod')) {
5339 foreach ($mods as $mod) {
5340 $fullmod = $CFG->dirroot
.'/mod/'. $mod;
5341 $module = new object();
5342 if (!is_readable($fullmod .'/version.php')) {
5343 notify('Module "'. $mod .'" is not readable - check permissions');
5346 include_once($fullmod .'/version.php'); # defines $module with version etc
5347 if ($currmodule = get_record('modules', 'name', $mod)) {
5348 if ($module->version
> $currmodule->version
) {
5361 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
5364 * Notify admin users or admin user of any failed logins (since last notification).
5370 function notify_login_failures() {
5373 switch ($CFG->notifyloginfailures
) {
5375 $recip = array(get_admin());
5378 $recip = get_admins();
5382 if (empty($CFG->lastnotifyfailure
)) {
5383 $CFG->lastnotifyfailure
=0;
5386 // we need to deal with the threshold stuff first.
5387 if (empty($CFG->notifyloginthreshold
)) {
5388 $CFG->notifyloginthreshold
= 10; // default to something sensible.
5391 $notifyipsrs = $db->Execute('SELECT ip FROM '. $CFG->prefix
.'log WHERE time > '. $CFG->lastnotifyfailure
.'
5392 AND module=\'login\' AND action=\'error\' GROUP BY ip HAVING count(*) > '. $CFG->notifyloginthreshold
);
5394 $notifyusersrs = $db->Execute('SELECT info FROM '. $CFG->prefix
.'log WHERE time > '. $CFG->lastnotifyfailure
.'
5395 AND module=\'login\' AND action=\'error\' GROUP BY info HAVING count(*) > '. $CFG->notifyloginthreshold
);
5399 while ($row = rs_fetch_next_record($notifyipsrs)) {
5400 $ipstr .= "'". $row->ip
."',";
5402 rs_close($notifyipsrs);
5403 $ipstr = substr($ipstr,0,strlen($ipstr)-1);
5405 if ($notifyusersrs) {
5407 while ($row = rs_fetch_next_record($notifyusersrs)) {
5408 $userstr .= "'". $row->info
."',";
5410 rs_close($notifyusersrs);
5411 $userstr = substr($userstr,0,strlen($userstr)-1);
5414 if (strlen($userstr) > 0 ||
strlen($ipstr) > 0) {
5416 $logs = get_logs('time > '. $CFG->lastnotifyfailure
.' AND module=\'login\' AND action=\'error\' '
5417 .((strlen($ipstr) > 0 && strlen($userstr) > 0) ?
' AND ( ip IN ('. $ipstr .') OR info IN ('. $userstr .') ) '
5418 : ((strlen($ipstr) != 0) ?
' AND ip IN ('. $ipstr .') ' : ' AND info IN ('. $userstr .') ')), 'l.time DESC', '', '', $count);
5420 // if we haven't run in the last hour and we have something useful to report and we are actually supposed to be reporting to somebody
5421 if (is_array($recip) and count($recip) > 0 and ((time() - HOURSECS
) > $CFG->lastnotifyfailure
)
5422 and is_array($logs) and count($logs) > 0) {
5426 $subject = get_string('notifyloginfailuressubject', '', $site->fullname
);
5427 $message .= get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot
)
5428 .(($CFG->lastnotifyfailure
!= 0) ?
'('.userdate($CFG->lastnotifyfailure
).')' : '')."\n\n";
5429 foreach ($logs as $log) {
5430 $log->time
= userdate($log->time
);
5431 $message .= get_string('notifyloginfailuresmessage','',$log)."\n";
5433 $message .= "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot
)."\n\n";
5434 foreach ($recip as $admin) {
5435 mtrace('Emailing '. $admin->username
.' about '. count($logs) .' failed login attempts');
5436 email_to_user($admin,get_admin(),$subject,$message);
5438 $conf = new object();
5439 $conf->name
= 'lastnotifyfailure';
5440 $conf->value
= time();
5441 if ($current = get_record('config', 'name', 'lastnotifyfailure')) {
5442 $conf->id
= $current->id
;
5443 if (! update_record('config', $conf)) {
5444 mtrace('Could not update last notify time');
5447 } else if (! insert_record('config', $conf)) {
5448 mtrace('Could not set last notify time');
5460 * @param string $locale ?
5461 * @todo Finish documenting this function
5463 function moodle_setlocale($locale='') {
5465 global $SESSION, $USER, $CFG;
5467 static $currentlocale; // last locale caching
5468 if (!isset($currentlocale)) {
5469 $currentlocale = '';
5472 $oldlocale = $currentlocale;
5474 /// Fetch the correct locale based on ostype
5475 if($CFG->ostype
== 'WINDOWS') {
5476 $stringtofetch = 'localewin';
5478 $stringtofetch = 'locale';
5481 /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
5482 if (!empty($locale)) {
5483 $currentlocale = $locale;
5484 } else if (!empty($CFG->locale
)) { // override locale for all language packs
5485 $currentlocale = $CFG->locale
;
5487 $currentlocale = get_string($stringtofetch);
5490 /// do nothing if locale already set up
5491 if ($oldlocale == $currentlocale) {
5495 /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
5496 /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
5497 /// Some day, numeric, monetary and other categories should be set too, I think. :-/
5499 /// Get current values
5500 $monetary= setlocale (LC_MONETARY
, 0);
5501 $numeric = setlocale (LC_NUMERIC
, 0);
5502 $ctype = setlocale (LC_CTYPE
, 0);
5503 if ($CFG->ostype
!= 'WINDOWS') {
5504 $messages= setlocale (LC_MESSAGES
, 0);
5506 /// Set locale to all
5507 setlocale (LC_ALL
, $currentlocale);
5509 setlocale (LC_MONETARY
, $monetary);
5510 setlocale (LC_NUMERIC
, $numeric);
5511 if ($CFG->ostype
!= 'WINDOWS') {
5512 setlocale (LC_MESSAGES
, $messages);
5514 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
5515 setlocale (LC_CTYPE
, $ctype);
5520 * Converts string to lowercase using most compatible function available.
5522 * @param string $string The string to convert to all lowercase characters.
5523 * @param string $encoding The encoding on the string.
5525 * @todo Add examples of calling this function with/without encoding types
5526 * @deprecated Use textlib->strtolower($text) instead.
5528 function moodle_strtolower ($string, $encoding='') {
5530 //If not specified use utf8
5531 if (empty($encoding)) {
5532 $encoding = 'UTF-8';
5535 $textlib = textlib_get_instance();
5537 return $textlib->strtolower($string, $encoding);
5541 * Count words in a string.
5543 * Words are defined as things between whitespace.
5545 * @param string $string The text to be searched for words.
5546 * @return int The count of words in the specified string
5548 function count_words($string) {
5549 $string = strip_tags($string);
5550 return count(preg_split("/\w\b/", $string)) - 1;
5553 /** Count letters in a string.
5555 * Letters are defined as chars not in tags and different from whitespace.
5557 * @param string $string The text to be searched for letters.
5558 * @return int The count of letters in the specified text.
5560 function count_letters($string) {
5561 /// Loading the textlib singleton instance. We are going to need it.
5562 $textlib = textlib_get_instance();
5564 $string = strip_tags($string); // Tags are out now
5565 $string = ereg_replace('[[:space:]]*','',$string); //Whitespace are out now
5567 return $textlib->strlen($string);
5571 * Generate and return a random string of the specified length.
5573 * @param int $length The length of the string to be created.
5576 function random_string ($length=15) {
5577 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
5578 $pool .= 'abcdefghijklmnopqrstuvwxyz';
5579 $pool .= '0123456789';
5580 $poollen = strlen($pool);
5581 mt_srand ((double) microtime() * 1000000);
5583 for ($i = 0; $i < $length; $i++
) {
5584 $string .= substr($pool, (mt_rand()%
($poollen)), 1);
5590 * Given some text (which may contain HTML) and an ideal length,
5591 * this function truncates the text neatly on a word boundary if possible
5593 function shorten_text($text, $ideal=30) {
5600 $length = strlen($text);
5605 if ($length <= $ideal) {
5609 for ($i=0; $i<$length; $i++
) {
5622 if ($char == '.' or $char == ' ') {
5625 } else if (ord($char) >= 0xE0) { // Chinese/Japanese/Korean text
5626 $truncate = $i; // can be truncated at any UTF-8
5627 break 2; // character boundary.
5635 if ($count > $ideal) {
5645 $ellipse = ($truncate < $length) ?
'...' : '';
5647 return substr($text, 0, $truncate).$ellipse;
5652 * Given dates in seconds, how many weeks is the date from startdate
5653 * The first week is 1, the second 2 etc ...
5656 * @param ? $startdate ?
5657 * @param ? $thedate ?
5659 * @todo Finish documenting this function
5661 function getweek ($startdate, $thedate) {
5662 if ($thedate < $startdate) { // error
5666 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
5670 * returns a randomly generated password of length $maxlen. inspired by
5671 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3}
5673 * @param int $maxlength The maximum size of the password being generated.
5676 function generate_password($maxlen=10) {
5679 $fillers = '1234567890!$-+';
5680 $wordlist = file($CFG->wordlist
);
5682 srand((double) microtime() * 1000000);
5683 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
5684 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
5685 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
5687 return substr($word1 . $filler1 . $word2, 0, $maxlen);
5691 * Given a float, prints it nicely
5693 * @param float $num The float to print
5694 * @param int $places The number of decimal places to print.
5697 function format_float($num, $places=1) {
5698 return sprintf("%.$places"."f", $num);
5702 * Given a simple array, this shuffles it up just like shuffle()
5703 * Unlike PHP's shuffle() ihis function works on any machine.
5705 * @param array $array The array to be rearranged
5708 function swapshuffle($array) {
5710 srand ((double) microtime() * 10000000);
5711 $last = count($array) - 1;
5712 for ($i=0;$i<=$last;$i++
) {
5713 $from = rand(0,$last);
5715 $array[$i] = $array[$from];
5716 $array[$from] = $curr;
5722 * Like {@link swapshuffle()}, but works on associative arrays
5724 * @param array $array The associative array to be rearranged
5727 function swapshuffle_assoc($array) {
5730 $newkeys = swapshuffle(array_keys($array));
5731 foreach ($newkeys as $newkey) {
5732 $newarray[$newkey] = $array[$newkey];
5738 * Given an arbitrary array, and a number of draws,
5739 * this function returns an array with that amount
5740 * of items. The indexes are retained.
5742 * @param array $array ?
5745 * @todo Finish documenting this function
5747 function draw_rand_array($array, $draws) {
5748 srand ((double) microtime() * 10000000);
5752 $last = count($array);
5754 if ($draws > $last) {
5758 while ($draws > 0) {
5761 $keys = array_keys($array);
5762 $rand = rand(0, $last);
5764 $return[$keys[$rand]] = $array[$keys[$rand]];
5765 unset($array[$keys[$rand]]);
5776 * @param string $a ?
5777 * @param string $b ?
5779 * @todo Finish documenting this function
5781 function microtime_diff($a, $b) {
5782 list($a_dec, $a_sec) = explode(' ', $a);
5783 list($b_dec, $b_sec) = explode(' ', $b);
5784 return $b_sec - $a_sec +
$b_dec - $a_dec;
5788 * Given a list (eg a,b,c,d,e) this function returns
5789 * an array of 1->a, 2->b, 3->c etc
5791 * @param array $list ?
5792 * @param string $separator ?
5793 * @todo Finish documenting this function
5795 function make_menu_from_list($list, $separator=',') {
5797 $array = array_reverse(explode($separator, $list), true);
5798 foreach ($array as $key => $item) {
5799 $outarray[$key+
1] = trim($item);
5805 * Creates an array that represents all the current grades that
5806 * can be chosen using the given grading type. Negative numbers
5807 * are scales, zero is no grade, and positive numbers are maximum
5810 * @param int $gradingtype ?
5812 * @todo Finish documenting this function
5814 function make_grades_menu($gradingtype) {
5816 if ($gradingtype < 0) {
5817 if ($scale = get_record('scale', 'id', - $gradingtype)) {
5818 return make_menu_from_list($scale->scale
);
5820 } else if ($gradingtype > 0) {
5821 for ($i=$gradingtype; $i>=0; $i--) {
5822 $grades[$i] = $i .' / '. $gradingtype;
5830 * This function returns the nummber of activities
5831 * using scaleid in a courseid
5833 * @param int $courseid ?
5834 * @param int $scaleid ?
5836 * @todo Finish documenting this function
5838 function course_scale_used($courseid, $scaleid) {
5844 if (!empty($scaleid)) {
5845 if ($cms = get_course_mods($courseid)) {
5846 foreach ($cms as $cm) {
5847 //Check cm->name/lib.php exists
5848 if (file_exists($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php')) {
5849 include_once($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php');
5850 $function_name = $cm->modname
.'_scale_used';
5851 if (function_exists($function_name)) {
5852 if ($function_name($cm->instance
,$scaleid)) {
5864 * This function returns the nummber of activities
5865 * using scaleid in the entire site
5867 * @param int $scaleid ?
5869 * @todo Finish documenting this function. Is return type correct?
5871 function site_scale_used($scaleid,&$courses) {
5877 if (!is_array($courses) ||
count($courses) == 0) {
5878 $courses = get_courses("all",false,"c.id,c.shortname");
5881 if (!empty($scaleid)) {
5882 if (is_array($courses) && count($courses) > 0) {
5883 foreach ($courses as $course) {
5884 $return +
= course_scale_used($course->id
,$scaleid);
5892 * make_unique_id_code
5894 * @param string $extra ?
5896 * @todo Finish documenting this function
5898 function make_unique_id_code($extra='') {
5900 $hostname = 'unknownhost';
5901 if (!empty($_SERVER['HTTP_HOST'])) {
5902 $hostname = $_SERVER['HTTP_HOST'];
5903 } else if (!empty($_ENV['HTTP_HOST'])) {
5904 $hostname = $_ENV['HTTP_HOST'];
5905 } else if (!empty($_SERVER['SERVER_NAME'])) {
5906 $hostname = $_SERVER['SERVER_NAME'];
5907 } else if (!empty($_ENV['SERVER_NAME'])) {
5908 $hostname = $_ENV['SERVER_NAME'];
5911 $date = gmdate("ymdHis");
5913 $random = random_string(6);
5916 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
5918 return $hostname .'+'. $date .'+'. $random;
5924 * Function to check the passed address is within the passed subnet
5926 * The parameter is a comma separated string of subnet definitions.
5927 * Subnet strings can be in one of three formats:
5928 * 1: xxx.xxx.xxx.xxx/xx
5930 * 3: xxx.xxx.xxx.xxx-xxx //a range of IP addresses in the last group.
5931 * Code for type 1 modified from user posted comments by mediator at
5932 * {@link http://au.php.net/manual/en/function.ip2long.php}
5934 * @param string $addr The address you are checking
5935 * @param string $subnetstr The string of subnet addresses
5938 function address_in_subnet($addr, $subnetstr) {
5940 $subnets = explode(',', $subnetstr);
5942 $addr = trim($addr);
5944 foreach ($subnets as $subnet) {
5945 $subnet = trim($subnet);
5946 if (strpos($subnet, '/') !== false) { /// type 1
5947 list($ip, $mask) = explode('/', $subnet);
5948 $mask = 0xffffffff << (32 - $mask);
5949 $found = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
5950 } else if (strpos($subnet, '-') !== false) {/// type 3
5951 $subnetparts = explode('.', $subnet);
5952 $addrparts = explode('.', $addr);
5953 $subnetrange = explode('-', array_pop($subnetparts));
5954 if (count($subnetrange) == 2) {
5955 $lastaddrpart = array_pop($addrparts);
5956 $found = ($subnetparts == $addrparts &&
5957 $subnetrange[0] <= $lastaddrpart && $lastaddrpart <= $subnetrange[1]);
5960 $found = (strpos($addr, $subnet) === 0);
5971 * This function sets the $HTTPSPAGEREQUIRED global
5972 * (used in some parts of moodle to change some links)
5973 * and calculate the proper wwwroot to be used
5975 * By using this function properly, we can ensure 100% https-ized pages
5976 * at our entire discretion (login, forgot_password, change_password)
5978 function httpsrequired() {
5980 global $CFG, $HTTPSPAGEREQUIRED;
5982 if (!empty($CFG->loginhttps
)) {
5983 $HTTPSPAGEREQUIRED = true;
5984 $CFG->httpswwwroot
= str_replace('http:', 'https:', $CFG->wwwroot
);
5985 $CFG->httpsthemewww
= str_replace('http:', 'https:', $CFG->themewww
);
5987 // change theme URLs to https
5991 $CFG->httpswwwroot
= $CFG->wwwroot
;
5992 $CFG->httpsthemewww
= $CFG->themewww
;
5997 * For outputting debugging info
6000 * @param string $string ?
6001 * @param string $eol ?
6002 * @todo Finish documenting this function
6004 function mtrace($string, $eol="\n", $sleep=0) {
6006 if (defined('STDOUT')) {
6007 fwrite(STDOUT
, $string.$eol);
6009 echo $string . $eol;
6014 //delay to keep message on user's screen in case of subsequent redirect
6020 //Replace 1 or more slashes or backslashes to 1 slash
6021 function cleardoubleslashes ($path) {
6022 return preg_replace('/(\/|\\\){1,}/','/',$path);
6025 function zip_files ($originalfiles, $destination) {
6026 //Zip an array of files/dirs to a destination zip file
6027 //Both parameters must be FULL paths to the files/dirs
6031 //Extract everything from destination
6032 $path_parts = pathinfo(cleardoubleslashes($destination));
6033 $destpath = $path_parts["dirname"]; //The path of the zip file
6034 $destfilename = $path_parts["basename"]; //The name of the zip file
6035 $extension = $path_parts["extension"]; //The extension of the file
6038 if (empty($destfilename)) {
6042 //If no extension, add it
6043 if (empty($extension)) {
6045 $destfilename = $destfilename.'.'.$extension;
6048 //Check destination path exists
6049 if (!is_dir($destpath)) {
6053 //Check destination path is writable. TODO!!
6055 //Clean destination filename
6056 $destfilename = clean_filename($destfilename);
6058 //Now check and prepare every file
6062 foreach ($originalfiles as $file) { //Iterate over each file
6063 //Check for every file
6064 $tempfile = cleardoubleslashes($file); // no doubleslashes!
6065 //Calculate the base path for all files if it isn't set
6066 if ($origpath === NULL) {
6067 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
6069 //See if the file is readable
6070 if (!is_readable($tempfile)) { //Is readable
6073 //See if the file/dir is in the same directory than the rest
6074 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
6077 //Add the file to the array
6078 $files[] = $tempfile;
6081 //Everything is ready:
6082 // -$origpath is the path where ALL the files to be compressed reside (dir).
6083 // -$destpath is the destination path where the zip file will go (dir).
6084 // -$files is an array of files/dirs to compress (fullpath)
6085 // -$destfilename is the name of the zip file (without path)
6087 //print_object($files); //Debug
6089 if (empty($CFG->zip
)) { // Use built-in php-based zip function
6091 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6092 //rewrite filenames because the old method with PCLZIP_OPT_REMOVE_PATH does not work under win32
6093 $zipfiles = array();
6094 $start = strlen($origpath)+
1;
6095 foreach($files as $file) {
6097 $tf[PCLZIP_ATT_FILE_NAME
] = $file;
6098 $tf[PCLZIP_ATT_FILE_NEW_FULL_NAME
] = substr($file, $start);
6101 //create the archive
6102 $archive = new PclZip(cleardoubleslashes("$destpath/$destfilename"));
6103 if (($list = $archive->create($zipfiles) == 0)) {
6104 notice($archive->errorInfo(true));
6108 } else { // Use external zip program
6111 foreach ($files as $filetozip) {
6112 $filestozip .= escapeshellarg(basename($filetozip));
6115 //Construct the command
6116 $separator = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
' &' : ' ;';
6117 $command = 'cd '.escapeshellarg($origpath).$separator.
6118 escapeshellarg($CFG->zip
).' -r '.
6119 escapeshellarg(cleardoubleslashes("$destpath/$destfilename")).' '.$filestozip;
6120 //All converted to backslashes in WIN
6121 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6122 $command = str_replace('/','\\',$command);
6129 function unzip_file ($zipfile, $destination = '', $showstatus = true) {
6130 //Unzip one zip file to a destination dir
6131 //Both parameters must be FULL paths
6132 //If destination isn't specified, it will be the
6133 //SAME directory where the zip file resides.
6137 //Extract everything from zipfile
6138 $path_parts = pathinfo(cleardoubleslashes($zipfile));
6139 $zippath = $path_parts["dirname"]; //The path of the zip file
6140 $zipfilename = $path_parts["basename"]; //The name of the zip file
6141 $extension = $path_parts["extension"]; //The extension of the file
6144 if (empty($zipfilename)) {
6148 //If no extension, error
6149 if (empty($extension)) {
6154 $zipfile = cleardoubleslashes($zipfile);
6156 //Check zipfile exists
6157 if (!file_exists($zipfile)) {
6161 //If no destination, passed let's go with the same directory
6162 if (empty($destination)) {
6163 $destination = $zippath;
6166 //Clear $destination
6167 $destpath = rtrim(cleardoubleslashes($destination), "/");
6169 //Check destination path exists
6170 if (!is_dir($destpath)) {
6174 //Check destination path is writable. TODO!!
6176 //Everything is ready:
6177 // -$zippath is the path where the zip file resides (dir)
6178 // -$zipfilename is the name of the zip file (without path)
6179 // -$destpath is the destination path where the zip file will uncompressed (dir)
6183 if (empty($CFG->unzip
)) { // Use built-in php-based unzip function
6185 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6186 $archive = new PclZip(cleardoubleslashes("$zippath/$zipfilename"));
6187 if (!$list = $archive->extract(PCLZIP_OPT_PATH
, $destpath,
6188 PCLZIP_CB_PRE_EXTRACT
, 'unzip_cleanfilename',
6189 PCLZIP_OPT_EXTRACT_DIR_RESTRICTION
, $destpath)) {
6190 notice($archive->errorInfo(true));
6194 } else { // Use external unzip program
6196 $separator = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
' &' : ' ;';
6197 $redirection = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
'' : ' 2>&1';
6199 $command = 'cd '.escapeshellarg($zippath).$separator.
6200 escapeshellarg($CFG->unzip
).' -o '.
6201 escapeshellarg(cleardoubleslashes("$zippath/$zipfilename")).' -d '.
6202 escapeshellarg($destpath).$redirection;
6203 //All converted to backslashes in WIN
6204 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6205 $command = str_replace('/','\\',$command);
6207 Exec($command,$list);
6210 //Display some info about the unzip execution
6212 unzip_show_status($list,$destpath);
6218 function unzip_cleanfilename ($p_event, &$p_header) {
6219 //This function is used as callback in unzip_file() function
6220 //to clean illegal characters for given platform and to prevent directory traversal.
6221 //Produces the same result as info-zip unzip.
6222 $p_header['filename'] = ereg_replace('[[:cntrl:]]', '', $p_header['filename']); //strip control chars first!
6223 $p_header['filename'] = ereg_replace('\.\.+', '', $p_header['filename']); //directory traversal protection
6224 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6225 $p_header['filename'] = ereg_replace('[:*"?<>|]', '_', $p_header['filename']); //replace illegal chars
6226 $p_header['filename'] = ereg_replace('^([a-zA-Z])_', '\1:', $p_header['filename']); //repair drive letter
6228 //Add filtering for other systems here
6229 // BSD: none (tested)
6233 $p_header['filename'] = cleardoubleslashes($p_header['filename']); //normalize the slashes/backslashes
6237 function unzip_show_status ($list,$removepath) {
6238 //This function shows the results of the unzip execution
6239 //depending of the value of the $CFG->zip, results will be
6240 //text or an array of files.
6244 if (empty($CFG->unzip
)) { // Use built-in php-based zip function
6245 $strname = get_string("name");
6246 $strsize = get_string("size");
6247 $strmodified = get_string("modified");
6248 $strstatus = get_string("status");
6249 echo "<table width=\"640\">";
6250 echo "<tr><th class=\"header\" scope=\"col\">$strname</th>";
6251 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strsize</th>";
6252 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strmodified</th>";
6253 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strstatus</th></tr>";
6254 foreach ($list as $item) {
6256 $item['filename'] = str_replace(cleardoubleslashes($removepath).'/', "", $item['filename']);
6257 print_cell("left", s($item['filename']));
6258 if (! $item['folder']) {
6259 print_cell("right", display_size($item['size']));
6261 echo "<td> </td>";
6263 $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
6264 print_cell("right", $filedate);
6265 print_cell("right", $item['status']);
6270 } else { // Use external zip program
6271 print_simple_box_start("center");
6273 foreach ($list as $item) {
6274 echo s(str_replace(cleardoubleslashes($removepath.'/'), '', $item)).'<br />';
6277 print_simple_box_end();
6282 * Returns most reliable client address
6284 * @return string The remote IP address
6286 function getremoteaddr() {
6287 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
6288 return cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
6290 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
6291 return cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
6293 if (!empty($_SERVER['REMOTE_ADDR'])) {
6294 return cleanremoteaddr($_SERVER['REMOTE_ADDR']);
6300 * Cleans a remote address ready to put into the log table
6302 function cleanremoteaddr($addr) {
6303 $originaladdr = $addr;
6305 // first get all things that look like IP addresses.
6306 if (!preg_match_all('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/',$addr,$matches,PREG_SET_ORDER
)) {
6309 $goodmatches = array();
6310 $lanmatches = array();
6311 foreach ($matches as $match) {
6313 // check to make sure it's not an internal address.
6314 // the following are reserved for private lans...
6315 // 10.0.0.0 - 10.255.255.255
6316 // 172.16.0.0 - 172.31.255.255
6317 // 192.168.0.0 - 192.168.255.255
6318 // 169.254.0.0 -169.254.255.255
6319 $bits = explode('.',$match[0]);
6320 if (count($bits) != 4) {
6321 // weird, preg match shouldn't give us it.
6324 if (($bits[0] == 10)
6325 ||
($bits[0] == 172 && $bits[1] >= 16 && $bits[1] <= 31)
6326 ||
($bits[0] == 192 && $bits[1] == 168)
6327 ||
($bits[0] == 169 && $bits[1] == 254)) {
6328 $lanmatches[] = $match[0];
6332 $goodmatches[] = $match[0];
6334 if (!count($goodmatches)) {
6335 // perhaps we have a lan match, it's probably better to return that.
6336 if (!count($lanmatches)) {
6339 return array_pop($lanmatches);
6342 if (count($goodmatches) == 1) {
6343 return $goodmatches[0];
6345 error_log("NOTICE: cleanremoteaddr gives us something funny: $originaladdr had ".count($goodmatches)." matches");
6346 // we need to return something, so
6347 return array_pop($goodmatches);
6351 * file_put_contents is only supported by php 5.0 and higher
6352 * so if it is not predefined, define it here
6354 * @param $file full path of the file to write
6355 * @param $contents contents to be sent
6356 * @return number of bytes written (false on error)
6358 if(!function_exists('file_put_contents')) {
6359 function file_put_contents($file, $contents) {
6361 if ($f = fopen($file, 'w')) {
6362 $result = fwrite($f, $contents);
6370 * The clone keyword is only supported from PHP 5 onwards.
6371 * The behaviour of $obj2 = $obj1 differs fundamentally
6372 * between PHP 4 and PHP 5. In PHP 4 a copy of $obj1 was
6373 * created, in PHP 5 $obj1 is referenced. To create a copy
6374 * in PHP 5 the clone keyword was introduced. This function
6375 * simulates this behaviour for PHP < 5.0.0.
6376 * See also: http://mjtsai.com/blog/2004/07/15/php-5-object-references/
6378 * Modified 2005-09-29 by Eloy (from Julian Sedding proposal)
6379 * Found a better implementation (more checks and possibilities) from PEAR:
6380 * http://cvs.php.net/co.php/pear/PHP_Compat/Compat/Function/clone.php
6382 * @param object $obj
6385 if(!check_php_version('5.0.0')) {
6386 // the eval is needed to prevent PHP 5 from getting a parse error!
6388 function clone($obj) {
6390 if (!is_object($obj)) {
6391 user_error(\'clone() __clone method called on non-object\', E_USER_WARNING);
6395 /// Use serialize/unserialize trick to deep copy the object
6396 $obj = unserialize(serialize($obj));
6398 /// If there is a __clone method call it on the "new" class
6399 if (method_exists($obj, \'__clone\')) {
6406 // Supply the PHP5 function scandir() to older versions.
6407 function scandir($directory) {
6409 if ($dh = opendir($directory)) {
6410 while (($file = readdir($dh)) !== false) {
6418 // Supply the PHP5 function array_combine() to older versions.
6419 function array_combine($keys, $values) {
6420 if (!is_array($keys) || !is_array($values) || count($keys) != count($values)) {
6425 foreach ($keys as $key) {
6426 $result[$key] = current($values);
6435 * This function will make a complete copy of anything it's given,
6436 * regardless of whether it's an object or not.
6437 * @param mixed $thing
6440 function fullclone($thing) {
6441 return unserialize(serialize($thing));
6446 * If new messages are waiting for the current user, then return
6447 * Javascript code to create a popup window
6449 * @return string Javascript code
6451 function message_popup_window() {
6454 $popuplimit = 30; // Minimum seconds between popups
6456 if (!defined('MESSAGE_WINDOW')) {
6457 if (isset($USER->id
)) {
6458 if (!isset($USER->message_lastpopup
)) {
6459 $USER->message_lastpopup
= 0;
6461 if ((time() - $USER->message_lastpopup
) > $popuplimit) { /// It's been long enough
6462 if (get_user_preferences('message_showmessagewindow', 1) == 1) {
6463 if (count_records_select('message', 'useridto = \''.$USER->id
.'\' AND timecreated > \''.$USER->message_lastpopup
.'\'')) {
6464 $USER->message_lastpopup
= time();
6465 return '<script type="text/javascript">'."\n//<![CDATA[\n openpopup('/message/index.php', 'message',
6466 'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500', 0);\n//]]>\n</script>";
6476 // Used to make sure that $min <= $value <= $max
6477 function bounded_number($min, $value, $max) {
6487 function array_is_nested($array) {
6488 foreach ($array as $value) {
6489 if (is_array($value)) {
6497 *** get_performance_info() pairs up with init_performance_info()
6498 *** loaded in setup.php. Returns an array with 'html' and 'txt'
6499 *** values ready for use, and each of the individual stats provided
6500 *** separately as well.
6503 function get_performance_info() {
6504 global $CFG, $PERF, $rcache;
6507 $info['html'] = ''; // holds userfriendly HTML representation
6508 $info['txt'] = me() . ' '; // holds log-friendly representation
6510 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
6512 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
6513 $info['txt'] .= 'time: '.$info['realtime'].'s ';
6515 if (function_exists('memory_get_usage')) {
6516 $info['memory_total'] = memory_get_usage();
6517 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
6518 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
6519 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
6522 $inc = get_included_files();
6523 //error_log(print_r($inc,1));
6524 $info['includecount'] = count($inc);
6525 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
6526 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
6528 if (!empty($PERF->dbqueries
)) {
6529 $info['dbqueries'] = $PERF->dbqueries
;
6530 $info['html'] .= '<span class="dbqueries">DB queries '.$info['dbqueries'].'</span> ';
6531 $info['txt'] .= 'dbqueries: '.$info['dbqueries'].' ';
6534 if (!empty($PERF->logwrites
)) {
6535 $info['logwrites'] = $PERF->logwrites
;
6536 $info['html'] .= '<span class="logwrites">Log writes '.$info['logwrites'].'</span> ';
6537 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
6540 if (function_exists('posix_times')) {
6541 $ptimes = posix_times();
6542 if (is_array($ptimes)) {
6543 foreach ($ptimes as $key => $val) {
6544 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
6546 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
6547 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
6551 // Grab the load average for the last minute
6552 // /proc will only work under some linux configurations
6553 // while uptime is there under MacOSX/Darwin and other unices
6554 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
6555 list($server_load) = explode(' ', $loadavg[0]);
6557 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
6558 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
6559 $server_load = $matches[1];
6561 trigger_error('Could not parse uptime output!');
6564 if (!empty($server_load)) {
6565 $info['serverload'] = $server_load;
6566 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
6567 $info['txt'] .= "serverload: {$info['serverload']} ";
6570 if (isset($rcache->hits
) && isset($rcache->misses
)) {
6571 $info['rcachehits'] = $rcache->hits
;
6572 $info['rcachemisses'] = $rcache->misses
;
6573 $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
6574 "{$rcache->hits}/{$rcache->misses}</span> ";
6575 $info['txt'] .= 'rcache: '.
6576 "{$rcache->hits}/{$rcache->misses} ";
6578 $info['html'] = '<div class="performanceinfo">'.$info['html'].'</div>';
6583 function remove_dir($dir, $content_only=false) {
6584 // if content_only=true then delete all but
6585 // the directory itself
6587 $handle = opendir($dir);
6588 while (false!==($item = readdir($handle))) {
6589 if($item != '.' && $item != '..') {
6590 if(is_dir($dir.'/'.$item)) {
6591 remove_dir($dir.'/'.$item);
6593 unlink($dir.'/'.$item);
6598 if ($content_only) {
6605 * Function to check if a directory exists and optionally create it.
6607 * @param string absolute directory path
6608 * @param boolean create directory if does not exist
6609 * @param boolean create directory recursively
6611 * @return boolean true if directory exists or created
6613 function check_dir_exists($dir, $create=false, $recursive=false) {
6625 // PHP 5.0 has recursive mkdir parameter, but 4.x does not :-(
6626 $dir = str_replace('\\', '/', $dir); //windows compatibility
6627 $dirs = explode('/', $dir);
6628 $dir = array_shift($dirs).'/'; //skip root or drive letter
6629 foreach ($dirs as $part) {
6634 if (!is_dir($dir)) {
6635 if (!mkdir($dir, $CFG->directorypermissions
)) {
6642 $status = mkdir($dir, $CFG->directorypermissions
);
6649 function report_session_error() {
6650 global $CFG, $FULLME;
6652 if (empty($CFG->lang
)) {
6655 // Set up default theme and locale
6659 //clear session cookies
6660 setcookie('MoodleSession'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
6661 setcookie('MoodleSessionTest'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
6662 //increment database error counters
6663 if (isset($CFG->session_error_counter
)) {
6664 set_config('session_error_counter', 1 +
$CFG->session_error_counter
);
6666 set_config('session_error_counter', 1);
6668 redirect($FULLME, get_string('sessionerroruser2', 'error'), 5);
6673 * Detect if an object or a class contains a given property
6674 * will take an actual object or the name of a class
6675 * @param mix $obj Name of class or real object to test
6676 * @param string $property name of property to find
6677 * @return bool true if property exists
6679 function object_property_exists( $obj, $property ) {
6680 if (is_string( $obj )) {
6681 $properties = get_class_vars( $obj );
6684 $properties = get_object_vars( $obj );
6686 return array_key_exists( $property, $properties );
6691 * Detect a custom script replacement in the data directory that will
6692 * replace an existing moodle script
6693 * @param string $urlpath path to the original script
6694 * @return string full path name if a custom script exists
6695 * @return bool false if no custom script exists
6697 function custom_script_path($urlpath='') {
6700 // set default $urlpath, if necessary
6701 if (empty($urlpath)) {
6702 $urlpath = qualified_me(); // e.g. http://www.this-server.com/moodle/this-script.php
6705 // $urlpath is invalid if it is empty or does not start with the Moodle wwwroot
6706 if (empty($urlpath) or (strpos($urlpath, $CFG->wwwroot
) === false )) {
6710 // replace wwwroot with the path to the customscripts folder and clean path
6711 $scriptpath = $CFG->customscripts
. clean_param(substr($urlpath, strlen($CFG->wwwroot
)), PARAM_PATH
);
6713 // remove the query string, if any
6714 if (($strpos = strpos($scriptpath, '?')) !== false) {
6715 $scriptpath = substr($scriptpath, 0, $strpos);
6718 // remove trailing slashes, if any
6719 $scriptpath = rtrim($scriptpath, '/\\');
6721 // append index.php, if necessary
6722 if (is_dir($scriptpath)) {
6723 $scriptpath .= '/index.php';
6726 // check the custom script exists
6727 if (file_exists($scriptpath)) {
6735 * Wrapper function to load necessary editor scripts
6736 * to $CFG->editorsrc array. Params can be coursei id
6737 * or associative array('courseid' => value, 'name' => 'editorname').
6739 * @param mixed $args Courseid or associative array.
6741 function loadeditor($args) {
6743 include($CFG->libdir
.'/editorlib.php');
6744 return editorObject
::loadeditor($args);
6748 * Returns whether or not the user object is a remote MNET user. This function
6749 * is in moodlelib because it does not rely on loading any of the MNET code.
6751 * @param object $user A valid user object
6752 * @return bool True if the user is from a remote Moodle.
6754 function is_mnet_remote_user($user) {
6757 if (!isset($CFG->mnet_localhost_id
)) {
6758 include_once $CFG->dirroot
. '/mnet/lib.php';
6759 $env = new mnet_environment();
6764 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
6768 * Checks if a given plugin is in the list of enabled enrolment plugins.
6770 * @param string $auth Enrolment plugin.
6771 * @return boolean Whether the plugin is enabled.
6773 function is_enabled_enrol($enrol='') {
6776 // use the global default if not specified
6778 $enrol = $CFG->enrol
;
6780 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled
));
6784 * This function will search for browser prefereed languages, setting Moodle
6785 * to use the best one available if $SESSION->lang is undefined
6787 function setup_lang_from_browser() {
6789 global $CFG, $SESSION, $USER;
6791 if (!empty($SESSION->lang
) or !empty($USER->lang
)) {
6792 // Lang is defined in session or user profile, nothing to do
6796 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
6800 /// Extract and clean langs from headers
6801 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
6802 $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
6803 $rawlangs = explode(',', $rawlangs); // Convert to array
6807 foreach ($rawlangs as $lang) {
6808 if (strpos($lang, ';') === false) {
6809 $langs[(string)$order] = $lang;
6810 $order = $order-0.01;
6812 $parts = explode(';', $lang);
6813 $pos = strpos($parts[1], '=');
6814 $langs[substr($parts[1], $pos+
1)] = $parts[0];
6817 krsort($langs, SORT_NUMERIC
);
6819 /// Look for such langs under standard locations
6820 foreach ($langs as $lang) {
6821 $lang = clean_param($lang.'_utf8', PARAM_SAFEDIR
); // clean it properly for include
6822 if (file_exists($CFG->dataroot
.'/lang/'. $lang) or file_exists($CFG->dirroot
.'/lang/'. $lang)) {
6823 $SESSION->lang
= $lang; /// Lang exists, set it in session
6824 break; /// We have finished. Go out
6830 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: