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);
46 /// Date and time constants ///
48 * Time constant - the number of seconds in a year
51 define('YEARSECS', 31536000);
54 * Time constant - the number of seconds in a week
56 define('WEEKSECS', 604800);
59 * Time constant - the number of seconds in a day
61 define('DAYSECS', 86400);
64 * Time constant - the number of seconds in an hour
66 define('HOURSECS', 3600);
69 * Time constant - the number of seconds in a minute
71 define('MINSECS', 60);
74 * Time constant - the number of minutes in a day
76 define('DAYMINS', 1440);
79 * Time constant - the number of minutes in an hour
81 define('HOURMINS', 60);
83 /// Parameter constants - every call to optional_param(), required_param() ///
84 /// or clean_param() should have a specified type of parameter. //////////////
87 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way;
88 * originally was 0, but changed because we need to detect unknown
89 * parameter types and swiched order in clean_param().
91 define('PARAM_RAW', 666);
94 * PARAM_CLEAN - obsoleted, please try to use more specific type of parameter.
95 * It was one of the first types, that is why it is abused so much ;-)
97 define('PARAM_CLEAN', 0x0001);
100 * PARAM_INT - integers only, use when expecting only numbers.
102 define('PARAM_INT', 0x0002);
105 * PARAM_INTEGER - an alias for PARAM_INT
107 define('PARAM_INTEGER', 0x0002);
110 * PARAM_NUMBER - a real/floating point number.
112 define('PARAM_NUMBER', 0x000a);
115 * PARAM_ALPHA - contains only english letters.
117 define('PARAM_ALPHA', 0x0004);
120 * PARAM_ACTION - an alias for PARAM_ALPHA, use for various actions in formas and urls
121 * @TODO: should we alias it to PARAM_ALPHANUM ?
123 define('PARAM_ACTION', 0x0004);
126 * PARAM_FORMAT - an alias for PARAM_ALPHA, use for names of plugins, formats, etc.
127 * @TODO: should we alias it to PARAM_ALPHANUM ?
129 define('PARAM_FORMAT', 0x0004);
132 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
134 define('PARAM_NOTAGS', 0x0008);
137 * PARAM_MULTILANG - alias of PARAM_TEXT.
139 define('PARAM_MULTILANG', 0x0009);
142 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
144 define('PARAM_TEXT', 0x0009);
147 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
149 define('PARAM_FILE', 0x0010);
152 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
153 * note: the leading slash is not removed, window drive letter is not allowed
155 define('PARAM_PATH', 0x0020);
158 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
160 define('PARAM_HOST', 0x0040);
163 * PARAM_URL - expected properly formatted URL.
165 define('PARAM_URL', 0x0080);
168 * 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!)
170 define('PARAM_LOCALURL', 0x0180);
173 * PARAM_CLEANFILE - safe file name, all dangerous and regional chars are removed,
174 * use when you want to store a new file submitted by students
176 define('PARAM_CLEANFILE',0x0200);
179 * PARAM_ALPHANUM - expected numbers and letters only.
181 define('PARAM_ALPHANUM', 0x0400);
184 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
186 define('PARAM_BOOL', 0x0800);
189 * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes
190 * note: do not forget to addslashes() before storing into database!
192 define('PARAM_CLEANHTML',0x1000);
195 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "/-_" allowed,
196 * suitable for include() and require()
197 * @TODO: should we rename this function to PARAM_SAFEDIRS??
199 define('PARAM_ALPHAEXT', 0x2000);
202 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
204 define('PARAM_SAFEDIR', 0x4000);
207 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
209 define('PARAM_SEQUENCE', 0x8000);
212 * PARAM_PEM - Privacy Enhanced Mail format
214 define('PARAM_PEM', 0x10000);
217 * PARAM_BASE64 - Base 64 encoded format
219 define('PARAM_BASE64', 0x20000);
224 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
226 define('PAGE_COURSE_VIEW', 'course-view');
229 /** no warnings at all */
230 define ('DEBUG_NONE', 0);
231 /** E_ERROR | E_PARSE */
232 define ('DEBUG_MINIMAL', 5);
233 /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
234 define ('DEBUG_NORMAL', 15);
235 /** E_ALL without E_STRICT and E_RECOVERABLE_ERROR for now */
236 define ('DEBUG_ALL', 2047);
237 /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
238 define ('DEBUG_DEVELOPER', 34815);
241 * Blog access level constant declaration
243 define ('BLOG_USER_LEVEL', 1);
244 define ('BLOG_GROUP_LEVEL', 2);
245 define ('BLOG_COURSE_LEVEL', 3);
246 define ('BLOG_SITE_LEVEL', 4);
247 define ('BLOG_GLOBAL_LEVEL', 5);
251 /// PARAMETER HANDLING ////////////////////////////////////////////////////
254 * Returns a particular value for the named variable, taken from
255 * POST or GET. If the parameter doesn't exist then an error is
256 * thrown because we require this variable.
258 * This function should be used to initialise all required values
259 * in a script that are based on parameters. Usually it will be
261 * $id = required_param('id');
263 * @param string $parname the name of the page parameter we want
264 * @param int $type expected type of parameter
267 function required_param($parname, $type=PARAM_CLEAN
) {
269 // detect_unchecked_vars addition
271 if (!empty($CFG->detect_unchecked_vars
)) {
272 global $UNCHECKED_VARS;
273 unset ($UNCHECKED_VARS->vars
[$parname]);
276 if (isset($_POST[$parname])) { // POST has precedence
277 $param = $_POST[$parname];
278 } else if (isset($_GET[$parname])) {
279 $param = $_GET[$parname];
281 error('A required parameter ('.$parname.') was missing');
284 return clean_param($param, $type);
288 * Returns a particular value for the named variable, taken from
289 * POST or GET, otherwise returning a given default.
291 * This function should be used to initialise all optional values
292 * in a script that are based on parameters. Usually it will be
294 * $name = optional_param('name', 'Fred');
296 * @param string $parname the name of the page parameter we want
297 * @param mixed $default the default value to return if nothing is found
298 * @param int $type expected type of parameter
301 function optional_param($parname, $default=NULL, $type=PARAM_CLEAN
) {
303 // detect_unchecked_vars addition
305 if (!empty($CFG->detect_unchecked_vars
)) {
306 global $UNCHECKED_VARS;
307 unset ($UNCHECKED_VARS->vars
[$parname]);
310 if (isset($_POST[$parname])) { // POST has precedence
311 $param = $_POST[$parname];
312 } else if (isset($_GET[$parname])) {
313 $param = $_GET[$parname];
318 return clean_param($param, $type);
322 * Used by {@link optional_param()} and {@link required_param()} to
323 * clean the variables and/or cast to specific types, based on
326 * $course->format = clean_param($course->format, PARAM_ALPHA);
327 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
333 * @uses PARAM_INTEGER
335 * @uses PARAM_ALPHANUM
337 * @uses PARAM_ALPHAEXT
339 * @uses PARAM_SAFEDIR
340 * @uses PARAM_CLEANFILE
345 * @uses PARAM_LOCALURL
346 * @uses PARAM_CLEANHTML
347 * @uses PARAM_SEQUENCE
348 * @param mixed $param the variable we are cleaning
349 * @param int $type expected format of param after cleaning.
352 function clean_param($param, $type) {
356 if (is_array($param)) { // Let's loop
358 foreach ($param as $key => $value) {
359 $newparam[$key] = clean_param($value, $type);
365 case PARAM_RAW
: // no cleaning at all
368 case PARAM_CLEAN
: // General HTML cleaning, try to use more specific type if possible
369 if (is_numeric($param)) {
372 $param = stripslashes($param); // Needed for kses to work fine
373 $param = clean_text($param); // Sweep for scripts, etc
374 return addslashes($param); // Restore original request parameter slashes
376 case PARAM_CLEANHTML
: // prepare html fragment for display, do not store it into db!!
377 $param = stripslashes($param); // Remove any slashes
378 $param = clean_text($param); // Sweep for scripts, etc
382 return (int)$param; // Convert to integer
385 return (float)$param; // Convert to integer
387 case PARAM_ALPHA
: // Remove everything not a-z
388 return eregi_replace('[^a-zA-Z]', '', $param);
390 case PARAM_ALPHANUM
: // Remove everything not a-zA-Z0-9
391 return eregi_replace('[^A-Za-z0-9]', '', $param);
393 case PARAM_ALPHAEXT
: // Remove everything not a-zA-Z/_-
394 return eregi_replace('[^a-zA-Z/_-]', '', $param);
396 case PARAM_SEQUENCE
: // Remove everything not 0-9,
397 return eregi_replace('[^0-9,]', '', $param);
399 case PARAM_BOOL
: // Convert to 1 or 0
400 $tempstr = strtolower($param);
401 if ($tempstr == 'on' or $tempstr == 'yes' ) {
403 } else if ($tempstr == 'off' or $tempstr == 'no') {
406 $param = empty($param) ?
0 : 1;
410 case PARAM_NOTAGS
: // Strip all tags
411 return strip_tags($param);
413 case PARAM_TEXT
: // leave only tags needed for multilang
414 return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN
);
416 case PARAM_SAFEDIR
: // Remove everything not a-zA-Z0-9_-
417 return eregi_replace('[^a-zA-Z0-9_-]', '', $param);
419 case PARAM_CLEANFILE
: // allow only safe characters
420 return clean_filename($param);
422 case PARAM_FILE
: // Strip all suspicious characters from filename
423 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':\\/]', '', $param);
424 $param = ereg_replace('\.\.+', '', $param);
430 case PARAM_PATH
: // Strip all suspicious characters from file path
431 $param = str_replace('\\\'', '\'', $param);
432 $param = str_replace('\\"', '"', $param);
433 $param = str_replace('\\', '/', $param);
434 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':]', '', $param);
435 $param = ereg_replace('\.\.+', '', $param);
436 $param = ereg_replace('//+', '/', $param);
437 return ereg_replace('/(\./)+', '/', $param);
439 case PARAM_HOST
: // allow FQDN or IPv4 dotted quad
440 preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
441 // match ipv4 dotted quad
442 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
443 // confirm values are ok
447 ||
$match[4] > 255 ) {
448 // hmmm, what kind of dotted quad is this?
451 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
452 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
453 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
455 // all is ok - $param is respected
462 case PARAM_URL
: // allow safe ftp, http, mailto urls
463 include_once($CFG->dirroot
. '/lib/validateurlsyntax.php');
464 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
465 // all is ok, param is respected
467 $param =''; // not really ok
471 case PARAM_LOCALURL
: // allow http absolute, root relative and relative URLs within wwwroot
472 $param = clean_param($param, PARAM_URL
);
473 if (!empty($param)) {
474 if (preg_match(':^/:', $param)) {
475 // root-relative, ok!
476 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot
, '/').'/i',$param)) {
477 // absolute, and matches our wwwroot
479 // relative - let's make sure there are no tricks
480 if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
489 $param = trim($param);
490 // PEM formatted strings may contain letters/numbers and the symbols
494 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
495 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
496 list($wholething, $body) = $matches;
497 unset($wholething, $matches);
498 $b64 = clean_param($body, PARAM_BASE64
);
500 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
507 if (!empty($param)) {
508 // PEM formatted strings may contain letters/numbers and the symbols
512 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
515 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY
);
516 // Each line of base64 encoded data must be 64 characters in
517 // length, except for the last line which may be less than (or
518 // equal to) 64 characters long.
519 for ($i=0, $j=count($lines); $i < $j; $i++
) {
521 if (64 < strlen($lines[$i])) {
527 if (64 != strlen($lines[$i])) {
531 return implode("\n",$lines);
535 default: // throw error, switched parameters in optional_param or another serious problem
536 error("Unknown parameter type: $type");
543 * Set a key in global configuration
545 * Set a key/value pair in both this session's {@link $CFG} global variable
546 * and in the 'config' database table for future sessions.
548 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
549 * In that case it doesn't affect $CFG.
551 * @param string $name the key to set
552 * @param string $value the value to set (without magic quotes)
553 * @param string $plugin (optional) the plugin scope
557 function set_config($name, $value, $plugin=NULL) {
558 /// No need for get_config because they are usually always available in $CFG
562 if (empty($plugin)) {
563 $CFG->$name = $value; // So it's defined for this invocation at least
565 if (get_field('config', 'name', 'name', $name)) {
566 return set_field('config', 'value', addslashes($value), 'name', $name);
568 $config = new object();
569 $config->name
= $name;
570 $config->value
= addslashes($value);
571 return insert_record('config', $config);
573 } else { // plugin scope
574 if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
575 return set_field('config_plugins', 'value', addslashes($value), 'id', $id);
577 $config = new object();
578 $config->plugin
= addslashes($plugin);
579 $config->name
= $name;
580 $config->value
= addslashes($value);
581 return insert_record('config_plugins', $config);
587 * Get configuration values from the global config table
588 * or the config_plugins table.
590 * If called with no parameters it will do the right thing
591 * generating $CFG safely from the database without overwriting
594 * If called with 2 parameters it will return a $string single
595 * value or false of the value is not found.
597 * @param string $plugin
598 * @param string $name
600 * @return hash-like object or single value
603 function get_config($plugin=NULL, $name=NULL) {
607 if (!empty($name)) { // the user is asking for a specific value
608 if (!empty($plugin)) {
609 return get_field('config_plugins', 'value', 'plugin' , $plugin, 'name', $name);
611 return get_field('config', 'value', 'name', $name);
615 // the user is after a recordset
616 if (!empty($plugin)) {
617 if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
618 $configs = (array)$configs;
620 foreach ($configs as $config) {
621 $localcfg[$config->name
] = $config->value
;
623 return (object)$localcfg;
628 // this was originally in setup.php
629 if ($configs = get_records('config')) {
630 $localcfg = (array)$CFG;
631 foreach ($configs as $config) {
632 if (!isset($localcfg[$config->name
])) {
633 $localcfg[$config->name
] = $config->value
;
635 if ($localcfg[$config->name
] != $config->value
) {
636 // complain if the DB has a different
637 // value than config.php does
638 error_log("\$CFG->{$config->name} in config.php ({$localcfg[$config->name]}) overrides database setting ({$config->value})");
643 $localcfg = (object)$localcfg;
646 // preserve $CFG if DB returns nothing or error
654 * Removes a key from global configuration
656 * @param string $name the key to set
657 * @param string $plugin (optional) the plugin scope
661 function unset_config($name, $plugin=NULL) {
667 if (empty($plugin)) {
668 return delete_records('config', 'name', $name);
670 return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
676 * Refresh current $USER session global variable with all their current preferences.
679 function reload_user_preferences() {
684 $USER->preference
= array();
686 if (!isloggedin() or isguestuser()) {
687 // no pernament storage for not-logged-in user and guest
689 } else if ($preferences = get_records('user_preferences', 'userid', $USER->id
)) {
690 foreach ($preferences as $preference) {
691 $USER->preference
[$preference->name
] = $preference->value
;
699 * Sets a preference for the current user
700 * Optionally, can set a preference for a different user object
702 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
704 * @param string $name The key to set as preference for the specified user
705 * @param string $value The value to set forthe $name key in the specified user's record
706 * @param int $otheruserid A moodle user ID
709 function set_user_preference($name, $value, $otheruserid=NULL) {
713 if (!isset($USER->preference
)) {
714 reload_user_preferences();
723 if (empty($otheruserid)){
724 if (!isloggedin() or isguestuser()) {
729 if (isguestuser($otheruserid)) {
732 $userid = $otheruserid;
737 // no pernament storage for not-logged-in user and guest
739 } else if ($preference = get_record('user_preferences', 'userid', $userid, 'name', addslashes($name))) {
740 if (!set_field('user_preferences', 'value', addslashes((string)$value), 'id', $preference->id
)) {
745 $preference = new object();
746 $preference->userid
= $userid;
747 $preference->name
= addslashes($name);
748 $preference->value
= addslashes((string)$value);
749 if (!insert_record('user_preferences', $preference)) {
754 // update value in USER session if needed
755 if ($userid == $USER->id
) {
756 $USER->preference
[$name] = (string)$value;
763 * Unsets a preference completely by deleting it from the database
764 * Optionally, can set a preference for a different user id
766 * @param string $name The key to unset as preference for the specified user
767 * @param int $otheruserid A moodle user ID
769 function unset_user_preference($name, $otheruserid=NULL) {
773 if (!isset($USER->preference
)) {
774 reload_user_preferences();
777 if (empty($otheruserid)){
780 $userid = $otheruserid;
783 //Delete the preference from $USER if needed
784 if ($userid == $USER->id
) {
785 unset($USER->preference
[$name]);
789 return delete_records('user_preferences', 'userid', $userid, 'name', addslashes($name));
794 * Sets a whole array of preferences for the current user
795 * @param array $prefarray An array of key/value pairs to be set
796 * @param int $otheruserid A moodle user ID
799 function set_user_preferences($prefarray, $otheruserid=NULL) {
801 if (!is_array($prefarray) or empty($prefarray)) {
806 foreach ($prefarray as $name => $value) {
807 // The order is important; test for return is done first
808 $return = (set_user_preference($name, $value, $otheruserid) && $return);
814 * If no arguments are supplied this function will return
815 * all of the current user preferences as an array.
816 * If a name is specified then this function
817 * attempts to return that particular preference value. If
818 * none is found, then the optional value $default is returned,
820 * @param string $name Name of the key to use in finding a preference value
821 * @param string $default Value to be returned if the $name key is not set in the user preferences
822 * @param int $otheruserid A moodle user ID
826 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
829 if (!isset($USER->preference
)) {
830 reload_user_preferences();
833 if (empty($otheruserid)){
836 $userid = $otheruserid;
839 if ($userid == $USER->id
) {
840 $preference = $USER->preference
;
843 $preference = array();
844 if ($prefdata = get_records('user_preferences', 'userid', $userid)) {
845 foreach ($prefdata as $pref) {
846 $preference[$pref->name
] = $pref->value
;
852 return $preference; // All values
854 } else if (array_key_exists($name, $preference)) {
855 return $preference[$name]; // The single value
858 return $default; // Default value (or NULL)
863 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
866 * Given date parts in user time produce a GMT timestamp.
868 * @param int $year The year part to create timestamp of
869 * @param int $month The month part to create timestamp of
870 * @param int $day The day part to create timestamp of
871 * @param int $hour The hour part to create timestamp of
872 * @param int $minute The minute part to create timestamp of
873 * @param int $second The second part to create timestamp of
874 * @param float $timezone ?
875 * @param bool $applydst ?
876 * @return int timestamp
877 * @todo Finish documenting this function
879 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
881 $timezone = get_user_timezone_offset($timezone);
883 if (abs($timezone) > 13) {
884 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
886 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
887 $time = usertime($time, $timezone);
889 $time -= dst_offset_on($time);
898 * Given an amount of time in seconds, returns string
899 * formatted nicely as weeks, days, hours etc as needed
905 * @param int $totalsecs ?
906 * @param array $str ?
909 function format_time($totalsecs, $str=NULL) {
911 $totalsecs = abs($totalsecs);
913 if (!$str) { // Create the str structure the slow way
914 $str->day
= get_string('day');
915 $str->days
= get_string('days');
916 $str->hour
= get_string('hour');
917 $str->hours
= get_string('hours');
918 $str->min
= get_string('min');
919 $str->mins
= get_string('mins');
920 $str->sec
= get_string('sec');
921 $str->secs
= get_string('secs');
922 $str->year
= get_string('year');
923 $str->years
= get_string('years');
927 $years = floor($totalsecs/YEARSECS
);
928 $remainder = $totalsecs - ($years*YEARSECS
);
929 $days = floor($remainder/DAYSECS
);
930 $remainder = $totalsecs - ($days*DAYSECS
);
931 $hours = floor($remainder/HOURSECS
);
932 $remainder = $remainder - ($hours*HOURSECS
);
933 $mins = floor($remainder/MINSECS
);
934 $secs = $remainder - ($mins*MINSECS
);
936 $ss = ($secs == 1) ?
$str->sec
: $str->secs
;
937 $sm = ($mins == 1) ?
$str->min
: $str->mins
;
938 $sh = ($hours == 1) ?
$str->hour
: $str->hours
;
939 $sd = ($days == 1) ?
$str->day
: $str->days
;
940 $sy = ($years == 1) ?
$str->year
: $str->years
;
948 if ($years) $oyears = $years .' '. $sy;
949 if ($days) $odays = $days .' '. $sd;
950 if ($hours) $ohours = $hours .' '. $sh;
951 if ($mins) $omins = $mins .' '. $sm;
952 if ($secs) $osecs = $secs .' '. $ss;
954 if ($years) return trim($oyears .' '. $odays);
955 if ($days) return trim($odays .' '. $ohours);
956 if ($hours) return trim($ohours .' '. $omins);
957 if ($mins) return trim($omins .' '. $osecs);
958 if ($secs) return $osecs;
959 return get_string('now');
963 * Returns a formatted string that represents a date in user time
964 * <b>WARNING: note that the format is for strftime(), not date().</b>
965 * Because of a bug in most Windows time libraries, we can't use
966 * the nicer %e, so we have to use %d which has leading zeroes.
967 * A lot of the fuss in the function is just getting rid of these leading
968 * zeroes as efficiently as possible.
970 * If parameter fixday = true (default), then take off leading
971 * zero from %d, else mantain it.
974 * @param int $date timestamp in GMT
975 * @param string $format strftime format
976 * @param float $timezone
977 * @param bool $fixday If true (default) then the leading
978 * zero from %d is removed. If false then the leading zero is mantained.
981 function userdate($date, $format='', $timezone=99, $fixday = true) {
985 if (empty($format)) {
986 $format = get_string('strftimedaydatetime');
989 if (!empty($CFG->nofixday
)) { // Config.php can force %d not to be fixed.
991 } else if ($fixday) {
992 $formatnoday = str_replace('%d', 'DD', $format);
993 $fixday = ($formatnoday != $format);
996 $date +
= dst_offset_on($date);
998 $timezone = get_user_timezone_offset($timezone);
1000 if (abs($timezone) > 13) { /// Server time
1002 $datestring = strftime($formatnoday, $date);
1003 $daystring = str_replace(' 0', '', strftime(' %d', $date));
1004 $datestring = str_replace('DD', $daystring, $datestring);
1006 $datestring = strftime($format, $date);
1009 $date +
= (int)($timezone * 3600);
1011 $datestring = gmstrftime($formatnoday, $date);
1012 $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
1013 $datestring = str_replace('DD', $daystring, $datestring);
1015 $datestring = gmstrftime($format, $date);
1019 /// If we are running under Windows convert from windows encoding to UTF-8
1020 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1022 if ($CFG->ostype
== 'WINDOWS') {
1023 if ($localewincharset = get_string('localewincharset')) {
1024 $textlib = textlib_get_instance();
1025 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1033 * Given a $time timestamp in GMT (seconds since epoch),
1034 * returns an array that represents the date in user time
1037 * @param int $time Timestamp in GMT
1038 * @param float $timezone ?
1039 * @return array An array that represents the date in user time
1040 * @todo Finish documenting this function
1042 function usergetdate($time, $timezone=99) {
1044 $timezone = get_user_timezone_offset($timezone);
1046 if (abs($timezone) > 13) { // Server time
1047 return getdate($time);
1050 // There is no gmgetdate so we use gmdate instead
1051 $time +
= dst_offset_on($time);
1052 $time +
= intval((float)$timezone * HOURSECS
);
1054 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
1057 $getdate['seconds'],
1058 $getdate['minutes'],
1065 $getdate['weekday'],
1067 ) = explode('_', $datestring);
1073 * Given a GMT timestamp (seconds since epoch), offsets it by
1074 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1077 * @param int $date Timestamp in GMT
1078 * @param float $timezone
1081 function usertime($date, $timezone=99) {
1083 $timezone = get_user_timezone_offset($timezone);
1085 if (abs($timezone) > 13) {
1088 return $date - (int)($timezone * HOURSECS
);
1092 * Given a time, return the GMT timestamp of the most recent midnight
1093 * for the current user.
1095 * @param int $date Timestamp in GMT
1096 * @param float $timezone ?
1099 function usergetmidnight($date, $timezone=99) {
1101 $timezone = get_user_timezone_offset($timezone);
1102 $userdate = usergetdate($date, $timezone);
1104 // Time of midnight of this user's day, in GMT
1105 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1110 * Returns a string that prints the user's timezone
1112 * @param float $timezone The user's timezone
1115 function usertimezone($timezone=99) {
1117 $tz = get_user_timezone($timezone);
1119 if (!is_float($tz)) {
1123 if(abs($tz) > 13) { // Server time
1124 return get_string('serverlocaltime');
1127 if($tz == intval($tz)) {
1128 // Don't show .0 for whole hours
1145 * Returns a float which represents the user's timezone difference from GMT in hours
1146 * Checks various settings and picks the most dominant of those which have a value
1150 * @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
1153 function get_user_timezone_offset($tz = 99) {
1157 $tz = get_user_timezone($tz);
1159 if (is_float($tz)) {
1162 $tzrecord = get_timezone_record($tz);
1163 if (empty($tzrecord)) {
1166 return (float)$tzrecord->gmtoff
/ HOURMINS
;
1171 * Returns a float or a string which denotes the user's timezone
1172 * 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)
1173 * means that for this timezone there are also DST rules to be taken into account
1174 * Checks various settings and picks the most dominant of those which have a value
1178 * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
1181 function get_user_timezone($tz = 99) {
1186 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
1187 isset($USER->timezone
) ?
$USER->timezone
: 99,
1188 isset($CFG->timezone
) ?
$CFG->timezone
: 99,
1193 while(($tz == '' ||
$tz == 99) && $next = each($timezones)) {
1194 $tz = $next['value'];
1197 return is_numeric($tz) ?
(float) $tz : $tz;
1205 * @param string $timezonename ?
1208 function get_timezone_record($timezonename) {
1210 static $cache = NULL;
1212 if ($cache === NULL) {
1216 if (isset($cache[$timezonename])) {
1217 return $cache[$timezonename];
1220 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix
.'timezone
1221 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
1229 * @param ? $fromyear ?
1230 * @param ? $to_year ?
1233 function calculate_user_dst_table($from_year = NULL, $to_year = NULL) {
1234 global $CFG, $SESSION;
1236 $usertz = get_user_timezone();
1238 if (is_float($usertz)) {
1239 // Trivial timezone, no DST
1243 if (!empty($SESSION->dst_offsettz
) && $SESSION->dst_offsettz
!= $usertz) {
1244 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1245 unset($SESSION->dst_offsets
);
1246 unset($SESSION->dst_range
);
1249 if (!empty($SESSION->dst_offsets
) && empty($from_year) && empty($to_year)) {
1250 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1251 // This will be the return path most of the time, pretty light computationally
1255 // Reaching here means we either need to extend our table or create it from scratch
1257 // Remember which TZ we calculated these changes for
1258 $SESSION->dst_offsettz
= $usertz;
1260 if(empty($SESSION->dst_offsets
)) {
1261 // If we 're creating from scratch, put the two guard elements in there
1262 $SESSION->dst_offsets
= array(1 => NULL, 0 => NULL);
1264 if(empty($SESSION->dst_range
)) {
1265 // If creating from scratch
1266 $from = max((empty($from_year) ?
intval(date('Y')) - 3 : $from_year), 1971);
1267 $to = min((empty($to_year) ?
intval(date('Y')) +
3 : $to_year), 2035);
1269 // Fill in the array with the extra years we need to process
1270 $yearstoprocess = array();
1271 for($i = $from; $i <= $to; ++
$i) {
1272 $yearstoprocess[] = $i;
1275 // Take note of which years we have processed for future calls
1276 $SESSION->dst_range
= array($from, $to);
1279 // If needing to extend the table, do the same
1280 $yearstoprocess = array();
1282 $from = max((empty($from_year) ?
$SESSION->dst_range
[0] : $from_year), 1971);
1283 $to = min((empty($to_year) ?
$SESSION->dst_range
[1] : $to_year), 2035);
1285 if($from < $SESSION->dst_range
[0]) {
1286 // Take note of which years we need to process and then note that we have processed them for future calls
1287 for($i = $from; $i < $SESSION->dst_range
[0]; ++
$i) {
1288 $yearstoprocess[] = $i;
1290 $SESSION->dst_range
[0] = $from;
1292 if($to > $SESSION->dst_range
[1]) {
1293 // Take note of which years we need to process and then note that we have processed them for future calls
1294 for($i = $SESSION->dst_range
[1] +
1; $i <= $to; ++
$i) {
1295 $yearstoprocess[] = $i;
1297 $SESSION->dst_range
[1] = $to;
1301 if(empty($yearstoprocess)) {
1302 // This means that there was a call requesting a SMALLER range than we have already calculated
1306 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1307 // Also, the array is sorted in descending timestamp order!
1310 $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');
1311 if(empty($presetrecords)) {
1315 // Remove ending guard (first element of the array)
1316 reset($SESSION->dst_offsets
);
1317 unset($SESSION->dst_offsets
[key($SESSION->dst_offsets
)]);
1319 // Add all required change timestamps
1320 foreach($yearstoprocess as $y) {
1321 // Find the record which is in effect for the year $y
1322 foreach($presetrecords as $year => $preset) {
1328 $changes = dst_changes_for_year($y, $preset);
1330 if($changes === NULL) {
1333 if($changes['dst'] != 0) {
1334 $SESSION->dst_offsets
[$changes['dst']] = $preset->dstoff
* MINSECS
;
1336 if($changes['std'] != 0) {
1337 $SESSION->dst_offsets
[$changes['std']] = 0;
1341 // Put in a guard element at the top
1342 $maxtimestamp = max(array_keys($SESSION->dst_offsets
));
1343 $SESSION->dst_offsets
[($maxtimestamp + DAYSECS
)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1346 krsort($SESSION->dst_offsets
);
1351 function dst_changes_for_year($year, $timezone) {
1353 if($timezone->dst_startday
== 0 && $timezone->dst_weekday
== 0 && $timezone->std_startday
== 0 && $timezone->std_weekday
== 0) {
1357 $monthdaydst = find_day_in_month($timezone->dst_startday
, $timezone->dst_weekday
, $timezone->dst_month
, $year);
1358 $monthdaystd = find_day_in_month($timezone->std_startday
, $timezone->std_weekday
, $timezone->std_month
, $year);
1360 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time
);
1361 list($std_hour, $std_min) = explode(':', $timezone->std_time
);
1363 $timedst = make_timestamp($year, $timezone->dst_month
, $monthdaydst, 0, 0, 0, 99, false);
1364 $timestd = make_timestamp($year, $timezone->std_month
, $monthdaystd, 0, 0, 0, 99, false);
1366 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1367 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1368 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1370 $timedst +
= $dst_hour * HOURSECS +
$dst_min * MINSECS
;
1371 $timestd +
= $std_hour * HOURSECS +
$std_min * MINSECS
;
1373 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1376 // $time must NOT be compensated at all, it has to be a pure timestamp
1377 function dst_offset_on($time) {
1380 if(!calculate_user_dst_table() ||
empty($SESSION->dst_offsets
)) {
1384 reset($SESSION->dst_offsets
);
1385 while(list($from, $offset) = each($SESSION->dst_offsets
)) {
1386 if($from <= $time) {
1391 // This is the normal return path
1392 if($offset !== NULL) {
1396 // Reaching this point means we haven't calculated far enough, do it now:
1397 // Calculate extra DST changes if needed and recurse. The recursion always
1398 // moves toward the stopping condition, so will always end.
1401 // We need a year smaller than $SESSION->dst_range[0]
1402 if($SESSION->dst_range
[0] == 1971) {
1405 calculate_user_dst_table($SESSION->dst_range
[0] - 5, NULL);
1406 return dst_offset_on($time);
1409 // We need a year larger than $SESSION->dst_range[1]
1410 if($SESSION->dst_range
[1] == 2035) {
1413 calculate_user_dst_table(NULL, $SESSION->dst_range
[1] +
5);
1414 return dst_offset_on($time);
1418 function find_day_in_month($startday, $weekday, $month, $year) {
1420 $daysinmonth = days_in_month($month, $year);
1422 if($weekday == -1) {
1423 // Don't care about weekday, so return:
1424 // abs($startday) if $startday != -1
1425 // $daysinmonth otherwise
1426 return ($startday == -1) ?
$daysinmonth : abs($startday);
1429 // From now on we 're looking for a specific weekday
1431 // Give "end of month" its actual value, since we know it
1432 if($startday == -1) {
1433 $startday = -1 * $daysinmonth;
1436 // Starting from day $startday, the sign is the direction
1440 $startday = abs($startday);
1441 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1443 // This is the last such weekday of the month
1444 $lastinmonth = $daysinmonth +
$weekday - $lastmonthweekday;
1445 if($lastinmonth > $daysinmonth) {
1449 // Find the first such weekday <= $startday
1450 while($lastinmonth > $startday) {
1454 return $lastinmonth;
1459 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
1461 $diff = $weekday - $indexweekday;
1466 // This is the first such weekday of the month equal to or after $startday
1467 $firstfromindex = $startday +
$diff;
1469 return $firstfromindex;
1475 * Calculate the number of days in a given month
1477 * @param int $month The month whose day count is sought
1478 * @param int $year The year of the month whose day count is sought
1481 function days_in_month($month, $year) {
1482 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1486 * Calculate the position in the week of a specific calendar day
1488 * @param int $day The day of the date whose position in the week is sought
1489 * @param int $month The month of the date whose position in the week is sought
1490 * @param int $year The year of the date whose position in the week is sought
1493 function dayofweek($day, $month, $year) {
1494 // I wonder if this is any different from
1495 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1496 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1499 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
1502 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1503 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1504 * sesskey string if $USER exists, or boolean false if not.
1509 function sesskey() {
1516 if (empty($USER->sesskey
)) {
1517 $USER->sesskey
= random_string(10);
1520 return $USER->sesskey
;
1525 * For security purposes, this function will check that the currently
1526 * given sesskey (passed as a parameter to the script or this function)
1527 * matches that of the current user.
1529 * @param string $sesskey optionally provided sesskey
1532 function confirm_sesskey($sesskey=NULL) {
1535 if (!empty($USER->ignoresesskey
) ||
!empty($CFG->ignoresesskey
)) {
1539 if (empty($sesskey)) {
1540 $sesskey = required_param('sesskey', PARAM_RAW
); // Check script parameters
1543 if (!isset($USER->sesskey
)) {
1547 return ($USER->sesskey
=== $sesskey);
1551 * Setup all global $CFG course variables, set locale and also themes
1552 * This function can be used on pages that do not require login instead of require_login()
1554 * @param mixed $courseorid id of the course or course object
1556 function course_setup($courseorid=0) {
1557 global $COURSE, $CFG, $SITE;
1559 /// Redefine global $COURSE if needed
1560 if (empty($courseorid)) {
1561 // no change in global $COURSE - for backwards compatibiltiy
1562 // if require_rogin() used after require_login($courseid);
1563 } else if (is_object($courseorid)) {
1564 $COURSE = clone($courseorid);
1566 global $course; // used here only to prevent repeated fetching from DB - may be removed later
1567 if (!empty($course->id
) and $course->id
== SITEID
) {
1568 $COURSE = clone($SITE);
1569 } else if (!empty($course->id
) and $course->id
== $courseorid) {
1570 $COURSE = clone($course);
1572 if (!$COURSE = get_record('course', 'id', $courseorid)) {
1573 error('Invalid course ID');
1578 /// set locale and themes
1585 * This function checks that the current user is logged in and has the
1586 * required privileges
1588 * This function checks that the current user is logged in, and optionally
1589 * whether they are allowed to be in a particular course and view a particular
1591 * If they are not logged in, then it redirects them to the site login unless
1592 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
1593 * case they are automatically logged in as guests.
1594 * If $courseid is given and the user is not enrolled in that course then the
1595 * user is redirected to the course enrolment page.
1596 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1597 * in the course then the user is redirected to the course home page.
1605 * @param mixed $courseorid id of the course or course object
1606 * @param bool $autologinguest
1607 * @param object $cm course module object
1609 function require_login($courseorid=0, $autologinguest=true, $cm=null) {
1611 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
1613 /// setup global $COURSE, themes, language and locale
1614 course_setup($courseorid);
1616 /// If the user is not even logged in yet then make sure they are
1617 if (!isloggedin()) {
1618 //NOTE: $USER->site check was obsoleted by session test cookie,
1619 // $USER->confirmed test is in login/index.php
1620 $SESSION->wantsurl
= $FULLME;
1621 if (!empty($_SERVER['HTTP_REFERER'])) {
1622 $SESSION->fromurl
= $_SERVER['HTTP_REFERER'];
1624 if ($autologinguest and !empty($CFG->guestloginbutton
) and !empty($CFG->autologinguests
) and ($COURSE->id
== SITEID
or $COURSE->guest
) ) {
1625 $loginguest = '?loginguest=true';
1629 if (empty($CFG->loginhttps
) or $loginguest) { //do not require https for guest logins
1630 redirect($CFG->wwwroot
.'/login/index.php'. $loginguest);
1632 $wwwroot = str_replace('http:','https:', $CFG->wwwroot
);
1633 redirect($wwwroot .'/login/index.php');
1638 /// loginas as redirection if needed
1639 if ($COURSE->id
!= SITEID
and !empty($USER->realuser
)) {
1640 if ($USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
1641 if ($USER->loginascontext
->instanceid
!= $COURSE->id
) {
1642 print_error('loginasonecourse', '', $CFG->wwwroot
.'/course/view.php?id='.$USER->loginascontext
->instanceid
);
1648 /// check whether the user should be changing password (but only if it is REALLY them)
1649 $userauth = get_auth_plugin($USER->auth
);
1650 if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser
)) {
1651 if ($userauth->can_change_password()) {
1652 $SESSION->wantsurl
= $FULLME;
1653 if ($changeurl = $userauth->change_password_url()) {
1654 //use plugin custom url
1655 redirect($changeurl);
1657 //use moodle internal method
1658 if (empty($CFG->loginhttps
)) {
1659 redirect($CFG->wwwroot
.'/login/change_password.php');
1661 $wwwroot = str_replace('http:','https:', $CFG->wwwroot
);
1662 redirect($wwwroot .'/login/change_password.php');
1666 error(get_string('nopasswordchangeforced', 'auth'));
1670 /// Check that the user account is properly set up
1671 if (user_not_fully_set_up($USER)) {
1672 $SESSION->wantsurl
= $FULLME;
1673 redirect($CFG->wwwroot
.'/user/edit.php?id='. $USER->id
.'&course='. SITEID
);
1676 /// Make sure current IP matches the one for this session (if required)
1677 if (!empty($CFG->tracksessionip
)) {
1678 if ($USER->sessionIP
!= md5(getremoteaddr())) {
1679 error(get_string('sessionipnomatch', 'error'));
1683 /// Make sure the USER has a sesskey set up. Used for checking script parameters.
1686 // Check that the user has agreed to a site policy if there is one
1687 if (!empty($CFG->sitepolicy
)) {
1688 if (!$USER->policyagreed
) {
1689 $SESSION->wantsurl
= $FULLME;
1690 redirect($CFG->wwwroot
.'/user/policy.php');
1694 /// If the site is currently under maintenance, then print a message
1695 if (!has_capability('moodle/site:config',get_context_instance(CONTEXT_SYSTEM
))) {
1696 if (file_exists($CFG->dataroot
.'/'.SITEID
.'/maintenance.html')) {
1697 print_maintenance_message();
1702 /// groupmembersonly access control
1703 if (!empty($CFG->enablegroupings
) and $cm and $cm->groupmembersonly
and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE
, $cm->id
))) {
1704 if (isguestuser() or !groups_has_membership($cm)) {
1705 error(get_string('groupmembersonlyerror', 'group'), $CFG->wwwroot
.'/course/view.php?id='.$cm->course
);
1709 if ($COURSE->id
== SITEID
) {
1710 /// We can eliminate hidden site activities straight away
1711 if (!empty($cm) && !$cm->visible
and !has_capability('moodle/course:viewhiddenactivities',
1712 get_context_instance(CONTEXT_SYSTEM
))) {
1713 redirect($CFG->wwwroot
, get_string('activityiscurrentlyhidden'));
1718 /// Check if the user can be in a particular course
1719 if (!$context = get_context_instance(CONTEXT_COURSE
, $COURSE->id
)) {
1720 print_error('nocontext');
1723 if (empty($USER->switchrole
[$context->id
]) &&
1724 !($COURSE->visible
&& course_parent_visible($COURSE)) &&
1725 !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $COURSE->id
)) ){
1726 print_header_simple();
1727 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
1730 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1732 if ($USER->username
!= 'guest' and !has_capability('moodle/course:view', $context)) {
1733 if ($COURSE->guest
== 1) {
1734 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
1735 has_capability('clearcache'); // Must clear cache
1736 $guestcaps = get_role_context_caps($CFG->guestroleid
, $context);
1737 $USER->capabilities
= merge_role_caps($USER->capabilities
, $guestcaps);
1741 /// If the user is a guest then treat them according to the course policy about guests
1743 if (has_capability('moodle/legacy:guest', $context, NULL, false)) {
1744 switch ($COURSE->guest
) { /// Check course policy about guest access
1746 case 1: /// Guests always allowed
1747 if (!has_capability('moodle/course:view', $context)) { // Prohibited by capability
1748 print_header_simple();
1749 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)), "$CFG->wwwroot/login/index.php");
1751 if (!empty($cm) and !$cm->visible
) { // Not allowed to see module, send to course page
1752 redirect($CFG->wwwroot
.'/course/view.php?id='.$cm->course
,
1753 get_string('activityiscurrentlyhidden'));
1756 return; // User is allowed to see this course
1760 case 2: /// Guests allowed with key
1761 if (!empty($USER->enrolkey
[$COURSE->id
])) { // Set by enrol/manual/enrol.php
1764 // otherwise drop through to logic below (--> enrol.php)
1767 default: /// Guests not allowed
1768 $strloggedinasguest = get_string('loggedinasguest');
1769 print_header_simple('', '',
1770 build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc'))));
1771 if (empty($USER->switchrole
[$context->id
])) { // Normal guest
1772 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)), "$CFG->wwwroot/login/index.php");
1774 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)));
1775 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id
).'</div>';
1776 print_footer($COURSE);
1782 /// For non-guests, check if they have course view access
1784 } else if (has_capability('moodle/course:view', $context)) {
1785 if (!empty($USER->realuser
)) { // Make sure the REAL person can also access this course
1786 if (!has_capability('moodle/course:view', $context, $USER->realuser
)) {
1787 print_header_simple();
1788 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot
.'/');
1792 /// Make sure they can read this activity too, if specified
1794 if (!empty($cm) and !$cm->visible
and !has_capability('moodle/course:viewhiddenactivities', $context)) {
1795 redirect($CFG->wwwroot
.'/course/view.php?id='.$cm->course
, get_string('activityiscurrentlyhidden'));
1797 return; // User is allowed to see this course
1802 /// Currently not enrolled in the course, so see if they want to enrol
1803 $SESSION->wantsurl
= $FULLME;
1804 redirect($CFG->wwwroot
.'/course/enrol.php?id='. $COURSE->id
);
1812 * This function just makes sure a user is logged out.
1817 function require_logout() {
1819 global $USER, $CFG, $SESSION;
1822 add_to_log(SITEID
, "user", "logout", "view.php?id=$USER->id&course=".SITEID
, $USER->id
, 0, $USER->id
);
1824 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
1825 foreach($authsequence as $authname) {
1826 $authplugin = get_auth_plugin($authname);
1827 $authplugin->prelogout_hook();
1831 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
1832 // This method is just to try to avoid silly warnings from PHP 4.3.0
1833 session_unregister("USER");
1834 session_unregister("SESSION");
1837 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
1838 $file = $line = null;
1839 if (headers_sent($file, $line)) {
1840 error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__
);
1841 error_log('Headers were already sent in file: '.$file.' on line '.$line);
1843 setcookie('MoodleSessionTest'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
1846 unset($_SESSION['USER']);
1847 unset($_SESSION['SESSION']);
1855 * This is a weaker version of {@link require_login()} which only requires login
1856 * when called from within a course rather than the site page, unless
1857 * the forcelogin option is turned on.
1860 * @param mixed $courseorid The course object or id in question
1861 * @param bool $autologinguest Allow autologin guests if that is wanted
1862 * @param object $cm Course activity module if known
1864 function require_course_login($courseorid, $autologinguest=true, $cm=null) {
1866 if (!empty($CFG->forcelogin
)) {
1867 // login required for both SITE and courses
1868 require_login($courseorid, $autologinguest, $cm);
1870 } else if (!empty($cm) and !$cm->visible
) {
1871 // always login for hidden activities
1872 require_login($courseorid, $autologinguest, $cm);
1874 } else if ((is_object($courseorid) and $courseorid->id
== SITEID
)
1875 or (!is_object($courseorid) and $courseorid == SITEID
)) {
1876 //login for SITE not required
1880 // course login always required
1881 require_login($courseorid, $autologinguest, $cm);
1886 * Require key login. Function terminates with error if key not found or incorrect.
1887 * @param string $script unique script identifier
1888 * @param int $instance optional instance id
1890 function require_user_key_login($script, $instance=null) {
1891 global $nomoodlecookie, $USER, $SESSION;
1893 if (empty($nomoodlecookie)) {
1894 error('Incorrect use of require_key_login() - session cookies must be disabled!');
1898 @session_write_close
();
1900 $keyvalue = required_param('key', PARAM_ALPHANUM
);
1902 if (!$key = get_record('user_private_key', 'script', $script, 'value', $keyvalue, 'instance', $instance)) {
1903 error('Incorrect key');
1906 if (!empty($key->validuntil
) and $key->validuntil
< time()) {
1907 error('Expired key');
1910 if ($key->iprestriction
) {
1911 $remoteaddr = getremoteaddr();
1912 if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction
)) {
1913 error('Client IP address mismatch');
1917 if (!$user = get_record('user', 'id', $key->userid
)) {
1918 error('Incorrect user record');
1921 /// emulate normal session
1922 $SESSION = new object();
1925 /// return isntance id - it might be empty
1926 return $key->instance
;
1930 * Creates a new private user access key.
1931 * @param string $script unique target identifier
1932 * @param int $userid
1933 * @param instance $int optional instance id
1934 * @param string $iprestriction optional ip restricted access
1935 * @param timestamp $validuntil key valid only until given data
1936 * @return string access key value
1938 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
1939 $key = new object();
1940 $key->script
= $script;
1941 $key->userid
= $userid;
1942 $key->instance
= $instance;
1943 $key->iprestriction
= $iprestriction;
1944 $key->validuntil
= $validuntil;
1945 $key->timecreated
= time();
1947 $key->value
= md5($userid.'_'.time().random_string(40)); // something long and unique
1948 while (record_exists('user_private_key', 'value', $key->value
)) {
1950 $key->value
= md5($userid.'_'.time().random_string(40));
1953 if (!insert_record('user_private_key', $key)) {
1954 error('Can not insert new key');
1961 * Modify the user table by setting the currently logged in user's
1962 * last login to now.
1967 function update_user_login_times() {
1970 $user = new object();
1971 $USER->lastlogin
= $user->lastlogin
= $USER->currentlogin
;
1972 $USER->currentlogin
= $user->lastaccess
= $user->currentlogin
= time();
1974 $user->id
= $USER->id
;
1976 return update_record('user', $user);
1980 * Determines if a user has completed setting up their account.
1982 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
1985 function user_not_fully_set_up($user) {
1986 return ($user->username
!= 'guest' and (empty($user->firstname
) or empty($user->lastname
) or empty($user->email
) or over_bounce_threshold($user)));
1989 function over_bounce_threshold($user) {
1993 if (empty($CFG->handlebounces
)) {
1996 // set sensible defaults
1997 if (empty($CFG->minbounces
)) {
1998 $CFG->minbounces
= 10;
2000 if (empty($CFG->bounceratio
)) {
2001 $CFG->bounceratio
= .20;
2005 if ($bounce = get_record('user_preferences','userid',$user->id
,'name','email_bounce_count')) {
2006 $bouncecount = $bounce->value
;
2008 if ($send = get_record('user_preferences','userid',$user->id
,'name','email_send_count')) {
2009 $sendcount = $send->value
;
2011 return ($bouncecount >= $CFG->minbounces
&& $bouncecount/$sendcount >= $CFG->bounceratio
);
2015 * @param $user - object containing an id
2016 * @param $reset - will reset the count to 0
2018 function set_send_count($user,$reset=false) {
2019 if ($pref = get_record('user_preferences','userid',$user->id
,'name','email_send_count')) {
2020 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
2021 update_record('user_preferences',$pref);
2023 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2025 $pref->name
= 'email_send_count';
2027 $pref->userid
= $user->id
;
2028 insert_record('user_preferences',$pref, false);
2033 * @param $user - object containing an id
2034 * @param $reset - will reset the count to 0
2036 function set_bounce_count($user,$reset=false) {
2037 if ($pref = get_record('user_preferences','userid',$user->id
,'name','email_bounce_count')) {
2038 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
2039 update_record('user_preferences',$pref);
2041 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2043 $pref->name
= 'email_bounce_count';
2045 $pref->userid
= $user->id
;
2046 insert_record('user_preferences',$pref, false);
2051 * Keeps track of login attempts
2055 function update_login_count() {
2061 if (empty($SESSION->logincount
)) {
2062 $SESSION->logincount
= 1;
2064 $SESSION->logincount++
;
2067 if ($SESSION->logincount
> $max_logins) {
2068 unset($SESSION->wantsurl
);
2069 error(get_string('errortoomanylogins'));
2074 * Resets login attempts
2078 function reset_login_count() {
2081 $SESSION->logincount
= 0;
2084 function sync_metacourses() {
2088 if (!$courses = get_records('course', 'metacourse', 1)) {
2092 foreach ($courses as $course) {
2093 sync_metacourse($course);
2098 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
2100 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
2102 function sync_metacourse($course) {
2105 // Check the course is valid.
2106 if (!is_object($course)) {
2107 if (!$course = get_record('course', 'id', $course)) {
2108 return false; // invalid course id
2112 // Check that we actually have a metacourse.
2113 if (empty($course->metacourse
)) {
2117 // Get a list of roles that should not be synced.
2118 if (!empty($CFG->nonmetacoursesyncroleids
)) {
2119 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids
. ') AND';
2121 $roleexclusions = '';
2124 // Get the context of the metacourse.
2125 $context = get_context_instance(CONTEXT_COURSE
, $course->id
); // SITEID can not be a metacourse
2127 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
2128 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
2129 $managers = array_keys($users);
2131 $managers = array();
2134 // Get assignments of a user to a role that exist in a child course, but
2135 // not in the meta coure. That is, get a list of the assignments that need to be made.
2136 if (!$assignments = get_records_sql("
2138 ra.id, ra.roleid, ra.userid
2140 {$CFG->prefix}role_assignments ra,
2141 {$CFG->prefix}context con,
2142 {$CFG->prefix}course_meta cm
2144 ra.contextid = con.id AND
2145 con.contextlevel = " . CONTEXT_COURSE
. " AND
2146 con.instanceid = cm.child_course AND
2147 cm.parent_course = {$course->id} AND
2151 {$CFG->prefix}role_assignments ra2
2153 ra2.userid = ra.userid AND
2154 ra2.roleid = ra.roleid AND
2155 ra2.contextid = {$context->id}
2158 $assignments = array();
2161 // Get assignments of a user to a role that exist in the meta course, but
2162 // not in any child courses. That is, get a list of the unassignments that need to be made.
2163 if (!$unassignments = get_records_sql("
2165 ra.id, ra.roleid, ra.userid
2167 {$CFG->prefix}role_assignments ra
2169 ra.contextid = {$context->id} AND
2173 {$CFG->prefix}role_assignments ra2,
2174 {$CFG->prefix}context con2,
2175 {$CFG->prefix}course_meta cm
2177 ra2.userid = ra.userid AND
2178 ra2.roleid = ra.roleid AND
2179 ra2.contextid = con2.id AND
2180 con2.contextlevel = " . CONTEXT_COURSE
. " AND
2181 con2.instanceid = cm.child_course AND
2182 cm.parent_course = {$course->id}
2185 $unassignments = array();
2190 // Make the unassignments, if they are not managers.
2191 foreach ($unassignments as $unassignment) {
2192 if (!in_array($unassignment->userid
, $managers)) {
2193 $success = role_unassign($unassignment->roleid
, $unassignment->userid
, 0, $context->id
) && $success;
2197 // Make the assignments.
2198 foreach ($assignments as $assignment) {
2199 $success = role_assign($assignment->roleid
, $assignment->userid
, 0, $context->id
) && $success;
2204 // TODO: finish timeend and timestart
2205 // maybe we could rely on cron job to do the cleaning from time to time
2209 * Adds a record to the metacourse table and calls sync_metacoures
2211 function add_to_metacourse ($metacourseid, $courseid) {
2213 if (!$metacourse = get_record("course","id",$metacourseid)) {
2217 if (!$course = get_record("course","id",$courseid)) {
2221 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
2222 $rec = new object();
2223 $rec->parent_course
= $metacourseid;
2224 $rec->child_course
= $courseid;
2225 if (!insert_record('course_meta',$rec)) {
2228 return sync_metacourse($metacourseid);
2235 * Removes the record from the metacourse table and calls sync_metacourse
2237 function remove_from_metacourse($metacourseid, $courseid) {
2239 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
2240 return sync_metacourse($metacourseid);
2247 * Determines if a user is currently logged in
2252 function isloggedin() {
2255 return (!empty($USER->id
));
2259 * Determines if a user is logged in as real guest user with username 'guest'.
2260 * This function is similar to original isguest() in 1.6 and earlier.
2261 * Current isguest() is deprecated - do not use it anymore.
2263 * @param $user mixed user object or id, $USER if not specified
2264 * @return bool true if user is the real guest user, false if not logged in or other user
2266 function isguestuser($user=NULL) {
2268 if ($user === NULL) {
2270 } else if (is_numeric($user)) {
2271 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2274 if (empty($user->id
)) {
2275 return false; // not logged in, can not be guest
2278 return ($user->username
== 'guest');
2282 * Determines if the currently logged in user is in editing mode.
2283 * Note: originally this function had $userid parameter - it was not usable anyway
2286 * @param int $courseid The id of the course being tested
2289 function isediting($courseid) {
2292 if (empty($USER->editing
)) {
2296 return editcourseallowed($courseid);
2301 * Verifies if user allowed to edit something in the course page.
2302 * @param int $courseid The id of the course being tested
2305 function editcourseallowed($courseid) {
2308 // cache the result per course, it is automatically reset when using switchrole or loginas
2309 if (!array_key_exists('courseeditallowed', $USER)) {
2310 $USER->courseeditallowed
= array();
2313 if (!array_key_exists($courseid, $USER->courseeditallowed
)) {
2314 $USER->courseeditallowed
[$courseid] = has_capability_including_child_contexts(get_context_instance(CONTEXT_COURSE
, $courseid),
2315 array('moodle/site:manageblocks', 'moodle/course:manageactivities'));
2318 return $USER->courseeditallowed
[$courseid];
2322 * Determines if the logged in user is currently moving an activity
2325 * @param int $courseid The id of the course being tested
2328 function ismoving($courseid) {
2331 if (!empty($USER->activitycopy
)) {
2332 return ($USER->activitycopycourse
== $courseid);
2338 * Given an object containing firstname and lastname
2339 * values, this function returns a string with the
2340 * full name of the person.
2341 * The result may depend on system settings
2342 * or language. 'override' will force both names
2343 * to be used even if system settings specify one.
2347 * @param object $user A {@link $USER} object to get full name of
2348 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
2350 function fullname($user, $override=false) {
2352 global $CFG, $SESSION;
2354 if (!isset($user->firstname
) and !isset($user->lastname
)) {
2359 if (!empty($CFG->forcefirstname
)) {
2360 $user->firstname
= $CFG->forcefirstname
;
2362 if (!empty($CFG->forcelastname
)) {
2363 $user->lastname
= $CFG->forcelastname
;
2367 if (!empty($SESSION->fullnamedisplay
)) {
2368 $CFG->fullnamedisplay
= $SESSION->fullnamedisplay
;
2371 if ($CFG->fullnamedisplay
== 'firstname lastname') {
2372 return $user->firstname
.' '. $user->lastname
;
2374 } else if ($CFG->fullnamedisplay
== 'lastname firstname') {
2375 return $user->lastname
.' '. $user->firstname
;
2377 } else if ($CFG->fullnamedisplay
== 'firstname') {
2379 return get_string('fullnamedisplay', '', $user);
2381 return $user->firstname
;
2385 return get_string('fullnamedisplay', '', $user);
2389 * Sets a moodle cookie with an encrypted string
2394 * @param string $thing The string to encrypt and place in a cookie
2396 function set_moodle_cookie($thing) {
2399 if ($thing == 'guest') { // Ignore guest account
2403 $cookiename = 'MOODLEID_'.$CFG->sessioncookie
;
2406 $seconds = DAYSECS
*$days;
2408 setCookie($cookiename, '', time() - HOURSECS
, '/');
2409 setCookie($cookiename, rc4encrypt($thing), time()+
$seconds, '/');
2413 * Gets a moodle cookie with an encrypted string
2418 function get_moodle_cookie() {
2421 $cookiename = 'MOODLEID_'.$CFG->sessioncookie
;
2423 if (empty($_COOKIE[$cookiename])) {
2426 $thing = rc4decrypt($_COOKIE[$cookiename]);
2427 return ($thing == 'guest') ?
'': $thing; // Ignore guest account
2432 * Returns whether a given authentication plugin exists.
2435 * @param string $auth Form of authentication to check for. Defaults to the
2436 * global setting in {@link $CFG}.
2437 * @return boolean Whether the plugin is available.
2439 function exists_auth_plugin($auth) {
2442 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2443 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2449 * Checks if a given plugin is in the list of enabled authentication plugins.
2451 * @param string $auth Authentication plugin.
2452 * @return boolean Whether the plugin is enabled.
2454 function is_enabled_auth($auth) {
2459 $enabled = get_enabled_auth_plugins();
2461 return in_array($auth, $enabled);
2465 * Returns an authentication plugin instance.
2468 * @param string $auth name of authentication plugin
2469 * @return object An instance of the required authentication plugin.
2471 function get_auth_plugin($auth) {
2474 // check the plugin exists first
2475 if (! exists_auth_plugin($auth)) {
2476 error("Authentication plugin '$auth' not found.");
2479 // return auth plugin instance
2480 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2481 $class = "auth_plugin_$auth";
2486 * Returns array of active auth plugins.
2488 * @param bool $fix fix $CFG->auth if needed
2491 function get_enabled_auth_plugins($fix=false) {
2494 $default = array('manual', 'nologin');
2496 if (empty($CFG->auth
)) {
2499 $auths = explode(',', $CFG->auth
);
2503 $auths = array_unique($auths);
2504 foreach($auths as $k=>$authname) {
2505 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
2509 $newconfig = implode(',', $auths);
2510 if (!isset($CFG->auth
) or $newconfig != $CFG->auth
) {
2511 set_config('auth', $newconfig);
2515 return (array_merge($default, $auths));
2519 * Returns true if an internal authentication method is being used.
2520 * if method not specified then, global default is assumed
2523 * @param string $auth Form of authentication required
2526 function is_internal_auth($auth) {
2527 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2528 return $authplugin->is_internal();
2532 * Returns an array of user fields
2536 * @return array User field/column names
2538 function get_user_fieldnames() {
2542 $fieldarray = $db->MetaColumnNames($CFG->prefix
.'user');
2543 unset($fieldarray['ID']);
2549 * Creates the default "guest" user. Used both from
2550 * admin/index.php and login/index.php
2551 * @return mixed user object created or boolean false if the creation has failed
2553 function create_guest_record() {
2557 $guest->auth
= 'manual';
2558 $guest->username
= 'guest';
2559 $guest->password
= hash_internal_user_password('guest');
2560 $guest->firstname
= addslashes(get_string('guestuser'));
2561 $guest->lastname
= ' ';
2562 $guest->email
= 'root@localhost';
2563 $guest->description
= addslashes(get_string('guestuserinfo'));
2564 $guest->mnethostid
= $CFG->mnet_localhost_id
;
2565 $guest->confirmed
= 1;
2566 $guest->lang
= $CFG->lang
;
2567 $guest->timemodified
= time();
2569 if (! $guest->id
= insert_record("user", $guest)) {
2577 * Creates a bare-bones user record
2580 * @param string $username New user's username to add to record
2581 * @param string $password New user's password to add to record
2582 * @param string $auth Form of authentication required
2583 * @return object A {@link $USER} object
2584 * @todo Outline auth types and provide code example
2586 function create_user_record($username, $password, $auth='manual') {
2589 //just in case check text case
2590 $username = trim(moodle_strtolower($username));
2592 $authplugin = get_auth_plugin($auth);
2594 if ($newinfo = $authplugin->get_userinfo($username)) {
2595 $newinfo = truncate_userinfo($newinfo);
2596 foreach ($newinfo as $key => $value){
2597 $newuser->$key = addslashes($value);
2601 if (!empty($newuser->email
)) {
2602 if (email_is_not_allowed($newuser->email
)) {
2603 unset($newuser->email
);
2607 $newuser->auth
= $auth;
2608 $newuser->username
= $username;
2611 // user CFG lang for user if $newuser->lang is empty
2612 // or $user->lang is not an installed language
2613 $sitelangs = array_keys(get_list_of_languages());
2614 if (empty($newuser->lang
) ||
!in_array($newuser->lang
, $sitelangs)) {
2615 $newuser -> lang
= $CFG->lang
;
2617 $newuser->confirmed
= 1;
2618 $newuser->lastip
= getremoteaddr();
2619 $newuser->timemodified
= time();
2620 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
2622 if (insert_record('user', $newuser)) {
2623 $user = get_complete_user_data('username', $newuser->username
);
2624 if(!empty($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'})){
2625 set_user_preference('auth_forcepasswordchange', 1, $user->id
);
2627 update_internal_user_password($user, $password);
2634 * Will update a local user record from an external source
2637 * @param string $username New user's username to add to record
2638 * @return user A {@link $USER} object
2640 function update_user_record($username, $authplugin) {
2641 $username = trim(moodle_strtolower($username)); /// just in case check text case
2643 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2644 $userauth = get_auth_plugin($oldinfo->auth
);
2646 if ($newinfo = $userauth->get_userinfo($username)) {
2647 $newinfo = truncate_userinfo($newinfo);
2648 foreach ($newinfo as $key => $value){
2649 $confkey = 'field_updatelocal_' . $key;
2650 if (!empty($userauth->config
->$confkey) and $userauth->config
->$confkey === 'onlogin') {
2651 $value = addslashes(stripslashes($value)); // Just in case
2652 set_field('user', $key, $value, 'username', $username)
2653 or error_log("Error updating $key for $username");
2658 return get_complete_user_data('username', $username);
2661 function truncate_userinfo($info) {
2662 /// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2663 /// which may have large fields
2665 // define the limits
2675 'institution' => 40,
2683 // apply where needed
2684 foreach (array_keys($info) as $key) {
2685 if (!empty($limit[$key])) {
2686 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
2694 * Marks user deleted in internal user database and notifies the auth plugin.
2695 * Also unenrols user from all roles and does other cleanup.
2696 * @param object $user Userobject before delete (without system magic quotes)
2697 * @return boolean success
2699 function delete_user($user) {
2701 require_once($CFG->libdir
.'/grouplib.php');
2705 // delete all grades - backup is kept in grade_grades_history table
2706 if ($grades = grade_grade
::fetch_all(array('userid'=>$user->id
))) {
2707 foreach ($grades as $grade) {
2708 $grade->delete('userdelete');
2712 // remove from all groups
2713 delete_records('groups_members', 'userid', $user->id
);
2715 // unenrol from all roles in all contexts
2716 role_unassign(0, $user->id
); // this might be slow but it is really needed - modules might do some extra cleanup!
2718 // now do a final accesslib cleanup - removes all role assingments in user context and context itself
2719 delete_context(CONTEXT_USER
, $user->id
);
2721 // mark internal user record as "deleted"
2722 $updateuser = new object();
2723 $updateuser->id
= $user->id
;
2724 $updateuser->deleted
= 1;
2725 $updateuser->username
= addslashes("$user->email.".time()); // Remember it just in case
2726 $updateuser->email
= ''; // Clear this field to free it up
2727 $updateuser->idnumber
= ''; // Clear this field to free it up
2728 $updateuser->timemodified
= time();
2730 if (update_record('user', $updateuser)) {
2732 // notify auth plugin - do not block the delete even when plugin fails
2733 $authplugin = get_auth_plugin($user->auth
);
2734 $authplugin->user_delete($user);
2744 * Retrieve the guest user object
2747 * @return user A {@link $USER} object
2749 function guest_user() {
2752 if ($newuser = get_record('user', 'username', 'guest', 'mnethostid', $CFG->mnet_localhost_id
)) {
2753 $newuser->confirmed
= 1;
2754 $newuser->lang
= $CFG->lang
;
2755 $newuser->lastip
= getremoteaddr();
2762 * Given a username and password, this function looks them
2763 * up using the currently selected authentication mechanism,
2764 * and if the authentication is successful, it returns a
2765 * valid $user object from the 'user' table.
2767 * Uses auth_ functions from the currently active auth module
2770 * @param string $username User's username (with system magic quotes)
2771 * @param string $password User's password (with system magic quotes)
2772 * @return user|flase A {@link $USER} object or false if error
2774 function authenticate_user_login($username, $password) {
2778 $authsenabled = get_enabled_auth_plugins();
2780 if ($user = get_complete_user_data('username', $username)) {
2781 $auth = empty($user->auth
) ?
'manual' : $user->auth
; // use manual if auth not set
2782 if ($auth=='nologin' or !is_enabled_auth($auth)) {
2783 add_to_log(0, 'login', 'error', 'index.php', $username);
2784 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2787 if (!empty($user->deleted
)) {
2788 add_to_log(0, 'login', 'error', 'index.php', $username);
2789 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2792 $auths = array($auth);
2795 $auths = $authsenabled;
2796 $user = new object();
2797 $user->id
= 0; // User does not exist
2800 foreach ($auths as $auth) {
2801 $authplugin = get_auth_plugin($auth);
2803 // on auth fail fall through to the next plugin
2804 if (!$authplugin->user_login($username, $password)) {
2808 // successful authentication
2809 if ($user->id
) { // User already exists in database
2810 if (empty($user->auth
)) { // For some reason auth isn't set yet
2811 set_field('user', 'auth', $auth, 'username', $username);
2812 $user->auth
= $auth;
2815 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
2817 if (!$authplugin->is_internal()) { // update user record from external DB
2818 $user = update_user_record($username, get_auth_plugin($user->auth
));
2821 // if user not found, create him
2822 $user = create_user_record($username, $password, $auth);
2825 $authplugin->sync_roles($user);
2827 foreach ($authsenabled as $hau) {
2828 $hauth = get_auth_plugin($hau);
2829 $hauth->user_authenticated_hook($user, $username, $password);
2832 /// Log in to a second system if necessary
2833 /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
2834 if (!empty($CFG->sso
)) {
2835 include_once($CFG->dirroot
.'/sso/'. $CFG->sso
.'/lib.php');
2836 if (function_exists('sso_user_login')) {
2837 if (!sso_user_login($username, $password)) { // Perform the signon process
2838 notify('Second sign-on failed');
2847 // failed if all the plugins have failed
2848 add_to_log(0, 'login', 'error', 'index.php', $username);
2849 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2854 * Compare password against hash stored in internal user table.
2855 * If necessary it also updates the stored hash to new format.
2857 * @param object user
2858 * @param string plain text password
2859 * @return bool is password valid?
2861 function validate_internal_user_password(&$user, $password) {
2864 if (!isset($CFG->passwordsaltmain
)) {
2865 $CFG->passwordsaltmain
= '';
2870 // get password original encoding in case it was not updated to unicode yet
2871 $textlib = textlib_get_instance();
2872 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
2874 if ($user->password
== md5($password.$CFG->passwordsaltmain
) or $user->password
== md5($password)
2875 or $user->password
== md5($convpassword.$CFG->passwordsaltmain
) or $user->password
== md5($convpassword)) {
2878 for ($i=1; $i<=20; $i++
) { //20 alternative salts should be enough, right?
2879 $alt = 'passwordsaltalt'.$i;
2880 if (!empty($CFG->$alt)) {
2881 if ($user->password
== md5($password.$CFG->$alt) or $user->password
== md5($convpassword.$CFG->$alt)) {
2890 // force update of password hash using latest main password salt and encoding if needed
2891 update_internal_user_password($user, $password);
2898 * Calculate hashed value from password using current hash mechanism.
2900 * @param string password
2901 * @return string password hash
2903 function hash_internal_user_password($password) {
2906 if (isset($CFG->passwordsaltmain
)) {
2907 return md5($password.$CFG->passwordsaltmain
);
2909 return md5($password);
2914 * Update pssword hash in user object.
2916 * @param object user
2917 * @param string plain text password
2918 * @param bool store changes also in db, default true
2919 * @return true if hash changed
2921 function update_internal_user_password(&$user, $password) {
2924 $authplugin = get_auth_plugin($user->auth
);
2925 if (!empty($authplugin->config
->preventpassindb
)) {
2926 $hashedpassword = 'not cached';
2928 $hashedpassword = hash_internal_user_password($password);
2931 return set_field('user', 'password', $hashedpassword, 'id', $user->id
);
2935 * Get a complete user record, which includes all the info
2936 * in the user record
2937 * Intended for setting as $USER session variable
2941 * @param string $field The user field to be checked for a given value.
2942 * @param string $value The value to match for $field.
2943 * @return user A {@link $USER} object.
2945 function get_complete_user_data($field, $value, $mnethostid=null) {
2949 if (!$field ||
!$value) {
2953 /// Build the WHERE clause for an SQL query
2955 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
2957 if (is_null($mnethostid)) {
2958 // if null, we restrict to local users
2959 // ** testing for local user can be done with
2960 // mnethostid = $CFG->mnet_localhost_id
2963 // but the first one is FAST with our indexes
2964 $mnethostid = $CFG->mnet_localhost_id
;
2966 $mnethostid = (int)$mnethostid;
2967 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
2969 /// Get all the basic user data
2971 if (! $user = get_record_select('user', $constraints)) {
2975 /// Get various settings and preferences
2977 if ($displays = get_records('course_display', 'userid', $user->id
)) {
2978 foreach ($displays as $display) {
2979 $user->display
[$display->course
] = $display->display
;
2983 $user->preference
= get_user_preferences(null, null, $user->id
);
2985 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id
)) {
2986 foreach ($lastaccesses as $lastaccess) {
2987 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
2991 $sql = "SELECT g.id, g.courseid
2992 FROM {$CFG->prefix}groups g, {$CFG->prefix}groups_members gm
2993 WHERE gm.groupid=g.id AND gm.userid={$user->id}";
2995 // this is a special hack to speedup calendar display
2996 $user->groupmember
= array();
2997 if ($groups = get_records_sql($sql)) {
2998 foreach ($groups as $group) {
2999 if (!array_key_exists($group->courseid
, $user->groupmember
)) {
3000 $user->groupmember
[$group->courseid
] = array();
3002 $user->groupmember
[$group->courseid
][$group->id
] = $group->id
;
3006 /// Rewrite some variables if necessary
3007 if (!empty($user->description
)) {
3008 $user->description
= true; // No need to cart all of it around
3010 if ($user->username
== 'guest') {
3011 $user->lang
= $CFG->lang
; // Guest language always same as site
3012 $user->firstname
= get_string('guestuser'); // Name always in current language
3013 $user->lastname
= ' ';
3016 $user->sesskey
= random_string(10);
3017 $user->sessionIP
= md5(getremoteaddr()); // Store the current IP in the session
3024 * @param string $password the password to be checked agains the password policy
3025 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
3026 * @return bool true if the password is valid according to the policy. false otherwise.
3028 function check_password_policy($password, &$errmsg) {
3031 if (empty($CFG->passwordpolicy
)) {
3035 $textlib = new textlib();
3037 if ($textlib->strlen($password) < $CFG->minpasswordlength
) {
3038 $errmsg = get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength
);
3040 } else if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits
) {
3041 $errmsg = get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits
);
3043 } else if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower
) {
3044 $errmsg = get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower
);
3046 } else if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper
) {
3047 $errmsg = get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper
);
3049 } else if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum
) {
3050 $errmsg = get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
);
3052 } else if ($password == 'admin' or $password == 'password') {
3053 $errmsg = get_string('unsafepassword');
3056 if ($errmsg == '') {
3065 * When logging in, this function is run to set certain preferences
3066 * for the current SESSION
3068 function set_login_session_preferences() {
3069 global $SESSION, $CFG;
3071 $SESSION->justloggedin
= true;
3073 unset($SESSION->lang
);
3075 // Restore the calendar filters, if saved
3076 if (intval(get_user_preferences('calendar_persistflt', 0))) {
3077 include_once($CFG->dirroot
.'/calendar/lib.php');
3078 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
3084 * Delete a course, including all related data from the database,
3085 * and any associated files from the moodledata folder.
3087 * @param int $courseid The id of the course to delete.
3088 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3089 * @return bool true if all the removals succeeded. false if there were any failures. If this
3090 * method returns false, some of the removals will probably have succeeded, and others
3091 * failed, but you have no way of knowing which.
3093 function delete_course($courseid, $showfeedback = true) {
3095 require_once($CFG->libdir
.'/gradelib.php');
3098 if (!remove_course_contents($courseid, $showfeedback)) {
3099 if ($showfeedback) {
3100 notify("An error occurred while deleting some of the course contents.");
3105 remove_course_grades($courseid, $showfeedback);
3107 if (!delete_records("course", "id", $courseid)) {
3108 if ($showfeedback) {
3109 notify("An error occurred while deleting the main course record.");
3114 if (!delete_records('context', 'contextlevel', CONTEXT_COURSE
, 'instanceid', $courseid)) {
3115 if ($showfeedback) {
3116 notify("An error occurred while deleting the main context record.");
3121 if (!fulldelete($CFG->dataroot
.'/'.$courseid)) {
3122 if ($showfeedback) {
3123 notify("An error occurred while deleting the course files.");
3132 * Clear a course out completely, deleting all content
3133 * but don't delete the course itself
3136 * @param int $courseid The id of the course that is being deleted
3137 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3138 * @return bool true if all the removals succeeded. false if there were any failures. If this
3139 * method returns false, some of the removals will probably have succeeded, and others
3140 * failed, but you have no way of knowing which.
3142 function remove_course_contents($courseid, $showfeedback=true) {
3145 include_once($CFG->libdir
.'/questionlib.php');
3149 if (! $course = get_record('course', 'id', $courseid)) {
3150 error('Course ID was incorrect (can\'t find it)');
3153 $strdeleted = get_string('deleted');
3155 /// First delete every instance of every module
3157 if ($allmods = get_records('modules') ) {
3158 foreach ($allmods as $mod) {
3159 $modname = $mod->name
;
3160 $modfile = $CFG->dirroot
.'/mod/'. $modname .'/lib.php';
3161 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
3162 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
3164 if (file_exists($modfile)) {
3165 include_once($modfile);
3166 if (function_exists($moddelete)) {
3167 if ($instances = get_records($modname, 'course', $course->id
)) {
3168 foreach ($instances as $instance) {
3169 if ($cm = get_coursemodule_from_instance($modname, $instance->id
, $course->id
)) {
3170 /// Delete activity context questions and question categories
3171 question_delete_activity($cm, $showfeedback);
3172 delete_context(CONTEXT_MODULE
, $cm->id
);
3174 if ($moddelete($instance->id
)) {
3178 notify('Could not delete '. $modname .' instance '. $instance->id
.' ('. format_string($instance->name
) .')');
3184 notify('Function '. $moddelete() .'doesn\'t exist!');
3188 if (function_exists($moddeletecourse)) {
3189 $moddeletecourse($course, $showfeedback);
3192 if ($showfeedback) {
3193 notify($strdeleted .' '. $count .' x '. $modname);
3197 error('No modules are installed!');
3200 /// Give local code a chance to delete its references to this course.
3201 require_once('locallib.php');
3202 notify_local_delete_course($courseid, $showfeedback);
3204 /// Delete course blocks
3206 if ($blocks = get_records_sql("SELECT *
3207 FROM {$CFG->prefix}block_instance
3208 WHERE pagetype = '".PAGE_COURSE_VIEW
."'
3209 AND pageid = $course->id")) {
3210 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW
, 'pageid', $course->id
)) {
3211 if ($showfeedback) {
3212 notify($strdeleted .' block_instance');
3215 require_once($CFG->libdir
.'/blocklib.php');
3216 foreach ($blocks as $block) { /// Delete any associated contexts for this block
3218 // Block instances are rarely created. Since the block instance is gone from the above delete
3219 // statement, calling delete_context() will generate a warning as get_context_instance could
3220 // no longer create the context as the block is already gone.
3221 if (record_exists('context', 'contextlevel', CONTEXT_BLOCK
, 'instanceid', $block->id
)) {
3222 delete_context(CONTEXT_BLOCK
, $block->id
);
3226 // Get the block object and call instance_delete()
3227 if (!$record = blocks_get_record($block->blockid
)) {
3231 if (!$obj = block_instance($record->name
, $block)) {
3235 // Return value ignored, in core mods this does not do anything, but just in case
3236 // third party blocks might have stuff to clean up
3237 // we execute this anyway
3238 $obj->instance_delete();
3245 /// Delete any groups, removing members and grouping/course links first.
3246 require_once($CFG->dirroot
.'/group/lib.php');
3247 groups_delete_groupings($courseid, true);
3248 groups_delete_groups($courseid, true);
3250 /// Delete all related records in other tables that may have a courseid
3251 /// This array stores the tables that need to be cleared, as
3252 /// table_name => column_name that contains the course id.
3254 $tablestoclear = array(
3255 'event' => 'courseid', // Delete events
3256 'log' => 'course', // Delete logs
3257 'course_sections' => 'course', // Delete any course stuff
3258 'course_modules' => 'course',
3259 'backup_courses' => 'courseid', // Delete scheduled backup stuff
3260 'backup_log' => 'courseid'
3262 foreach ($tablestoclear as $table => $col) {
3263 if (delete_records($table, $col, $course->id
)) {
3264 if ($showfeedback) {
3265 notify($strdeleted . ' ' . $table);
3273 /// Clean up metacourse stuff
3275 if ($course->metacourse
) {
3276 delete_records("course_meta","parent_course",$course->id
);
3277 sync_metacourse($course->id
); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
3278 if ($showfeedback) {
3279 notify("$strdeleted course_meta");
3282 if ($parents = get_records("course_meta","child_course",$course->id
)) {
3283 foreach ($parents as $parent) {
3284 remove_from_metacourse($parent->parent_course
,$parent->child_course
); // this will do the unenrolments as well.
3286 if ($showfeedback) {
3287 notify("$strdeleted course_meta");
3292 /// Delete questions and question categories
3293 question_delete_course($course, $showfeedback);
3295 /// Delete all roles and overiddes in the course context (but keep the course context)
3296 if ($courseid != SITEID
) {
3297 delete_context(CONTEXT_COURSE
, $course->id
);
3301 // clear the cache because the course context is deleted, and
3302 // we don't want to write assignment, overrides and context_rel table
3303 // with this old context id!
3304 get_context_instance('clearcache');
3310 * This function will empty a course of USER data as much as
3311 /// possible. It will retain the activities and the structure
3317 * @param object $data an object containing all the boolean settings and courseid
3318 * @param bool $showfeedback if false then do it all silently
3320 * @todo Finish documenting this function
3322 function reset_course_userdata($data, $showfeedback=true) {
3324 global $CFG, $USER, $SESSION;
3325 require_once($CFG->dirroot
.'/group/lib.php');
3329 $strdeleted = get_string('deleted');
3331 // Look in every instance of every module for data to delete
3333 if ($allmods = get_records('modules') ) {
3334 foreach ($allmods as $mod) {
3335 $modname = $mod->name
;
3336 $modfile = $CFG->dirroot
.'/mod/'. $modname .'/lib.php';
3337 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3338 if (file_exists($modfile)) {
3339 @include_once
($modfile);
3340 if (function_exists($moddeleteuserdata)) {
3341 $moddeleteuserdata($data, $showfeedback);
3346 error('No modules are installed!');
3349 // Delete other stuff
3350 $coursecontext = get_context_instance(CONTEXT_COURSE
, $data->courseid
);
3352 if (!empty($data->reset_students
) or !empty($data->reset_teachers
)) {
3353 $teachers = array_keys(get_users_by_capability($coursecontext, 'moodle/course:update'));
3354 $participants = array_keys(get_users_by_capability($coursecontext, 'moodle/course:view'));
3355 $students = array_diff($participants, $teachers);
3357 if (!empty($data->reset_students
)) {
3358 foreach ($students as $studentid) {
3359 role_unassign(0, $studentid, 0, $coursecontext->id
);
3361 if ($showfeedback) {
3362 notify($strdeleted .' '.get_string('students'), 'notifysuccess');
3365 /// Delete group members (but keep the groups)
3366 $result = groups_delete_group_members($data->courseid
, $showfeedback) && $result;
3369 if (!empty($data->reset_teachers
)) {
3370 foreach ($teachers as $teacherid) {
3371 role_unassign(0, $teacherid, 0, $coursecontext->id
);
3373 if ($showfeedback) {
3374 notify($strdeleted .' '.get_string('teachers'), 'notifysuccess');
3379 if (!empty($data->reset_groups
)) {
3380 $result = groups_delete_groupings($data->courseid
, $showfeedback) && $result;
3381 $result = groups_delete_groups($data->courseid
, $showfeedback) && $result;
3384 if (!empty($data->reset_events
)) {
3385 if (delete_records('event', 'courseid', $data->courseid
)) {
3386 if ($showfeedback) {
3387 notify($strdeleted .' event', 'notifysuccess');
3394 if (!empty($data->reset_logs
)) {
3395 if (delete_records('log', 'course', $data->courseid
)) {
3396 if ($showfeedback) {
3397 notify($strdeleted .' log', 'notifysuccess');
3404 // deletes all role assignments, and local override, these have no courseid in table and needs separate process
3405 $context = get_context_instance(CONTEXT_COURSE
, $data->courseid
);
3406 delete_records('role_capabilities', 'contextid', $context->id
);
3411 function generate_email_processing_address($modid,$modargs) {
3414 if (empty($CFG->siteidentifier
)) { // Unique site identification code
3415 set_config('siteidentifier', random_string(32));
3418 $header = $CFG->mailprefix
. substr(base64_encode(pack('C',$modid)),0,2).$modargs;
3419 return $header . substr(md5($header.$CFG->siteidentifier
),0,16).'@'.$CFG->maildomain
;
3423 function moodle_process_email($modargs,$body) {
3424 // the first char should be an unencoded letter. We'll take this as an action
3425 switch ($modargs{0}) {
3426 case 'B': { // bounce
3427 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
3428 if ($user = get_record_select("user","id=$userid","id,email")) {
3429 // check the half md5 of their email
3430 $md5check = substr(md5($user->email
),0,16);
3431 if ($md5check == substr($modargs, -16)) {
3432 set_bounce_count($user);
3434 // else maybe they've already changed it?
3438 // maybe more later?
3442 /// CORRESPONDENCE ////////////////////////////////////////////////
3445 * Send an email to a specified user
3450 * @param user $user A {@link $USER} object
3451 * @param user $from A {@link $USER} object
3452 * @param string $subject plain text subject line of the email
3453 * @param string $messagetext plain text version of the message
3454 * @param string $messagehtml complete html version of the message (optional)
3455 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
3456 * @param string $attachname the name of the file (extension indicates MIME)
3457 * @param bool $usetrueaddress determines whether $from email address should
3458 * be sent out. Will be overruled by user profile setting for maildisplay
3459 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3460 * was blocked by user and "false" if there was another sort of error.
3462 function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='') {
3464 global $CFG, $FULLME;
3466 include_once($CFG->libdir
.'/phpmailer/class.phpmailer.php');
3468 /// We are going to use textlib services here
3469 $textlib = textlib_get_instance();
3475 // skip mail to suspended users
3476 if (isset($user->auth
) && $user->auth
=='nologin') {
3480 if (!empty($user->emailstop
)) {
3484 if (over_bounce_threshold($user)) {
3485 error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
3489 $mail = new phpmailer
;
3491 $mail->Version
= 'Moodle '. $CFG->version
; // mailer version
3492 $mail->PluginDir
= $CFG->libdir
.'/phpmailer/'; // plugin directory (eg smtp plugin)
3494 $mail->CharSet
= 'UTF-8';
3496 if ($CFG->smtphosts
== 'qmail') {
3497 $mail->IsQmail(); // use Qmail system
3499 } else if (empty($CFG->smtphosts
)) {
3500 $mail->IsMail(); // use PHP mail() = sendmail
3503 $mail->IsSMTP(); // use SMTP directly
3504 if (!empty($CFG->debugsmtp
)) {
3505 echo '<pre>' . "\n";
3506 $mail->SMTPDebug
= true;
3508 $mail->Host
= $CFG->smtphosts
; // specify main and backup servers
3510 if ($CFG->smtpuser
) { // Use SMTP authentication
3511 $mail->SMTPAuth
= true;
3512 $mail->Username
= $CFG->smtpuser
;
3513 $mail->Password
= $CFG->smtppass
;
3517 $supportuser = generate_email_supportuser();
3520 // make up an email address for handling bounces
3521 if (!empty($CFG->handlebounces
)) {
3522 $modargs = 'B'.base64_encode(pack('V',$user->id
)).substr(md5($user->email
),0,16);
3523 $mail->Sender
= generate_email_processing_address(0,$modargs);
3525 $mail->Sender
= $supportuser->email
;
3528 if (is_string($from)) { // So we can pass whatever we want if there is need
3529 $mail->From
= $CFG->noreplyaddress
;
3530 $mail->FromName
= $from;
3531 } else if ($usetrueaddress and $from->maildisplay
) {
3532 $mail->From
= $from->email
;
3533 $mail->FromName
= fullname($from);
3535 $mail->From
= $CFG->noreplyaddress
;
3536 $mail->FromName
= fullname($from);
3537 if (empty($replyto)) {
3538 $mail->AddReplyTo($CFG->noreplyaddress
,get_string('noreplyname'));
3542 if (!empty($replyto)) {
3543 $mail->AddReplyTo($replyto,$replytoname);
3546 $mail->Subject
= substr(stripslashes($subject), 0, 900);
3548 $mail->AddAddress($user->email
, fullname($user) );
3550 $mail->WordWrap
= 79; // set word wrap
3552 if (!empty($from->customheaders
)) { // Add custom headers
3553 if (is_array($from->customheaders
)) {
3554 foreach ($from->customheaders
as $customheader) {
3555 $mail->AddCustomHeader($customheader);
3558 $mail->AddCustomHeader($from->customheaders
);
3562 if (!empty($from->priority
)) {
3563 $mail->Priority
= $from->priority
;
3566 if ($messagehtml && $user->mailformat
== 1) { // Don't ever send HTML to users who don't want it
3567 $mail->IsHTML(true);
3568 $mail->Encoding
= 'quoted-printable'; // Encoding to use
3569 $mail->Body
= $messagehtml;
3570 $mail->AltBody
= "\n$messagetext\n";
3572 $mail->IsHTML(false);
3573 $mail->Body
= "\n$messagetext\n";
3576 if ($attachment && $attachname) {
3577 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
3578 $mail->AddAddress($supportuser->email
, fullname($supportuser, true) );
3579 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
3581 require_once($CFG->libdir
.'/filelib.php');
3582 $mimetype = mimeinfo('type', $attachname);
3583 $mail->AddAttachment($CFG->dataroot
.'/'. $attachment, $attachname, 'base64', $mimetype);
3589 /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
3590 /// encoding to the specified one
3591 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
3592 /// Set it to site mail charset
3593 $charset = $CFG->sitemailcharset
;
3594 /// Overwrite it with the user mail charset
3595 if (!empty($CFG->allowusermailcharset
)) {
3596 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
3597 $charset = $useremailcharset;
3600 /// If it has changed, convert all the necessary strings
3601 $charsets = get_list_of_charsets();
3602 unset($charsets['UTF-8']);
3603 if (in_array($charset, $charsets)) {
3604 /// Save the new mail charset
3605 $mail->CharSet
= $charset;
3606 /// And convert some strings
3607 $mail->FromName
= $textlib->convert($mail->FromName
, 'utf-8', $mail->CharSet
); //From Name
3608 foreach ($mail->ReplyTo
as $key => $rt) { //ReplyTo Names
3609 $mail->ReplyTo
[$key][1] = $textlib->convert($rt, 'utf-8', $mail->CharSet
);
3611 $mail->Subject
= $textlib->convert($mail->Subject
, 'utf-8', $mail->CharSet
); //Subject
3612 foreach ($mail->to
as $key => $to) {
3613 $mail->to
[$key][1] = $textlib->convert($to, 'utf-8', $mail->CharSet
); //To Names
3615 $mail->Body
= $textlib->convert($mail->Body
, 'utf-8', $mail->CharSet
); //Body
3616 $mail->AltBody
= $textlib->convert($mail->AltBody
, 'utf-8', $mail->CharSet
); //Subject
3620 if ($mail->Send()) {
3621 set_send_count($user);
3622 $mail->IsSMTP(); // use SMTP directly
3623 if (!empty($CFG->debugsmtp
)) {
3628 mtrace('ERROR: '. $mail->ErrorInfo
);
3629 add_to_log(SITEID
, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo
);
3630 if (!empty($CFG->debugsmtp
)) {
3638 * Generate a signoff for emails based on support settings
3641 function generate_email_signoff() {
3645 if (!empty($CFG->supportname
)) {
3646 $signoff .= $CFG->supportname
."\n";
3648 if (!empty($CFG->supportemail
)) {
3649 $signoff .= $CFG->supportemail
."\n";
3651 if (!empty($CFG->supportpage
)) {
3652 $signoff .= $CFG->supportpage
."\n";
3658 * Generate a fake user for emails based on support settings
3661 function generate_email_supportuser() {
3665 static $supportuser;
3667 if (!empty($supportuser)) {
3668 return $supportuser;
3671 $supportuser = new object;
3672 $supportuser->email
= $CFG->supportemail ?
$CFG->supportemail
: $CFG->noreplyaddress
;
3673 $supportuser->firstname
= $CFG->supportname ?
$CFG->supportname
: get_string('noreplyname');
3674 $supportuser->lastname
= '';
3676 return $supportuser;
3681 * Sets specified user's password and send the new password to the user via email.
3684 * @param user $user A {@link $USER} object
3685 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
3686 * was blocked by user and "false" if there was another sort of error.
3688 function setnew_password_and_mail($user) {
3694 $supportuser = generate_email_supportuser();
3696 $newpassword = generate_password();
3698 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id
) ) {
3699 trigger_error('Could not set user password!');
3704 $a->firstname
= fullname($user, true);
3705 $a->sitename
= format_string($site->fullname
);
3706 $a->username
= $user->username
;
3707 $a->newpassword
= $newpassword;
3708 $a->link
= $CFG->wwwroot
.'/login/';
3709 $a->signoff
= generate_email_signoff();
3711 $message = get_string('newusernewpasswordtext', '', $a);
3713 $subject = format_string($site->fullname
) .': '. get_string('newusernewpasswordsubj');
3715 return email_to_user($user, $supportuser, $subject, $message);
3720 * Resets specified user's password and send the new password to the user via email.
3723 * @param user $user A {@link $USER} object
3724 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3725 * was blocked by user and "false" if there was another sort of error.
3727 function reset_password_and_mail($user) {
3732 $supportuser = generate_email_supportuser();
3734 $userauth = get_auth_plugin($user->auth
);
3735 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth
)) {
3736 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
3740 $newpassword = generate_password();
3742 if (!$userauth->user_update_password(addslashes_recursive($user), addslashes($newpassword))) {
3743 error("Could not set user password!");
3747 $a->firstname
= $user->firstname
;
3748 $a->sitename
= format_string($site->fullname
);
3749 $a->username
= $user->username
;
3750 $a->newpassword
= $newpassword;
3751 $a->link
= $CFG->httpswwwroot
.'/login/change_password.php';
3752 $a->signoff
= generate_email_signoff();
3754 $message = get_string('newpasswordtext', '', $a);
3756 $subject = format_string($site->fullname
) .': '. get_string('changedpassword');
3758 return email_to_user($user, $supportuser, $subject, $message);
3763 * Send email to specified user with confirmation text and activation link.
3766 * @param user $user A {@link $USER} object
3767 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3768 * was blocked by user and "false" if there was another sort of error.
3770 function send_confirmation_email($user) {
3775 $supportuser = generate_email_supportuser();
3777 $data = new object();
3778 $data->firstname
= fullname($user);
3779 $data->sitename
= format_string($site->fullname
);
3780 $data->admin
= generate_email_signoff();
3782 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname
));
3784 $data->link
= $CFG->wwwroot
.'/login/confirm.php?data='. $user->secret
.'/'. urlencode($user->username
);
3785 $message = get_string('emailconfirmation', '', $data);
3786 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
3788 $user->mailformat
= 1; // Always send HTML version as well
3790 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
3795 * send_password_change_confirmation_email.
3798 * @param user $user A {@link $USER} object
3799 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3800 * was blocked by user and "false" if there was another sort of error.
3802 function send_password_change_confirmation_email($user) {
3807 $supportuser = generate_email_supportuser();
3809 $data = new object();
3810 $data->firstname
= $user->firstname
;
3811 $data->sitename
= format_string($site->fullname
);
3812 $data->link
= $CFG->httpswwwroot
.'/login/forgot_password.php?p='. $user->secret
.'&s='. urlencode($user->username
);
3813 $data->admin
= generate_email_signoff();
3815 $message = get_string('emailpasswordconfirmation', '', $data);
3816 $subject = get_string('emailpasswordconfirmationsubject', '', format_string($site->fullname
));
3818 return email_to_user($user, $supportuser, $subject, $message);
3823 * send_password_change_info.
3826 * @param user $user A {@link $USER} object
3827 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3828 * was blocked by user and "false" if there was another sort of error.
3830 function send_password_change_info($user) {
3835 $supportuser = generate_email_supportuser();
3836 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
3838 $data = new object();
3839 $data->firstname
= $user->firstname
;
3840 $data->sitename
= format_string($site->fullname
);
3841 $data->admin
= generate_email_signoff();
3843 $userauth = get_auth_plugin($user->auth
);
3845 if (!is_enabled_auth($user->auth
) or $user->auth
== 'nologin') {
3846 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
3847 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
3848 return email_to_user($user, $supportuser, $subject, $message);
3851 if ($userauth->can_change_password() and $userauth->change_password_url()) {
3852 // we have some external url for password changing
3853 $data->link
.= $userauth->change_password_url();
3856 //no way to change password, sorry
3860 if (!empty($data->link
) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id
)) {
3861 $message = get_string('emailpasswordchangeinfo', '', $data);
3862 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
3864 $message = get_string('emailpasswordchangeinfofail', '', $data);
3865 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
3868 return email_to_user($user, $supportuser, $subject, $message);
3873 * Check that an email is allowed. It returns an error message if there
3877 * @param string $email Content of email
3878 * @return string|false
3880 function email_is_not_allowed($email) {
3884 if (!empty($CFG->allowemailaddresses
)) {
3885 $allowed = explode(' ', $CFG->allowemailaddresses
);
3886 foreach ($allowed as $allowedpattern) {
3887 $allowedpattern = trim($allowedpattern);
3888 if (!$allowedpattern) {
3891 if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) { // Match! (bug 5250)
3895 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
3897 } else if (!empty($CFG->denyemailaddresses
)) {
3898 $denied = explode(' ', $CFG->denyemailaddresses
);
3899 foreach ($denied as $deniedpattern) {
3900 $deniedpattern = trim($deniedpattern);
3901 if (!$deniedpattern) {
3904 if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) { // Match! (bug 5250)
3905 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
3913 function email_welcome_message_to_user($course, $user=NULL) {
3917 if (!isloggedin()) {
3923 if (!empty($course->welcomemessage
)) {
3924 $subject = get_string('welcometocourse', '', format_string($course->fullname
));
3926 $a->coursename
= $course->fullname
;
3927 $a->profileurl
= "$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id";
3928 //$message = get_string("welcometocoursetext", "", $a);
3929 $message = $course->welcomemessage
;
3931 if (! $teacher = get_teacher($course->id
)) {
3932 $teacher = get_admin();
3934 email_to_user($user, $teacher, $subject, $message);
3938 /// FILE HANDLING /////////////////////////////////////////////
3942 * Makes an upload directory for a particular module.
3945 * @param int $courseid The id of the course in question - maps to id field of 'course' table.
3946 * @return string|false Returns full path to directory if successful, false if not
3948 function make_mod_upload_directory($courseid) {
3951 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata
)) {
3955 $strreadme = get_string('readme');
3957 if (file_exists($CFG->dirroot
.'/lang/'. $CFG->lang
.'/docs/module_files.txt')) {
3958 copy($CFG->dirroot
.'/lang/'. $CFG->lang
.'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
3960 copy($CFG->dirroot
.'/lang/en_utf8/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
3966 * Returns current name of file on disk if it exists.
3968 * @param string $newfile File to be verified
3969 * @return string Current name of file on disk if true
3971 function valid_uploaded_file($newfile) {
3972 if (empty($newfile)) {
3975 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
3976 return $newfile['tmp_name'];
3983 * Returns the maximum size for uploading files.
3985 * There are seven possible upload limits:
3986 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
3987 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
3988 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
3989 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
3990 * 5. by the Moodle admin in $CFG->maxbytes
3991 * 6. by the teacher in the current course $course->maxbytes
3992 * 7. by the teacher for the current module, eg $assignment->maxbytes
3994 * These last two are passed to this function as arguments (in bytes).
3995 * Anything defined as 0 is ignored.
3996 * The smallest of all the non-zero numbers is returned.
3998 * @param int $sizebytes ?
3999 * @param int $coursebytes Current course $course->maxbytes (in bytes)
4000 * @param int $modulebytes Current module ->maxbytes (in bytes)
4001 * @return int The maximum size for uploading files.
4002 * @todo Finish documenting this function
4004 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4006 if (! $filesize = ini_get('upload_max_filesize')) {
4009 $minimumsize = get_real_size($filesize);
4011 if ($postsize = ini_get('post_max_size')) {
4012 $postsize = get_real_size($postsize);
4013 if ($postsize < $minimumsize) {
4014 $minimumsize = $postsize;
4018 if ($sitebytes and $sitebytes < $minimumsize) {
4019 $minimumsize = $sitebytes;
4022 if ($coursebytes and $coursebytes < $minimumsize) {
4023 $minimumsize = $coursebytes;
4026 if ($modulebytes and $modulebytes < $minimumsize) {
4027 $minimumsize = $modulebytes;
4030 return $minimumsize;
4034 * Related to {@link get_max_upload_file_size()} - this function returns an
4035 * array of possible sizes in an array, translated to the
4038 * @uses SORT_NUMERIC
4039 * @param int $sizebytes ?
4040 * @param int $coursebytes Current course $course->maxbytes (in bytes)
4041 * @param int $modulebytes Current module ->maxbytes (in bytes)
4043 * @todo Finish documenting this function
4045 function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4048 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
4052 $filesize[$maxsize] = display_size($maxsize);
4054 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
4055 5242880, 10485760, 20971520, 52428800, 104857600);
4057 // Allow maxbytes to be selected if it falls outside the above boundaries
4058 if( isset($CFG->maxbytes
) && !in_array($CFG->maxbytes
, $sizelist) ){
4059 $sizelist[] = $CFG->maxbytes
;
4062 foreach ($sizelist as $sizebytes) {
4063 if ($sizebytes < $maxsize) {
4064 $filesize[$sizebytes] = display_size($sizebytes);
4068 krsort($filesize, SORT_NUMERIC
);
4074 * If there has been an error uploading a file, print the appropriate error message
4075 * Numerical constants used as constant definitions not added until PHP version 4.2.0
4077 * $filearray is a 1-dimensional sub-array of the $_FILES array
4078 * eg $filearray = $_FILES['userfile1']
4079 * If left empty then the first element of the $_FILES array will be used
4082 * @param array $filearray A 1-dimensional sub-array of the $_FILES array
4083 * @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.
4084 * @return bool|string
4086 function print_file_upload_error($filearray = '', $returnerror = false) {
4088 if ($filearray == '' or !isset($filearray['error'])) {
4090 if (empty($_FILES)) return false;
4092 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
4093 $filearray = array_shift($files); /// use first element of array
4096 switch ($filearray['error']) {
4098 case 0: // UPLOAD_ERR_OK
4099 if ($filearray['size'] > 0) {
4100 $errmessage = get_string('uploadproblem', $filearray['name']);
4102 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
4106 case 1: // UPLOAD_ERR_INI_SIZE
4107 $errmessage = get_string('uploadserverlimit');
4110 case 2: // UPLOAD_ERR_FORM_SIZE
4111 $errmessage = get_string('uploadformlimit');
4114 case 3: // UPLOAD_ERR_PARTIAL
4115 $errmessage = get_string('uploadpartialfile');
4118 case 4: // UPLOAD_ERR_NO_FILE
4119 $errmessage = get_string('uploadnofilefound');
4123 $errmessage = get_string('uploadproblem', $filearray['name']);
4129 notify($errmessage);
4136 * handy function to loop through an array of files and resolve any filename conflicts
4137 * both in the array of filenames and for what is already on disk.
4138 * not really compatible with the similar function in uploadlib.php
4139 * but this could be used for files/index.php for moving files around.
4142 function resolve_filename_collisions($destination,$files,$format='%s_%d.%s') {
4143 foreach ($files as $k => $f) {
4144 if (check_potential_filename($destination,$f,$files)) {
4145 $bits = explode('.', $f);
4146 for ($i = 1; true; $i++
) {
4147 $try = sprintf($format, $bits[0], $i, $bits[1]);
4148 if (!check_potential_filename($destination,$try,$files)) {
4159 * @used by resolve_filename_collisions
4161 function check_potential_filename($destination,$filename,$files) {
4162 if (file_exists($destination.'/'.$filename)) {
4165 if (count(array_keys($files,$filename)) > 1) {
4173 * Returns an array with all the filenames in
4174 * all subdirectories, relative to the given rootdir.
4175 * If excludefile is defined, then that file/directory is ignored
4176 * If getdirs is true, then (sub)directories are included in the output
4177 * If getfiles is true, then files are included in the output
4178 * (at least one of these must be true!)
4180 * @param string $rootdir ?
4181 * @param string $excludefile If defined then the specified file/directory is ignored
4182 * @param bool $descend ?
4183 * @param bool $getdirs If true then (sub)directories are included in the output
4184 * @param bool $getfiles If true then files are included in the output
4185 * @return array An array with all the filenames in
4186 * all subdirectories, relative to the given rootdir
4187 * @todo Finish documenting this function. Add examples of $excludefile usage.
4189 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
4193 if (!$getdirs and !$getfiles) { // Nothing to show
4197 if (!is_dir($rootdir)) { // Must be a directory
4201 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
4205 if (!is_array($excludefiles)) {
4206 $excludefiles = array($excludefiles);
4209 while (false !== ($file = readdir($dir))) {
4210 $firstchar = substr($file, 0, 1);
4211 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
4214 $fullfile = $rootdir .'/'. $file;
4215 if (filetype($fullfile) == 'dir') {
4220 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
4221 foreach ($subdirs as $subdir) {
4222 $dirs[] = $file .'/'. $subdir;
4225 } else if ($getfiles) {
4238 * Adds up all the files in a directory and works out the size.
4240 * @param string $rootdir ?
4241 * @param string $excludefile ?
4243 * @todo Finish documenting this function
4245 function get_directory_size($rootdir, $excludefile='') {
4249 // do it this way if we can, it's much faster
4250 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
4251 $command = trim($CFG->pathtodu
).' -sk --apparent-size '.escapeshellarg($rootdir);
4254 exec($command,$output,$return);
4255 if (is_array($output)) {
4256 return get_real_size(intval($output[0]).'k'); // we told it to return k.
4260 if (!is_dir($rootdir)) { // Must be a directory
4264 if (!$dir = @opendir
($rootdir)) { // Can't open it for some reason
4270 while (false !== ($file = readdir($dir))) {
4271 $firstchar = substr($file, 0, 1);
4272 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
4275 $fullfile = $rootdir .'/'. $file;
4276 if (filetype($fullfile) == 'dir') {
4277 $size +
= get_directory_size($fullfile, $excludefile);
4279 $size +
= filesize($fullfile);
4288 * Converts bytes into display form
4290 * @param string $size ?
4292 * @staticvar string $gb Localized string for size in gigabytes
4293 * @staticvar string $mb Localized string for size in megabytes
4294 * @staticvar string $kb Localized string for size in kilobytes
4295 * @staticvar string $b Localized string for size in bytes
4296 * @todo Finish documenting this function. Verify return type.
4298 function display_size($size) {
4300 static $gb, $mb, $kb, $b;
4303 $gb = get_string('sizegb');
4304 $mb = get_string('sizemb');
4305 $kb = get_string('sizekb');
4306 $b = get_string('sizeb');
4309 if ($size >= 1073741824) {
4310 $size = round($size / 1073741824 * 10) / 10 . $gb;
4311 } else if ($size >= 1048576) {
4312 $size = round($size / 1048576 * 10) / 10 . $mb;
4313 } else if ($size >= 1024) {
4314 $size = round($size / 1024 * 10) / 10 . $kb;
4316 $size = $size .' '. $b;
4322 * Cleans a given filename by removing suspicious or troublesome characters
4323 * Only these are allowed: alphanumeric _ - .
4324 * Unicode characters can be enabled by setting $CFG->unicodecleanfilename = true in config.php
4326 * WARNING: unicode characters may not be compatible with zip compression in backup/restore,
4327 * because native zip binaries do weird character conversions. Use PHP zipping instead.
4329 * @param string $string file name
4330 * @return string cleaned file name
4332 function clean_filename($string) {
4334 if (empty($CFG->unicodecleanfilename
)) {
4335 $textlib = textlib_get_instance();
4336 $string = $textlib->specialtoascii($string);
4337 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
4339 //clean only ascii range
4340 $string = preg_replace("/[\\000-\\x2c\\x2f\\x3a-\\x40\\x5b-\\x5e\\x60\\x7b-\\177]/s", '_', $string);
4342 $string = preg_replace("/_+/", '_', $string);
4343 $string = preg_replace("/\.\.+/", '.', $string);
4348 /// STRING TRANSLATION ////////////////////////////////////////
4351 * Returns the code for the current language
4358 function current_language() {
4359 global $CFG, $USER, $SESSION, $COURSE;
4361 if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) { // Course language can override all other settings for this page
4362 $return = $COURSE->lang
;
4364 } else if (!empty($SESSION->lang
)) { // Session language can override other settings
4365 $return = $SESSION->lang
;
4367 } else if (!empty($USER->lang
)) {
4368 $return = $USER->lang
;
4371 $return = $CFG->lang
;
4374 if ($return == 'en') {
4375 $return = 'en_utf8';
4382 * Prints out a translated string.
4384 * Prints out a translated string using the return value from the {@link get_string()} function.
4386 * Example usage of this function when the string is in the moodle.php file:<br/>
4389 * print_string('wordforstudent');
4393 * Example usage of this function when the string is not in the moodle.php file:<br/>
4396 * print_string('typecourse', 'calendar');
4400 * @param string $identifier The key identifier for the localized string
4401 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4402 * @param mixed $a An object, string or number that can be used
4403 * within translation strings
4405 function print_string($identifier, $module='', $a=NULL) {
4406 echo get_string($identifier, $module, $a);
4410 * fix up the optional data in get_string()/print_string() etc
4411 * ensure possible sprintf() format characters are escaped correctly
4412 * needs to handle arbitrary strings and objects
4413 * @param mixed $a An object, string or number that can be used
4414 * @return mixed the supplied parameter 'cleaned'
4416 function clean_getstring_data( $a ) {
4417 if (is_string($a)) {
4418 return str_replace( '%','%%',$a );
4420 elseif (is_object($a)) {
4421 $a_vars = get_object_vars( $a );
4422 $new_a_vars = array();
4423 foreach ($a_vars as $fname => $a_var) {
4424 $new_a_vars[$fname] = clean_getstring_data( $a_var );
4426 return (object)$new_a_vars;
4434 * @return array places to look for lang strings based on the prefix to the
4435 * module name. For example qtype_ in question/type. Used by get_string and
4438 function places_to_search_for_lang_strings() {
4442 '__exceptions' => array('moodle', 'langconfig'),
4443 'assignment_' => array('mod/assignment/type'),
4444 'auth_' => array('auth'),
4445 'block_' => array('blocks'),
4446 'datafield_' => array('mod/data/field'),
4447 'datapreset_' => array('mod/data/preset'),
4448 'enrol_' => array('enrol'),
4449 'format_' => array('course/format'),
4450 'qtype_' => array('question/type'),
4451 'report_' => array($CFG->admin
.'/report', 'course/report', 'mod/quiz/report'),
4452 'resource_' => array('mod/resource/type'),
4453 'gradereport_' => array('grade/report'),
4454 'gradeimport_' => array('grade/import'),
4455 'gradeexport_' => array('grade/export'),
4461 * Returns a localized string.
4463 * Returns the translated string specified by $identifier as
4464 * for $module. Uses the same format files as STphp.
4465 * $a is an object, string or number that can be used
4466 * within translation strings
4468 * eg "hello \$a->firstname \$a->lastname"
4471 * If you would like to directly echo the localized string use
4472 * the function {@link print_string()}
4474 * Example usage of this function involves finding the string you would
4475 * like a local equivalent of and using its identifier and module information
4476 * to retrive it.<br/>
4477 * If you open moodle/lang/en/moodle.php and look near line 1031
4478 * you will find a string to prompt a user for their word for student
4480 * $string['wordforstudent'] = 'Your word for Student';
4482 * So if you want to display the string 'Your word for student'
4483 * in any language that supports it on your site
4484 * you just need to use the identifier 'wordforstudent'
4486 * $mystring = '<strong>'. get_string('wordforstudent') .'</strong>';
4489 * If the string you want is in another file you'd take a slightly
4490 * different approach. Looking in moodle/lang/en/calendar.php you find
4493 * $string['typecourse'] = 'Course event';
4495 * If you want to display the string "Course event" in any language
4496 * supported you would use the identifier 'typecourse' and the module 'calendar'
4497 * (because it is in the file calendar.php):
4499 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
4502 * As a last resort, should the identifier fail to map to a string
4503 * the returned string will be [[ $identifier ]]
4506 * @param string $identifier The key identifier for the localized string
4507 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4508 * @param mixed $a An object, string or number that can be used
4509 * within translation strings
4510 * @param array $extralocations An array of strings with other locations to look for string files
4511 * @return string The localized string.
4513 function get_string($identifier, $module='', $a=NULL, $extralocations=NULL) {
4517 /// originally these special strings were stored in moodle.php now we are only in langconfig.php
4518 $langconfigstrs = array('alphabet', 'backupnameformat', 'decsep', 'firstdayofweek', 'listsep', 'locale',
4519 'localewin', 'localewincharset', 'oldcharset',
4520 'parentlanguage', 'strftimedate', 'strftimedateshort', 'strftimedatetime',
4521 'strftimedaydate', 'strftimedaydatetime', 'strftimedayshort', 'strftimedaytime',
4522 'strftimemonthyear', 'strftimerecent', 'strftimerecentfull', 'strftimetime',
4523 'thischarset', 'thisdirection', 'thislanguage');
4525 $filetocheck = 'langconfig.php';
4526 $defaultlang = 'en_utf8';
4527 if (in_array($identifier, $langconfigstrs)) {
4528 $module = 'langconfig'; //This strings are under langconfig.php for 1.6 lang packs
4531 $lang = current_language();
4533 if ($module == '') {
4537 // if $a happens to have % in it, double it so sprintf() doesn't break
4539 $a = clean_getstring_data( $a );
4542 /// Define the two or three major locations of language strings for this module
4543 $locations = array();
4545 if (!empty($extralocations)) { // Calling code has a good idea where to look
4546 if (is_array($extralocations)) {
4547 $locations +
= $extralocations;
4548 } else if (is_string($extralocations)) {
4549 $locations[] = $extralocations;
4551 debugging('Bad lang path provided');
4555 if (isset($CFG->running_installer
)) {
4556 $module = 'installer';
4557 $filetocheck = 'installer.php';
4558 $locations[] = $CFG->dirroot
.'/install/lang/';
4559 $locations[] = $CFG->dataroot
.'/lang/';
4560 $locations[] = $CFG->dirroot
.'/lang/';
4561 $defaultlang = 'en_utf8';
4563 $locations[] = $CFG->dataroot
.'/lang/';
4564 $locations[] = $CFG->dirroot
.'/lang/';
4567 /// Add extra places to look for strings for particular plugin types.
4568 $rules = places_to_search_for_lang_strings();
4569 $exceptions = $rules['__exceptions'];
4570 unset($rules['__exceptions']);
4572 if (!in_array($module, $exceptions)) {
4573 $dividerpos = strpos($module, '_');
4574 if ($dividerpos === false) {
4578 $type = substr($module, 0, $dividerpos +
1);
4579 $plugin = substr($module, $dividerpos +
1);
4581 if (!empty($rules[$type])) {
4582 foreach ($rules[$type] as $location) {
4583 $locations[] = $CFG->dirroot
. "/$location/$plugin/lang/";
4588 /// First check all the normal locations for the string in the current language
4590 foreach ($locations as $location) {
4591 $locallangfile = $location.$lang.'_local'.'/'.$module.'.php'; //first, see if there's a local file
4592 if (file_exists($locallangfile)) {
4593 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4595 return $resultstring;
4598 //if local directory not found, or particular string does not exist in local direcotry
4599 $langfile = $location.$lang.'/'.$module.'.php';
4600 if (file_exists($langfile)) {
4601 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4603 return $resultstring;
4608 /// If the preferred language was English (utf8) we can abort now
4609 /// saving some checks beacuse it's the only "root" lang
4610 if ($lang == 'en_utf8') {
4611 return '[['. $identifier .']]';
4614 /// Is a parent language defined? If so, try to find this string in a parent language file
4616 foreach ($locations as $location) {
4617 $langfile = $location.$lang.'/'.$filetocheck;
4618 if (file_exists($langfile)) {
4619 if ($result = get_string_from_file('parentlanguage', $langfile, "\$parentlang")) {
4621 if (!empty($parentlang)) { // found it!
4623 //first, see if there's a local file for parent
4624 $locallangfile = $location.$parentlang.'_local'.'/'.$module.'.php';
4625 if (file_exists($locallangfile)) {
4626 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4628 return $resultstring;
4632 //if local directory not found, or particular string does not exist in local direcotry
4633 $langfile = $location.$parentlang.'/'.$module.'.php';
4634 if (file_exists($langfile)) {
4635 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4637 return $resultstring;
4645 /// Our only remaining option is to try English
4647 foreach ($locations as $location) {
4648 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4649 if (file_exists($locallangfile)) {
4650 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4652 return $resultstring;
4656 //if local_en not found, or string not found in local_en
4657 $langfile = $location.$defaultlang.'/'.$module.'.php';
4659 if (file_exists($langfile)) {
4660 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4662 return $resultstring;
4667 /// And, because under 1.6 en is defined as en_utf8 child, me must try
4668 /// if it hasn't been queried before.
4669 if ($defaultlang == 'en') {
4670 $defaultlang = 'en_utf8';
4671 foreach ($locations as $location) {
4672 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4673 if (file_exists($locallangfile)) {
4674 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4676 return $resultstring;
4680 //if local_en not found, or string not found in local_en
4681 $langfile = $location.$defaultlang.'/'.$module.'.php';
4683 if (file_exists($langfile)) {
4684 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4686 return $resultstring;
4692 return '[['.$identifier.']]'; // Last resort
4696 * This function is only used from {@link get_string()}.
4698 * @internal Only used from get_string, not meant to be public API
4699 * @param string $identifier ?
4700 * @param string $langfile ?
4701 * @param string $destination ?
4702 * @return string|false ?
4703 * @staticvar array $strings Localized strings
4705 * @todo Finish documenting this function.
4707 function get_string_from_file($identifier, $langfile, $destination) {
4709 static $strings; // Keep the strings cached in memory.
4711 if (empty($strings[$langfile])) {
4713 include ($langfile);
4714 $strings[$langfile] = $string;
4716 $string = &$strings[$langfile];
4719 if (!isset ($string[$identifier])) {
4723 return $destination .'= sprintf("'. $string[$identifier] .'");';
4727 * Converts an array of strings to their localized value.
4729 * @param array $array An array of strings
4730 * @param string $module The language module that these strings can be found in.
4733 function get_strings($array, $module='') {
4736 foreach ($array as $item) {
4737 $string->$item = get_string($item, $module);
4743 * Returns a list of language codes and their full names
4744 * hides the _local files from everyone.
4745 * @param bool refreshcache force refreshing of lang cache
4746 * @param bool returnall ignore langlist, return all languages available
4747 * @return array An associative array with contents in the form of LanguageCode => LanguageName
4749 function get_list_of_languages($refreshcache=false, $returnall=false) {
4753 $languages = array();
4755 $filetocheck = 'langconfig.php';
4757 if (!$refreshcache && !$returnall && !empty($CFG->langcache
) && file_exists($CFG->dataroot
.'/cache/languages')) {
4758 /// read available langs from cache
4760 $lines = file($CFG->dataroot
.'/cache/languages');
4761 foreach ($lines as $line) {
4762 $line = trim($line);
4763 if (preg_match('/^(\w+)\s+(.+)/', $line, $matches)) {
4764 $languages[$matches[1]] = $matches[2];
4767 unset($lines); unset($line); unset($matches);
4771 if (!$returnall && !empty($CFG->langlist
)) {
4772 /// return only languages allowed in langlist admin setting
4774 $langlist = explode(',', $CFG->langlist
);
4775 // fix short lang names first - non existing langs are skipped anyway...
4776 foreach ($langlist as $lang) {
4777 if (strpos($lang, '_utf8') === false) {
4778 $langlist[] = $lang.'_utf8';
4781 // find existing langs from langlist
4782 foreach ($langlist as $lang) {
4783 $lang = trim($lang); //Just trim spaces to be a bit more permissive
4784 if (strstr($lang, '_local')!==false) {
4787 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4788 $shortlang = substr($lang, 0, -5);
4792 /// Search under dirroot/lang
4793 if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4794 include($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck);
4795 if (!empty($string['thislanguage'])) {
4796 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4800 /// And moodledata/lang
4801 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4802 include($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck);
4803 if (!empty($string['thislanguage'])) {
4804 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4811 /// return all languages available in system
4812 /// Fetch langs from moodle/lang directory
4813 $langdirs = get_list_of_plugins('lang');
4814 /// Fetch langs from moodledata/lang directory
4815 $langdirs2 = get_list_of_plugins('lang', '', $CFG->dataroot
);
4816 /// Merge both lists of langs
4817 $langdirs = array_merge($langdirs, $langdirs2);
4820 /// Get some info from each lang (first from moodledata, then from moodle)
4821 foreach ($langdirs as $lang) {
4822 if (strstr($lang, '_local')!==false) {
4825 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4826 $shortlang = substr($lang, 0, -5);
4830 /// Search under moodledata/lang
4831 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4832 include($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck);
4833 if (!empty($string['thislanguage'])) {
4834 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4838 /// And dirroot/lang
4839 if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4840 include($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck);
4841 if (!empty($string['thislanguage'])) {
4842 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4849 if ($refreshcache && !empty($CFG->langcache
)) {
4851 // we have a list of all langs only, just delete old cache
4852 @unlink
($CFG->dataroot
.'/cache/languages');
4855 // store the list of allowed languages
4856 if ($file = fopen($CFG->dataroot
.'/cache/languages', 'w')) {
4857 foreach ($languages as $key => $value) {
4858 fwrite($file, "$key $value\n");
4869 * Returns a list of charset codes. It's hardcoded, so they should be added manually
4870 * (cheking that such charset is supported by the texlib library!)
4872 * @return array And associative array with contents in the form of charset => charset
4874 function get_list_of_charsets() {
4877 'EUC-JP' => 'EUC-JP',
4878 'ISO-2022-JP'=> 'ISO-2022-JP',
4879 'ISO-8859-1' => 'ISO-8859-1',
4880 'SHIFT-JIS' => 'SHIFT-JIS',
4881 'GB2312' => 'GB2312',
4882 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
4883 'UTF-8' => 'UTF-8');
4891 * Returns a list of country names in the current language
4897 function get_list_of_countries() {
4900 $lang = current_language();
4902 if (!file_exists($CFG->dirroot
.'/lang/'. $lang .'/countries.php') &&
4903 !file_exists($CFG->dataroot
.'/lang/'. $lang .'/countries.php')) {
4904 if ($parentlang = get_string('parentlanguage')) {
4905 if (file_exists($CFG->dirroot
.'/lang/'. $parentlang .'/countries.php') ||
4906 file_exists($CFG->dataroot
.'/lang/'. $parentlang .'/countries.php')) {
4907 $lang = $parentlang;
4909 $lang = 'en_utf8'; // countries.php must exist in this pack
4912 $lang = 'en_utf8'; // countries.php must exist in this pack
4916 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/countries.php')) {
4917 include($CFG->dataroot
.'/lang/'. $lang .'/countries.php');
4918 } else if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/countries.php')) {
4919 include($CFG->dirroot
.'/lang/'. $lang .'/countries.php');
4922 if (!empty($string)) {
4930 * Returns a list of valid and compatible themes
4935 function get_list_of_themes() {
4941 if (!empty($CFG->themelist
)) { // use admin's list of themes
4942 $themelist = explode(',', $CFG->themelist
);
4944 $themelist = get_list_of_plugins("theme");
4947 foreach ($themelist as $key => $theme) {
4948 if (!file_exists("$CFG->themedir/$theme/config.php")) { // bad folder
4951 $THEME = new object(); // Note this is not the global one!! :-)
4952 include("$CFG->themedir/$theme/config.php");
4953 if (!isset($THEME->sheets
)) { // Not a valid 1.5 theme
4956 $themes[$theme] = $theme;
4965 * Returns a list of picture names in the current or specified language
4970 function get_list_of_pixnames($lang = '') {
4974 $lang = current_language();
4979 $path = $CFG->dirroot
.'/lang/en_utf8/pix.php'; // always exists
4981 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'_local/pix.php')) {
4982 $path = $CFG->dataroot
.'/lang/'. $lang .'_local/pix.php';
4984 } else if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/pix.php')) {
4985 $path = $CFG->dirroot
.'/lang/'. $lang .'/pix.php';
4987 } else if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/pix.php')) {
4988 $path = $CFG->dataroot
.'/lang/'. $lang .'/pix.php';
4990 } else if ($parentlang = get_string('parentlanguage') and $parentlang != '[[parentlanguage]]') {
4991 return get_list_of_pixnames($parentlang); //return pixnames from parent language instead
5000 * Returns a list of timezones in the current language
5005 function get_list_of_timezones() {
5010 if (!empty($timezones)) { // This function has been called recently
5014 $timezones = array();
5016 if ($rawtimezones = get_records_sql('SELECT MAX(id), name FROM '.$CFG->prefix
.'timezone GROUP BY name')) {
5017 foreach($rawtimezones as $timezone) {
5018 if (!empty($timezone->name
)) {
5019 $timezones[$timezone->name
] = get_string(strtolower($timezone->name
), 'timezones');
5020 if (substr($timezones[$timezone->name
], 0, 1) == '[') { // No translation found
5021 $timezones[$timezone->name
] = $timezone->name
;
5029 for ($i = -13; $i <= 13; $i +
= .5) {
5032 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
5033 } else if ($i > 0) {
5034 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
5036 $timezones[sprintf("%.1f", $i)] = $tzstring;
5044 * Returns a list of currencies in the current language
5050 function get_list_of_currencies() {
5053 $lang = current_language();
5055 if (!file_exists($CFG->dataroot
.'/lang/'. $lang .'/currencies.php')) {
5056 if ($parentlang = get_string('parentlanguage')) {
5057 if (file_exists($CFG->dataroot
.'/lang/'. $parentlang .'/currencies.php')) {
5058 $lang = $parentlang;
5060 $lang = 'en_utf8'; // currencies.php must exist in this pack
5063 $lang = 'en_utf8'; // currencies.php must exist in this pack
5067 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/currencies.php')) {
5068 include_once($CFG->dataroot
.'/lang/'. $lang .'/currencies.php');
5069 } else { //if en_utf8 is not installed in dataroot
5070 include_once($CFG->dirroot
.'/lang/'. $lang .'/currencies.php');
5073 if (!empty($string)) {
5083 * Can include a given document file (depends on second
5084 * parameter) or just return info about it.
5087 * @param string $file ?
5088 * @param bool $include ?
5090 * @todo Finish documenting this function
5092 function document_file($file, $include=true) {
5095 $file = clean_filename($file);
5101 $langs = array(current_language(), get_string('parentlanguage'), 'en');
5103 foreach ($langs as $lang) {
5104 $info = new object();
5105 $info->filepath
= $CFG->dirroot
.'/lang/'. $lang .'/docs/'. $file;
5106 $info->urlpath
= $CFG->wwwroot
.'/lang/'. $lang .'/docs/'. $file;
5108 if (file_exists($info->filepath
)) {
5110 include($info->filepath
);
5119 /// ENCRYPTION ////////////////////////////////////////////////
5124 * @param string $data ?
5126 * @todo Finish documenting this function
5128 function rc4encrypt($data) {
5129 $password = 'nfgjeingjk';
5130 return endecrypt($password, $data, '');
5136 * @param string $data ?
5138 * @todo Finish documenting this function
5140 function rc4decrypt($data) {
5141 $password = 'nfgjeingjk';
5142 return endecrypt($password, $data, 'de');
5146 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
5148 * @param string $pwd ?
5149 * @param string $data ?
5150 * @param string $case ?
5152 * @todo Finish documenting this function
5154 function endecrypt ($pwd, $data, $case) {
5156 if ($case == 'de') {
5157 $data = urldecode($data);
5165 $pwd_length = strlen($pwd);
5167 for ($i = 0; $i <= 255; $i++
) {
5168 $key[$i] = ord(substr($pwd, ($i %
$pwd_length), 1));
5174 for ($i = 0; $i <= 255; $i++
) {
5175 $x = ($x +
$box[$i] +
$key[$i]) %
256;
5176 $temp_swap = $box[$i];
5177 $box[$i] = $box[$x];
5178 $box[$x] = $temp_swap;
5190 for ($i = 0; $i < strlen($data); $i++
) {
5191 $a = ($a +
1) %
256;
5192 $j = ($j +
$box[$a]) %
256;
5194 $box[$a] = $box[$j];
5196 $k = $box[(($box[$a] +
$box[$j]) %
256)];
5197 $cipherby = ord(substr($data, $i, 1)) ^
$k;
5198 $cipher .= chr($cipherby);
5201 if ($case == 'de') {
5202 $cipher = urldecode(urlencode($cipher));
5204 $cipher = urlencode($cipher);
5211 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
5215 * Call this function to add an event to the calendar table
5216 * and to call any calendar plugins
5219 * @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:
5221 * <li><b>$event->name</b> - Name for the event
5222 * <li><b>$event->description</b> - Description of the event (defaults to '')
5223 * <li><b>$event->format</b> - Format for the description (using formatting types defined at the top of weblib.php)
5224 * <li><b>$event->courseid</b> - The id of the course this event belongs to (0 = all courses)
5225 * <li><b>$event->groupid</b> - The id of the group this event belongs to (0 = no group)
5226 * <li><b>$event->userid</b> - The id of the user this event belongs to (0 = no user)
5227 * <li><b>$event->modulename</b> - Name of the module that creates this event
5228 * <li><b>$event->instance</b> - Instance of the module that owns this event
5229 * <li><b>$event->eventtype</b> - The type info together with the module info could
5230 * be used by calendar plugins to decide how to display event
5231 * <li><b>$event->timestart</b>- Timestamp for start of event
5232 * <li><b>$event->timeduration</b> - Duration (defaults to zero)
5233 * <li><b>$event->visible</b> - 0 if the event should be hidden (e.g. because the activity that created it is hidden)
5235 * @return int The id number of the resulting record
5237 function add_event($event) {
5241 $event->timemodified
= time();
5243 if (!$event->id
= insert_record('event', $event)) {
5247 if (!empty($CFG->calendar
)) { // call the add_event function of the selected calendar
5248 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5249 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5250 $calendar_add_event = $CFG->calendar
.'_add_event';
5251 if (function_exists($calendar_add_event)) {
5252 $calendar_add_event($event);
5261 * Call this function to update an event in the calendar table
5262 * the event will be identified by the id field of the $event object.
5265 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5268 function update_event($event) {
5272 $event->timemodified
= time();
5274 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
5275 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5276 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5277 $calendar_update_event = $CFG->calendar
.'_update_event';
5278 if (function_exists($calendar_update_event)) {
5279 $calendar_update_event($event);
5283 return update_record('event', $event);
5287 * Call this function to delete the event with id $id from calendar table.
5290 * @param int $id The id of an event from the 'calendar' table.
5291 * @return array An associative array with the results from the SQL call.
5292 * @todo Verify return type
5294 function delete_event($id) {
5298 if (!empty($CFG->calendar
)) { // call the delete_event function of the selected calendar
5299 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5300 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5301 $calendar_delete_event = $CFG->calendar
.'_delete_event';
5302 if (function_exists($calendar_delete_event)) {
5303 $calendar_delete_event($id);
5307 return delete_records('event', 'id', $id);
5311 * Call this function to hide an event in the calendar table
5312 * the event will be identified by the id field of the $event object.
5315 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5316 * @return array An associative array with the results from the SQL call.
5317 * @todo Verify return type
5319 function hide_event($event) {
5322 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
5323 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5324 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5325 $calendar_hide_event = $CFG->calendar
.'_hide_event';
5326 if (function_exists($calendar_hide_event)) {
5327 $calendar_hide_event($event);
5331 return set_field('event', 'visible', 0, 'id', $event->id
);
5335 * Call this function to unhide an event in the calendar table
5336 * the event will be identified by the id field of the $event object.
5339 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5340 * @return array An associative array with the results from the SQL call.
5341 * @todo Verify return type
5343 function show_event($event) {
5346 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
5347 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5348 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5349 $calendar_show_event = $CFG->calendar
.'_show_event';
5350 if (function_exists($calendar_show_event)) {
5351 $calendar_show_event($event);
5355 return set_field('event', 'visible', 1, 'id', $event->id
);
5359 /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
5362 * Lists plugin directories within some directory
5365 * @param string $plugin dir under we'll look for plugins (defaults to 'mod')
5366 * @param string $exclude dir name to exclude from the list (defaults to none)
5367 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
5368 * @return array of plugins found under the requested parameters
5370 function get_list_of_plugins($plugin='mod', $exclude='', $basedir='') {
5376 if (empty($basedir)) {
5378 # This switch allows us to use the appropiate theme directory - and potentialy alternatives for other plugins
5381 $basedir = $CFG->themedir
;
5385 $basedir = $CFG->dirroot
.'/'. $plugin;
5389 $basedir = $basedir .'/'. $plugin;
5392 if (file_exists($basedir) && filetype($basedir) == 'dir') {
5393 $dirhandle = opendir($basedir);
5394 while (false !== ($dir = readdir($dirhandle))) {
5395 $firstchar = substr($dir, 0, 1);
5396 if ($firstchar == '.' or $dir == 'CVS' or $dir == '_vti_cnf' or $dir == $exclude) {
5399 if (filetype($basedir .'/'. $dir) != 'dir') {
5404 closedir($dirhandle);
5413 * Returns true if the current version of PHP is greater that the specified one.
5415 * @param string $version The version of php being tested.
5418 function check_php_version($version='4.1.0') {
5419 return (version_compare(phpversion(), $version) >= 0);
5424 * Checks to see if is a browser matches the specified
5425 * brand and is equal or better version.
5428 * @param string $brand The browser identifier being tested
5429 * @param int $version The version of the browser
5430 * @return bool true if the given version is below that of the detected browser
5432 function check_browser_version($brand='MSIE', $version=5.5) {
5433 if (empty($_SERVER['HTTP_USER_AGENT'])) {
5437 $agent = $_SERVER['HTTP_USER_AGENT'];
5441 case 'Camino': /// Mozilla Firefox browsers
5443 if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
5444 if (version_compare($match[1], $version) >= 0) {
5451 case 'Firefox': /// Mozilla Firefox browsers
5453 if (preg_match("/Firefox\/([0-9\.]+)/i", $agent, $match)) {
5454 if (version_compare($match[1], $version) >= 0) {
5461 case 'Gecko': /// Gecko based browsers
5463 if (substr_count($agent, 'Camino')) {
5464 // MacOS X Camino support
5465 $version = 20041110;
5468 // the proper string - Gecko/CCYYMMDD Vendor/Version
5469 // Faster version and work-a-round No IDN problem.
5470 if (preg_match("/Gecko\/([0-9]+)/i", $agent, $match)) {
5471 if ($match[1] > $version) {
5478 case 'MSIE': /// Internet Explorer
5480 if (strpos($agent, 'Opera')) { // Reject Opera
5483 $string = explode(';', $agent);
5484 if (!isset($string[1])) {
5487 $string = explode(' ', trim($string[1]));
5488 if (!isset($string[0]) and !isset($string[1])) {
5491 if ($string[0] == $brand and (float)$string[1] >= $version ) {
5496 case 'Opera': /// Opera
5498 if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
5499 if (version_compare($match[1], $version) >= 0) {
5505 case 'Safari': /// Safari
5506 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SimbianOS
5507 if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
5509 } elseif (strpos($agent, 'Shiira')) { // Reject Shiira
5511 } elseif (strpos($agent, 'SimbianOS')) { // Reject SimbianOS
5515 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
5516 if (version_compare($match[1], $version) >= 0) {
5529 * This function makes the return value of ini_get consistent if you are
5530 * setting server directives through the .htaccess file in apache.
5531 * Current behavior for value set from php.ini On = 1, Off = [blank]
5532 * Current behavior for value set from .htaccess On = On, Off = Off
5533 * Contributed by jdell @ unr.edu
5535 * @param string $ini_get_arg ?
5537 * @todo Finish documenting this function
5539 function ini_get_bool($ini_get_arg) {
5540 $temp = ini_get($ini_get_arg);
5542 if ($temp == '1' or strtolower($temp) == 'on') {
5549 * Compatibility stub to provide backward compatibility
5551 * Determines if the HTML editor is enabled.
5552 * @deprecated Use {@link can_use_html_editor()} instead.
5554 function can_use_richtext_editor() {
5555 return can_use_html_editor();
5559 * Determines if the HTML editor is enabled.
5561 * This depends on site and user
5562 * settings, as well as the current browser being used.
5564 * @return string|false Returns false if editor is not being used, otherwise
5565 * returns 'MSIE' or 'Gecko'.
5567 function can_use_html_editor() {
5570 if (!empty($USER->htmleditor
) and !empty($CFG->htmleditor
)) {
5571 if (check_browser_version('MSIE', 5.5)) {
5573 } else if (check_browser_version('Gecko', 20030516)) {
5581 * Hack to find out the GD version by parsing phpinfo output
5583 * @return int GD version (1, 2, or 0)
5585 function check_gd_version() {
5588 if (function_exists('gd_info')){
5589 $gd_info = gd_info();
5590 if (substr_count($gd_info['GD Version'], '2.')) {
5592 } else if (substr_count($gd_info['GD Version'], '1.')) {
5599 $phpinfo = ob_get_contents();
5602 $phpinfo = explode("\n", $phpinfo);
5605 foreach ($phpinfo as $text) {
5606 $parts = explode('</td>', $text);
5607 foreach ($parts as $key => $val) {
5608 $parts[$key] = trim(strip_tags($val));
5610 if ($parts[0] == 'GD Version') {
5611 if (substr_count($parts[1], '2.0')) {
5614 $gdversion = intval($parts[1]);
5619 return $gdversion; // 1, 2 or 0
5623 * Determine if moodle installation requires update
5625 * Checks version numbers of main code and all modules to see
5626 * if there are any mismatches
5631 function moodle_needs_upgrading() {
5635 include_once($CFG->dirroot
.'/version.php'); # defines $version and upgrades
5636 if ($CFG->version
) {
5637 if ($version > $CFG->version
) {
5640 if ($mods = get_list_of_plugins('mod')) {
5641 foreach ($mods as $mod) {
5642 $fullmod = $CFG->dirroot
.'/mod/'. $mod;
5643 $module = new object();
5644 if (!is_readable($fullmod .'/version.php')) {
5645 notify('Module "'. $mod .'" is not readable - check permissions');
5648 include_once($fullmod .'/version.php'); # defines $module with version etc
5649 if ($currmodule = get_record('modules', 'name', $mod)) {
5650 if ($module->version
> $currmodule->version
) {
5663 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
5666 * Notify admin users or admin user of any failed logins (since last notification).
5672 function notify_login_failures() {
5675 switch ($CFG->notifyloginfailures
) {
5677 $recip = array(get_admin());
5680 $recip = get_admins();
5684 if (empty($CFG->lastnotifyfailure
)) {
5685 $CFG->lastnotifyfailure
=0;
5688 // we need to deal with the threshold stuff first.
5689 if (empty($CFG->notifyloginthreshold
)) {
5690 $CFG->notifyloginthreshold
= 10; // default to something sensible.
5693 $notifyipsrs = $db->Execute('SELECT ip FROM '. $CFG->prefix
.'log WHERE time > '. $CFG->lastnotifyfailure
.'
5694 AND module=\'login\' AND action=\'error\' GROUP BY ip HAVING count(*) > '. $CFG->notifyloginthreshold
);
5696 $notifyusersrs = $db->Execute('SELECT info FROM '. $CFG->prefix
.'log WHERE time > '. $CFG->lastnotifyfailure
.'
5697 AND module=\'login\' AND action=\'error\' GROUP BY info HAVING count(*) > '. $CFG->notifyloginthreshold
);
5701 while ($row = rs_fetch_next_record($notifyipsrs)) {
5702 $ipstr .= "'". $row->ip
."',";
5704 rs_close($notifyipsrs);
5705 $ipstr = substr($ipstr,0,strlen($ipstr)-1);
5707 if ($notifyusersrs) {
5709 while ($row = rs_fetch_next_record($notifyusersrs)) {
5710 $userstr .= "'". $row->info
."',";
5712 rs_close($notifyusersrs);
5713 $userstr = substr($userstr,0,strlen($userstr)-1);
5716 if (strlen($userstr) > 0 ||
strlen($ipstr) > 0) {
5718 $logs = get_logs('time > '. $CFG->lastnotifyfailure
.' AND module=\'login\' AND action=\'error\' '
5719 .((strlen($ipstr) > 0 && strlen($userstr) > 0) ?
' AND ( ip IN ('. $ipstr .') OR info IN ('. $userstr .') ) '
5720 : ((strlen($ipstr) != 0) ?
' AND ip IN ('. $ipstr .') ' : ' AND info IN ('. $userstr .') ')), 'l.time DESC', '', '', $count);
5722 // 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
5723 if (is_array($recip) and count($recip) > 0 and ((time() - HOURSECS
) > $CFG->lastnotifyfailure
)
5724 and is_array($logs) and count($logs) > 0) {
5728 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname
));
5729 $message .= get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot
)
5730 .(($CFG->lastnotifyfailure
!= 0) ?
'('.userdate($CFG->lastnotifyfailure
).')' : '')."\n\n";
5731 foreach ($logs as $log) {
5732 $log->time
= userdate($log->time
);
5733 $message .= get_string('notifyloginfailuresmessage','',$log)."\n";
5735 $message .= "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot
)."\n\n";
5736 foreach ($recip as $admin) {
5737 mtrace('Emailing '. $admin->username
.' about '. count($logs) .' failed login attempts');
5738 email_to_user($admin,get_admin(),$subject,$message);
5740 $conf = new object();
5741 $conf->name
= 'lastnotifyfailure';
5742 $conf->value
= time();
5743 if ($current = get_record('config', 'name', 'lastnotifyfailure')) {
5744 $conf->id
= $current->id
;
5745 if (! update_record('config', $conf)) {
5746 mtrace('Could not update last notify time');
5749 } else if (! insert_record('config', $conf)) {
5750 mtrace('Could not set last notify time');
5760 * @param string $locale ?
5761 * @todo Finish documenting this function
5763 function moodle_setlocale($locale='') {
5767 static $currentlocale = ''; // last locale caching
5769 $oldlocale = $currentlocale;
5771 /// Fetch the correct locale based on ostype
5772 if($CFG->ostype
== 'WINDOWS') {
5773 $stringtofetch = 'localewin';
5775 $stringtofetch = 'locale';
5778 /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
5779 if (!empty($locale)) {
5780 $currentlocale = $locale;
5781 } else if (!empty($CFG->locale
)) { // override locale for all language packs
5782 $currentlocale = $CFG->locale
;
5784 $currentlocale = get_string($stringtofetch);
5787 /// do nothing if locale already set up
5788 if ($oldlocale == $currentlocale) {
5792 /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
5793 /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
5794 /// Some day, numeric, monetary and other categories should be set too, I think. :-/
5796 /// Get current values
5797 $monetary= setlocale (LC_MONETARY
, 0);
5798 $numeric = setlocale (LC_NUMERIC
, 0);
5799 $ctype = setlocale (LC_CTYPE
, 0);
5800 if ($CFG->ostype
!= 'WINDOWS') {
5801 $messages= setlocale (LC_MESSAGES
, 0);
5803 /// Set locale to all
5804 setlocale (LC_ALL
, $currentlocale);
5806 setlocale (LC_MONETARY
, $monetary);
5807 setlocale (LC_NUMERIC
, $numeric);
5808 if ($CFG->ostype
!= 'WINDOWS') {
5809 setlocale (LC_MESSAGES
, $messages);
5811 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
5812 setlocale (LC_CTYPE
, $ctype);
5817 * Converts string to lowercase using most compatible function available.
5819 * @param string $string The string to convert to all lowercase characters.
5820 * @param string $encoding The encoding on the string.
5822 * @todo Add examples of calling this function with/without encoding types
5823 * @deprecated Use textlib->strtolower($text) instead.
5825 function moodle_strtolower ($string, $encoding='') {
5827 //If not specified use utf8
5828 if (empty($encoding)) {
5829 $encoding = 'UTF-8';
5832 $textlib = textlib_get_instance();
5834 return $textlib->strtolower($string, $encoding);
5838 * Count words in a string.
5840 * Words are defined as things between whitespace.
5842 * @param string $string The text to be searched for words.
5843 * @return int The count of words in the specified string
5845 function count_words($string) {
5846 $string = strip_tags($string);
5847 return count(preg_split("/\w\b/", $string)) - 1;
5850 /** Count letters in a string.
5852 * Letters are defined as chars not in tags and different from whitespace.
5854 * @param string $string The text to be searched for letters.
5855 * @return int The count of letters in the specified text.
5857 function count_letters($string) {
5858 /// Loading the textlib singleton instance. We are going to need it.
5859 $textlib = textlib_get_instance();
5861 $string = strip_tags($string); // Tags are out now
5862 $string = ereg_replace('[[:space:]]*','',$string); //Whitespace are out now
5864 return $textlib->strlen($string);
5868 * Generate and return a random string of the specified length.
5870 * @param int $length The length of the string to be created.
5873 function random_string ($length=15) {
5874 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
5875 $pool .= 'abcdefghijklmnopqrstuvwxyz';
5876 $pool .= '0123456789';
5877 $poollen = strlen($pool);
5878 mt_srand ((double) microtime() * 1000000);
5880 for ($i = 0; $i < $length; $i++
) {
5881 $string .= substr($pool, (mt_rand()%
($poollen)), 1);
5887 * Given some text (which may contain HTML) and an ideal length,
5888 * this function truncates the text neatly on a word boundary if possible
5890 function shorten_text($text, $ideal=30) {
5897 $length = strlen($text);
5902 if ($length <= $ideal) {
5906 for ($i=0; $i<$length; $i++
) {
5919 if ($char == '.' or $char == ' ') {
5922 } else if (ord($char) >= 0xE0) { // Chinese/Japanese/Korean text
5923 $truncate = $i; // can be truncated at any UTF-8
5924 break 2; // character boundary.
5932 if ($count > $ideal) {
5942 $ellipse = ($truncate < $length) ?
'...' : '';
5944 return substr($text, 0, $truncate).$ellipse;
5949 * Given dates in seconds, how many weeks is the date from startdate
5950 * The first week is 1, the second 2 etc ...
5953 * @param ? $startdate ?
5954 * @param ? $thedate ?
5956 * @todo Finish documenting this function
5958 function getweek ($startdate, $thedate) {
5959 if ($thedate < $startdate) { // error
5963 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
5967 * returns a randomly generated password of length $maxlen. inspired by
5968 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3}
5970 * @param int $maxlength The maximum size of the password being generated.
5973 function generate_password($maxlen=10) {
5976 $fillers = '1234567890!$-+';
5977 $wordlist = file($CFG->wordlist
);
5979 srand((double) microtime() * 1000000);
5980 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
5981 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
5982 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
5984 return substr($word1 . $filler1 . $word2, 0, $maxlen);
5988 * Given a float, prints it nicely.
5989 * Do NOT use the result in any calculation later!
5991 * @param float $flaot The float to print
5992 * @param int $places The number of decimal places to print.
5993 * @return string locale float
5995 function format_float($float, $decimalpoints=1) {
5996 if (is_null($float)) {
5999 return number_format($float, $decimalpoints, get_string('decsep'), '');
6003 * Converts locale specific floating point/comma number back to standard PHP float value
6004 * Do NOT try to do any math operations before this conversion on any user submitted floats!
6006 * @param string $locale_float locale aware float representation
6008 function unformat_float($locale_float) {
6009 $locale_float = trim($locale_float);
6011 if ($locale_float == '') {
6015 $locale_float = str_replace(' ', '', $locale_float); // no spaces - those might be used as thousand separators
6017 return (float)str_replace(get_string('decsep'), '.', $locale_float);
6021 * Given a simple array, this shuffles it up just like shuffle()
6022 * Unlike PHP's shuffle() this function works on any machine.
6024 * @param array $array The array to be rearranged
6027 function swapshuffle($array) {
6029 srand ((double) microtime() * 10000000);
6030 $last = count($array) - 1;
6031 for ($i=0;$i<=$last;$i++
) {
6032 $from = rand(0,$last);
6034 $array[$i] = $array[$from];
6035 $array[$from] = $curr;
6041 * Like {@link swapshuffle()}, but works on associative arrays
6043 * @param array $array The associative array to be rearranged
6046 function swapshuffle_assoc($array) {
6049 $newkeys = swapshuffle(array_keys($array));
6050 foreach ($newkeys as $newkey) {
6051 $newarray[$newkey] = $array[$newkey];
6057 * Given an arbitrary array, and a number of draws,
6058 * this function returns an array with that amount
6059 * of items. The indexes are retained.
6061 * @param array $array ?
6064 * @todo Finish documenting this function
6066 function draw_rand_array($array, $draws) {
6067 srand ((double) microtime() * 10000000);
6071 $last = count($array);
6073 if ($draws > $last) {
6077 while ($draws > 0) {
6080 $keys = array_keys($array);
6081 $rand = rand(0, $last);
6083 $return[$keys[$rand]] = $array[$keys[$rand]];
6084 unset($array[$keys[$rand]]);
6095 * @param string $a ?
6096 * @param string $b ?
6098 * @todo Finish documenting this function
6100 function microtime_diff($a, $b) {
6101 list($a_dec, $a_sec) = explode(' ', $a);
6102 list($b_dec, $b_sec) = explode(' ', $b);
6103 return $b_sec - $a_sec +
$b_dec - $a_dec;
6107 * Given a list (eg a,b,c,d,e) this function returns
6108 * an array of 1->a, 2->b, 3->c etc
6110 * @param array $list ?
6111 * @param string $separator ?
6112 * @todo Finish documenting this function
6114 function make_menu_from_list($list, $separator=',') {
6116 $array = array_reverse(explode($separator, $list), true);
6117 foreach ($array as $key => $item) {
6118 $outarray[$key+
1] = trim($item);
6124 * Creates an array that represents all the current grades that
6125 * can be chosen using the given grading type. Negative numbers
6126 * are scales, zero is no grade, and positive numbers are maximum
6129 * @param int $gradingtype ?
6131 * @todo Finish documenting this function
6133 function make_grades_menu($gradingtype) {
6135 if ($gradingtype < 0) {
6136 if ($scale = get_record('scale', 'id', - $gradingtype)) {
6137 return make_menu_from_list($scale->scale
);
6139 } else if ($gradingtype > 0) {
6140 for ($i=$gradingtype; $i>=0; $i--) {
6141 $grades[$i] = $i .' / '. $gradingtype;
6149 * This function returns the nummber of activities
6150 * using scaleid in a courseid
6152 * @param int $courseid ?
6153 * @param int $scaleid ?
6155 * @todo Finish documenting this function
6157 function course_scale_used($courseid, $scaleid) {
6163 if (!empty($scaleid)) {
6164 if ($cms = get_course_mods($courseid)) {
6165 foreach ($cms as $cm) {
6166 //Check cm->name/lib.php exists
6167 if (file_exists($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php')) {
6168 include_once($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php');
6169 $function_name = $cm->modname
.'_scale_used';
6170 if (function_exists($function_name)) {
6171 if ($function_name($cm->instance
,$scaleid)) {
6179 // check if any course grade item makes use of the scale
6180 $return +
= count_records('grade_items', 'courseid', $courseid, 'scaleid', $scaleid);
6186 * This function returns the nummber of activities
6187 * using scaleid in the entire site
6189 * @param int $scaleid ?
6191 * @todo Finish documenting this function. Is return type correct?
6193 function site_scale_used($scaleid,&$courses) {
6199 if (!is_array($courses) ||
count($courses) == 0) {
6200 $courses = get_courses("all",false,"c.id,c.shortname");
6203 if (!empty($scaleid)) {
6204 if (is_array($courses) && count($courses) > 0) {
6205 foreach ($courses as $course) {
6206 $return +
= course_scale_used($course->id
,$scaleid);
6214 * make_unique_id_code
6216 * @param string $extra ?
6218 * @todo Finish documenting this function
6220 function make_unique_id_code($extra='') {
6222 $hostname = 'unknownhost';
6223 if (!empty($_SERVER['HTTP_HOST'])) {
6224 $hostname = $_SERVER['HTTP_HOST'];
6225 } else if (!empty($_ENV['HTTP_HOST'])) {
6226 $hostname = $_ENV['HTTP_HOST'];
6227 } else if (!empty($_SERVER['SERVER_NAME'])) {
6228 $hostname = $_SERVER['SERVER_NAME'];
6229 } else if (!empty($_ENV['SERVER_NAME'])) {
6230 $hostname = $_ENV['SERVER_NAME'];
6233 $date = gmdate("ymdHis");
6235 $random = random_string(6);
6238 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
6240 return $hostname .'+'. $date .'+'. $random;
6246 * Function to check the passed address is within the passed subnet
6248 * The parameter is a comma separated string of subnet definitions.
6249 * Subnet strings can be in one of three formats:
6250 * 1: xxx.xxx.xxx.xxx/xx
6252 * 3: xxx.xxx.xxx.xxx-xxx //a range of IP addresses in the last group.
6253 * Code for type 1 modified from user posted comments by mediator at
6254 * {@link http://au.php.net/manual/en/function.ip2long.php}
6256 * @param string $addr The address you are checking
6257 * @param string $subnetstr The string of subnet addresses
6260 function address_in_subnet($addr, $subnetstr) {
6262 $subnets = explode(',', $subnetstr);
6264 $addr = trim($addr);
6266 foreach ($subnets as $subnet) {
6267 $subnet = trim($subnet);
6268 if (strpos($subnet, '/') !== false) { /// type 1
6269 list($ip, $mask) = explode('/', $subnet);
6270 $mask = 0xffffffff << (32 - $mask);
6271 $found = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
6272 } else if (strpos($subnet, '-') !== false) {/// type 3
6273 $subnetparts = explode('.', $subnet);
6274 $addrparts = explode('.', $addr);
6275 $subnetrange = explode('-', array_pop($subnetparts));
6276 if (count($subnetrange) == 2) {
6277 $lastaddrpart = array_pop($addrparts);
6278 $found = ($subnetparts == $addrparts &&
6279 $subnetrange[0] <= $lastaddrpart && $lastaddrpart <= $subnetrange[1]);
6282 $found = (strpos($addr, $subnet) === 0);
6293 * This function sets the $HTTPSPAGEREQUIRED global
6294 * (used in some parts of moodle to change some links)
6295 * and calculate the proper wwwroot to be used
6297 * By using this function properly, we can ensure 100% https-ized pages
6298 * at our entire discretion (login, forgot_password, change_password)
6300 function httpsrequired() {
6302 global $CFG, $HTTPSPAGEREQUIRED;
6304 if (!empty($CFG->loginhttps
)) {
6305 $HTTPSPAGEREQUIRED = true;
6306 $CFG->httpswwwroot
= str_replace('http:', 'https:', $CFG->wwwroot
);
6307 $CFG->httpsthemewww
= str_replace('http:', 'https:', $CFG->themewww
);
6309 // change theme URLs to https
6313 $CFG->httpswwwroot
= $CFG->wwwroot
;
6314 $CFG->httpsthemewww
= $CFG->themewww
;
6319 * For outputting debugging info
6322 * @param string $string ?
6323 * @param string $eol ?
6324 * @todo Finish documenting this function
6326 function mtrace($string, $eol="\n", $sleep=0) {
6328 if (defined('STDOUT')) {
6329 fwrite(STDOUT
, $string.$eol);
6331 echo $string . $eol;
6336 //delay to keep message on user's screen in case of subsequent redirect
6342 //Replace 1 or more slashes or backslashes to 1 slash
6343 function cleardoubleslashes ($path) {
6344 return preg_replace('/(\/|\\\){1,}/','/',$path);
6347 function zip_files ($originalfiles, $destination) {
6348 //Zip an array of files/dirs to a destination zip file
6349 //Both parameters must be FULL paths to the files/dirs
6353 //Extract everything from destination
6354 $path_parts = pathinfo(cleardoubleslashes($destination));
6355 $destpath = $path_parts["dirname"]; //The path of the zip file
6356 $destfilename = $path_parts["basename"]; //The name of the zip file
6357 $extension = $path_parts["extension"]; //The extension of the file
6360 if (empty($destfilename)) {
6364 //If no extension, add it
6365 if (empty($extension)) {
6367 $destfilename = $destfilename.'.'.$extension;
6370 //Check destination path exists
6371 if (!is_dir($destpath)) {
6375 //Check destination path is writable. TODO!!
6377 //Clean destination filename
6378 $destfilename = clean_filename($destfilename);
6380 //Now check and prepare every file
6384 foreach ($originalfiles as $file) { //Iterate over each file
6385 //Check for every file
6386 $tempfile = cleardoubleslashes($file); // no doubleslashes!
6387 //Calculate the base path for all files if it isn't set
6388 if ($origpath === NULL) {
6389 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
6391 //See if the file is readable
6392 if (!is_readable($tempfile)) { //Is readable
6395 //See if the file/dir is in the same directory than the rest
6396 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
6399 //Add the file to the array
6400 $files[] = $tempfile;
6403 //Everything is ready:
6404 // -$origpath is the path where ALL the files to be compressed reside (dir).
6405 // -$destpath is the destination path where the zip file will go (dir).
6406 // -$files is an array of files/dirs to compress (fullpath)
6407 // -$destfilename is the name of the zip file (without path)
6409 //print_object($files); //Debug
6411 if (empty($CFG->zip
)) { // Use built-in php-based zip function
6413 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6414 //rewrite filenames because the old method with PCLZIP_OPT_REMOVE_PATH does not work under win32
6415 $zipfiles = array();
6416 $start = strlen($origpath)+
1;
6417 foreach($files as $file) {
6419 $tf[PCLZIP_ATT_FILE_NAME
] = $file;
6420 $tf[PCLZIP_ATT_FILE_NEW_FULL_NAME
] = substr($file, $start);
6423 //create the archive
6424 $archive = new PclZip(cleardoubleslashes("$destpath/$destfilename"));
6425 if (($list = $archive->create($zipfiles) == 0)) {
6426 notice($archive->errorInfo(true));
6430 } else { // Use external zip program
6433 foreach ($files as $filetozip) {
6434 $filestozip .= escapeshellarg(basename($filetozip));
6437 //Construct the command
6438 $separator = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
' &' : ' ;';
6439 $command = 'cd '.escapeshellarg($origpath).$separator.
6440 escapeshellarg($CFG->zip
).' -r '.
6441 escapeshellarg(cleardoubleslashes("$destpath/$destfilename")).' '.$filestozip;
6442 //All converted to backslashes in WIN
6443 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6444 $command = str_replace('/','\\',$command);
6451 function unzip_file ($zipfile, $destination = '', $showstatus = true) {
6452 //Unzip one zip file to a destination dir
6453 //Both parameters must be FULL paths
6454 //If destination isn't specified, it will be the
6455 //SAME directory where the zip file resides.
6459 //Extract everything from zipfile
6460 $path_parts = pathinfo(cleardoubleslashes($zipfile));
6461 $zippath = $path_parts["dirname"]; //The path of the zip file
6462 $zipfilename = $path_parts["basename"]; //The name of the zip file
6463 $extension = $path_parts["extension"]; //The extension of the file
6466 if (empty($zipfilename)) {
6470 //If no extension, error
6471 if (empty($extension)) {
6476 $zipfile = cleardoubleslashes($zipfile);
6478 //Check zipfile exists
6479 if (!file_exists($zipfile)) {
6483 //If no destination, passed let's go with the same directory
6484 if (empty($destination)) {
6485 $destination = $zippath;
6488 //Clear $destination
6489 $destpath = rtrim(cleardoubleslashes($destination), "/");
6491 //Check destination path exists
6492 if (!is_dir($destpath)) {
6496 //Check destination path is writable. TODO!!
6498 //Everything is ready:
6499 // -$zippath is the path where the zip file resides (dir)
6500 // -$zipfilename is the name of the zip file (without path)
6501 // -$destpath is the destination path where the zip file will uncompressed (dir)
6505 if (empty($CFG->unzip
)) { // Use built-in php-based unzip function
6507 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6508 $archive = new PclZip(cleardoubleslashes("$zippath/$zipfilename"));
6509 if (!$list = $archive->extract(PCLZIP_OPT_PATH
, $destpath,
6510 PCLZIP_CB_PRE_EXTRACT
, 'unzip_cleanfilename',
6511 PCLZIP_OPT_EXTRACT_DIR_RESTRICTION
, $destpath)) {
6512 notice($archive->errorInfo(true));
6516 } else { // Use external unzip program
6518 $separator = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
' &' : ' ;';
6519 $redirection = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
'' : ' 2>&1';
6521 $command = 'cd '.escapeshellarg($zippath).$separator.
6522 escapeshellarg($CFG->unzip
).' -o '.
6523 escapeshellarg(cleardoubleslashes("$zippath/$zipfilename")).' -d '.
6524 escapeshellarg($destpath).$redirection;
6525 //All converted to backslashes in WIN
6526 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6527 $command = str_replace('/','\\',$command);
6529 Exec($command,$list);
6532 //Display some info about the unzip execution
6534 unzip_show_status($list,$destpath);
6540 function unzip_cleanfilename ($p_event, &$p_header) {
6541 //This function is used as callback in unzip_file() function
6542 //to clean illegal characters for given platform and to prevent directory traversal.
6543 //Produces the same result as info-zip unzip.
6544 $p_header['filename'] = ereg_replace('[[:cntrl:]]', '', $p_header['filename']); //strip control chars first!
6545 $p_header['filename'] = ereg_replace('\.\.+', '', $p_header['filename']); //directory traversal protection
6546 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6547 $p_header['filename'] = ereg_replace('[:*"?<>|]', '_', $p_header['filename']); //replace illegal chars
6548 $p_header['filename'] = ereg_replace('^([a-zA-Z])_', '\1:', $p_header['filename']); //repair drive letter
6550 //Add filtering for other systems here
6551 // BSD: none (tested)
6555 $p_header['filename'] = cleardoubleslashes($p_header['filename']); //normalize the slashes/backslashes
6559 function unzip_show_status ($list,$removepath) {
6560 //This function shows the results of the unzip execution
6561 //depending of the value of the $CFG->zip, results will be
6562 //text or an array of files.
6566 if (empty($CFG->unzip
)) { // Use built-in php-based zip function
6567 $strname = get_string("name");
6568 $strsize = get_string("size");
6569 $strmodified = get_string("modified");
6570 $strstatus = get_string("status");
6571 echo "<table width=\"640\">";
6572 echo "<tr><th class=\"header\" scope=\"col\">$strname</th>";
6573 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strsize</th>";
6574 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strmodified</th>";
6575 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strstatus</th></tr>";
6576 foreach ($list as $item) {
6578 $item['filename'] = str_replace(cleardoubleslashes($removepath).'/', "", $item['filename']);
6579 print_cell("left", s($item['filename']));
6580 if (! $item['folder']) {
6581 print_cell("right", display_size($item['size']));
6583 echo "<td> </td>";
6585 $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
6586 print_cell("right", $filedate);
6587 print_cell("right", $item['status']);
6592 } else { // Use external zip program
6593 print_simple_box_start("center");
6595 foreach ($list as $item) {
6596 echo s(str_replace(cleardoubleslashes($removepath.'/'), '', $item)).'<br />';
6599 print_simple_box_end();
6604 * Returns most reliable client address
6606 * @return string The remote IP address
6608 function getremoteaddr() {
6609 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
6610 return cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
6612 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
6613 return cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
6615 if (!empty($_SERVER['REMOTE_ADDR'])) {
6616 return cleanremoteaddr($_SERVER['REMOTE_ADDR']);
6622 * Cleans a remote address ready to put into the log table
6624 function cleanremoteaddr($addr) {
6625 $originaladdr = $addr;
6627 // first get all things that look like IP addresses.
6628 if (!preg_match_all('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/',$addr,$matches,PREG_SET_ORDER
)) {
6631 $goodmatches = array();
6632 $lanmatches = array();
6633 foreach ($matches as $match) {
6635 // check to make sure it's not an internal address.
6636 // the following are reserved for private lans...
6637 // 10.0.0.0 - 10.255.255.255
6638 // 172.16.0.0 - 172.31.255.255
6639 // 192.168.0.0 - 192.168.255.255
6640 // 169.254.0.0 -169.254.255.255
6641 $bits = explode('.',$match[0]);
6642 if (count($bits) != 4) {
6643 // weird, preg match shouldn't give us it.
6646 if (($bits[0] == 10)
6647 ||
($bits[0] == 172 && $bits[1] >= 16 && $bits[1] <= 31)
6648 ||
($bits[0] == 192 && $bits[1] == 168)
6649 ||
($bits[0] == 169 && $bits[1] == 254)) {
6650 $lanmatches[] = $match[0];
6654 $goodmatches[] = $match[0];
6656 if (!count($goodmatches)) {
6657 // perhaps we have a lan match, it's probably better to return that.
6658 if (!count($lanmatches)) {
6661 return array_pop($lanmatches);
6664 if (count($goodmatches) == 1) {
6665 return $goodmatches[0];
6667 error_log("NOTICE: cleanremoteaddr gives us something funny: $originaladdr had ".count($goodmatches)." matches");
6668 // we need to return something, so
6669 return array_pop($goodmatches);
6673 * file_put_contents is only supported by php 5.0 and higher
6674 * so if it is not predefined, define it here
6676 * @param $file full path of the file to write
6677 * @param $contents contents to be sent
6678 * @return number of bytes written (false on error)
6680 if(!function_exists('file_put_contents')) {
6681 function file_put_contents($file, $contents) {
6683 if ($f = fopen($file, 'w')) {
6684 $result = fwrite($f, $contents);
6692 * The clone keyword is only supported from PHP 5 onwards.
6693 * The behaviour of $obj2 = $obj1 differs fundamentally
6694 * between PHP 4 and PHP 5. In PHP 4 a copy of $obj1 was
6695 * created, in PHP 5 $obj1 is referenced. To create a copy
6696 * in PHP 5 the clone keyword was introduced. This function
6697 * simulates this behaviour for PHP < 5.0.0.
6698 * See also: http://mjtsai.com/blog/2004/07/15/php-5-object-references/
6700 * Modified 2005-09-29 by Eloy (from Julian Sedding proposal)
6701 * Found a better implementation (more checks and possibilities) from PEAR:
6702 * http://cvs.php.net/co.php/pear/PHP_Compat/Compat/Function/clone.php
6704 * @param object $obj
6707 if(!check_php_version('5.0.0')) {
6708 // the eval is needed to prevent PHP 5 from getting a parse error!
6710 function clone($obj) {
6712 if (!is_object($obj)) {
6713 user_error(\'clone() __clone method called on non-object\', E_USER_WARNING);
6717 /// Use serialize/unserialize trick to deep copy the object
6718 $obj = unserialize(serialize($obj));
6720 /// If there is a __clone method call it on the "new" class
6721 if (method_exists($obj, \'__clone\')) {
6728 // Supply the PHP5 function scandir() to older versions.
6729 function scandir($directory) {
6731 if ($dh = opendir($directory)) {
6732 while (($file = readdir($dh)) !== false) {
6740 // Supply the PHP5 function array_combine() to older versions.
6741 function array_combine($keys, $values) {
6742 if (!is_array($keys) || !is_array($values) || count($keys) != count($values)) {
6747 foreach ($keys as $key) {
6748 $result[$key] = current($values);
6757 * This function will make a complete copy of anything it's given,
6758 * regardless of whether it's an object or not.
6759 * @param mixed $thing
6762 function fullclone($thing) {
6763 return unserialize(serialize($thing));
6768 * This function expects to called during shutdown
6769 * should be set via register_shutdown_function()
6770 * in lib/setup.php .
6772 * Right now we do it only if we are under apache, to
6773 * make sure apache children that hog too much mem are
6777 function moodle_request_shutdown() {
6781 // initially, we are only ever called under apache
6782 // but check just in case
6783 if (function_exists('apache_child_terminate')
6784 && function_exists('memory_get_usage')
6785 && ini_get_bool('child_terminate')) {
6786 if (empty($CFG->apachemaxmem
)) {
6787 $CFG->apachemaxmem
= 25000000; // default 25MiB
6789 if (memory_get_usage() > (int)$CFG->apachemaxmem
) {
6790 trigger_error('Mem usage over $CFG->apachemaxmem: marking child for reaping.');
6791 @apache_child_terminate
();
6797 * If new messages are waiting for the current user, then return
6798 * Javascript code to create a popup window
6800 * @return string Javascript code
6802 function message_popup_window() {
6805 $popuplimit = 30; // Minimum seconds between popups
6807 if (!defined('MESSAGE_WINDOW')) {
6808 if (isset($USER->id
)) {
6809 if (!isset($USER->message_lastpopup
)) {
6810 $USER->message_lastpopup
= 0;
6812 if ((time() - $USER->message_lastpopup
) > $popuplimit) { /// It's been long enough
6813 if (get_user_preferences('message_showmessagewindow', 1) == 1) {
6814 if (count_records_select('message', 'useridto = \''.$USER->id
.'\' AND timecreated > \''.$USER->message_lastpopup
.'\'')) {
6815 $USER->message_lastpopup
= time();
6816 return '<script type="text/javascript">'."\n//<![CDATA[\n openpopup('/message/index.php', 'message',
6817 'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500', 0);\n//]]>\n</script>";
6827 // Used to make sure that $min <= $value <= $max
6828 function bounded_number($min, $value, $max) {
6838 function array_is_nested($array) {
6839 foreach ($array as $value) {
6840 if (is_array($value)) {
6848 *** get_performance_info() pairs up with init_performance_info()
6849 *** loaded in setup.php. Returns an array with 'html' and 'txt'
6850 *** values ready for use, and each of the individual stats provided
6851 *** separately as well.
6854 function get_performance_info() {
6855 global $CFG, $PERF, $rcache;
6858 $info['html'] = ''; // holds userfriendly HTML representation
6859 $info['txt'] = me() . ' '; // holds log-friendly representation
6861 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
6863 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
6864 $info['txt'] .= 'time: '.$info['realtime'].'s ';
6866 if (function_exists('memory_get_usage')) {
6867 $info['memory_total'] = memory_get_usage();
6868 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
6869 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
6870 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
6873 $inc = get_included_files();
6874 //error_log(print_r($inc,1));
6875 $info['includecount'] = count($inc);
6876 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
6877 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
6879 if (!empty($PERF->dbqueries
)) {
6880 $info['dbqueries'] = $PERF->dbqueries
;
6881 $info['html'] .= '<span class="dbqueries">DB queries '.$info['dbqueries'].'</span> ';
6882 $info['txt'] .= 'dbqueries: '.$info['dbqueries'].' ';
6885 if (!empty($PERF->logwrites
)) {
6886 $info['logwrites'] = $PERF->logwrites
;
6887 $info['html'] .= '<span class="logwrites">Log writes '.$info['logwrites'].'</span> ';
6888 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
6891 if (!empty($PERF->profiling
) && $PERF->profiling
) {
6892 require_once($CFG->dirroot
.'/lib/profilerlib.php');
6893 $info['html'] .= '<span class="profilinginfo">'.Profiler
::get_profiling(array('-R')).'</span>';
6896 if (function_exists('posix_times')) {
6897 $ptimes = posix_times();
6898 if (is_array($ptimes)) {
6899 foreach ($ptimes as $key => $val) {
6900 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
6902 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
6903 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
6907 // Grab the load average for the last minute
6908 // /proc will only work under some linux configurations
6909 // while uptime is there under MacOSX/Darwin and other unices
6910 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
6911 list($server_load) = explode(' ', $loadavg[0]);
6913 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
6914 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
6915 $server_load = $matches[1];
6917 trigger_error('Could not parse uptime output!');
6920 if (!empty($server_load)) {
6921 $info['serverload'] = $server_load;
6922 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
6923 $info['txt'] .= "serverload: {$info['serverload']} ";
6926 if (isset($rcache->hits
) && isset($rcache->misses
)) {
6927 $info['rcachehits'] = $rcache->hits
;
6928 $info['rcachemisses'] = $rcache->misses
;
6929 $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
6930 "{$rcache->hits}/{$rcache->misses}</span> ";
6931 $info['txt'] .= 'rcache: '.
6932 "{$rcache->hits}/{$rcache->misses} ";
6934 $info['html'] = '<div class="performanceinfo">'.$info['html'].'</div>';
6938 function apd_get_profiling() {
6939 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
6942 function remove_dir($dir, $content_only=false) {
6943 // if content_only=true then delete all but
6944 // the directory itself
6946 $handle = opendir($dir);
6947 while (false!==($item = readdir($handle))) {
6948 if($item != '.' && $item != '..') {
6949 if(is_dir($dir.'/'.$item)) {
6950 remove_dir($dir.'/'.$item);
6952 unlink($dir.'/'.$item);
6957 if ($content_only) {
6964 * Function to check if a directory exists and optionally create it.
6966 * @param string absolute directory path
6967 * @param boolean create directory if does not exist
6968 * @param boolean create directory recursively
6970 * @return boolean true if directory exists or created
6972 function check_dir_exists($dir, $create=false, $recursive=false) {
6984 // PHP 5.0 has recursive mkdir parameter, but 4.x does not :-(
6985 $dir = str_replace('\\', '/', $dir); //windows compatibility
6986 $dirs = explode('/', $dir);
6987 $dir = array_shift($dirs).'/'; //skip root or drive letter
6988 foreach ($dirs as $part) {
6993 if (!is_dir($dir)) {
6994 if (!mkdir($dir, $CFG->directorypermissions
)) {
7001 $status = mkdir($dir, $CFG->directorypermissions
);
7008 function report_session_error() {
7009 global $CFG, $FULLME;
7011 if (empty($CFG->lang
)) {
7014 // Set up default theme and locale
7018 //clear session cookies
7019 setcookie('MoodleSession'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
7020 setcookie('MoodleSessionTest'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
7021 //increment database error counters
7022 if (isset($CFG->session_error_counter
)) {
7023 set_config('session_error_counter', 1 +
$CFG->session_error_counter
);
7025 set_config('session_error_counter', 1);
7027 redirect($FULLME, get_string('sessionerroruser2', 'error'), 5);
7032 * Detect if an object or a class contains a given property
7033 * will take an actual object or the name of a class
7034 * @param mix $obj Name of class or real object to test
7035 * @param string $property name of property to find
7036 * @return bool true if property exists
7038 function object_property_exists( $obj, $property ) {
7039 if (is_string( $obj )) {
7040 $properties = get_class_vars( $obj );
7043 $properties = get_object_vars( $obj );
7045 return array_key_exists( $property, $properties );
7050 * Detect a custom script replacement in the data directory that will
7051 * replace an existing moodle script
7052 * @param string $urlpath path to the original script
7053 * @return string full path name if a custom script exists
7054 * @return bool false if no custom script exists
7056 function custom_script_path($urlpath='') {
7059 // set default $urlpath, if necessary
7060 if (empty($urlpath)) {
7061 $urlpath = qualified_me(); // e.g. http://www.this-server.com/moodle/this-script.php
7064 // $urlpath is invalid if it is empty or does not start with the Moodle wwwroot
7065 if (empty($urlpath) or (strpos($urlpath, $CFG->wwwroot
) === false )) {
7069 // replace wwwroot with the path to the customscripts folder and clean path
7070 $scriptpath = $CFG->customscripts
. clean_param(substr($urlpath, strlen($CFG->wwwroot
)), PARAM_PATH
);
7072 // remove the query string, if any
7073 if (($strpos = strpos($scriptpath, '?')) !== false) {
7074 $scriptpath = substr($scriptpath, 0, $strpos);
7077 // remove trailing slashes, if any
7078 $scriptpath = rtrim($scriptpath, '/\\');
7080 // append index.php, if necessary
7081 if (is_dir($scriptpath)) {
7082 $scriptpath .= '/index.php';
7085 // check the custom script exists
7086 if (file_exists($scriptpath)) {
7094 * Wrapper function to load necessary editor scripts
7095 * to $CFG->editorsrc array. Params can be coursei id
7096 * or associative array('courseid' => value, 'name' => 'editorname').
7098 * @param mixed $args Courseid or associative array.
7100 function loadeditor($args) {
7102 include($CFG->libdir
.'/editorlib.php');
7103 return editorObject
::loadeditor($args);
7107 * Returns whether or not the user object is a remote MNET user. This function
7108 * is in moodlelib because it does not rely on loading any of the MNET code.
7110 * @param object $user A valid user object
7111 * @return bool True if the user is from a remote Moodle.
7113 function is_mnet_remote_user($user) {
7116 if (!isset($CFG->mnet_localhost_id
)) {
7117 include_once $CFG->dirroot
. '/mnet/lib.php';
7118 $env = new mnet_environment();
7123 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
7127 * Checks if a given plugin is in the list of enabled enrolment plugins.
7129 * @param string $auth Enrolment plugin.
7130 * @return boolean Whether the plugin is enabled.
7132 function is_enabled_enrol($enrol='') {
7135 // use the global default if not specified
7137 $enrol = $CFG->enrol
;
7139 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled
));
7143 * This function will search for browser prefereed languages, setting Moodle
7144 * to use the best one available if $SESSION->lang is undefined
7146 function setup_lang_from_browser() {
7148 global $CFG, $SESSION, $USER;
7150 if (!empty($SESSION->lang
) or !empty($USER->lang
)) {
7151 // Lang is defined in session or user profile, nothing to do
7155 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
7159 /// Extract and clean langs from headers
7160 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
7161 $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
7162 $rawlangs = explode(',', $rawlangs); // Convert to array
7166 foreach ($rawlangs as $lang) {
7167 if (strpos($lang, ';') === false) {
7168 $langs[(string)$order] = $lang;
7169 $order = $order-0.01;
7171 $parts = explode(';', $lang);
7172 $pos = strpos($parts[1], '=');
7173 $langs[substr($parts[1], $pos+
1)] = $parts[0];
7176 krsort($langs, SORT_NUMERIC
);
7178 $langlist = get_list_of_languages();
7180 /// Look for such langs under standard locations
7181 foreach ($langs as $lang) {
7182 $lang = strtolower(clean_param($lang.'_utf8', PARAM_SAFEDIR
)); // clean it properly for include
7183 if (!array_key_exists($lang, $langlist)) {
7184 continue; // language not allowed, try next one
7186 if (file_exists($CFG->dataroot
.'/lang/'. $lang) or file_exists($CFG->dirroot
.'/lang/'. $lang)) {
7187 $SESSION->lang
= $lang; /// Lang exists, set it in session
7188 break; /// We have finished. Go out
7195 ////////////////////////////////////////////////////////////////////////////////
7197 function is_newnav($navigation) {
7198 if (is_array($navigation) && !empty($navigation['newnav'])) {
7206 * Checks whether the given variable name is defined as a variable within the given object.
7207 * @note This will NOT work with stdClass objects, which have no class variables.
7208 * @param string $var The variable name
7209 * @param object $object The object to check
7212 function in_object_vars($var, $object) {
7213 $class_vars = get_class_vars(get_class($object));
7214 $class_vars = array_keys($class_vars);
7215 return in_array($var, $class_vars);
7219 * Returns an array without repeated objects.
7220 * This function is similar to array_unique, but for arrays that have objects as values
7222 * @param unknown_type $array
7223 * @param unknown_type $keep_key_assoc
7226 function object_array_unique($array, $keep_key_assoc = true) {
7227 $duplicate_keys = array();
7230 foreach ($array as $key=>$val) {
7231 // convert objects to arrays, in_array() does not support objects
7232 if (is_object($val)) {
7236 if (!in_array($val, $tmp)) {
7239 $duplicate_keys[] = $key;
7243 foreach ($duplicate_keys as $key) {
7244 unset($array[$key]);
7247 return $keep_key_assoc ?
$array : array_values($array);
7250 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: