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 if (empty($format)) {
1009 $format = get_string('strftimedaydatetime');
1012 if (!empty($CFG->nofixday
)) { // Config.php can force %d not to be fixed.
1014 } else if ($fixday) {
1015 $formatnoday = str_replace('%d', 'DD', $format);
1016 $fixday = ($formatnoday != $format);
1019 $date +
= dst_offset_on($date);
1021 $timezone = get_user_timezone_offset($timezone);
1023 if (abs($timezone) > 13) { /// Server time
1025 $datestring = strftime($formatnoday, $date);
1026 $daystring = str_replace(' 0', '', strftime(' %d', $date));
1027 $datestring = str_replace('DD', $daystring, $datestring);
1029 $datestring = strftime($format, $date);
1032 $date +
= (int)($timezone * 3600);
1034 $datestring = gmstrftime($formatnoday, $date);
1035 $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
1036 $datestring = str_replace('DD', $daystring, $datestring);
1038 $datestring = gmstrftime($format, $date);
1042 /// If we are running under Windows convert from windows encoding to UTF-8
1043 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1045 if ($CFG->ostype
== 'WINDOWS') {
1046 if ($localewincharset = get_string('localewincharset')) {
1047 $textlib = textlib_get_instance();
1048 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1056 * Given a $time timestamp in GMT (seconds since epoch),
1057 * returns an array that represents the date in user time
1060 * @param int $time Timestamp in GMT
1061 * @param float $timezone ?
1062 * @return array An array that represents the date in user time
1063 * @todo Finish documenting this function
1065 function usergetdate($time, $timezone=99) {
1067 $timezone = get_user_timezone_offset($timezone);
1069 if (abs($timezone) > 13) { // Server time
1070 return getdate($time);
1073 // There is no gmgetdate so we use gmdate instead
1074 $time +
= dst_offset_on($time);
1075 $time +
= intval((float)$timezone * HOURSECS
);
1077 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
1080 $getdate['seconds'],
1081 $getdate['minutes'],
1088 $getdate['weekday'],
1090 ) = explode('_', $datestring);
1096 * Given a GMT timestamp (seconds since epoch), offsets it by
1097 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1100 * @param int $date Timestamp in GMT
1101 * @param float $timezone
1104 function usertime($date, $timezone=99) {
1106 $timezone = get_user_timezone_offset($timezone);
1108 if (abs($timezone) > 13) {
1111 return $date - (int)($timezone * HOURSECS
);
1115 * Given a time, return the GMT timestamp of the most recent midnight
1116 * for the current user.
1118 * @param int $date Timestamp in GMT
1119 * @param float $timezone ?
1122 function usergetmidnight($date, $timezone=99) {
1124 $timezone = get_user_timezone_offset($timezone);
1125 $userdate = usergetdate($date, $timezone);
1127 // Time of midnight of this user's day, in GMT
1128 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1133 * Returns a string that prints the user's timezone
1135 * @param float $timezone The user's timezone
1138 function usertimezone($timezone=99) {
1140 $tz = get_user_timezone($timezone);
1142 if (!is_float($tz)) {
1146 if(abs($tz) > 13) { // Server time
1147 return get_string('serverlocaltime');
1150 if($tz == intval($tz)) {
1151 // Don't show .0 for whole hours
1168 * Returns a float which represents the user's timezone difference from GMT in hours
1169 * Checks various settings and picks the most dominant of those which have a value
1173 * @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
1176 function get_user_timezone_offset($tz = 99) {
1180 $tz = get_user_timezone($tz);
1182 if (is_float($tz)) {
1185 $tzrecord = get_timezone_record($tz);
1186 if (empty($tzrecord)) {
1189 return (float)$tzrecord->gmtoff
/ HOURMINS
;
1194 * Returns a float or a string which denotes the user's timezone
1195 * 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)
1196 * means that for this timezone there are also DST rules to be taken into account
1197 * Checks various settings and picks the most dominant of those which have a value
1201 * @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
1204 function get_user_timezone($tz = 99) {
1209 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
1210 isset($USER->timezone
) ?
$USER->timezone
: 99,
1211 isset($CFG->timezone
) ?
$CFG->timezone
: 99,
1216 while(($tz == '' ||
$tz == 99) && $next = each($timezones)) {
1217 $tz = $next['value'];
1220 return is_numeric($tz) ?
(float) $tz : $tz;
1228 * @param string $timezonename ?
1231 function get_timezone_record($timezonename) {
1233 static $cache = NULL;
1235 if ($cache === NULL) {
1239 if (isset($cache[$timezonename])) {
1240 return $cache[$timezonename];
1243 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix
.'timezone
1244 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
1252 * @param ? $fromyear ?
1253 * @param ? $to_year ?
1256 function calculate_user_dst_table($from_year = NULL, $to_year = NULL) {
1257 global $CFG, $SESSION;
1259 $usertz = get_user_timezone();
1261 if (is_float($usertz)) {
1262 // Trivial timezone, no DST
1266 if (!empty($SESSION->dst_offsettz
) && $SESSION->dst_offsettz
!= $usertz) {
1267 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1268 unset($SESSION->dst_offsets
);
1269 unset($SESSION->dst_range
);
1272 if (!empty($SESSION->dst_offsets
) && empty($from_year) && empty($to_year)) {
1273 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1274 // This will be the return path most of the time, pretty light computationally
1278 // Reaching here means we either need to extend our table or create it from scratch
1280 // Remember which TZ we calculated these changes for
1281 $SESSION->dst_offsettz
= $usertz;
1283 if(empty($SESSION->dst_offsets
)) {
1284 // If we 're creating from scratch, put the two guard elements in there
1285 $SESSION->dst_offsets
= array(1 => NULL, 0 => NULL);
1287 if(empty($SESSION->dst_range
)) {
1288 // If creating from scratch
1289 $from = max((empty($from_year) ?
intval(date('Y')) - 3 : $from_year), 1971);
1290 $to = min((empty($to_year) ?
intval(date('Y')) +
3 : $to_year), 2035);
1292 // Fill in the array with the extra years we need to process
1293 $yearstoprocess = array();
1294 for($i = $from; $i <= $to; ++
$i) {
1295 $yearstoprocess[] = $i;
1298 // Take note of which years we have processed for future calls
1299 $SESSION->dst_range
= array($from, $to);
1302 // If needing to extend the table, do the same
1303 $yearstoprocess = array();
1305 $from = max((empty($from_year) ?
$SESSION->dst_range
[0] : $from_year), 1971);
1306 $to = min((empty($to_year) ?
$SESSION->dst_range
[1] : $to_year), 2035);
1308 if($from < $SESSION->dst_range
[0]) {
1309 // Take note of which years we need to process and then note that we have processed them for future calls
1310 for($i = $from; $i < $SESSION->dst_range
[0]; ++
$i) {
1311 $yearstoprocess[] = $i;
1313 $SESSION->dst_range
[0] = $from;
1315 if($to > $SESSION->dst_range
[1]) {
1316 // Take note of which years we need to process and then note that we have processed them for future calls
1317 for($i = $SESSION->dst_range
[1] +
1; $i <= $to; ++
$i) {
1318 $yearstoprocess[] = $i;
1320 $SESSION->dst_range
[1] = $to;
1324 if(empty($yearstoprocess)) {
1325 // This means that there was a call requesting a SMALLER range than we have already calculated
1329 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1330 // Also, the array is sorted in descending timestamp order!
1333 $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');
1334 if(empty($presetrecords)) {
1338 // Remove ending guard (first element of the array)
1339 reset($SESSION->dst_offsets
);
1340 unset($SESSION->dst_offsets
[key($SESSION->dst_offsets
)]);
1342 // Add all required change timestamps
1343 foreach($yearstoprocess as $y) {
1344 // Find the record which is in effect for the year $y
1345 foreach($presetrecords as $year => $preset) {
1351 $changes = dst_changes_for_year($y, $preset);
1353 if($changes === NULL) {
1356 if($changes['dst'] != 0) {
1357 $SESSION->dst_offsets
[$changes['dst']] = $preset->dstoff
* MINSECS
;
1359 if($changes['std'] != 0) {
1360 $SESSION->dst_offsets
[$changes['std']] = 0;
1364 // Put in a guard element at the top
1365 $maxtimestamp = max(array_keys($SESSION->dst_offsets
));
1366 $SESSION->dst_offsets
[($maxtimestamp + DAYSECS
)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1369 krsort($SESSION->dst_offsets
);
1374 function dst_changes_for_year($year, $timezone) {
1376 if($timezone->dst_startday
== 0 && $timezone->dst_weekday
== 0 && $timezone->std_startday
== 0 && $timezone->std_weekday
== 0) {
1380 $monthdaydst = find_day_in_month($timezone->dst_startday
, $timezone->dst_weekday
, $timezone->dst_month
, $year);
1381 $monthdaystd = find_day_in_month($timezone->std_startday
, $timezone->std_weekday
, $timezone->std_month
, $year);
1383 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time
);
1384 list($std_hour, $std_min) = explode(':', $timezone->std_time
);
1386 $timedst = make_timestamp($year, $timezone->dst_month
, $monthdaydst, 0, 0, 0, 99, false);
1387 $timestd = make_timestamp($year, $timezone->std_month
, $monthdaystd, 0, 0, 0, 99, false);
1389 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1390 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1391 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1393 $timedst +
= $dst_hour * HOURSECS +
$dst_min * MINSECS
;
1394 $timestd +
= $std_hour * HOURSECS +
$std_min * MINSECS
;
1396 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1399 // $time must NOT be compensated at all, it has to be a pure timestamp
1400 function dst_offset_on($time) {
1403 if(!calculate_user_dst_table() ||
empty($SESSION->dst_offsets
)) {
1407 reset($SESSION->dst_offsets
);
1408 while(list($from, $offset) = each($SESSION->dst_offsets
)) {
1409 if($from <= $time) {
1414 // This is the normal return path
1415 if($offset !== NULL) {
1419 // Reaching this point means we haven't calculated far enough, do it now:
1420 // Calculate extra DST changes if needed and recurse. The recursion always
1421 // moves toward the stopping condition, so will always end.
1424 // We need a year smaller than $SESSION->dst_range[0]
1425 if($SESSION->dst_range
[0] == 1971) {
1428 calculate_user_dst_table($SESSION->dst_range
[0] - 5, NULL);
1429 return dst_offset_on($time);
1432 // We need a year larger than $SESSION->dst_range[1]
1433 if($SESSION->dst_range
[1] == 2035) {
1436 calculate_user_dst_table(NULL, $SESSION->dst_range
[1] +
5);
1437 return dst_offset_on($time);
1441 function find_day_in_month($startday, $weekday, $month, $year) {
1443 $daysinmonth = days_in_month($month, $year);
1445 if($weekday == -1) {
1446 // Don't care about weekday, so return:
1447 // abs($startday) if $startday != -1
1448 // $daysinmonth otherwise
1449 return ($startday == -1) ?
$daysinmonth : abs($startday);
1452 // From now on we 're looking for a specific weekday
1454 // Give "end of month" its actual value, since we know it
1455 if($startday == -1) {
1456 $startday = -1 * $daysinmonth;
1459 // Starting from day $startday, the sign is the direction
1463 $startday = abs($startday);
1464 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1466 // This is the last such weekday of the month
1467 $lastinmonth = $daysinmonth +
$weekday - $lastmonthweekday;
1468 if($lastinmonth > $daysinmonth) {
1472 // Find the first such weekday <= $startday
1473 while($lastinmonth > $startday) {
1477 return $lastinmonth;
1482 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
1484 $diff = $weekday - $indexweekday;
1489 // This is the first such weekday of the month equal to or after $startday
1490 $firstfromindex = $startday +
$diff;
1492 return $firstfromindex;
1498 * Calculate the number of days in a given month
1500 * @param int $month The month whose day count is sought
1501 * @param int $year The year of the month whose day count is sought
1504 function days_in_month($month, $year) {
1505 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1509 * Calculate the position in the week of a specific calendar day
1511 * @param int $day The day of the date whose position in the week is sought
1512 * @param int $month The month of the date whose position in the week is sought
1513 * @param int $year The year of the date whose position in the week is sought
1516 function dayofweek($day, $month, $year) {
1517 // I wonder if this is any different from
1518 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1519 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1522 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
1525 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1526 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1527 * sesskey string if $USER exists, or boolean false if not.
1532 function sesskey() {
1539 if (empty($USER->sesskey
)) {
1540 $USER->sesskey
= random_string(10);
1543 return $USER->sesskey
;
1548 * For security purposes, this function will check that the currently
1549 * given sesskey (passed as a parameter to the script or this function)
1550 * matches that of the current user.
1552 * @param string $sesskey optionally provided sesskey
1555 function confirm_sesskey($sesskey=NULL) {
1558 if (!empty($USER->ignoresesskey
) ||
!empty($CFG->ignoresesskey
)) {
1562 if (empty($sesskey)) {
1563 $sesskey = required_param('sesskey', PARAM_RAW
); // Check script parameters
1566 if (!isset($USER->sesskey
)) {
1570 return ($USER->sesskey
=== $sesskey);
1574 * Setup all global $CFG course variables, set locale and also themes
1575 * This function can be used on pages that do not require login instead of require_login()
1577 * @param mixed $courseorid id of the course or course object
1579 function course_setup($courseorid=0) {
1580 global $COURSE, $CFG, $SITE;
1582 /// Redefine global $COURSE if needed
1583 if (empty($courseorid)) {
1584 // no change in global $COURSE - for backwards compatibiltiy
1585 // if require_rogin() used after require_login($courseid);
1586 } else if (is_object($courseorid)) {
1587 $COURSE = clone($courseorid);
1589 global $course; // used here only to prevent repeated fetching from DB - may be removed later
1590 if (!empty($course->id
) and $course->id
== SITEID
) {
1591 $COURSE = clone($SITE);
1592 } else if (!empty($course->id
) and $course->id
== $courseorid) {
1593 $COURSE = clone($course);
1595 if (!$COURSE = get_record('course', 'id', $courseorid)) {
1596 error('Invalid course ID');
1601 /// set locale and themes
1608 * This function checks that the current user is logged in and has the
1609 * required privileges
1611 * This function checks that the current user is logged in, and optionally
1612 * whether they are allowed to be in a particular course and view a particular
1614 * If they are not logged in, then it redirects them to the site login unless
1615 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
1616 * case they are automatically logged in as guests.
1617 * If $courseid is given and the user is not enrolled in that course then the
1618 * user is redirected to the course enrolment page.
1619 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1620 * in the course then the user is redirected to the course home page.
1628 * @param mixed $courseorid id of the course or course object
1629 * @param bool $autologinguest
1630 * @param object $cm course module object
1632 function require_login($courseorid=0, $autologinguest=true, $cm=null) {
1634 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
1636 /// setup global $COURSE, themes, language and locale
1637 course_setup($courseorid);
1639 /// If the user is not even logged in yet then make sure they are
1640 if (!isloggedin()) {
1641 //NOTE: $USER->site check was obsoleted by session test cookie,
1642 // $USER->confirmed test is in login/index.php
1643 $SESSION->wantsurl
= $FULLME;
1644 if (!empty($_SERVER['HTTP_REFERER'])) {
1645 $SESSION->fromurl
= $_SERVER['HTTP_REFERER'];
1647 if ($autologinguest and !empty($CFG->autologinguests
) and ($COURSE->id
== SITEID
or $COURSE->guest
) ) {
1648 $loginguest = '?loginguest=true';
1652 if (empty($CFG->loginhttps
) or $autologinguest) { //do not require https for guest logins
1653 redirect($CFG->wwwroot
.'/login/index.php'. $loginguest);
1655 $wwwroot = str_replace('http:','https:', $CFG->wwwroot
);
1656 redirect($wwwroot .'/login/index.php');
1661 /// loginas as redirection if needed
1662 if ($COURSE->id
!= SITEID
and !empty($USER->realuser
)) {
1663 if ($USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
1664 if ($USER->loginascontext
->instanceid
!= $COURSE->id
) {
1665 print_error('loginascourseredir', '', $CFG->wwwroot
.'/course/view.php?id='.$USER->loginascontext
->instanceid
);
1671 /// check whether the user should be changing password (but only if it is REALLY them)
1672 $userauth = get_auth_plugin($USER->auth
);
1673 if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser
)) {
1674 if ($userauth->can_change_password()) {
1675 $SESSION->wantsurl
= $FULLME;
1676 if (method_exists($userauth, 'change_password_url') and $userauth->change_password_url()) {
1677 //use plugin custom url
1678 redirect($userauth->change_password_url());
1680 //use moodle internal method
1681 if (empty($CFG->loginhttps
)) {
1682 redirect($CFG->wwwroot
.'/login/change_password.php');
1684 $wwwroot = str_replace('http:','https:', $CFG->wwwroot
);
1685 redirect($wwwroot .'/login/change_password.php');
1689 error(get_strin('nopasswordchangeforced', 'auth'));
1693 /// Check that the user account is properly set up
1694 if (user_not_fully_set_up($USER)) {
1695 $SESSION->wantsurl
= $FULLME;
1696 redirect($CFG->wwwroot
.'/user/edit.php?id='. $USER->id
.'&course='. SITEID
);
1699 /// Make sure current IP matches the one for this session (if required)
1700 if (!empty($CFG->tracksessionip
)) {
1701 if ($USER->sessionIP
!= md5(getremoteaddr())) {
1702 error(get_string('sessionipnomatch', 'error'));
1706 /// Make sure the USER has a sesskey set up. Used for checking script parameters.
1709 // Check that the user has agreed to a site policy if there is one
1710 if (!empty($CFG->sitepolicy
)) {
1711 if (!$USER->policyagreed
) {
1712 $SESSION->wantsurl
= $FULLME;
1713 redirect($CFG->wwwroot
.'/user/policy.php');
1717 /// If the site is currently under maintenance, then print a message
1718 if (!has_capability('moodle/site:config',get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
1719 if (file_exists($CFG->dataroot
.'/'.SITEID
.'/maintenance.html')) {
1720 print_maintenance_message();
1726 if ($COURSE->id
== SITEID
) {
1727 /// We can eliminate hidden site activities straight away
1728 if (!empty($cm) && !$cm->visible
and !has_capability('moodle/course:viewhiddenactivities',
1729 get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
1730 redirect($CFG->wwwroot
, get_string('activityiscurrentlyhidden'));
1735 /// Check if the user can be in a particular course
1736 if (!$context = get_context_instance(CONTEXT_COURSE
, $COURSE->id
)) {
1737 print_error('nocontext');
1740 if (empty($USER->switchrole
[$context->id
]) &&
1741 !($COURSE->visible
&& course_parent_visible($COURSE)) &&
1742 !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $COURSE->id
)) ){
1743 print_header_simple();
1744 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
1747 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1749 if ($USER->username
!= 'guest' and !has_capability('moodle/course:view', $context)) {
1750 if ($COURSE->guest
== 1) {
1751 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
1752 has_capability('clearcache'); // Must clear cache
1753 $guestcaps = get_role_context_caps($CFG->guestroleid
, $context);
1754 $USER->capabilities
= merge_role_caps($USER->capabilities
, $guestcaps);
1758 /// If the user is a guest then treat them according to the course policy about guests
1760 if (has_capability('moodle/legacy:guest', $context, NULL, false)) {
1761 switch ($COURSE->guest
) { /// Check course policy about guest access
1763 case 1: /// Guests always allowed
1764 if (!has_capability('moodle/course:view', $context)) { // Prohibited by capability
1765 print_header_simple();
1766 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)), "$CFG->wwwroot/login/index.php");
1768 if (!empty($cm) and !$cm->visible
) { // Not allowed to see module, send to course page
1769 redirect($CFG->wwwroot
.'/course/view.php?id='.$cm->course
,
1770 get_string('activityiscurrentlyhidden'));
1773 return; // User is allowed to see this course
1777 case 2: /// Guests allowed with key
1778 if (!empty($USER->enrolkey
[$COURSE->id
])) { // Set by enrol/manual/enrol.php
1781 // otherwise drop through to logic below (--> enrol.php)
1784 default: /// Guests not allowed
1785 print_header_simple('', '', get_string('loggedinasguest'));
1786 if (empty($USER->switchrole
[$context->id
])) { // Normal guest
1787 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)), "$CFG->wwwroot/login/index.php");
1789 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)));
1790 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id
).'</div>';
1791 print_footer($COURSE);
1797 /// For non-guests, check if they have course view access
1799 } else if (has_capability('moodle/course:view', $context)) {
1800 if (!empty($USER->realuser
)) { // Make sure the REAL person can also access this course
1801 if (!has_capability('moodle/course:view', $context, $USER->realuser
)) {
1802 print_header_simple();
1803 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot
.'/');
1807 /// Make sure they can read this activity too, if specified
1809 if (!empty($cm) and !$cm->visible
and !has_capability('moodle/course:viewhiddenactivities', $context)) {
1810 redirect($CFG->wwwroot
.'/course/view.php?id='.$cm->course
, get_string('activityiscurrentlyhidden'));
1812 return; // User is allowed to see this course
1817 /// Currently not enrolled in the course, so see if they want to enrol
1818 $SESSION->wantsurl
= $FULLME;
1819 redirect($CFG->wwwroot
.'/course/enrol.php?id='. $COURSE->id
);
1827 * This function just makes sure a user is logged out.
1832 function require_logout() {
1834 global $USER, $CFG, $SESSION;
1836 if (isset($USER) and isset($USER->id
)) {
1837 add_to_log(SITEID
, "user", "logout", "view.php?id=$USER->id&course=".SITEID
, $USER->id
, 0, $USER->id
);
1839 if ($USER->auth
== 'cas' && !empty($CFG->cas_enabled
)) {
1840 require($CFG->dirroot
.'/auth/cas/logout.php');
1843 if (extension_loaded('openssl')) {
1844 require($CFG->dirroot
.'/auth/mnet/auth.php');
1845 $authplugin = new auth_plugin_mnet();
1846 $authplugin->logout();
1850 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
1851 // This method is just to try to avoid silly warnings from PHP 4.3.0
1852 session_unregister("USER");
1853 session_unregister("SESSION");
1856 setcookie('MoodleSessionTest'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
1857 unset($_SESSION['USER']);
1858 unset($_SESSION['SESSION']);
1866 * This is a weaker version of {@link require_login()} which only requires login
1867 * when called from within a course rather than the site page, unless
1868 * the forcelogin option is turned on.
1871 * @param mixed $courseorid The course object or id in question
1872 * @param bool $autologinguest Allow autologin guests if that is wanted
1873 * @param object $cm Course activity module if known
1875 function require_course_login($courseorid, $autologinguest=true, $cm=null) {
1877 if (!empty($CFG->forcelogin
)) {
1878 // login required for both SITE and courses
1879 require_login($courseorid, $autologinguest, $cm);
1880 } else if ((is_object($courseorid) and $courseorid->id
== SITEID
)
1881 or (!is_object($courseorid) and $courseorid == SITEID
)) {
1882 //login for SITE not required
1884 // course login always required
1885 require_login($courseorid, $autologinguest, $cm);
1890 * Modify the user table by setting the currently logged in user's
1891 * last login to now.
1896 function update_user_login_times() {
1899 $user = new object();
1900 $USER->lastlogin
= $user->lastlogin
= $USER->currentlogin
;
1901 $USER->currentlogin
= $user->lastaccess
= $user->currentlogin
= time();
1903 $user->id
= $USER->id
;
1905 return update_record('user', $user);
1909 * Determines if a user has completed setting up their account.
1911 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
1914 function user_not_fully_set_up($user) {
1915 return ($user->username
!= 'guest' and (empty($user->firstname
) or empty($user->lastname
) or empty($user->email
) or over_bounce_threshold($user)));
1918 function over_bounce_threshold($user) {
1922 if (empty($CFG->handlebounces
)) {
1925 // set sensible defaults
1926 if (empty($CFG->minbounces
)) {
1927 $CFG->minbounces
= 10;
1929 if (empty($CFG->bounceratio
)) {
1930 $CFG->bounceratio
= .20;
1934 if ($bounce = get_record('user_preferences','userid',$user->id
,'name','email_bounce_count')) {
1935 $bouncecount = $bounce->value
;
1937 if ($send = get_record('user_preferences','userid',$user->id
,'name','email_send_count')) {
1938 $sendcount = $send->value
;
1940 return ($bouncecount >= $CFG->minbounces
&& $bouncecount/$sendcount >= $CFG->bounceratio
);
1944 * @param $user - object containing an id
1945 * @param $reset - will reset the count to 0
1947 function set_send_count($user,$reset=false) {
1948 if ($pref = get_record('user_preferences','userid',$user->id
,'name','email_send_count')) {
1949 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
1950 update_record('user_preferences',$pref);
1952 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1954 $pref->name
= 'email_send_count';
1956 $pref->userid
= $user->id
;
1957 insert_record('user_preferences',$pref, false);
1962 * @param $user - object containing an id
1963 * @param $reset - will reset the count to 0
1965 function set_bounce_count($user,$reset=false) {
1966 if ($pref = get_record('user_preferences','userid',$user->id
,'name','email_bounce_count')) {
1967 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
1968 update_record('user_preferences',$pref);
1970 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1972 $pref->name
= 'email_bounce_count';
1974 $pref->userid
= $user->id
;
1975 insert_record('user_preferences',$pref, false);
1980 * Keeps track of login attempts
1984 function update_login_count() {
1990 if (empty($SESSION->logincount
)) {
1991 $SESSION->logincount
= 1;
1993 $SESSION->logincount++
;
1996 if ($SESSION->logincount
> $max_logins) {
1997 unset($SESSION->wantsurl
);
1998 error(get_string('errortoomanylogins'));
2003 * Resets login attempts
2007 function reset_login_count() {
2010 $SESSION->logincount
= 0;
2013 function sync_metacourses() {
2017 if (!$courses = get_records('course', 'metacourse', 1)) {
2021 foreach ($courses as $course) {
2022 sync_metacourse($course);
2027 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
2029 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
2031 function sync_metacourse($course) {
2034 // Check the course is valid.
2035 if (!is_object($course)) {
2036 if (!$course = get_record('course', 'id', $course)) {
2037 return false; // invalid course id
2041 // Check that we actually have a metacourse.
2042 if (empty($course->metacourse
)) {
2046 // Get a list of roles that should not be synced.
2047 if ($CFG->nonmetacoursesyncroleids
) {
2048 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids
. ') AND';
2050 $roleexclusions = '';
2053 // Get the context of the metacourse.
2054 $context = get_context_instance(CONTEXT_COURSE
, $course->id
); // SITEID can not be a metacourse
2056 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
2057 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
2058 $managers = array_keys($users);
2060 $managers = array();
2063 // Get assignments of a user to a role that exist in a child course, but
2064 // not in the meta coure. That is, get a list of the assignments that need to be made.
2065 if (!$assignments = get_records_sql("
2067 ra.id, ra.roleid, ra.userid
2069 {$CFG->prefix}role_assignments ra,
2070 {$CFG->prefix}context con,
2071 {$CFG->prefix}course_meta cm
2073 ra.contextid = con.id AND
2074 con.contextlevel = " . CONTEXT_COURSE
. " AND
2075 con.instanceid = cm.child_course AND
2076 cm.parent_course = {$course->id} AND
2080 {$CFG->prefix}role_assignments ra2
2082 ra2.userid = ra.userid AND
2083 ra2.roleid = ra.roleid AND
2084 ra2.contextid = {$context->id}
2087 $assignments = array();
2090 // Get assignments of a user to a role that exist in the meta course, but
2091 // not in any child courses. That is, get a list of the unassignments that need to be made.
2092 if (!$unassignments = get_records_sql("
2094 ra.id, ra.roleid, ra.userid
2096 {$CFG->prefix}role_assignments ra
2098 ra.contextid = {$context->id} AND
2102 {$CFG->prefix}role_assignments ra2,
2103 {$CFG->prefix}context con2,
2104 {$CFG->prefix}course_meta cm
2106 ra2.userid = ra.userid AND
2107 ra2.roleid = ra.roleid AND
2108 ra2.contextid = con2.id AND
2109 con2.contextlevel = " . CONTEXT_COURSE
. " AND
2110 con2.instanceid = cm.child_course AND
2111 cm.parent_course = {$course->id}
2114 $unassignments = array();
2119 // Make the unassignments, if they are not managers.
2120 foreach ($unassignments as $unassignment) {
2121 if (!in_array($unassignment->userid
, $managers)) {
2122 $success = role_unassign($unassignment->roleid
, $unassignment->userid
, 0, $context->id
) && $success;
2126 // Make the assignments.
2127 foreach ($assignments as $assignment) {
2128 $success = role_assign($assignment->roleid
, $assignment->userid
, 0, $context->id
) && $success;
2133 // TODO: finish timeend and timestart
2134 // maybe we could rely on cron job to do the cleaning from time to time
2138 * Adds a record to the metacourse table and calls sync_metacoures
2140 function add_to_metacourse ($metacourseid, $courseid) {
2142 if (!$metacourse = get_record("course","id",$metacourseid)) {
2146 if (!$course = get_record("course","id",$courseid)) {
2150 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
2151 $rec = new object();
2152 $rec->parent_course
= $metacourseid;
2153 $rec->child_course
= $courseid;
2154 if (!insert_record('course_meta',$rec)) {
2157 return sync_metacourse($metacourseid);
2164 * Removes the record from the metacourse table and calls sync_metacourse
2166 function remove_from_metacourse($metacourseid, $courseid) {
2168 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
2169 return sync_metacourse($metacourseid);
2176 * Determines if a user is currently logged in
2181 function isloggedin() {
2184 return (!empty($USER->id
));
2188 * Determines if a user is logged in as real guest user with username 'guest'.
2189 * This function is similar to original isguest() in 1.6 and earlier.
2190 * Current isguest() is deprecated - do not use it anymore.
2192 * @param $user mixed user object or id, $USER if not specified
2193 * @return bool true if user is the real guest user, false if not logged in or other user
2195 function isguestuser($user=NULL) {
2197 if ($user === NULL) {
2199 } else if (is_numeric($user)) {
2200 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2203 if (empty($user->id
)) {
2204 return false; // not logged in, can not be guest
2207 return ($user->username
== 'guest');
2211 * Determines if the currently logged in user is in editing mode
2214 * @param int $courseid The id of the course being tested
2215 * @param user $user A {@link $USER} object. If null then the currently logged in user is used.
2218 function isediting($courseid, $user=NULL) {
2223 if (empty($user->editing
)) {
2228 $coursecontext = get_context_instance(CONTEXT_COURSE
, $courseid);
2230 if (has_capability('moodle/course:manageactivities', $coursecontext) ||
2231 has_capability('moodle/site:manageblocks', $coursecontext)) {
2234 // loop through all child context, see if user has moodle/course:manageactivities or moodle/site:manageblocks
2235 if ($children = get_child_contexts($coursecontext)) {
2236 foreach ($children as $child) {
2237 $childcontext = get_record('context', 'id', $child);
2238 if (has_capability('moodle/course:manageactivities', $childcontext) ||
2239 has_capability('moodle/site:manageblocks', $childcontext)) {
2247 return ($user->editing
&& $capcheck);
2248 //return ($user->editing and has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $courseid)));
2252 * Determines if the logged in user is currently moving an activity
2255 * @param int $courseid The id of the course being tested
2258 function ismoving($courseid) {
2261 if (!empty($USER->activitycopy
)) {
2262 return ($USER->activitycopycourse
== $courseid);
2268 * Given an object containing firstname and lastname
2269 * values, this function returns a string with the
2270 * full name of the person.
2271 * The result may depend on system settings
2272 * or language. 'override' will force both names
2273 * to be used even if system settings specify one.
2277 * @param object $user A {@link $USER} object to get full name of
2278 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
2280 function fullname($user, $override=false) {
2282 global $CFG, $SESSION;
2284 if (!isset($user->firstname
) and !isset($user->lastname
)) {
2289 if (!empty($CFG->forcefirstname
)) {
2290 $user->firstname
= $CFG->forcefirstname
;
2292 if (!empty($CFG->forcelastname
)) {
2293 $user->lastname
= $CFG->forcelastname
;
2297 if (!empty($SESSION->fullnamedisplay
)) {
2298 $CFG->fullnamedisplay
= $SESSION->fullnamedisplay
;
2301 if ($CFG->fullnamedisplay
== 'firstname lastname') {
2302 return $user->firstname
.' '. $user->lastname
;
2304 } else if ($CFG->fullnamedisplay
== 'lastname firstname') {
2305 return $user->lastname
.' '. $user->firstname
;
2307 } else if ($CFG->fullnamedisplay
== 'firstname') {
2309 return get_string('fullnamedisplay', '', $user);
2311 return $user->firstname
;
2315 return get_string('fullnamedisplay', '', $user);
2319 * Sets a moodle cookie with an encrypted string
2324 * @param string $thing The string to encrypt and place in a cookie
2326 function set_moodle_cookie($thing) {
2329 if ($thing == 'guest') { // Ignore guest account
2333 $cookiename = 'MOODLEID_'.$CFG->sessioncookie
;
2336 $seconds = DAYSECS
*$days;
2338 setCookie($cookiename, '', time() - HOURSECS
, '/');
2339 setCookie($cookiename, rc4encrypt($thing), time()+
$seconds, '/');
2343 * Gets a moodle cookie with an encrypted string
2348 function get_moodle_cookie() {
2351 $cookiename = 'MOODLEID_'.$CFG->sessioncookie
;
2353 if (empty($_COOKIE[$cookiename])) {
2356 $thing = rc4decrypt($_COOKIE[$cookiename]);
2357 return ($thing == 'guest') ?
'': $thing; // Ignore guest account
2362 * Returns whether a given authentication plugin exists.
2365 * @param string $auth Form of authentication to check for. Defaults to the
2366 * global setting in {@link $CFG}.
2367 * @return boolean Whether the plugin is available.
2369 function exists_auth_plugin($auth) {
2372 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2373 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2379 * Checks if a given plugin is in the list of enabled authentication plugins.
2381 * @param string $auth Authentication plugin.
2382 * @return boolean Whether the plugin is enabled.
2384 function is_enabled_auth($auth) {
2389 } else if ($auth == 'manual') {
2393 return in_array($auth, explode(',', $CFG->auth
));
2397 * Returns an authentication plugin instance.
2400 * @param string $auth name of authentication plugin
2401 * @return object An instance of the required authentication plugin.
2403 function get_auth_plugin($auth) {
2406 // check the plugin exists first
2407 if (! exists_auth_plugin($auth)) {
2408 error("Authentication plugin '$auth' not found.");
2411 // return auth plugin instance
2412 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2413 $class = "auth_plugin_$auth";
2418 * Returns true if an internal authentication method is being used.
2419 * if method not specified then, global default is assumed
2422 * @param string $auth Form of authentication required
2425 function is_internal_auth($auth) {
2426 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2427 return $authplugin->is_internal();
2431 * Returns an array of user fields
2435 * @return array User field/column names
2437 function get_user_fieldnames() {
2441 $fieldarray = $db->MetaColumnNames($CFG->prefix
.'user');
2442 unset($fieldarray['ID']);
2448 * Creates a bare-bones user record
2451 * @param string $username New user's username to add to record
2452 * @param string $password New user's password to add to record
2453 * @param string $auth Form of authentication required
2454 * @return object A {@link $USER} object
2455 * @todo Outline auth types and provide code example
2457 function create_user_record($username, $password, $auth='') {
2460 //just in case check text case
2461 $username = trim(moodle_strtolower($username));
2463 $authplugin = get_auth_plugin($auth);
2465 if (method_exists($authplugin, 'get_userinfo')) {
2466 if ($newinfo = $authplugin->get_userinfo($username)) {
2467 $newinfo = truncate_userinfo($newinfo);
2468 foreach ($newinfo as $key => $value){
2469 $newuser->$key = addslashes($value);
2474 if (!empty($newuser->email
)) {
2475 if (email_is_not_allowed($newuser->email
)) {
2476 unset($newuser->email
);
2480 $newuser->auth
= (empty($auth)) ?
'manual' : $auth;
2481 $newuser->username
= $username;
2484 // user CFG lang for user if $newuser->lang is empty
2485 // or $user->lang is not an installed language
2486 $sitelangs = array_keys(get_list_of_languages());
2487 if (empty($newuser->lang
) ||
!in_array($newuser->lang
, $sitelangs)) {
2488 $newuser -> lang
= $CFG->lang
;
2490 $newuser->confirmed
= 1;
2491 $newuser->lastip
= getremoteaddr();
2492 $newuser->timemodified
= time();
2493 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
2495 if (insert_record('user', $newuser)) {
2496 $user = get_complete_user_data('username', $newuser->username
);
2497 if($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'}){
2498 set_user_preference('auth_forcepasswordchange', 1, $user->id
);
2500 update_internal_user_password($user, $password);
2507 * Will update a local user record from an external source
2510 * @param string $username New user's username to add to record
2511 * @return user A {@link $USER} object
2513 function update_user_record($username, $authplugin) {
2514 if (method_exists($authplugin, 'get_userinfo')) {
2515 $username = trim(moodle_strtolower($username)); /// just in case check text case
2517 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2518 $userauth = get_auth_plugin($oldinfo->auth
);
2520 if ($newinfo = $authplugin->get_userinfo($username)) {
2521 $newinfo = truncate_userinfo($newinfo);
2522 foreach ($newinfo as $key => $value){
2523 $confkey = 'field_updatelocal_' . $key;
2524 if (!empty($userauth->config
->$confkey) and $userauth->config
->$confkey === 'onlogin') {
2525 $value = addslashes(stripslashes($value)); // Just in case
2526 set_field('user', $key, $value, 'username', $username)
2527 or error_log("Error updating $key for $username");
2532 return get_complete_user_data('username', $username);
2535 function truncate_userinfo($info) {
2536 /// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2537 /// which may have large fields
2539 // define the limits
2549 'institution' => 40,
2557 // apply where needed
2558 foreach (array_keys($info) as $key) {
2559 if (!empty($limit[$key])) {
2560 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
2568 * Retrieve the guest user object
2571 * @return user A {@link $USER} object
2573 function guest_user() {
2576 if ($newuser = get_record('user', 'username', 'guest')) {
2577 $newuser->confirmed
= 1;
2578 $newuser->lang
= $CFG->lang
;
2579 $newuser->lastip
= getremoteaddr();
2586 * Given a username and password, this function looks them
2587 * up using the currently selected authentication mechanism,
2588 * and if the authentication is successful, it returns a
2589 * valid $user object from the 'user' table.
2591 * Uses auth_ functions from the currently active auth module
2594 * @param string $username User's username
2595 * @param string $password User's password
2596 * @return user|flase A {@link $USER} object or false if error
2598 function authenticate_user_login($username, $password) {
2602 if (empty($CFG->auth
)) {
2603 $authsenabled = array('manual');
2605 $authsenabled = explode(',', 'manual,'.$CFG->auth
);
2608 if ($user = get_complete_user_data('username', $username)) {
2609 $auth = empty($user->auth
) ?
'manual' : $user->auth
; // use manual if auth not set
2610 if ($auth=='nologin' or !is_enabled_auth($auth)) {
2611 add_to_log(0, 'login', 'error', 'index.php', $username);
2612 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2615 if (!empty($user->deleted
)) {
2616 add_to_log(0, 'login', 'error', 'index.php', $username);
2617 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2620 $auths = array($auth);
2623 $auths = $authsenabled;
2624 $user = new object();
2625 $user->id
= 0; // User does not exist
2628 foreach ($auths as $auth) {
2629 $authplugin = get_auth_plugin($auth);
2631 // on auth fail fall through to the next plugin
2632 if (!$authplugin->user_login($username, $password)) {
2636 // successful authentication
2637 if ($user->id
) { // User already exists in database
2638 if (empty($user->auth
)) { // For some reason auth isn't set yet
2639 set_field('user', 'auth', $auth, 'username', $username);
2640 $user->auth
= $auth;
2643 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
2645 if (!$authplugin->is_internal()) { // update user record from external DB
2646 $user = update_user_record($username, get_auth_plugin($user->auth
));
2649 // if user not found, create him
2650 $user = create_user_record($username, $password, $auth);
2653 if (method_exists($authplugin, 'iscreator')) {
2654 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2655 if ($creatorroles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW
)) {
2656 $creatorrole = array_shift($creatorroles); // We can only use one, let's use the first one
2657 // Check if the user is a creator
2658 if ($authplugin->iscreator($username)) { // Following calls will not create duplicates
2659 role_assign($creatorrole->id
, $user->id
, 0, $sitecontext->id
, 0, 0, 0, $auth);
2661 role_unassign($creatorrole->id
, $user->id
, 0, $sitecontext->id
);
2666 /// Log in to a second system if necessary
2667 if (!empty($CFG->sso
)) {
2668 include_once($CFG->dirroot
.'/sso/'. $CFG->sso
.'/lib.php');
2669 if (function_exists('sso_user_login')) {
2670 if (!sso_user_login($username, $password)) { // Perform the signon process
2671 notify('Second sign-on failed');
2680 // failed if all the plugins have failed
2681 add_to_log(0, 'login', 'error', 'index.php', $username);
2682 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2687 * Compare password against hash stored in internal user table.
2688 * If necessary it also updates the stored hash to new format.
2690 * @param object user
2691 * @param string plain text password
2692 * @return bool is password valid?
2694 function validate_internal_user_password(&$user, $password) {
2697 if (!isset($CFG->passwordsaltmain
)) {
2698 $CFG->passwordsaltmain
= '';
2703 // get password original encoding in case it was not updated to unicode yet
2704 $textlib = textlib_get_instance();
2705 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
2707 if ($user->password
== md5($password.$CFG->passwordsaltmain
) or $user->password
== md5($password)
2708 or $user->password
== md5($convpassword.$CFG->passwordsaltmain
) or $user->password
== md5($convpassword)) {
2711 for ($i=1; $i<=20; $i++
) { //20 alternative salts should be enough, right?
2712 $alt = 'passwordsaltalt'.$i;
2713 if (!empty($CFG->$alt)) {
2714 if ($user->password
== md5($password.$CFG->$alt) or $user->password
== md5($convpassword.$CFG->$alt)) {
2723 // force update of password hash using latest main password salt and encoding if needed
2724 update_internal_user_password($user, $password);
2731 * Calculate hashed value from password using current hash mechanism.
2733 * @param string password
2734 * @return string password hash
2736 function hash_internal_user_password($password) {
2739 if (isset($CFG->passwordsaltmain
)) {
2740 return md5($password.$CFG->passwordsaltmain
);
2742 return md5($password);
2747 * Update pssword hash in user object.
2749 * @param object user
2750 * @param string plain text password
2751 * @param bool store changes also in db, default true
2752 * @return true if hash changed
2754 function update_internal_user_password(&$user, $password) {
2757 $authplugin = get_auth_plugin($user->auth
);
2758 if (!empty($authplugin->config
->preventpassindb
)) {
2759 $hashedpassword = 'not cached';
2761 $hashedpassword = hash_internal_user_password($password);
2764 return set_field('user', 'password', $hashedpassword, 'id', $user->id
);
2768 * Get a complete user record, which includes all the info
2769 * in the user record
2770 * Intended for setting as $USER session variable
2774 * @param string $field The user field to be checked for a given value.
2775 * @param string $value The value to match for $field.
2776 * @return user A {@link $USER} object.
2778 function get_complete_user_data($field, $value, $mnethostid=null) {
2782 if (!$field ||
!$value) {
2786 /// Build the WHERE clause for an SQL query
2788 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
2790 if (is_null($mnethostid)) {
2791 // if null, we restrict to local users
2792 // ** testing for local user can be done with
2793 // mnethostid = $CFG->mnet_localhost_id
2796 // but the first one is FAST with our indexes
2797 $mnethostid = $CFG->mnet_localhost_id
;
2799 $mnethostid = (int)$mnethostid;
2800 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
2802 /// Get all the basic user data
2804 if (! $user = get_record_select('user', $constraints)) {
2808 /// Get various settings and preferences
2810 if ($displays = get_records('course_display', 'userid', $user->id
)) {
2811 foreach ($displays as $display) {
2812 $user->display
[$display->course
] = $display->display
;
2816 $user->preference
= get_user_preferences(null, null, $user->id
);
2818 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id
)) {
2819 foreach ($lastaccesses as $lastaccess) {
2820 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
2824 if ($groupids = groups_get_all_groups_for_user($user->id
)) { //TODO:check.
2825 foreach ($groupids as $groupid) {
2826 $courseid = groups_get_course($groupid);
2827 //change this to 2D array so we can put multiple groups in a course
2828 $user->groupmember
[$courseid][] = $groupid;
2832 /// Rewrite some variables if necessary
2833 if (!empty($user->description
)) {
2834 $user->description
= true; // No need to cart all of it around
2836 if ($user->username
== 'guest') {
2837 $user->lang
= $CFG->lang
; // Guest language always same as site
2838 $user->firstname
= get_string('guestuser'); // Name always in current language
2839 $user->lastname
= ' ';
2842 $user->sesskey
= random_string(10);
2843 $user->sessionIP
= md5(getremoteaddr()); // Store the current IP in the session
2851 * When logging in, this function is run to set certain preferences
2852 * for the current SESSION
2854 function set_login_session_preferences() {
2855 global $SESSION, $CFG;
2857 $SESSION->justloggedin
= true;
2859 unset($SESSION->lang
);
2861 // Restore the calendar filters, if saved
2862 if (intval(get_user_preferences('calendar_persistflt', 0))) {
2863 include_once($CFG->dirroot
.'/calendar/lib.php');
2864 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
2870 * Delete a course, including all related data from the database,
2871 * and any associated files from the moodledata folder.
2873 * @param int $courseid The id of the course to delete.
2874 * @param bool $showfeedback Whether to display notifications of each action the function performs.
2875 * @return bool true if all the removals succeeded. false if there were any failures. If this
2876 * method returns false, some of the removals will probably have succeeded, and others
2877 * failed, but you have no way of knowing which.
2879 function delete_course($courseid, $showfeedback = true) {
2883 if (!remove_course_contents($courseid, $showfeedback)) {
2884 if ($showfeedback) {
2885 notify("An error occurred while deleting some of the course contents.");
2890 if (!delete_records("course", "id", $courseid)) {
2891 if ($showfeedback) {
2892 notify("An error occurred while deleting the main course record.");
2897 if (!delete_records('context', 'contextlevel', CONTEXT_COURSE
, 'instanceid', $courseid)) {
2898 if ($showfeedback) {
2899 notify("An error occurred while deleting the main context record.");
2904 if (!fulldelete($CFG->dataroot
.'/'.$courseid)) {
2905 if ($showfeedback) {
2906 notify("An error occurred while deleting the course files.");
2915 * Clear a course out completely, deleting all content
2916 * but don't delete the course itself
2919 * @param int $courseid The id of the course that is being deleted
2920 * @param bool $showfeedback Whether to display notifications of each action the function performs.
2921 * @return bool true if all the removals succeeded. false if there were any failures. If this
2922 * method returns false, some of the removals will probably have succeeded, and others
2923 * failed, but you have no way of knowing which.
2925 function remove_course_contents($courseid, $showfeedback=true) {
2931 if (! $course = get_record('course', 'id', $courseid)) {
2932 error('Course ID was incorrect (can\'t find it)');
2935 $strdeleted = get_string('deleted');
2937 /// First delete every instance of every module
2939 if ($allmods = get_records('modules') ) {
2940 foreach ($allmods as $mod) {
2941 $modname = $mod->name
;
2942 $modfile = $CFG->dirroot
.'/mod/'. $modname .'/lib.php';
2943 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
2944 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
2946 if (file_exists($modfile)) {
2947 include_once($modfile);
2948 if (function_exists($moddelete)) {
2949 if ($instances = get_records($modname, 'course', $course->id
)) {
2950 foreach ($instances as $instance) {
2951 if ($cm = get_coursemodule_from_instance($modname, $instance->id
, $course->id
)) {
2952 delete_context(CONTEXT_MODULE
, $cm->id
);
2954 if ($moddelete($instance->id
)) {
2958 notify('Could not delete '. $modname .' instance '. $instance->id
.' ('. format_string($instance->name
) .')');
2964 notify('Function '. $moddelete() .'doesn\'t exist!');
2968 if (function_exists($moddeletecourse)) {
2969 $moddeletecourse($course, $showfeedback);
2972 if ($showfeedback) {
2973 notify($strdeleted .' '. $count .' x '. $modname);
2977 error('No modules are installed!');
2980 /// Give local code a chance to delete its references to this course.
2981 require_once('locallib.php');
2982 notify_local_delete_course($courseid, $showfeedback);
2984 /// Delete course blocks
2986 if ($blocks = get_records_sql("SELECT *
2987 FROM {$CFG->prefix}block_instance
2988 WHERE pagetype = '".PAGE_COURSE_VIEW
."'
2989 AND pageid = $course->id")) {
2990 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW
, 'pageid', $course->id
)) {
2991 if ($showfeedback) {
2992 notify($strdeleted .' block_instance');
2994 foreach ($blocks as $block) { /// Delete any associated contexts for this block
2995 delete_context(CONTEXT_BLOCK
, $block->id
);
3002 /// Delete any groups, removing members and grouping/course links first.
3003 //TODO: If groups or groupings are to be shared between courses, think again!
3004 if ($groupids = groups_get_groups($course->id
)) {
3005 foreach ($groupids as $groupid) {
3006 if (groups_remove_all_members($groupid)) {
3007 if ($showfeedback) {
3008 notify($strdeleted .' groups_members');
3013 /// Delete any associated context for this group ??
3014 delete_context(CONTEXT_GROUP
, $groupid);
3016 if (groups_delete_group($groupid)) {
3017 if ($showfeedback) {
3018 notify($strdeleted .' groups');
3025 /// Delete any groupings.
3026 $result = groups_delete_all_groupings($course->id
);
3027 if ($result && $showfeedback) {
3028 notify($strdeleted .' groupings');
3031 /// Delete all related records in other tables that may have a courseid
3032 /// This array stores the tables that need to be cleared, as
3033 /// table_name => column_name that contains the course id.
3035 $tablestoclear = array(
3036 'event' => 'courseid', // Delete events
3037 'log' => 'course', // Delete logs
3038 'course_sections' => 'course', // Delete any course stuff
3039 'course_modules' => 'course',
3040 'grade_category' => 'courseid', // Delete gradebook stuff
3041 'grade_exceptions' => 'courseid',
3042 'grade_item' => 'courseid',
3043 'grade_letter' => 'courseid',
3044 'grade_preferences' => 'courseid',
3045 'backup_courses' => 'courseid', // Delete scheduled backup stuff
3046 'backup_log' => 'courseid'
3048 foreach ($tablestoclear as $table => $col) {
3049 if (delete_records($table, $col, $course->id
)) {
3050 if ($showfeedback) {
3051 notify($strdeleted . ' ' . $table);
3059 /// Clean up metacourse stuff
3061 if ($course->metacourse
) {
3062 delete_records("course_meta","parent_course",$course->id
);
3063 sync_metacourse($course->id
); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
3064 if ($showfeedback) {
3065 notify("$strdeleted course_meta");
3068 if ($parents = get_records("course_meta","child_course",$course->id
)) {
3069 foreach ($parents as $parent) {
3070 remove_from_metacourse($parent->parent_course
,$parent->child_course
); // this will do the unenrolments as well.
3072 if ($showfeedback) {
3073 notify("$strdeleted course_meta");
3078 /// Delete questions and question categories
3079 include_once($CFG->libdir
.'/questionlib.php');
3080 question_delete_course($course, $showfeedback);
3082 /// Delete all roles and overiddes in the course context (but keep the course context)
3083 if ($courseid != SITEID
) {
3084 delete_context(CONTEXT_COURSE
, $course->id
);
3092 * This function will empty a course of USER data as much as
3093 /// possible. It will retain the activities and the structure
3099 * @param object $data an object containing all the boolean settings and courseid
3100 * @param bool $showfeedback if false then do it all silently
3102 * @todo Finish documenting this function
3104 function reset_course_userdata($data, $showfeedback=true) {
3106 global $CFG, $USER, $SESSION;
3110 $strdeleted = get_string('deleted');
3112 // Look in every instance of every module for data to delete
3114 if ($allmods = get_records('modules') ) {
3115 foreach ($allmods as $mod) {
3116 $modname = $mod->name
;
3117 $modfile = $CFG->dirroot
.'/mod/'. $modname .'/lib.php';
3118 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3119 if (file_exists($modfile)) {
3120 @include_once
($modfile);
3121 if (function_exists($moddeleteuserdata)) {
3122 $moddeleteuserdata($data, $showfeedback);
3127 error('No modules are installed!');
3130 // Delete other stuff
3131 $coursecontext = get_context_instance(CONTEXT_COURSE
, $data->courseid
);
3133 if (!empty($data->reset_students
) or !empty($data->reset_teachers
)) {
3134 $teachers = array_keys(get_users_by_capability($coursecontext, 'moodle/course:update'));
3135 $participants = array_keys(get_users_by_capability($coursecontext, 'moodle/course:view'));
3136 $students = array_diff($participants, $teachers);
3138 if (!empty($data->reset_students
)) {
3139 foreach ($students as $studentid) {
3140 role_unassign(0, $studentid, 0, $coursecontext->id
);
3142 if ($showfeedback) {
3143 notify($strdeleted .' '.get_string('students'), 'notifysuccess');
3146 /// Delete group members (but keep the groups) TODO:check.
3147 if ($groupids = groups_get_groups($data->courseid
)) {
3148 foreach ($groupids as $groupid) {
3149 if (groups_remove_all_group_members($groupid)) {
3150 if ($showfeedback) {
3151 notify($strdeleted .' groups_members', 'notifysuccess');
3160 if (!empty($data->reset_teachers
)) {
3161 foreach ($teachers as $teacherid) {
3162 role_unassign(0, $teacherid, 0, $coursecontext->id
);
3164 if ($showfeedback) {
3165 notify($strdeleted .' '.get_string('teachers'), 'notifysuccess');
3170 if (!empty($data->reset_groups
)) {
3171 if ($groupids = groups_get_groups($data->courseid
)) {
3172 foreach ($groupids as $groupid) {
3173 if (groups_delete_group($groupid)) {
3174 if ($showfeedback) {
3175 notify($strdeleted .' groups', 'notifysuccess');
3184 if (!empty($data->reset_events
)) {
3185 if (delete_records('event', 'courseid', $data->courseid
)) {
3186 if ($showfeedback) {
3187 notify($strdeleted .' event', 'notifysuccess');
3194 if (!empty($data->reset_logs
)) {
3195 if (delete_records('log', 'course', $data->courseid
)) {
3196 if ($showfeedback) {
3197 notify($strdeleted .' log', 'notifysuccess');
3204 // deletes all role assignments, and local override, these have no courseid in table and needs separate process
3205 $context = get_context_instance(CONTEXT_COURSE
, $data->courseid
);
3206 delete_records('role_capabilities', 'contextid', $context->id
);
3212 require_once($CFG->dirroot
.'/group/lib.php');
3213 /*TODO: functions moved to /group/lib/legacylib.php
3223 function generate_email_processing_address($modid,$modargs) {
3226 if (empty($CFG->siteidentifier
)) { // Unique site identification code
3227 set_config('siteidentifier', random_string(32));
3230 $header = $CFG->mailprefix
. substr(base64_encode(pack('C',$modid)),0,2).$modargs;
3231 return $header . substr(md5($header.$CFG->siteidentifier
),0,16).'@'.$CFG->maildomain
;
3235 function moodle_process_email($modargs,$body) {
3236 // the first char should be an unencoded letter. We'll take this as an action
3237 switch ($modargs{0}) {
3238 case 'B': { // bounce
3239 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
3240 if ($user = get_record_select("user","id=$userid","id,email")) {
3241 // check the half md5 of their email
3242 $md5check = substr(md5($user->email
),0,16);
3243 if ($md5check == substr($modargs, -16)) {
3244 set_bounce_count($user);
3246 // else maybe they've already changed it?
3250 // maybe more later?
3254 /// CORRESPONDENCE ////////////////////////////////////////////////
3257 * Send an email to a specified user
3262 * @param user $user A {@link $USER} object
3263 * @param user $from A {@link $USER} object
3264 * @param string $subject plain text subject line of the email
3265 * @param string $messagetext plain text version of the message
3266 * @param string $messagehtml complete html version of the message (optional)
3267 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
3268 * @param string $attachname the name of the file (extension indicates MIME)
3269 * @param bool $usetrueaddress determines whether $from email address should
3270 * be sent out. Will be overruled by user profile setting for maildisplay
3271 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3272 * was blocked by user and "false" if there was another sort of error.
3274 function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='') {
3276 global $CFG, $FULLME;
3278 include_once($CFG->libdir
.'/phpmailer/class.phpmailer.php');
3280 /// We are going to use textlib services here
3281 $textlib = textlib_get_instance();
3287 // skip mail to suspended users
3288 if (isset($user->auth
) && $user->auth
=='nologin') {
3292 if (!empty($user->emailstop
)) {
3296 if (over_bounce_threshold($user)) {
3297 error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
3301 $mail = new phpmailer
;
3303 $mail->Version
= 'Moodle '. $CFG->version
; // mailer version
3304 $mail->PluginDir
= $CFG->libdir
.'/phpmailer/'; // plugin directory (eg smtp plugin)
3306 $mail->CharSet
= 'UTF-8';
3308 if ($CFG->smtphosts
== 'qmail') {
3309 $mail->IsQmail(); // use Qmail system
3311 } else if (empty($CFG->smtphosts
)) {
3312 $mail->IsMail(); // use PHP mail() = sendmail
3315 $mail->IsSMTP(); // use SMTP directly
3316 if (!empty($CFG->debugsmtp
)) {
3317 echo '<pre>' . "\n";
3318 $mail->SMTPDebug
= true;
3320 $mail->Host
= $CFG->smtphosts
; // specify main and backup servers
3322 if ($CFG->smtpuser
) { // Use SMTP authentication
3323 $mail->SMTPAuth
= true;
3324 $mail->Username
= $CFG->smtpuser
;
3325 $mail->Password
= $CFG->smtppass
;
3329 $adminuser = get_admin();
3331 // make up an email address for handling bounces
3332 if (!empty($CFG->handlebounces
)) {
3333 $modargs = 'B'.base64_encode(pack('V',$user->id
)).substr(md5($user->email
),0,16);
3334 $mail->Sender
= generate_email_processing_address(0,$modargs);
3337 $mail->Sender
= $adminuser->email
;
3340 if (is_string($from)) { // So we can pass whatever we want if there is need
3341 $mail->From
= $CFG->noreplyaddress
;
3342 $mail->FromName
= $from;
3343 } else if ($usetrueaddress and $from->maildisplay
) {
3344 $mail->From
= $from->email
;
3345 $mail->FromName
= fullname($from);
3347 $mail->From
= $CFG->noreplyaddress
;
3348 $mail->FromName
= fullname($from);
3349 if (empty($replyto)) {
3350 $mail->AddReplyTo($CFG->noreplyaddress
,get_string('noreplyname'));
3354 if (!empty($replyto)) {
3355 $mail->AddReplyTo($replyto,$replytoname);
3358 $mail->Subject
= substr(stripslashes($subject), 0, 900);
3360 $mail->AddAddress($user->email
, fullname($user) );
3362 $mail->WordWrap
= 79; // set word wrap
3364 if (!empty($from->customheaders
)) { // Add custom headers
3365 if (is_array($from->customheaders
)) {
3366 foreach ($from->customheaders
as $customheader) {
3367 $mail->AddCustomHeader($customheader);
3370 $mail->AddCustomHeader($from->customheaders
);
3374 if (!empty($from->priority
)) {
3375 $mail->Priority
= $from->priority
;
3378 if ($messagehtml && $user->mailformat
== 1) { // Don't ever send HTML to users who don't want it
3379 $mail->IsHTML(true);
3380 $mail->Encoding
= 'quoted-printable'; // Encoding to use
3381 $mail->Body
= $messagehtml;
3382 $mail->AltBody
= "\n$messagetext\n";
3384 $mail->IsHTML(false);
3385 $mail->Body
= "\n$messagetext\n";
3388 if ($attachment && $attachname) {
3389 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
3390 $mail->AddAddress($adminuser->email
, fullname($adminuser) );
3391 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
3393 require_once($CFG->libdir
.'/filelib.php');
3394 $mimetype = mimeinfo('type', $attachname);
3395 $mail->AddAttachment($CFG->dataroot
.'/'. $attachment, $attachname, 'base64', $mimetype);
3401 /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
3402 /// encoding to the specified one
3403 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
3404 /// Set it to site mail charset
3405 $charset = $CFG->sitemailcharset
;
3406 /// Overwrite it with the user mail charset
3407 if (!empty($CFG->allowusermailcharset
)) {
3408 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
3409 $charset = $useremailcharset;
3412 /// If it has changed, convert all the necessary strings
3413 $charsets = get_list_of_charsets();
3414 unset($charsets['UTF-8']);
3415 if (in_array($charset, $charsets)) {
3416 /// Save the new mail charset
3417 $mail->CharSet
= $charset;
3418 /// And convert some strings
3419 $mail->FromName
= $textlib->convert($mail->FromName
, 'utf-8', $mail->CharSet
); //From Name
3420 foreach ($mail->ReplyTo
as $key => $rt) { //ReplyTo Names
3421 $mail->ReplyTo
[$key][1] = $textlib->convert($rt, 'utf-8', $mail->CharSet
);
3423 $mail->Subject
= $textlib->convert($mail->Subject
, 'utf-8', $mail->CharSet
); //Subject
3424 foreach ($mail->to
as $key => $to) {
3425 $mail->to
[$key][1] = $textlib->convert($to, 'utf-8', $mail->CharSet
); //To Names
3427 $mail->Body
= $textlib->convert($mail->Body
, 'utf-8', $mail->CharSet
); //Body
3428 $mail->AltBody
= $textlib->convert($mail->AltBody
, 'utf-8', $mail->CharSet
); //Subject
3432 if ($mail->Send()) {
3433 set_send_count($user);
3434 $mail->IsSMTP(); // use SMTP directly
3435 if (!empty($CFG->debugsmtp
)) {
3440 mtrace('ERROR: '. $mail->ErrorInfo
);
3441 add_to_log(SITEID
, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo
);
3442 if (!empty($CFG->debugsmtp
)) {
3450 * Sets specified user's password and send the new password to the user via email.
3453 * @param user $user A {@link $USER} object
3454 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
3455 * was blocked by user and "false" if there was another sort of error.
3457 function setnew_password_and_mail($user) {
3462 $from = get_admin();
3464 $newpassword = generate_password();
3466 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id
) ) {
3467 trigger_error('Could not set user password!');
3472 $a->firstname
= $user->firstname
;
3473 $a->sitename
= $site->fullname
;
3474 $a->username
= $user->username
;
3475 $a->newpassword
= $newpassword;
3476 $a->link
= $CFG->wwwroot
.'/login/';
3477 $a->signoff
= fullname($from, true).' ('. $from->email
.')';
3479 $message = get_string('newusernewpasswordtext', '', $a);
3481 $subject = $site->fullname
.': '. get_string('newusernewpasswordsubj');
3483 return email_to_user($user, $from, $subject, $message);
3488 * Resets specified user's password and send the new password to the user via email.
3491 * @param user $user A {@link $USER} object
3492 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3493 * was blocked by user and "false" if there was another sort of error.
3495 function reset_password_and_mail($user) {
3500 $from = get_admin();
3502 $userauth = get_auth_plugin($user->auth
);
3503 if (!$userauth->can_reset_password()) {
3504 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
3508 $newpassword = generate_password();
3510 if (!$userauth->user_update_password(addslashes_recursive($user), addslashes($newpassword))) {
3511 error("Could not set user password!");
3515 $a->firstname
= $user->firstname
;
3516 $a->sitename
= $site->fullname
;
3517 $a->username
= $user->username
;
3518 $a->newpassword
= $newpassword;
3519 $a->link
= $CFG->httpswwwroot
.'/login/change_password.php';
3520 $a->signoff
= fullname($from, true).' ('. $from->email
.')';
3522 $message = get_string('newpasswordtext', '', $a);
3524 $subject = $site->fullname
.': '. get_string('changedpassword');
3526 return email_to_user($user, $from, $subject, $message);
3531 * Send email to specified user with confirmation text and activation link.
3534 * @param user $user A {@link $USER} object
3535 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3536 * was blocked by user and "false" if there was another sort of error.
3538 function send_confirmation_email($user) {
3543 $from = get_admin();
3545 $data = new object();
3546 $data->firstname
= fullname($user);
3547 $data->sitename
= $site->fullname
;
3548 $data->admin
= fullname($from) .' ('. $from->email
.')';
3550 $subject = get_string('emailconfirmationsubject', '', $site->fullname
);
3552 $data->link
= $CFG->wwwroot
.'/login/confirm.php?data='. $user->secret
.'/'. $user->username
;
3553 $message = get_string('emailconfirmation', '', $data);
3554 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
3556 $user->mailformat
= 1; // Always send HTML version as well
3558 return email_to_user($user, $from, $subject, $message, $messagehtml);
3563 * send_password_change_confirmation_email.
3566 * @param user $user A {@link $USER} object
3567 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3568 * was blocked by user and "false" if there was another sort of error.
3570 function send_password_change_confirmation_email($user) {
3575 $from = get_admin();
3577 $data = new object();
3578 $data->firstname
= $user->firstname
;
3579 $data->sitename
= $site->fullname
;
3580 $data->link
= $CFG->httpswwwroot
.'/login/forgot_password.php?p='. $user->secret
.'&s='. $user->username
;
3581 $data->admin
= fullname($from).' ('. $from->email
.')';
3583 $message = get_string('emailpasswordconfirmation', '', $data);
3584 $subject = get_string('emailpasswordconfirmationsubject', '', $site->fullname
);
3586 return email_to_user($user, $from, $subject, $message);
3591 * send_password_change_info.
3594 * @param user $user A {@link $USER} object
3595 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3596 * was blocked by user and "false" if there was another sort of error.
3598 function send_password_change_info($user) {
3603 $from = get_admin();
3605 $data = new object();
3606 $data->firstname
= $user->firstname
;
3607 $data->sitename
= $site->fullname
;
3608 $data->admin
= fullname($from).' ('. $from->email
.')';
3610 $userauth = get_auth_plugin($user->auth
);
3611 if ($userauth->can_change_password() and method_exists($userauth, 'change_password_url') and $userauth->change_password_url()) {
3612 // we have some external url for password cahnging
3613 $data->link
.= $userauth->change_password_url();
3616 //no way to change password, sorry
3620 if (!empty($data->link
)) {
3621 $message = get_string('emailpasswordchangeinfo', '', $data);
3622 $subject = get_string('emailpasswordchangeinfosubject', '', $site->fullname
);
3624 $message = get_string('emailpasswordchangeinfofail', '', $data);
3625 $subject = get_string('emailpasswordchangeinfosubject', '', $site->fullname
);
3628 return email_to_user($user, $from, $subject, $message);
3633 * Check that an email is allowed. It returns an error message if there
3637 * @param string $email Content of email
3638 * @return string|false
3640 function email_is_not_allowed($email) {
3644 if (!empty($CFG->allowemailaddresses
)) {
3645 $allowed = explode(' ', $CFG->allowemailaddresses
);
3646 foreach ($allowed as $allowedpattern) {
3647 $allowedpattern = trim($allowedpattern);
3648 if (!$allowedpattern) {
3651 if (strpos(strrev($email), strrev($allowedpattern)) === 0) { // Match! (bug 5250)
3655 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
3657 } else if (!empty($CFG->denyemailaddresses
)) {
3658 $denied = explode(' ', $CFG->denyemailaddresses
);
3659 foreach ($denied as $deniedpattern) {
3660 $deniedpattern = trim($deniedpattern);
3661 if (!$deniedpattern) {
3664 if (strpos(strrev($email), strrev($deniedpattern)) === 0) { // Match! (bug 5250)
3665 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
3673 function email_welcome_message_to_user($course, $user=NULL) {
3677 if (!isloggedin()) {
3683 if (!empty($course->welcomemessage
)) {
3684 $subject = get_string('welcometocourse', '', format_string($course->fullname
));
3686 $a->coursename
= $course->fullname
;
3687 $a->profileurl
= "$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id";
3688 //$message = get_string("welcometocoursetext", "", $a);
3689 $message = $course->welcomemessage
;
3691 if (! $teacher = get_teacher($course->id
)) {
3692 $teacher = get_admin();
3694 email_to_user($user, $teacher, $subject, $message);
3698 /// FILE HANDLING /////////////////////////////////////////////
3702 * Makes an upload directory for a particular module.
3705 * @param int $courseid The id of the course in question - maps to id field of 'course' table.
3706 * @return string|false Returns full path to directory if successful, false if not
3708 function make_mod_upload_directory($courseid) {
3711 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata
)) {
3715 $strreadme = get_string('readme');
3717 if (file_exists($CFG->dirroot
.'/lang/'. $CFG->lang
.'/docs/module_files.txt')) {
3718 copy($CFG->dirroot
.'/lang/'. $CFG->lang
.'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
3720 copy($CFG->dirroot
.'/lang/en_utf8/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
3726 * Returns current name of file on disk if it exists.
3728 * @param string $newfile File to be verified
3729 * @return string Current name of file on disk if true
3731 function valid_uploaded_file($newfile) {
3732 if (empty($newfile)) {
3735 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
3736 return $newfile['tmp_name'];
3743 * Returns the maximum size for uploading files.
3745 * There are seven possible upload limits:
3746 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
3747 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
3748 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
3749 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
3750 * 5. by the Moodle admin in $CFG->maxbytes
3751 * 6. by the teacher in the current course $course->maxbytes
3752 * 7. by the teacher for the current module, eg $assignment->maxbytes
3754 * These last two are passed to this function as arguments (in bytes).
3755 * Anything defined as 0 is ignored.
3756 * The smallest of all the non-zero numbers is returned.
3758 * @param int $sizebytes ?
3759 * @param int $coursebytes Current course $course->maxbytes (in bytes)
3760 * @param int $modulebytes Current module ->maxbytes (in bytes)
3761 * @return int The maximum size for uploading files.
3762 * @todo Finish documenting this function
3764 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
3766 if (! $filesize = ini_get('upload_max_filesize')) {
3769 $minimumsize = get_real_size($filesize);
3771 if ($postsize = ini_get('post_max_size')) {
3772 $postsize = get_real_size($postsize);
3773 if ($postsize < $minimumsize) {
3774 $minimumsize = $postsize;
3778 if ($sitebytes and $sitebytes < $minimumsize) {
3779 $minimumsize = $sitebytes;
3782 if ($coursebytes and $coursebytes < $minimumsize) {
3783 $minimumsize = $coursebytes;
3786 if ($modulebytes and $modulebytes < $minimumsize) {
3787 $minimumsize = $modulebytes;
3790 return $minimumsize;
3794 * Related to {@link get_max_upload_file_size()} - this function returns an
3795 * array of possible sizes in an array, translated to the
3798 * @uses SORT_NUMERIC
3799 * @param int $sizebytes ?
3800 * @param int $coursebytes Current course $course->maxbytes (in bytes)
3801 * @param int $modulebytes Current module ->maxbytes (in bytes)
3803 * @todo Finish documenting this function
3805 function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
3807 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
3811 $filesize[$maxsize] = display_size($maxsize);
3813 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
3814 5242880, 10485760, 20971520, 52428800, 104857600);
3816 foreach ($sizelist as $sizebytes) {
3817 if ($sizebytes < $maxsize) {
3818 $filesize[$sizebytes] = display_size($sizebytes);
3822 krsort($filesize, SORT_NUMERIC
);
3828 * If there has been an error uploading a file, print the appropriate error message
3829 * Numerical constants used as constant definitions not added until PHP version 4.2.0
3831 * $filearray is a 1-dimensional sub-array of the $_FILES array
3832 * eg $filearray = $_FILES['userfile1']
3833 * If left empty then the first element of the $_FILES array will be used
3836 * @param array $filearray A 1-dimensional sub-array of the $_FILES array
3837 * @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.
3838 * @return bool|string
3840 function print_file_upload_error($filearray = '', $returnerror = false) {
3842 if ($filearray == '' or !isset($filearray['error'])) {
3844 if (empty($_FILES)) return false;
3846 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
3847 $filearray = array_shift($files); /// use first element of array
3850 switch ($filearray['error']) {
3852 case 0: // UPLOAD_ERR_OK
3853 if ($filearray['size'] > 0) {
3854 $errmessage = get_string('uploadproblem', $filearray['name']);
3856 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
3860 case 1: // UPLOAD_ERR_INI_SIZE
3861 $errmessage = get_string('uploadserverlimit');
3864 case 2: // UPLOAD_ERR_FORM_SIZE
3865 $errmessage = get_string('uploadformlimit');
3868 case 3: // UPLOAD_ERR_PARTIAL
3869 $errmessage = get_string('uploadpartialfile');
3872 case 4: // UPLOAD_ERR_NO_FILE
3873 $errmessage = get_string('uploadnofilefound');
3877 $errmessage = get_string('uploadproblem', $filearray['name']);
3883 notify($errmessage);
3890 * handy function to loop through an array of files and resolve any filename conflicts
3891 * both in the array of filenames and for what is already on disk.
3892 * not really compatible with the similar function in uploadlib.php
3893 * but this could be used for files/index.php for moving files around.
3896 function resolve_filename_collisions($destination,$files,$format='%s_%d.%s') {
3897 foreach ($files as $k => $f) {
3898 if (check_potential_filename($destination,$f,$files)) {
3899 $bits = explode('.', $f);
3900 for ($i = 1; true; $i++
) {
3901 $try = sprintf($format, $bits[0], $i, $bits[1]);
3902 if (!check_potential_filename($destination,$try,$files)) {
3913 * @used by resolve_filename_collisions
3915 function check_potential_filename($destination,$filename,$files) {
3916 if (file_exists($destination.'/'.$filename)) {
3919 if (count(array_keys($files,$filename)) > 1) {
3927 * Returns an array with all the filenames in
3928 * all subdirectories, relative to the given rootdir.
3929 * If excludefile is defined, then that file/directory is ignored
3930 * If getdirs is true, then (sub)directories are included in the output
3931 * If getfiles is true, then files are included in the output
3932 * (at least one of these must be true!)
3934 * @param string $rootdir ?
3935 * @param string $excludefile If defined then the specified file/directory is ignored
3936 * @param bool $descend ?
3937 * @param bool $getdirs If true then (sub)directories are included in the output
3938 * @param bool $getfiles If true then files are included in the output
3939 * @return array An array with all the filenames in
3940 * all subdirectories, relative to the given rootdir
3941 * @todo Finish documenting this function. Add examples of $excludefile usage.
3943 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
3947 if (!$getdirs and !$getfiles) { // Nothing to show
3951 if (!is_dir($rootdir)) { // Must be a directory
3955 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
3959 if (!is_array($excludefiles)) {
3960 $excludefiles = array($excludefiles);
3963 while (false !== ($file = readdir($dir))) {
3964 $firstchar = substr($file, 0, 1);
3965 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
3968 $fullfile = $rootdir .'/'. $file;
3969 if (filetype($fullfile) == 'dir') {
3974 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
3975 foreach ($subdirs as $subdir) {
3976 $dirs[] = $file .'/'. $subdir;
3979 } else if ($getfiles) {
3992 * Adds up all the files in a directory and works out the size.
3994 * @param string $rootdir ?
3995 * @param string $excludefile ?
3997 * @todo Finish documenting this function
3999 function get_directory_size($rootdir, $excludefile='') {
4003 // do it this way if we can, it's much faster
4004 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
4005 $command = trim($CFG->pathtodu
).' -sk --apparent-size '.escapeshellarg($rootdir);
4008 exec($command,$output,$return);
4009 if (is_array($output)) {
4010 return get_real_size(intval($output[0]).'k'); // we told it to return k.
4014 if (!is_dir($rootdir)) { // Must be a directory
4018 if (!$dir = @opendir
($rootdir)) { // Can't open it for some reason
4024 while (false !== ($file = readdir($dir))) {
4025 $firstchar = substr($file, 0, 1);
4026 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
4029 $fullfile = $rootdir .'/'. $file;
4030 if (filetype($fullfile) == 'dir') {
4031 $size +
= get_directory_size($fullfile, $excludefile);
4033 $size +
= filesize($fullfile);
4042 * Converts bytes into display form
4044 * @param string $size ?
4046 * @staticvar string $gb Localized string for size in gigabytes
4047 * @staticvar string $mb Localized string for size in megabytes
4048 * @staticvar string $kb Localized string for size in kilobytes
4049 * @staticvar string $b Localized string for size in bytes
4050 * @todo Finish documenting this function. Verify return type.
4052 function display_size($size) {
4054 static $gb, $mb, $kb, $b;
4057 $gb = get_string('sizegb');
4058 $mb = get_string('sizemb');
4059 $kb = get_string('sizekb');
4060 $b = get_string('sizeb');
4063 if ($size >= 1073741824) {
4064 $size = round($size / 1073741824 * 10) / 10 . $gb;
4065 } else if ($size >= 1048576) {
4066 $size = round($size / 1048576 * 10) / 10 . $mb;
4067 } else if ($size >= 1024) {
4068 $size = round($size / 1024 * 10) / 10 . $kb;
4070 $size = $size .' '. $b;
4076 * Cleans a given filename by removing suspicious or troublesome characters
4077 * Only these are allowed: alphanumeric _ - .
4078 * Unicode characters can be enabled by setting $CFG->unicodecleanfilename = true in config.php
4080 * WARNING: unicode characters may not be compatible with zip compression in backup/restore,
4081 * because native zip binaries do weird character conversions. Use PHP zipping instead.
4083 * @param string $string file name
4084 * @return string cleaned file name
4086 function clean_filename($string) {
4088 if (empty($CFG->unicodecleanfilename
)) {
4089 $textlib = textlib_get_instance();
4090 $string = $textlib->specialtoascii($string);
4091 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
4093 //clean only ascii range
4094 $string = preg_replace("/[\\000-\\x2c\\x2f\\x3a-\\x40\\x5b-\\x5e\\x60\\x7b-\\177]/s", '_', $string);
4096 $string = preg_replace("/_+/", '_', $string);
4097 $string = preg_replace("/\.\.+/", '.', $string);
4102 /// STRING TRANSLATION ////////////////////////////////////////
4105 * Returns the code for the current language
4112 function current_language() {
4113 global $CFG, $USER, $SESSION, $COURSE;
4115 if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) { // Course language can override all other settings for this page
4116 $return = $COURSE->lang
;
4118 } else if (!empty($SESSION->lang
)) { // Session language can override other settings
4119 $return = $SESSION->lang
;
4121 } else if (!empty($USER->lang
)) {
4122 $return = $USER->lang
;
4125 $return = $CFG->lang
;
4128 if ($return == 'en') {
4129 $return = 'en_utf8';
4136 * Prints out a translated string.
4138 * Prints out a translated string using the return value from the {@link get_string()} function.
4140 * Example usage of this function when the string is in the moodle.php file:<br/>
4143 * print_string('wordforstudent');
4147 * Example usage of this function when the string is not in the moodle.php file:<br/>
4150 * print_string('typecourse', 'calendar');
4154 * @param string $identifier The key identifier for the localized string
4155 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4156 * @param mixed $a An object, string or number that can be used
4157 * within translation strings
4159 function print_string($identifier, $module='', $a=NULL) {
4160 echo get_string($identifier, $module, $a);
4164 * fix up the optional data in get_string()/print_string() etc
4165 * ensure possible sprintf() format characters are escaped correctly
4166 * needs to handle arbitrary strings and objects
4167 * @param mixed $a An object, string or number that can be used
4168 * @return mixed the supplied parameter 'cleaned'
4170 function clean_getstring_data( $a ) {
4171 if (is_string($a)) {
4172 return str_replace( '%','%%',$a );
4174 elseif (is_object($a)) {
4175 $a_vars = get_object_vars( $a );
4176 $new_a_vars = array();
4177 foreach ($a_vars as $fname => $a_var) {
4178 $new_a_vars[$fname] = clean_getstring_data( $a_var );
4180 return (object)$new_a_vars;
4188 * @return array places to look for lang strings based on the prefix to the
4189 * module name. For example qtype_ in question/type. Used by get_string and
4192 function places_to_search_for_lang_strings() {
4196 '__exceptions' => array('moodle', 'langconfig'),
4197 'assignment_' => array('mod/assignment/type'),
4198 'auth_' => array('auth'),
4199 'block_' => array('blocks'),
4200 'datafield_' => array('mod/data/field'),
4201 'datapreset_' => array('mod/data/preset'),
4202 'enrol_' => array('enrol'),
4203 'format_' => array('course/format'),
4204 'qtype_' => array('question/type'),
4205 'report_' => array($CFG->admin
.'/report', 'course/report', 'mod/quiz/report'),
4206 'resource_' => array('mod/resource/type'),
4212 * Returns a localized string.
4214 * Returns the translated string specified by $identifier as
4215 * for $module. Uses the same format files as STphp.
4216 * $a is an object, string or number that can be used
4217 * within translation strings
4219 * eg "hello \$a->firstname \$a->lastname"
4222 * If you would like to directly echo the localized string use
4223 * the function {@link print_string()}
4225 * Example usage of this function involves finding the string you would
4226 * like a local equivalent of and using its identifier and module information
4227 * to retrive it.<br/>
4228 * If you open moodle/lang/en/moodle.php and look near line 1031
4229 * you will find a string to prompt a user for their word for student
4231 * $string['wordforstudent'] = 'Your word for Student';
4233 * So if you want to display the string 'Your word for student'
4234 * in any language that supports it on your site
4235 * you just need to use the identifier 'wordforstudent'
4237 * $mystring = '<strong>'. get_string('wordforstudent') .'</strong>';
4240 * If the string you want is in another file you'd take a slightly
4241 * different approach. Looking in moodle/lang/en/calendar.php you find
4244 * $string['typecourse'] = 'Course event';
4246 * If you want to display the string "Course event" in any language
4247 * supported you would use the identifier 'typecourse' and the module 'calendar'
4248 * (because it is in the file calendar.php):
4250 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
4253 * As a last resort, should the identifier fail to map to a string
4254 * the returned string will be [[ $identifier ]]
4257 * @param string $identifier The key identifier for the localized string
4258 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4259 * @param mixed $a An object, string or number that can be used
4260 * within translation strings
4261 * @param array $extralocations An array of strings with other locations to look for string files
4262 * @return string The localized string.
4264 function get_string($identifier, $module='', $a=NULL, $extralocations=NULL) {
4268 /// originally these special strings were stored in moodle.php now we are only in langconfig.php
4269 $langconfigstrs = array('alphabet', 'backupnameformat', 'firstdayofweek', 'locale',
4270 'localewin', 'localewincharset', 'oldcharset',
4271 'parentlanguage', 'strftimedate', 'strftimedateshort', 'strftimedatetime',
4272 'strftimedaydate', 'strftimedaydatetime', 'strftimedayshort', 'strftimedaytime',
4273 'strftimemonthyear', 'strftimerecent', 'strftimerecentfull', 'strftimetime',
4274 'thischarset', 'thisdirection', 'thislanguage');
4276 $filetocheck = 'langconfig.php';
4277 $defaultlang = 'en_utf8';
4278 if (in_array($identifier, $langconfigstrs)) {
4279 $module = 'langconfig'; //This strings are under langconfig.php for 1.6 lang packs
4282 $lang = current_language();
4284 if ($module == '') {
4288 // if $a happens to have % in it, double it so sprintf() doesn't break
4290 $a = clean_getstring_data( $a );
4293 /// Define the two or three major locations of language strings for this module
4294 $locations = array();
4296 if (!empty($extralocations)) { // Calling code has a good idea where to look
4297 if (is_array($extralocations)) {
4298 $locations +
= $extralocations;
4299 } else if (is_string($extralocations)) {
4300 $locations[] = $extralocations;
4302 debugging('Bad lang path provided');
4306 if (isset($CFG->running_installer
)) {
4307 $module = 'installer';
4308 $filetocheck = 'installer.php';
4309 $locations +
= array( $CFG->dirroot
.'/install/lang/', $CFG->dataroot
.'/lang/', $CFG->dirroot
.'/lang/' );
4310 $defaultlang = 'en_utf8';
4312 $locations +
= array( $CFG->dataroot
.'/lang/', $CFG->dirroot
.'/lang/' );
4315 /// Add extra places to look for strings for particular plugin types.
4316 $rules = places_to_search_for_lang_strings();
4317 $exceptions = $rules['__exceptions'];
4318 unset($rules['__exceptions']);
4320 if (!in_array($module, $exceptions)) {
4321 $dividerpos = strpos($module, '_');
4322 if ($dividerpos === false) {
4326 $type = substr($module, 0, $dividerpos +
1);
4327 $plugin = substr($module, $dividerpos +
1);
4329 if (!empty($rules[$type])) {
4330 foreach ($rules[$type] as $location) {
4331 $locations[] = $CFG->dirroot
. "/$location/$plugin/lang/";
4336 /// First check all the normal locations for the string in the current language
4338 foreach ($locations as $location) {
4339 $locallangfile = $location.$lang.'_local'.'/'.$module.'.php'; //first, see if there's a local file
4340 if (file_exists($locallangfile)) {
4341 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4343 return $resultstring;
4346 //if local directory not found, or particular string does not exist in local direcotry
4347 $langfile = $location.$lang.'/'.$module.'.php';
4348 if (file_exists($langfile)) {
4349 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4351 return $resultstring;
4356 /// If the preferred language was English (utf8) we can abort now
4357 /// saving some checks beacuse it's the only "root" lang
4358 if ($lang == 'en_utf8') {
4359 return '[['. $identifier .']]';
4362 /// Is a parent language defined? If so, try to find this string in a parent language file
4364 foreach ($locations as $location) {
4365 $langfile = $location.$lang.'/'.$filetocheck;
4366 if (file_exists($langfile)) {
4367 if ($result = get_string_from_file('parentlanguage', $langfile, "\$parentlang")) {
4369 if (!empty($parentlang)) { // found it!
4371 //first, see if there's a local file for parent
4372 $locallangfile = $location.$parentlang.'_local'.'/'.$module.'.php';
4373 if (file_exists($locallangfile)) {
4374 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4376 return $resultstring;
4380 //if local directory not found, or particular string does not exist in local direcotry
4381 $langfile = $location.$parentlang.'/'.$module.'.php';
4382 if (file_exists($langfile)) {
4383 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4385 return $resultstring;
4393 /// Our only remaining option is to try English
4395 foreach ($locations as $location) {
4396 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4397 if (file_exists($locallangfile)) {
4398 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4400 return $resultstring;
4404 //if local_en not found, or string not found in local_en
4405 $langfile = $location.$defaultlang.'/'.$module.'.php';
4407 if (file_exists($langfile)) {
4408 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4410 return $resultstring;
4415 /// And, because under 1.6 en is defined as en_utf8 child, me must try
4416 /// if it hasn't been queried before.
4417 if ($defaultlang == 'en') {
4418 $defaultlang = 'en_utf8';
4419 foreach ($locations as $location) {
4420 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4421 if (file_exists($locallangfile)) {
4422 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4424 return $resultstring;
4428 //if local_en not found, or string not found in local_en
4429 $langfile = $location.$defaultlang.'/'.$module.'.php';
4431 if (file_exists($langfile)) {
4432 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4434 return $resultstring;
4440 return '[['.$identifier.']]'; // Last resort
4444 * This function is only used from {@link get_string()}.
4446 * @internal Only used from get_string, not meant to be public API
4447 * @param string $identifier ?
4448 * @param string $langfile ?
4449 * @param string $destination ?
4450 * @return string|false ?
4451 * @staticvar array $strings Localized strings
4453 * @todo Finish documenting this function.
4455 function get_string_from_file($identifier, $langfile, $destination) {
4457 static $strings; // Keep the strings cached in memory.
4459 if (empty($strings[$langfile])) {
4461 include ($langfile);
4462 $strings[$langfile] = $string;
4464 $string = &$strings[$langfile];
4467 if (!isset ($string[$identifier])) {
4471 return $destination .'= sprintf("'. $string[$identifier] .'");';
4475 * Converts an array of strings to their localized value.
4477 * @param array $array An array of strings
4478 * @param string $module The language module that these strings can be found in.
4481 function get_strings($array, $module='') {
4484 foreach ($array as $item) {
4485 $string->$item = get_string($item, $module);
4491 * Returns a list of language codes and their full names
4492 * hides the _local files from everyone.
4494 * @return array An associative array with contents in the form of LanguageCode => LanguageName
4496 function get_list_of_languages() {
4500 $languages = array();
4502 $filetocheck = 'langconfig.php';
4504 if ( (!defined('FULLME') || FULLME
!== 'cron')
4505 && !empty($CFG->langcache
) && file_exists($CFG->dataroot
.'/cache/languages')) {
4508 $lines = file($CFG->dataroot
.'/cache/languages');
4509 foreach ($lines as $line) {
4510 $line = trim($line);
4511 if (preg_match('/^(\w+)\s+(.+)/', $line, $matches)) {
4512 $languages[$matches[1]] = $matches[2];
4515 unset($lines); unset($line); unset($matches);
4519 if (!empty($CFG->langlist
)) { // use admin's list of languages
4521 $langlist = explode(',', $CFG->langlist
);
4522 foreach ($langlist as $lang) {
4523 $lang = trim($lang); //Just trim spaces to be a bit more permissive
4524 if (strstr($lang, '_local')!==false) {
4527 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4528 $shortlang = substr($lang, 0, -5);
4532 /// Search under dirroot/lang
4533 if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4534 include($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck);
4535 if (!empty($string['thislanguage'])) {
4536 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4540 /// And moodledata/lang
4541 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4542 include($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck);
4543 if (!empty($string['thislanguage'])) {
4544 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4550 /// Fetch langs from moodle/lang directory
4551 $langdirs = get_list_of_plugins('lang');
4552 /// Fetch langs from moodledata/lang directory
4553 $langdirs2 = get_list_of_plugins('lang', '', $CFG->dataroot
);
4554 /// Merge both lists of langs
4555 $langdirs = array_merge($langdirs, $langdirs2);
4558 /// Get some info from each lang (first from moodledata, then from moodle)
4559 foreach ($langdirs as $lang) {
4560 if (strstr($lang, '_local')!==false) {
4563 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4564 $shortlang = substr($lang, 0, -5);
4568 /// Search under moodledata/lang
4569 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4570 include($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck);
4571 if (!empty($string['thislanguage'])) {
4572 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4576 /// And dirroot/lang
4577 if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4578 include($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck);
4579 if (!empty($string['thislanguage'])) {
4580 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4587 if ( defined('FULLME') && FULLME
=== 'cron' && !empty($CFG->langcache
)) {
4588 if ($file = fopen($CFG->dataroot
.'/cache/languages', 'w')) {
4589 foreach ($languages as $key => $value) {
4590 fwrite($file, "$key $value\n");
4600 * Returns a list of charset codes. It's hardcoded, so they should be added manually
4601 * (cheking that such charset is supported by the texlib library!)
4603 * @return array And associative array with contents in the form of charset => charset
4605 function get_list_of_charsets() {
4608 'EUC-JP' => 'EUC-JP',
4609 'ISO-2022-JP'=> 'ISO-2022-JP',
4610 'ISO-8859-1' => 'ISO-8859-1',
4611 'SHIFT-JIS' => 'SHIFT-JIS',
4612 'GB2312' => 'GB2312',
4613 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
4614 'UTF-8' => 'UTF-8');
4622 * Returns a list of country names in the current language
4628 function get_list_of_countries() {
4631 $lang = current_language();
4633 if (!file_exists($CFG->dirroot
.'/lang/'. $lang .'/countries.php') &&
4634 !file_exists($CFG->dataroot
.'/lang/'. $lang .'/countries.php')) {
4635 if ($parentlang = get_string('parentlanguage')) {
4636 if (file_exists($CFG->dirroot
.'/lang/'. $parentlang .'/countries.php') ||
4637 file_exists($CFG->dataroot
.'/lang/'. $parentlang .'/countries.php')) {
4638 $lang = $parentlang;
4640 $lang = 'en_utf8'; // countries.php must exist in this pack
4643 $lang = 'en_utf8'; // countries.php must exist in this pack
4647 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/countries.php')) {
4648 include($CFG->dataroot
.'/lang/'. $lang .'/countries.php');
4649 } else if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/countries.php')) {
4650 include($CFG->dirroot
.'/lang/'. $lang .'/countries.php');
4653 if (!empty($string)) {
4661 * Returns a list of valid and compatible themes
4666 function get_list_of_themes() {
4672 if (!empty($CFG->themelist
)) { // use admin's list of themes
4673 $themelist = explode(',', $CFG->themelist
);
4675 $themelist = get_list_of_plugins("theme");
4678 foreach ($themelist as $key => $theme) {
4679 if (!file_exists("$CFG->themedir/$theme/config.php")) { // bad folder
4682 $THEME = new object(); // Note this is not the global one!! :-)
4683 include("$CFG->themedir/$theme/config.php");
4684 if (!isset($THEME->sheets
)) { // Not a valid 1.5 theme
4687 $themes[$theme] = $theme;
4696 * Returns a list of picture names in the current or specified language
4701 function get_list_of_pixnames($lang = '') {
4705 $lang = current_language();
4710 $path = $CFG->dirroot
.'/lang/en_utf8/pix.php'; // always exists
4712 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'_local/pix.php')) {
4713 $path = $CFG->dataroot
.'/lang/'. $lang .'_local/pix.php';
4715 } else if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/pix.php')) {
4716 $path = $CFG->dirroot
.'/lang/'. $lang .'/pix.php';
4718 } else if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/pix.php')) {
4719 $path = $CFG->dataroot
.'/lang/'. $lang .'/pix.php';
4721 } else if ($parentlang = get_string('parentlanguage') and $parentlang != '[[parentlanguage]]') {
4722 return get_list_of_pixnames($parentlang); //return pixnames from parent language instead
4731 * Returns a list of timezones in the current language
4736 function get_list_of_timezones() {
4739 $timezones = array();
4741 if ($rawtimezones = get_records_sql('SELECT MAX(id), name FROM '.$CFG->prefix
.'timezone GROUP BY name')) {
4742 foreach($rawtimezones as $timezone) {
4743 if (!empty($timezone->name
)) {
4744 $timezones[$timezone->name
] = get_string(strtolower($timezone->name
), 'timezones');
4745 if (substr($timezones[$timezone->name
], 0, 1) == '[') { // No translation found
4746 $timezones[$timezone->name
] = $timezone->name
;
4754 for ($i = -13; $i <= 13; $i +
= .5) {
4757 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
4758 } else if ($i > 0) {
4759 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
4761 $timezones[sprintf("%.1f", $i)] = $tzstring;
4769 * Returns a list of currencies in the current language
4775 function get_list_of_currencies() {
4778 $lang = current_language();
4780 if (!file_exists($CFG->dataroot
.'/lang/'. $lang .'/currencies.php')) {
4781 if ($parentlang = get_string('parentlanguage')) {
4782 if (file_exists($CFG->dataroot
.'/lang/'. $parentlang .'/currencies.php')) {
4783 $lang = $parentlang;
4785 $lang = 'en_utf8'; // currencies.php must exist in this pack
4788 $lang = 'en_utf8'; // currencies.php must exist in this pack
4792 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/currencies.php')) {
4793 include_once($CFG->dataroot
.'/lang/'. $lang .'/currencies.php');
4794 } else { //if en_utf8 is not installed in dataroot
4795 include_once($CFG->dirroot
.'/lang/'. $lang .'/currencies.php');
4798 if (!empty($string)) {
4808 * Can include a given document file (depends on second
4809 * parameter) or just return info about it.
4812 * @param string $file ?
4813 * @param bool $include ?
4815 * @todo Finish documenting this function
4817 function document_file($file, $include=true) {
4820 $file = clean_filename($file);
4826 $langs = array(current_language(), get_string('parentlanguage'), 'en');
4828 foreach ($langs as $lang) {
4829 $info = new object();
4830 $info->filepath
= $CFG->dirroot
.'/lang/'. $lang .'/docs/'. $file;
4831 $info->urlpath
= $CFG->wwwroot
.'/lang/'. $lang .'/docs/'. $file;
4833 if (file_exists($info->filepath
)) {
4835 include($info->filepath
);
4844 /// ENCRYPTION ////////////////////////////////////////////////
4849 * @param string $data ?
4851 * @todo Finish documenting this function
4853 function rc4encrypt($data) {
4854 $password = 'nfgjeingjk';
4855 return endecrypt($password, $data, '');
4861 * @param string $data ?
4863 * @todo Finish documenting this function
4865 function rc4decrypt($data) {
4866 $password = 'nfgjeingjk';
4867 return endecrypt($password, $data, 'de');
4871 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
4873 * @param string $pwd ?
4874 * @param string $data ?
4875 * @param string $case ?
4877 * @todo Finish documenting this function
4879 function endecrypt ($pwd, $data, $case) {
4881 if ($case == 'de') {
4882 $data = urldecode($data);
4890 $pwd_length = strlen($pwd);
4892 for ($i = 0; $i <= 255; $i++
) {
4893 $key[$i] = ord(substr($pwd, ($i %
$pwd_length), 1));
4899 for ($i = 0; $i <= 255; $i++
) {
4900 $x = ($x +
$box[$i] +
$key[$i]) %
256;
4901 $temp_swap = $box[$i];
4902 $box[$i] = $box[$x];
4903 $box[$x] = $temp_swap;
4915 for ($i = 0; $i < strlen($data); $i++
) {
4916 $a = ($a +
1) %
256;
4917 $j = ($j +
$box[$a]) %
256;
4919 $box[$a] = $box[$j];
4921 $k = $box[(($box[$a] +
$box[$j]) %
256)];
4922 $cipherby = ord(substr($data, $i, 1)) ^
$k;
4923 $cipher .= chr($cipherby);
4926 if ($case == 'de') {
4927 $cipher = urldecode(urlencode($cipher));
4929 $cipher = urlencode($cipher);
4936 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
4940 * Call this function to add an event to the calendar table
4941 * and to call any calendar plugins
4944 * @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:
4946 * <li><b>$event->name</b> - Name for the event
4947 * <li><b>$event->description</b> - Description of the event (defaults to '')
4948 * <li><b>$event->format</b> - Format for the description (using formatting types defined at the top of weblib.php)
4949 * <li><b>$event->courseid</b> - The id of the course this event belongs to (0 = all courses)
4950 * <li><b>$event->groupid</b> - The id of the group this event belongs to (0 = no group)
4951 * <li><b>$event->userid</b> - The id of the user this event belongs to (0 = no user)
4952 * <li><b>$event->modulename</b> - Name of the module that creates this event
4953 * <li><b>$event->instance</b> - Instance of the module that owns this event
4954 * <li><b>$event->eventtype</b> - The type info together with the module info could
4955 * be used by calendar plugins to decide how to display event
4956 * <li><b>$event->timestart</b>- Timestamp for start of event
4957 * <li><b>$event->timeduration</b> - Duration (defaults to zero)
4958 * <li><b>$event->visible</b> - 0 if the event should be hidden (e.g. because the activity that created it is hidden)
4960 * @return int The id number of the resulting record
4962 function add_event($event) {
4966 $event->timemodified
= time();
4968 if (!$event->id
= insert_record('event', $event)) {
4972 if (!empty($CFG->calendar
)) { // call the add_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_add_event = $CFG->calendar
.'_add_event';
4976 if (function_exists($calendar_add_event)) {
4977 $calendar_add_event($event);
4986 * Call this function to update an event in the calendar table
4987 * the event will be identified by the id field of the $event object.
4990 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
4993 function update_event($event) {
4997 $event->timemodified
= time();
4999 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
5000 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5001 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5002 $calendar_update_event = $CFG->calendar
.'_update_event';
5003 if (function_exists($calendar_update_event)) {
5004 $calendar_update_event($event);
5008 return update_record('event', $event);
5012 * Call this function to delete the event with id $id from calendar table.
5015 * @param int $id The id of an event from the 'calendar' table.
5016 * @return array An associative array with the results from the SQL call.
5017 * @todo Verify return type
5019 function delete_event($id) {
5023 if (!empty($CFG->calendar
)) { // call the delete_event function of the selected calendar
5024 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5025 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5026 $calendar_delete_event = $CFG->calendar
.'_delete_event';
5027 if (function_exists($calendar_delete_event)) {
5028 $calendar_delete_event($id);
5032 return delete_records('event', 'id', $id);
5036 * Call this function to hide an event in the calendar table
5037 * the event will be identified by the id field of the $event object.
5040 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5041 * @return array An associative array with the results from the SQL call.
5042 * @todo Verify return type
5044 function hide_event($event) {
5047 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
5048 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5049 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5050 $calendar_hide_event = $CFG->calendar
.'_hide_event';
5051 if (function_exists($calendar_hide_event)) {
5052 $calendar_hide_event($event);
5056 return set_field('event', 'visible', 0, 'id', $event->id
);
5060 * Call this function to unhide an event in the calendar table
5061 * the event will be identified by the id field of the $event object.
5064 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5065 * @return array An associative array with the results from the SQL call.
5066 * @todo Verify return type
5068 function show_event($event) {
5071 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
5072 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5073 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5074 $calendar_show_event = $CFG->calendar
.'_show_event';
5075 if (function_exists($calendar_show_event)) {
5076 $calendar_show_event($event);
5080 return set_field('event', 'visible', 1, 'id', $event->id
);
5084 /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
5087 * Lists plugin directories within some directory
5090 * @param string $plugin dir under we'll look for plugins (defaults to 'mod')
5091 * @param string $exclude dir name to exclude from the list (defaults to none)
5092 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
5093 * @return array of plugins found under the requested parameters
5095 function get_list_of_plugins($plugin='mod', $exclude='', $basedir='') {
5101 if (empty($basedir)) {
5103 # This switch allows us to use the appropiate theme directory - and potentialy alternatives for other plugins
5106 $basedir = $CFG->themedir
;
5110 $basedir = $CFG->dirroot
.'/'. $plugin;
5114 $basedir = $basedir .'/'. $plugin;
5117 if (file_exists($basedir) && filetype($basedir) == 'dir') {
5118 $dirhandle = opendir($basedir);
5119 while (false !== ($dir = readdir($dirhandle))) {
5120 $firstchar = substr($dir, 0, 1);
5121 if ($firstchar == '.' or $dir == 'CVS' or $dir == '_vti_cnf' or $dir == $exclude) {
5124 if (filetype($basedir .'/'. $dir) != 'dir') {
5129 closedir($dirhandle);
5138 * Returns true if the current version of PHP is greater that the specified one.
5140 * @param string $version The version of php being tested.
5143 function check_php_version($version='4.1.0') {
5144 return (version_compare(phpversion(), $version) >= 0);
5149 * Checks to see if is a browser matches the specified
5150 * brand and is equal or better version.
5153 * @param string $brand The browser identifier being tested
5154 * @param int $version The version of the browser
5155 * @return bool true if the given version is below that of the detected browser
5157 function check_browser_version($brand='MSIE', $version=5.5) {
5158 if (empty($_SERVER['HTTP_USER_AGENT'])) {
5162 $agent = $_SERVER['HTTP_USER_AGENT'];
5166 case 'Camino': /// Mozilla Firefox browsers
5168 if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
5169 if (version_compare($match[1], $version) >= 0) {
5176 case 'Firefox': /// Mozilla Firefox browsers
5178 if (preg_match("/Firefox\/([0-9\.]+)/i", $agent, $match)) {
5179 if (version_compare($match[1], $version) >= 0) {
5186 case 'Gecko': /// Gecko based browsers
5188 if (substr_count($agent, 'Camino')) {
5189 // MacOS X Camino support
5190 $version = 20041110;
5193 // the proper string - Gecko/CCYYMMDD Vendor/Version
5194 // Faster version and work-a-round No IDN problem.
5195 if (preg_match("/Gecko\/([0-9]+)/i", $agent, $match)) {
5196 if ($match[1] > $version) {
5203 case 'MSIE': /// Internet Explorer
5205 if (strpos($agent, 'Opera')) { // Reject Opera
5208 $string = explode(';', $agent);
5209 if (!isset($string[1])) {
5212 $string = explode(' ', trim($string[1]));
5213 if (!isset($string[0]) and !isset($string[1])) {
5216 if ($string[0] == $brand and (float)$string[1] >= $version ) {
5221 case 'Opera': /// Opera
5223 if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
5224 if (version_compare($match[1], $version) >= 0) {
5230 case 'Safari': /// Safari
5231 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SimbianOS
5232 if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
5234 } elseif (strpos($agent, 'Shiira')) { // Reject Shiira
5236 } elseif (strpos($agent, 'SimbianOS')) { // Reject SimbianOS
5240 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
5241 if (version_compare($match[1], $version) >= 0) {
5254 * This function makes the return value of ini_get consistent if you are
5255 * setting server directives through the .htaccess file in apache.
5256 * Current behavior for value set from php.ini On = 1, Off = [blank]
5257 * Current behavior for value set from .htaccess On = On, Off = Off
5258 * Contributed by jdell @ unr.edu
5260 * @param string $ini_get_arg ?
5262 * @todo Finish documenting this function
5264 function ini_get_bool($ini_get_arg) {
5265 $temp = ini_get($ini_get_arg);
5267 if ($temp == '1' or strtolower($temp) == 'on') {
5274 * Compatibility stub to provide backward compatibility
5276 * Determines if the HTML editor is enabled.
5277 * @deprecated Use {@link can_use_html_editor()} instead.
5279 function can_use_richtext_editor() {
5280 return can_use_html_editor();
5284 * Determines if the HTML editor is enabled.
5286 * This depends on site and user
5287 * settings, as well as the current browser being used.
5289 * @return string|false Returns false if editor is not being used, otherwise
5290 * returns 'MSIE' or 'Gecko'.
5292 function can_use_html_editor() {
5295 if (!empty($USER->htmleditor
) and !empty($CFG->htmleditor
)) {
5296 if (check_browser_version('MSIE', 5.5)) {
5298 } else if (check_browser_version('Gecko', 20030516)) {
5306 * Hack to find out the GD version by parsing phpinfo output
5308 * @return int GD version (1, 2, or 0)
5310 function check_gd_version() {
5313 if (function_exists('gd_info')){
5314 $gd_info = gd_info();
5315 if (substr_count($gd_info['GD Version'], '2.')) {
5317 } else if (substr_count($gd_info['GD Version'], '1.')) {
5324 $phpinfo = ob_get_contents();
5327 $phpinfo = explode("\n", $phpinfo);
5330 foreach ($phpinfo as $text) {
5331 $parts = explode('</td>', $text);
5332 foreach ($parts as $key => $val) {
5333 $parts[$key] = trim(strip_tags($val));
5335 if ($parts[0] == 'GD Version') {
5336 if (substr_count($parts[1], '2.0')) {
5339 $gdversion = intval($parts[1]);
5344 return $gdversion; // 1, 2 or 0
5348 * Determine if moodle installation requires update
5350 * Checks version numbers of main code and all modules to see
5351 * if there are any mismatches
5356 function moodle_needs_upgrading() {
5360 include_once($CFG->dirroot
.'/version.php'); # defines $version and upgrades
5361 if ($CFG->version
) {
5362 if ($version > $CFG->version
) {
5365 if ($mods = get_list_of_plugins('mod')) {
5366 foreach ($mods as $mod) {
5367 $fullmod = $CFG->dirroot
.'/mod/'. $mod;
5368 $module = new object();
5369 if (!is_readable($fullmod .'/version.php')) {
5370 notify('Module "'. $mod .'" is not readable - check permissions');
5373 include_once($fullmod .'/version.php'); # defines $module with version etc
5374 if ($currmodule = get_record('modules', 'name', $mod)) {
5375 if ($module->version
> $currmodule->version
) {
5388 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
5391 * Notify admin users or admin user of any failed logins (since last notification).
5397 function notify_login_failures() {
5400 switch ($CFG->notifyloginfailures
) {
5402 $recip = array(get_admin());
5405 $recip = get_admins();
5409 if (empty($CFG->lastnotifyfailure
)) {
5410 $CFG->lastnotifyfailure
=0;
5413 // we need to deal with the threshold stuff first.
5414 if (empty($CFG->notifyloginthreshold
)) {
5415 $CFG->notifyloginthreshold
= 10; // default to something sensible.
5418 $notifyipsrs = $db->Execute('SELECT ip FROM '. $CFG->prefix
.'log WHERE time > '. $CFG->lastnotifyfailure
.'
5419 AND module=\'login\' AND action=\'error\' GROUP BY ip HAVING count(*) > '. $CFG->notifyloginthreshold
);
5421 $notifyusersrs = $db->Execute('SELECT info FROM '. $CFG->prefix
.'log WHERE time > '. $CFG->lastnotifyfailure
.'
5422 AND module=\'login\' AND action=\'error\' GROUP BY info HAVING count(*) > '. $CFG->notifyloginthreshold
);
5426 while ($row = rs_fetch_next_record($notifyipsrs)) {
5427 $ipstr .= "'". $row->ip
."',";
5429 rs_close($notifyipsrs);
5430 $ipstr = substr($ipstr,0,strlen($ipstr)-1);
5432 if ($notifyusersrs) {
5434 while ($row = rs_fetch_next_record($notifyusersrs)) {
5435 $userstr .= "'". $row->info
."',";
5437 rs_close($notifyusersrs);
5438 $userstr = substr($userstr,0,strlen($userstr)-1);
5441 if (strlen($userstr) > 0 ||
strlen($ipstr) > 0) {
5443 $logs = get_logs('time > '. $CFG->lastnotifyfailure
.' AND module=\'login\' AND action=\'error\' '
5444 .((strlen($ipstr) > 0 && strlen($userstr) > 0) ?
' AND ( ip IN ('. $ipstr .') OR info IN ('. $userstr .') ) '
5445 : ((strlen($ipstr) != 0) ?
' AND ip IN ('. $ipstr .') ' : ' AND info IN ('. $userstr .') ')), 'l.time DESC', '', '', $count);
5447 // 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
5448 if (is_array($recip) and count($recip) > 0 and ((time() - HOURSECS
) > $CFG->lastnotifyfailure
)
5449 and is_array($logs) and count($logs) > 0) {
5453 $subject = get_string('notifyloginfailuressubject', '', $site->fullname
);
5454 $message .= get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot
)
5455 .(($CFG->lastnotifyfailure
!= 0) ?
'('.userdate($CFG->lastnotifyfailure
).')' : '')."\n\n";
5456 foreach ($logs as $log) {
5457 $log->time
= userdate($log->time
);
5458 $message .= get_string('notifyloginfailuresmessage','',$log)."\n";
5460 $message .= "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot
)."\n\n";
5461 foreach ($recip as $admin) {
5462 mtrace('Emailing '. $admin->username
.' about '. count($logs) .' failed login attempts');
5463 email_to_user($admin,get_admin(),$subject,$message);
5465 $conf = new object();
5466 $conf->name
= 'lastnotifyfailure';
5467 $conf->value
= time();
5468 if ($current = get_record('config', 'name', 'lastnotifyfailure')) {
5469 $conf->id
= $current->id
;
5470 if (! update_record('config', $conf)) {
5471 mtrace('Could not update last notify time');
5474 } else if (! insert_record('config', $conf)) {
5475 mtrace('Could not set last notify time');
5485 * @param string $locale ?
5486 * @todo Finish documenting this function
5488 function moodle_setlocale($locale='') {
5492 static $currentlocale = ''; // last locale caching
5494 $oldlocale = $currentlocale;
5496 /// Fetch the correct locale based on ostype
5497 if($CFG->ostype
== 'WINDOWS') {
5498 $stringtofetch = 'localewin';
5500 $stringtofetch = 'locale';
5503 /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
5504 if (!empty($locale)) {
5505 $currentlocale = $locale;
5506 } else if (!empty($CFG->locale
)) { // override locale for all language packs
5507 $currentlocale = $CFG->locale
;
5509 $currentlocale = get_string($stringtofetch);
5512 /// do nothing if locale already set up
5513 if ($oldlocale == $currentlocale) {
5517 /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
5518 /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
5519 /// Some day, numeric, monetary and other categories should be set too, I think. :-/
5521 /// Get current values
5522 $monetary= setlocale (LC_MONETARY
, 0);
5523 $numeric = setlocale (LC_NUMERIC
, 0);
5524 $ctype = setlocale (LC_CTYPE
, 0);
5525 if ($CFG->ostype
!= 'WINDOWS') {
5526 $messages= setlocale (LC_MESSAGES
, 0);
5528 /// Set locale to all
5529 setlocale (LC_ALL
, $currentlocale);
5531 setlocale (LC_MONETARY
, $monetary);
5532 setlocale (LC_NUMERIC
, $numeric);
5533 if ($CFG->ostype
!= 'WINDOWS') {
5534 setlocale (LC_MESSAGES
, $messages);
5536 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
5537 setlocale (LC_CTYPE
, $ctype);
5542 * Converts string to lowercase using most compatible function available.
5544 * @param string $string The string to convert to all lowercase characters.
5545 * @param string $encoding The encoding on the string.
5547 * @todo Add examples of calling this function with/without encoding types
5548 * @deprecated Use textlib->strtolower($text) instead.
5550 function moodle_strtolower ($string, $encoding='') {
5552 //If not specified use utf8
5553 if (empty($encoding)) {
5554 $encoding = 'UTF-8';
5557 $textlib = textlib_get_instance();
5559 return $textlib->strtolower($string, $encoding);
5563 * Count words in a string.
5565 * Words are defined as things between whitespace.
5567 * @param string $string The text to be searched for words.
5568 * @return int The count of words in the specified string
5570 function count_words($string) {
5571 $string = strip_tags($string);
5572 return count(preg_split("/\w\b/", $string)) - 1;
5575 /** Count letters in a string.
5577 * Letters are defined as chars not in tags and different from whitespace.
5579 * @param string $string The text to be searched for letters.
5580 * @return int The count of letters in the specified text.
5582 function count_letters($string) {
5583 /// Loading the textlib singleton instance. We are going to need it.
5584 $textlib = textlib_get_instance();
5586 $string = strip_tags($string); // Tags are out now
5587 $string = ereg_replace('[[:space:]]*','',$string); //Whitespace are out now
5589 return $textlib->strlen($string);
5593 * Generate and return a random string of the specified length.
5595 * @param int $length The length of the string to be created.
5598 function random_string ($length=15) {
5599 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
5600 $pool .= 'abcdefghijklmnopqrstuvwxyz';
5601 $pool .= '0123456789';
5602 $poollen = strlen($pool);
5603 mt_srand ((double) microtime() * 1000000);
5605 for ($i = 0; $i < $length; $i++
) {
5606 $string .= substr($pool, (mt_rand()%
($poollen)), 1);
5612 * Given some text (which may contain HTML) and an ideal length,
5613 * this function truncates the text neatly on a word boundary if possible
5615 function shorten_text($text, $ideal=30) {
5622 $length = strlen($text);
5627 if ($length <= $ideal) {
5631 for ($i=0; $i<$length; $i++
) {
5644 if ($char == '.' or $char == ' ') {
5647 } else if (ord($char) >= 0xE0) { // Chinese/Japanese/Korean text
5648 $truncate = $i; // can be truncated at any UTF-8
5649 break 2; // character boundary.
5657 if ($count > $ideal) {
5667 $ellipse = ($truncate < $length) ?
'...' : '';
5669 return substr($text, 0, $truncate).$ellipse;
5674 * Given dates in seconds, how many weeks is the date from startdate
5675 * The first week is 1, the second 2 etc ...
5678 * @param ? $startdate ?
5679 * @param ? $thedate ?
5681 * @todo Finish documenting this function
5683 function getweek ($startdate, $thedate) {
5684 if ($thedate < $startdate) { // error
5688 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
5692 * returns a randomly generated password of length $maxlen. inspired by
5693 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3}
5695 * @param int $maxlength The maximum size of the password being generated.
5698 function generate_password($maxlen=10) {
5701 $fillers = '1234567890!$-+';
5702 $wordlist = file($CFG->wordlist
);
5704 srand((double) microtime() * 1000000);
5705 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
5706 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
5707 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
5709 return substr($word1 . $filler1 . $word2, 0, $maxlen);
5713 * Given a float, prints it nicely
5715 * @param float $num The float to print
5716 * @param int $places The number of decimal places to print.
5719 function format_float($num, $places=1) {
5720 return sprintf("%.$places"."f", $num);
5724 * Given a simple array, this shuffles it up just like shuffle()
5725 * Unlike PHP's shuffle() ihis function works on any machine.
5727 * @param array $array The array to be rearranged
5730 function swapshuffle($array) {
5732 srand ((double) microtime() * 10000000);
5733 $last = count($array) - 1;
5734 for ($i=0;$i<=$last;$i++
) {
5735 $from = rand(0,$last);
5737 $array[$i] = $array[$from];
5738 $array[$from] = $curr;
5744 * Like {@link swapshuffle()}, but works on associative arrays
5746 * @param array $array The associative array to be rearranged
5749 function swapshuffle_assoc($array) {
5752 $newkeys = swapshuffle(array_keys($array));
5753 foreach ($newkeys as $newkey) {
5754 $newarray[$newkey] = $array[$newkey];
5760 * Given an arbitrary array, and a number of draws,
5761 * this function returns an array with that amount
5762 * of items. The indexes are retained.
5764 * @param array $array ?
5767 * @todo Finish documenting this function
5769 function draw_rand_array($array, $draws) {
5770 srand ((double) microtime() * 10000000);
5774 $last = count($array);
5776 if ($draws > $last) {
5780 while ($draws > 0) {
5783 $keys = array_keys($array);
5784 $rand = rand(0, $last);
5786 $return[$keys[$rand]] = $array[$keys[$rand]];
5787 unset($array[$keys[$rand]]);
5798 * @param string $a ?
5799 * @param string $b ?
5801 * @todo Finish documenting this function
5803 function microtime_diff($a, $b) {
5804 list($a_dec, $a_sec) = explode(' ', $a);
5805 list($b_dec, $b_sec) = explode(' ', $b);
5806 return $b_sec - $a_sec +
$b_dec - $a_dec;
5810 * Given a list (eg a,b,c,d,e) this function returns
5811 * an array of 1->a, 2->b, 3->c etc
5813 * @param array $list ?
5814 * @param string $separator ?
5815 * @todo Finish documenting this function
5817 function make_menu_from_list($list, $separator=',') {
5819 $array = array_reverse(explode($separator, $list), true);
5820 foreach ($array as $key => $item) {
5821 $outarray[$key+
1] = trim($item);
5827 * Creates an array that represents all the current grades that
5828 * can be chosen using the given grading type. Negative numbers
5829 * are scales, zero is no grade, and positive numbers are maximum
5832 * @param int $gradingtype ?
5834 * @todo Finish documenting this function
5836 function make_grades_menu($gradingtype) {
5838 if ($gradingtype < 0) {
5839 if ($scale = get_record('scale', 'id', - $gradingtype)) {
5840 return make_menu_from_list($scale->scale
);
5842 } else if ($gradingtype > 0) {
5843 for ($i=$gradingtype; $i>=0; $i--) {
5844 $grades[$i] = $i .' / '. $gradingtype;
5852 * This function returns the nummber of activities
5853 * using scaleid in a courseid
5855 * @param int $courseid ?
5856 * @param int $scaleid ?
5858 * @todo Finish documenting this function
5860 function course_scale_used($courseid, $scaleid) {
5866 if (!empty($scaleid)) {
5867 if ($cms = get_course_mods($courseid)) {
5868 foreach ($cms as $cm) {
5869 //Check cm->name/lib.php exists
5870 if (file_exists($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php')) {
5871 include_once($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php');
5872 $function_name = $cm->modname
.'_scale_used';
5873 if (function_exists($function_name)) {
5874 if ($function_name($cm->instance
,$scaleid)) {
5886 * This function returns the nummber of activities
5887 * using scaleid in the entire site
5889 * @param int $scaleid ?
5891 * @todo Finish documenting this function. Is return type correct?
5893 function site_scale_used($scaleid,&$courses) {
5899 if (!is_array($courses) ||
count($courses) == 0) {
5900 $courses = get_courses("all",false,"c.id,c.shortname");
5903 if (!empty($scaleid)) {
5904 if (is_array($courses) && count($courses) > 0) {
5905 foreach ($courses as $course) {
5906 $return +
= course_scale_used($course->id
,$scaleid);
5914 * make_unique_id_code
5916 * @param string $extra ?
5918 * @todo Finish documenting this function
5920 function make_unique_id_code($extra='') {
5922 $hostname = 'unknownhost';
5923 if (!empty($_SERVER['HTTP_HOST'])) {
5924 $hostname = $_SERVER['HTTP_HOST'];
5925 } else if (!empty($_ENV['HTTP_HOST'])) {
5926 $hostname = $_ENV['HTTP_HOST'];
5927 } else if (!empty($_SERVER['SERVER_NAME'])) {
5928 $hostname = $_SERVER['SERVER_NAME'];
5929 } else if (!empty($_ENV['SERVER_NAME'])) {
5930 $hostname = $_ENV['SERVER_NAME'];
5933 $date = gmdate("ymdHis");
5935 $random = random_string(6);
5938 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
5940 return $hostname .'+'. $date .'+'. $random;
5946 * Function to check the passed address is within the passed subnet
5948 * The parameter is a comma separated string of subnet definitions.
5949 * Subnet strings can be in one of three formats:
5950 * 1: xxx.xxx.xxx.xxx/xx
5952 * 3: xxx.xxx.xxx.xxx-xxx //a range of IP addresses in the last group.
5953 * Code for type 1 modified from user posted comments by mediator at
5954 * {@link http://au.php.net/manual/en/function.ip2long.php}
5956 * @param string $addr The address you are checking
5957 * @param string $subnetstr The string of subnet addresses
5960 function address_in_subnet($addr, $subnetstr) {
5962 $subnets = explode(',', $subnetstr);
5964 $addr = trim($addr);
5966 foreach ($subnets as $subnet) {
5967 $subnet = trim($subnet);
5968 if (strpos($subnet, '/') !== false) { /// type 1
5969 list($ip, $mask) = explode('/', $subnet);
5970 $mask = 0xffffffff << (32 - $mask);
5971 $found = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
5972 } else if (strpos($subnet, '-') !== false) {/// type 3
5973 $subnetparts = explode('.', $subnet);
5974 $addrparts = explode('.', $addr);
5975 $subnetrange = explode('-', array_pop($subnetparts));
5976 if (count($subnetrange) == 2) {
5977 $lastaddrpart = array_pop($addrparts);
5978 $found = ($subnetparts == $addrparts &&
5979 $subnetrange[0] <= $lastaddrpart && $lastaddrpart <= $subnetrange[1]);
5982 $found = (strpos($addr, $subnet) === 0);
5993 * This function sets the $HTTPSPAGEREQUIRED global
5994 * (used in some parts of moodle to change some links)
5995 * and calculate the proper wwwroot to be used
5997 * By using this function properly, we can ensure 100% https-ized pages
5998 * at our entire discretion (login, forgot_password, change_password)
6000 function httpsrequired() {
6002 global $CFG, $HTTPSPAGEREQUIRED;
6004 if (!empty($CFG->loginhttps
)) {
6005 $HTTPSPAGEREQUIRED = true;
6006 $CFG->httpswwwroot
= str_replace('http:', 'https:', $CFG->wwwroot
);
6007 $CFG->httpsthemewww
= str_replace('http:', 'https:', $CFG->themewww
);
6009 // change theme URLs to https
6013 $CFG->httpswwwroot
= $CFG->wwwroot
;
6014 $CFG->httpsthemewww
= $CFG->themewww
;
6019 * For outputting debugging info
6022 * @param string $string ?
6023 * @param string $eol ?
6024 * @todo Finish documenting this function
6026 function mtrace($string, $eol="\n", $sleep=0) {
6028 if (defined('STDOUT')) {
6029 fwrite(STDOUT
, $string.$eol);
6031 echo $string . $eol;
6036 //delay to keep message on user's screen in case of subsequent redirect
6042 //Replace 1 or more slashes or backslashes to 1 slash
6043 function cleardoubleslashes ($path) {
6044 return preg_replace('/(\/|\\\){1,}/','/',$path);
6047 function zip_files ($originalfiles, $destination) {
6048 //Zip an array of files/dirs to a destination zip file
6049 //Both parameters must be FULL paths to the files/dirs
6053 //Extract everything from destination
6054 $path_parts = pathinfo(cleardoubleslashes($destination));
6055 $destpath = $path_parts["dirname"]; //The path of the zip file
6056 $destfilename = $path_parts["basename"]; //The name of the zip file
6057 $extension = $path_parts["extension"]; //The extension of the file
6060 if (empty($destfilename)) {
6064 //If no extension, add it
6065 if (empty($extension)) {
6067 $destfilename = $destfilename.'.'.$extension;
6070 //Check destination path exists
6071 if (!is_dir($destpath)) {
6075 //Check destination path is writable. TODO!!
6077 //Clean destination filename
6078 $destfilename = clean_filename($destfilename);
6080 //Now check and prepare every file
6084 foreach ($originalfiles as $file) { //Iterate over each file
6085 //Check for every file
6086 $tempfile = cleardoubleslashes($file); // no doubleslashes!
6087 //Calculate the base path for all files if it isn't set
6088 if ($origpath === NULL) {
6089 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
6091 //See if the file is readable
6092 if (!is_readable($tempfile)) { //Is readable
6095 //See if the file/dir is in the same directory than the rest
6096 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
6099 //Add the file to the array
6100 $files[] = $tempfile;
6103 //Everything is ready:
6104 // -$origpath is the path where ALL the files to be compressed reside (dir).
6105 // -$destpath is the destination path where the zip file will go (dir).
6106 // -$files is an array of files/dirs to compress (fullpath)
6107 // -$destfilename is the name of the zip file (without path)
6109 //print_object($files); //Debug
6111 if (empty($CFG->zip
)) { // Use built-in php-based zip function
6113 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6114 //rewrite filenames because the old method with PCLZIP_OPT_REMOVE_PATH does not work under win32
6115 $zipfiles = array();
6116 $start = strlen($origpath)+
1;
6117 foreach($files as $file) {
6119 $tf[PCLZIP_ATT_FILE_NAME
] = $file;
6120 $tf[PCLZIP_ATT_FILE_NEW_FULL_NAME
] = substr($file, $start);
6123 //create the archive
6124 $archive = new PclZip(cleardoubleslashes("$destpath/$destfilename"));
6125 if (($list = $archive->create($zipfiles) == 0)) {
6126 notice($archive->errorInfo(true));
6130 } else { // Use external zip program
6133 foreach ($files as $filetozip) {
6134 $filestozip .= escapeshellarg(basename($filetozip));
6137 //Construct the command
6138 $separator = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
' &' : ' ;';
6139 $command = 'cd '.escapeshellarg($origpath).$separator.
6140 escapeshellarg($CFG->zip
).' -r '.
6141 escapeshellarg(cleardoubleslashes("$destpath/$destfilename")).' '.$filestozip;
6142 //All converted to backslashes in WIN
6143 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6144 $command = str_replace('/','\\',$command);
6151 function unzip_file ($zipfile, $destination = '', $showstatus = true) {
6152 //Unzip one zip file to a destination dir
6153 //Both parameters must be FULL paths
6154 //If destination isn't specified, it will be the
6155 //SAME directory where the zip file resides.
6159 //Extract everything from zipfile
6160 $path_parts = pathinfo(cleardoubleslashes($zipfile));
6161 $zippath = $path_parts["dirname"]; //The path of the zip file
6162 $zipfilename = $path_parts["basename"]; //The name of the zip file
6163 $extension = $path_parts["extension"]; //The extension of the file
6166 if (empty($zipfilename)) {
6170 //If no extension, error
6171 if (empty($extension)) {
6176 $zipfile = cleardoubleslashes($zipfile);
6178 //Check zipfile exists
6179 if (!file_exists($zipfile)) {
6183 //If no destination, passed let's go with the same directory
6184 if (empty($destination)) {
6185 $destination = $zippath;
6188 //Clear $destination
6189 $destpath = rtrim(cleardoubleslashes($destination), "/");
6191 //Check destination path exists
6192 if (!is_dir($destpath)) {
6196 //Check destination path is writable. TODO!!
6198 //Everything is ready:
6199 // -$zippath is the path where the zip file resides (dir)
6200 // -$zipfilename is the name of the zip file (without path)
6201 // -$destpath is the destination path where the zip file will uncompressed (dir)
6205 if (empty($CFG->unzip
)) { // Use built-in php-based unzip function
6207 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6208 $archive = new PclZip(cleardoubleslashes("$zippath/$zipfilename"));
6209 if (!$list = $archive->extract(PCLZIP_OPT_PATH
, $destpath,
6210 PCLZIP_CB_PRE_EXTRACT
, 'unzip_cleanfilename',
6211 PCLZIP_OPT_EXTRACT_DIR_RESTRICTION
, $destpath)) {
6212 notice($archive->errorInfo(true));
6216 } else { // Use external unzip program
6218 $separator = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
' &' : ' ;';
6219 $redirection = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
'' : ' 2>&1';
6221 $command = 'cd '.escapeshellarg($zippath).$separator.
6222 escapeshellarg($CFG->unzip
).' -o '.
6223 escapeshellarg(cleardoubleslashes("$zippath/$zipfilename")).' -d '.
6224 escapeshellarg($destpath).$redirection;
6225 //All converted to backslashes in WIN
6226 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6227 $command = str_replace('/','\\',$command);
6229 Exec($command,$list);
6232 //Display some info about the unzip execution
6234 unzip_show_status($list,$destpath);
6240 function unzip_cleanfilename ($p_event, &$p_header) {
6241 //This function is used as callback in unzip_file() function
6242 //to clean illegal characters for given platform and to prevent directory traversal.
6243 //Produces the same result as info-zip unzip.
6244 $p_header['filename'] = ereg_replace('[[:cntrl:]]', '', $p_header['filename']); //strip control chars first!
6245 $p_header['filename'] = ereg_replace('\.\.+', '', $p_header['filename']); //directory traversal protection
6246 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6247 $p_header['filename'] = ereg_replace('[:*"?<>|]', '_', $p_header['filename']); //replace illegal chars
6248 $p_header['filename'] = ereg_replace('^([a-zA-Z])_', '\1:', $p_header['filename']); //repair drive letter
6250 //Add filtering for other systems here
6251 // BSD: none (tested)
6255 $p_header['filename'] = cleardoubleslashes($p_header['filename']); //normalize the slashes/backslashes
6259 function unzip_show_status ($list,$removepath) {
6260 //This function shows the results of the unzip execution
6261 //depending of the value of the $CFG->zip, results will be
6262 //text or an array of files.
6266 if (empty($CFG->unzip
)) { // Use built-in php-based zip function
6267 $strname = get_string("name");
6268 $strsize = get_string("size");
6269 $strmodified = get_string("modified");
6270 $strstatus = get_string("status");
6271 echo "<table width=\"640\">";
6272 echo "<tr><th class=\"header\" scope=\"col\">$strname</th>";
6273 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strsize</th>";
6274 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strmodified</th>";
6275 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strstatus</th></tr>";
6276 foreach ($list as $item) {
6278 $item['filename'] = str_replace(cleardoubleslashes($removepath).'/', "", $item['filename']);
6279 print_cell("left", s($item['filename']));
6280 if (! $item['folder']) {
6281 print_cell("right", display_size($item['size']));
6283 echo "<td> </td>";
6285 $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
6286 print_cell("right", $filedate);
6287 print_cell("right", $item['status']);
6292 } else { // Use external zip program
6293 print_simple_box_start("center");
6295 foreach ($list as $item) {
6296 echo s(str_replace(cleardoubleslashes($removepath.'/'), '', $item)).'<br />';
6299 print_simple_box_end();
6304 * Returns most reliable client address
6306 * @return string The remote IP address
6308 function getremoteaddr() {
6309 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
6310 return cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
6312 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
6313 return cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
6315 if (!empty($_SERVER['REMOTE_ADDR'])) {
6316 return cleanremoteaddr($_SERVER['REMOTE_ADDR']);
6322 * Cleans a remote address ready to put into the log table
6324 function cleanremoteaddr($addr) {
6325 $originaladdr = $addr;
6327 // first get all things that look like IP addresses.
6328 if (!preg_match_all('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/',$addr,$matches,PREG_SET_ORDER
)) {
6331 $goodmatches = array();
6332 $lanmatches = array();
6333 foreach ($matches as $match) {
6335 // check to make sure it's not an internal address.
6336 // the following are reserved for private lans...
6337 // 10.0.0.0 - 10.255.255.255
6338 // 172.16.0.0 - 172.31.255.255
6339 // 192.168.0.0 - 192.168.255.255
6340 // 169.254.0.0 -169.254.255.255
6341 $bits = explode('.',$match[0]);
6342 if (count($bits) != 4) {
6343 // weird, preg match shouldn't give us it.
6346 if (($bits[0] == 10)
6347 ||
($bits[0] == 172 && $bits[1] >= 16 && $bits[1] <= 31)
6348 ||
($bits[0] == 192 && $bits[1] == 168)
6349 ||
($bits[0] == 169 && $bits[1] == 254)) {
6350 $lanmatches[] = $match[0];
6354 $goodmatches[] = $match[0];
6356 if (!count($goodmatches)) {
6357 // perhaps we have a lan match, it's probably better to return that.
6358 if (!count($lanmatches)) {
6361 return array_pop($lanmatches);
6364 if (count($goodmatches) == 1) {
6365 return $goodmatches[0];
6367 error_log("NOTICE: cleanremoteaddr gives us something funny: $originaladdr had ".count($goodmatches)." matches");
6368 // we need to return something, so
6369 return array_pop($goodmatches);
6373 * file_put_contents is only supported by php 5.0 and higher
6374 * so if it is not predefined, define it here
6376 * @param $file full path of the file to write
6377 * @param $contents contents to be sent
6378 * @return number of bytes written (false on error)
6380 if(!function_exists('file_put_contents')) {
6381 function file_put_contents($file, $contents) {
6383 if ($f = fopen($file, 'w')) {
6384 $result = fwrite($f, $contents);
6392 * The clone keyword is only supported from PHP 5 onwards.
6393 * The behaviour of $obj2 = $obj1 differs fundamentally
6394 * between PHP 4 and PHP 5. In PHP 4 a copy of $obj1 was
6395 * created, in PHP 5 $obj1 is referenced. To create a copy
6396 * in PHP 5 the clone keyword was introduced. This function
6397 * simulates this behaviour for PHP < 5.0.0.
6398 * See also: http://mjtsai.com/blog/2004/07/15/php-5-object-references/
6400 * Modified 2005-09-29 by Eloy (from Julian Sedding proposal)
6401 * Found a better implementation (more checks and possibilities) from PEAR:
6402 * http://cvs.php.net/co.php/pear/PHP_Compat/Compat/Function/clone.php
6404 * @param object $obj
6407 if(!check_php_version('5.0.0')) {
6408 // the eval is needed to prevent PHP 5 from getting a parse error!
6410 function clone($obj) {
6412 if (!is_object($obj)) {
6413 user_error(\'clone() __clone method called on non-object\', E_USER_WARNING);
6417 /// Use serialize/unserialize trick to deep copy the object
6418 $obj = unserialize(serialize($obj));
6420 /// If there is a __clone method call it on the "new" class
6421 if (method_exists($obj, \'__clone\')) {
6428 // Supply the PHP5 function scandir() to older versions.
6429 function scandir($directory) {
6431 if ($dh = opendir($directory)) {
6432 while (($file = readdir($dh)) !== false) {
6440 // Supply the PHP5 function array_combine() to older versions.
6441 function array_combine($keys, $values) {
6442 if (!is_array($keys) || !is_array($values) || count($keys) != count($values)) {
6447 foreach ($keys as $key) {
6448 $result[$key] = current($values);
6457 * This function will make a complete copy of anything it's given,
6458 * regardless of whether it's an object or not.
6459 * @param mixed $thing
6462 function fullclone($thing) {
6463 return unserialize(serialize($thing));
6468 * If new messages are waiting for the current user, then return
6469 * Javascript code to create a popup window
6471 * @return string Javascript code
6473 function message_popup_window() {
6476 $popuplimit = 30; // Minimum seconds between popups
6478 if (!defined('MESSAGE_WINDOW')) {
6479 if (isset($USER->id
)) {
6480 if (!isset($USER->message_lastpopup
)) {
6481 $USER->message_lastpopup
= 0;
6483 if ((time() - $USER->message_lastpopup
) > $popuplimit) { /// It's been long enough
6484 if (get_user_preferences('message_showmessagewindow', 1) == 1) {
6485 if (count_records_select('message', 'useridto = \''.$USER->id
.'\' AND timecreated > \''.$USER->message_lastpopup
.'\'')) {
6486 $USER->message_lastpopup
= time();
6487 return '<script type="text/javascript">'."\n//<![CDATA[\n openpopup('/message/index.php', 'message',
6488 'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500', 0);\n//]]>\n</script>";
6498 // Used to make sure that $min <= $value <= $max
6499 function bounded_number($min, $value, $max) {
6509 function array_is_nested($array) {
6510 foreach ($array as $value) {
6511 if (is_array($value)) {
6519 *** get_performance_info() pairs up with init_performance_info()
6520 *** loaded in setup.php. Returns an array with 'html' and 'txt'
6521 *** values ready for use, and each of the individual stats provided
6522 *** separately as well.
6525 function get_performance_info() {
6526 global $CFG, $PERF, $rcache;
6529 $info['html'] = ''; // holds userfriendly HTML representation
6530 $info['txt'] = me() . ' '; // holds log-friendly representation
6532 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
6534 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
6535 $info['txt'] .= 'time: '.$info['realtime'].'s ';
6537 if (function_exists('memory_get_usage')) {
6538 $info['memory_total'] = memory_get_usage();
6539 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
6540 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
6541 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
6544 $inc = get_included_files();
6545 //error_log(print_r($inc,1));
6546 $info['includecount'] = count($inc);
6547 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
6548 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
6550 if (!empty($PERF->dbqueries
)) {
6551 $info['dbqueries'] = $PERF->dbqueries
;
6552 $info['html'] .= '<span class="dbqueries">DB queries '.$info['dbqueries'].'</span> ';
6553 $info['txt'] .= 'dbqueries: '.$info['dbqueries'].' ';
6556 if (!empty($PERF->logwrites
)) {
6557 $info['logwrites'] = $PERF->logwrites
;
6558 $info['html'] .= '<span class="logwrites">Log writes '.$info['logwrites'].'</span> ';
6559 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
6562 if (!empty($PERF->profiling
)) {
6563 require_once($CFG->dirroot
.'/lib/profilerlib.php');
6564 $profiler = new Profiler();
6565 $info['html'] .= '<span class="profilinginfo">'.$profiler->get_profiling().'</span>';
6568 if (function_exists('posix_times')) {
6569 $ptimes = posix_times();
6570 if (is_array($ptimes)) {
6571 foreach ($ptimes as $key => $val) {
6572 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
6574 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
6575 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
6579 // Grab the load average for the last minute
6580 // /proc will only work under some linux configurations
6581 // while uptime is there under MacOSX/Darwin and other unices
6582 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
6583 list($server_load) = explode(' ', $loadavg[0]);
6585 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
6586 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
6587 $server_load = $matches[1];
6589 trigger_error('Could not parse uptime output!');
6592 if (!empty($server_load)) {
6593 $info['serverload'] = $server_load;
6594 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
6595 $info['txt'] .= "serverload: {$info['serverload']} ";
6598 if (isset($rcache->hits
) && isset($rcache->misses
)) {
6599 $info['rcachehits'] = $rcache->hits
;
6600 $info['rcachemisses'] = $rcache->misses
;
6601 $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
6602 "{$rcache->hits}/{$rcache->misses}</span> ";
6603 $info['txt'] .= 'rcache: '.
6604 "{$rcache->hits}/{$rcache->misses} ";
6606 $info['html'] = '<div class="performanceinfo">'.$info['html'].'</div>';
6610 function apd_get_profiling() {
6611 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
6614 function remove_dir($dir, $content_only=false) {
6615 // if content_only=true then delete all but
6616 // the directory itself
6618 $handle = opendir($dir);
6619 while (false!==($item = readdir($handle))) {
6620 if($item != '.' && $item != '..') {
6621 if(is_dir($dir.'/'.$item)) {
6622 remove_dir($dir.'/'.$item);
6624 unlink($dir.'/'.$item);
6629 if ($content_only) {
6636 * Function to check if a directory exists and optionally create it.
6638 * @param string absolute directory path
6639 * @param boolean create directory if does not exist
6640 * @param boolean create directory recursively
6642 * @return boolean true if directory exists or created
6644 function check_dir_exists($dir, $create=false, $recursive=false) {
6656 // PHP 5.0 has recursive mkdir parameter, but 4.x does not :-(
6657 $dir = str_replace('\\', '/', $dir); //windows compatibility
6658 $dirs = explode('/', $dir);
6659 $dir = array_shift($dirs).'/'; //skip root or drive letter
6660 foreach ($dirs as $part) {
6665 if (!is_dir($dir)) {
6666 if (!mkdir($dir, $CFG->directorypermissions
)) {
6673 $status = mkdir($dir, $CFG->directorypermissions
);
6680 function report_session_error() {
6681 global $CFG, $FULLME;
6683 if (empty($CFG->lang
)) {
6686 // Set up default theme and locale
6690 //clear session cookies
6691 setcookie('MoodleSession'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
6692 setcookie('MoodleSessionTest'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
6693 //increment database error counters
6694 if (isset($CFG->session_error_counter
)) {
6695 set_config('session_error_counter', 1 +
$CFG->session_error_counter
);
6697 set_config('session_error_counter', 1);
6699 redirect($FULLME, get_string('sessionerroruser2', 'error'), 5);
6704 * Detect if an object or a class contains a given property
6705 * will take an actual object or the name of a class
6706 * @param mix $obj Name of class or real object to test
6707 * @param string $property name of property to find
6708 * @return bool true if property exists
6710 function object_property_exists( $obj, $property ) {
6711 if (is_string( $obj )) {
6712 $properties = get_class_vars( $obj );
6715 $properties = get_object_vars( $obj );
6717 return array_key_exists( $property, $properties );
6722 * Detect a custom script replacement in the data directory that will
6723 * replace an existing moodle script
6724 * @param string $urlpath path to the original script
6725 * @return string full path name if a custom script exists
6726 * @return bool false if no custom script exists
6728 function custom_script_path($urlpath='') {
6731 // set default $urlpath, if necessary
6732 if (empty($urlpath)) {
6733 $urlpath = qualified_me(); // e.g. http://www.this-server.com/moodle/this-script.php
6736 // $urlpath is invalid if it is empty or does not start with the Moodle wwwroot
6737 if (empty($urlpath) or (strpos($urlpath, $CFG->wwwroot
) === false )) {
6741 // replace wwwroot with the path to the customscripts folder and clean path
6742 $scriptpath = $CFG->customscripts
. clean_param(substr($urlpath, strlen($CFG->wwwroot
)), PARAM_PATH
);
6744 // remove the query string, if any
6745 if (($strpos = strpos($scriptpath, '?')) !== false) {
6746 $scriptpath = substr($scriptpath, 0, $strpos);
6749 // remove trailing slashes, if any
6750 $scriptpath = rtrim($scriptpath, '/\\');
6752 // append index.php, if necessary
6753 if (is_dir($scriptpath)) {
6754 $scriptpath .= '/index.php';
6757 // check the custom script exists
6758 if (file_exists($scriptpath)) {
6766 * Wrapper function to load necessary editor scripts
6767 * to $CFG->editorsrc array. Params can be coursei id
6768 * or associative array('courseid' => value, 'name' => 'editorname').
6770 * @param mixed $args Courseid or associative array.
6772 function loadeditor($args) {
6774 include($CFG->libdir
.'/editorlib.php');
6775 return editorObject
::loadeditor($args);
6779 * Returns whether or not the user object is a remote MNET user. This function
6780 * is in moodlelib because it does not rely on loading any of the MNET code.
6782 * @param object $user A valid user object
6783 * @return bool True if the user is from a remote Moodle.
6785 function is_mnet_remote_user($user) {
6788 if (!isset($CFG->mnet_localhost_id
)) {
6789 include_once $CFG->dirroot
. '/mnet/lib.php';
6790 $env = new mnet_environment();
6795 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
6799 * Checks if a given plugin is in the list of enabled enrolment plugins.
6801 * @param string $auth Enrolment plugin.
6802 * @return boolean Whether the plugin is enabled.
6804 function is_enabled_enrol($enrol='') {
6807 // use the global default if not specified
6809 $enrol = $CFG->enrol
;
6811 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled
));
6815 * This function will search for browser prefereed languages, setting Moodle
6816 * to use the best one available if $SESSION->lang is undefined
6818 function setup_lang_from_browser() {
6820 global $CFG, $SESSION, $USER;
6822 if (!empty($SESSION->lang
) or !empty($USER->lang
)) {
6823 // Lang is defined in session or user profile, nothing to do
6827 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
6831 /// Extract and clean langs from headers
6832 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
6833 $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
6834 $rawlangs = explode(',', $rawlangs); // Convert to array
6838 foreach ($rawlangs as $lang) {
6839 if (strpos($lang, ';') === false) {
6840 $langs[(string)$order] = $lang;
6841 $order = $order-0.01;
6843 $parts = explode(';', $lang);
6844 $pos = strpos($parts[1], '=');
6845 $langs[substr($parts[1], $pos+
1)] = $parts[0];
6848 krsort($langs, SORT_NUMERIC
);
6850 /// Look for such langs under standard locations
6851 foreach ($langs as $lang) {
6852 $lang = clean_param($lang.'_utf8', PARAM_SAFEDIR
); // clean it properly for include
6853 if (file_exists($CFG->dataroot
.'/lang/'. $lang) or file_exists($CFG->dirroot
.'/lang/'. $lang)) {
6854 $SESSION->lang
= $lang; /// Lang exists, set it in session
6855 break; /// We have finished. Go out
6861 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: