3 ///////////////////////////////////////////////////////////////////////////
5 // NOTICE OF COPYRIGHT //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
10 // Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
22 // http://www.gnu.org/copyleft/gpl.html //
24 ///////////////////////////////////////////////////////////////////////////
27 * moodlelib.php - Moodle main library
29 * Main library file of miscellaneous general-purpose Moodle functions.
30 * Other main libraries:
31 * - weblib.php - functions that produce web output
32 * - datalib.php - functions that access the database
33 * @author Martin Dougiamas
35 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
39 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
42 * Used by some scripts to check they are being called by Moodle
44 define('MOODLE_INTERNAL', true);
49 define('NOGROUPS', 0);
54 define('SEPARATEGROUPS', 1);
59 define('VISIBLEGROUPS', 2);
61 /// Date and time constants ///
63 * Time constant - the number of seconds in a year
66 define('YEARSECS', 31536000);
69 * Time constant - the number of seconds in a week
71 define('WEEKSECS', 604800);
74 * Time constant - the number of seconds in a day
76 define('DAYSECS', 86400);
79 * Time constant - the number of seconds in an hour
81 define('HOURSECS', 3600);
84 * Time constant - the number of seconds in a minute
86 define('MINSECS', 60);
89 * Time constant - the number of minutes in a day
91 define('DAYMINS', 1440);
94 * Time constant - the number of minutes in an hour
96 define('HOURMINS', 60);
98 /// Parameter constants - every call to optional_param(), required_param() ///
99 /// or clean_param() should have a specified type of parameter. //////////////
102 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way;
103 * originally was 0, but changed because we need to detect unknown
104 * parameter types and swiched order in clean_param().
106 define('PARAM_RAW', 666);
109 * PARAM_CLEAN - obsoleted, please try to use more specific type of parameter.
110 * It was one of the first types, that is why it is abused so much ;-)
112 define('PARAM_CLEAN', 0x0001);
115 * PARAM_INT - integers only, use when expecting only numbers.
117 define('PARAM_INT', 0x0002);
120 * PARAM_INTEGER - an alias for PARAM_INT
122 define('PARAM_INTEGER', 0x0002);
125 * PARAM_NUMBER - a real/floating point number.
127 define('PARAM_NUMBER', 0x000a);
130 * PARAM_ALPHA - contains only english letters.
132 define('PARAM_ALPHA', 0x0004);
135 * PARAM_ACTION - an alias for PARAM_ALPHA, use for various actions in formas and urls
136 * @TODO: should we alias it to PARAM_ALPHANUM ?
138 define('PARAM_ACTION', 0x0004);
141 * PARAM_FORMAT - an alias for PARAM_ALPHA, use for names of plugins, formats, etc.
142 * @TODO: should we alias it to PARAM_ALPHANUM ?
144 define('PARAM_FORMAT', 0x0004);
147 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
149 define('PARAM_NOTAGS', 0x0008);
152 * PARAM_MULTILANG - alias of PARAM_TEXT.
154 define('PARAM_MULTILANG', 0x0009);
157 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
159 define('PARAM_TEXT', 0x0009);
162 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
164 define('PARAM_FILE', 0x0010);
167 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
168 * note: the leading slash is not removed, window drive letter is not allowed
170 define('PARAM_PATH', 0x0020);
173 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
175 define('PARAM_HOST', 0x0040);
178 * PARAM_URL - expected properly formatted URL.
180 define('PARAM_URL', 0x0080);
183 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
185 define('PARAM_LOCALURL', 0x0180);
188 * PARAM_CLEANFILE - safe file name, all dangerous and regional chars are removed,
189 * use when you want to store a new file submitted by students
191 define('PARAM_CLEANFILE',0x0200);
194 * PARAM_ALPHANUM - expected numbers and letters only.
196 define('PARAM_ALPHANUM', 0x0400);
199 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
201 define('PARAM_BOOL', 0x0800);
204 * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes
205 * note: do not forget to addslashes() before storing into database!
207 define('PARAM_CLEANHTML',0x1000);
210 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "/-_" allowed,
211 * suitable for include() and require()
212 * @TODO: should we rename this function to PARAM_SAFEDIRS??
214 define('PARAM_ALPHAEXT', 0x2000);
217 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
219 define('PARAM_SAFEDIR', 0x4000);
222 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
224 define('PARAM_SEQUENCE', 0x8000);
227 * PARAM_PEM - Privacy Enhanced Mail format
229 define('PARAM_PEM', 0x10000);
232 * PARAM_BASE64 - Base 64 encoded format
234 define('PARAM_BASE64', 0x20000);
239 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
241 define('PAGE_COURSE_VIEW', 'course-view');
244 /** no warnings at all */
245 define ('DEBUG_NONE', 0);
246 /** E_ERROR | E_PARSE */
247 define ('DEBUG_MINIMAL', 5);
248 /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
249 define ('DEBUG_NORMAL', 15);
250 /** E_ALL without E_STRICT and E_RECOVERABLE_ERROR for now */
251 define ('DEBUG_ALL', 2047);
252 /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
253 define ('DEBUG_DEVELOPER', 34815);
256 * Blog access level constant declaration
258 define ('BLOG_USER_LEVEL', 1);
259 define ('BLOG_GROUP_LEVEL', 2);
260 define ('BLOG_COURSE_LEVEL', 3);
261 define ('BLOG_SITE_LEVEL', 4);
262 define ('BLOG_GLOBAL_LEVEL', 5);
266 /// PARAMETER HANDLING ////////////////////////////////////////////////////
269 * Returns a particular value for the named variable, taken from
270 * POST or GET. If the parameter doesn't exist then an error is
271 * thrown because we require this variable.
273 * This function should be used to initialise all required values
274 * in a script that are based on parameters. Usually it will be
276 * $id = required_param('id');
278 * @param string $parname the name of the page parameter we want
279 * @param int $type expected type of parameter
282 function required_param($parname, $type=PARAM_CLEAN
) {
284 // detect_unchecked_vars addition
286 if (!empty($CFG->detect_unchecked_vars
)) {
287 global $UNCHECKED_VARS;
288 unset ($UNCHECKED_VARS->vars
[$parname]);
291 if (isset($_POST[$parname])) { // POST has precedence
292 $param = $_POST[$parname];
293 } else if (isset($_GET[$parname])) {
294 $param = $_GET[$parname];
296 error('A required parameter ('.$parname.') was missing');
299 return clean_param($param, $type);
303 * Returns a particular value for the named variable, taken from
304 * POST or GET, otherwise returning a given default.
306 * This function should be used to initialise all optional values
307 * in a script that are based on parameters. Usually it will be
309 * $name = optional_param('name', 'Fred');
311 * @param string $parname the name of the page parameter we want
312 * @param mixed $default the default value to return if nothing is found
313 * @param int $type expected type of parameter
316 function optional_param($parname, $default=NULL, $type=PARAM_CLEAN
) {
318 // detect_unchecked_vars addition
320 if (!empty($CFG->detect_unchecked_vars
)) {
321 global $UNCHECKED_VARS;
322 unset ($UNCHECKED_VARS->vars
[$parname]);
325 if (isset($_POST[$parname])) { // POST has precedence
326 $param = $_POST[$parname];
327 } else if (isset($_GET[$parname])) {
328 $param = $_GET[$parname];
333 return clean_param($param, $type);
337 * Used by {@link optional_param()} and {@link required_param()} to
338 * clean the variables and/or cast to specific types, based on
341 * $course->format = clean_param($course->format, PARAM_ALPHA);
342 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
348 * @uses PARAM_INTEGER
350 * @uses PARAM_ALPHANUM
352 * @uses PARAM_ALPHAEXT
354 * @uses PARAM_SAFEDIR
355 * @uses PARAM_CLEANFILE
360 * @uses PARAM_LOCALURL
361 * @uses PARAM_CLEANHTML
362 * @uses PARAM_SEQUENCE
363 * @param mixed $param the variable we are cleaning
364 * @param int $type expected format of param after cleaning.
367 function clean_param($param, $type) {
371 if (is_array($param)) { // Let's loop
373 foreach ($param as $key => $value) {
374 $newparam[$key] = clean_param($value, $type);
380 case PARAM_RAW
: // no cleaning at all
383 case PARAM_CLEAN
: // General HTML cleaning, try to use more specific type if possible
384 if (is_numeric($param)) {
387 $param = stripslashes($param); // Needed for kses to work fine
388 $param = clean_text($param); // Sweep for scripts, etc
389 return addslashes($param); // Restore original request parameter slashes
391 case PARAM_CLEANHTML
: // prepare html fragment for display, do not store it into db!!
392 $param = stripslashes($param); // Remove any slashes
393 $param = clean_text($param); // Sweep for scripts, etc
397 return (int)$param; // Convert to integer
400 return (float)$param; // Convert to integer
402 case PARAM_ALPHA
: // Remove everything not a-z
403 return eregi_replace('[^a-zA-Z]', '', $param);
405 case PARAM_ALPHANUM
: // Remove everything not a-zA-Z0-9
406 return eregi_replace('[^A-Za-z0-9]', '', $param);
408 case PARAM_ALPHAEXT
: // Remove everything not a-zA-Z/_-
409 return eregi_replace('[^a-zA-Z/_-]', '', $param);
411 case PARAM_SEQUENCE
: // Remove everything not 0-9,
412 return eregi_replace('[^0-9,]', '', $param);
414 case PARAM_BOOL
: // Convert to 1 or 0
415 $tempstr = strtolower($param);
416 if ($tempstr == 'on' or $tempstr == 'yes' ) {
418 } else if ($tempstr == 'off' or $tempstr == 'no') {
421 $param = empty($param) ?
0 : 1;
425 case PARAM_NOTAGS
: // Strip all tags
426 return strip_tags($param);
428 case PARAM_TEXT
: // leave only tags needed for multilang
429 return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN
);
431 case PARAM_SAFEDIR
: // Remove everything not a-zA-Z0-9_-
432 return eregi_replace('[^a-zA-Z0-9_-]', '', $param);
434 case PARAM_CLEANFILE
: // allow only safe characters
435 return clean_filename($param);
437 case PARAM_FILE
: // Strip all suspicious characters from filename
438 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':\\/]', '', $param);
439 $param = ereg_replace('\.\.+', '', $param);
445 case PARAM_PATH
: // Strip all suspicious characters from file path
446 $param = str_replace('\\\'', '\'', $param);
447 $param = str_replace('\\"', '"', $param);
448 $param = str_replace('\\', '/', $param);
449 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':]', '', $param);
450 $param = ereg_replace('\.\.+', '', $param);
451 $param = ereg_replace('//+', '/', $param);
452 return ereg_replace('/(\./)+', '/', $param);
454 case PARAM_HOST
: // allow FQDN or IPv4 dotted quad
455 preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
456 // match ipv4 dotted quad
457 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
458 // confirm values are ok
462 ||
$match[4] > 255 ) {
463 // hmmm, what kind of dotted quad is this?
466 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
467 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
468 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
470 // all is ok - $param is respected
477 case PARAM_URL
: // allow safe ftp, http, mailto urls
478 include_once($CFG->dirroot
. '/lib/validateurlsyntax.php');
479 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
480 // all is ok, param is respected
482 $param =''; // not really ok
486 case PARAM_LOCALURL
: // allow http absolute, root relative and relative URLs within wwwroot
487 $param = clean_param($param, PARAM_URL
);
488 if (!empty($param)) {
489 if (preg_match(':^/:', $param)) {
490 // root-relative, ok!
491 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot
, '/').'/i',$param)) {
492 // absolute, and matches our wwwroot
494 // relative - let's make sure there are no tricks
495 if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
504 $param = trim($param);
505 // PEM formatted strings may contain letters/numbers and the symbols
509 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
510 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
511 list($wholething, $body) = $matches;
512 unset($wholething, $matches);
513 $b64 = clean_param($body, PARAM_BASE64
);
515 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
522 if (!empty($param)) {
523 // PEM formatted strings may contain letters/numbers and the symbols
527 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
530 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY
);
531 // Each line of base64 encoded data must be 64 characters in
532 // length, except for the last line which may be less than (or
533 // equal to) 64 characters long.
534 for ($i=0, $j=count($lines); $i < $j; $i++
) {
536 if (64 < strlen($lines[$i])) {
542 if (64 != strlen($lines[$i])) {
546 return implode("\n",$lines);
550 default: // throw error, switched parameters in optional_param or another serious problem
551 error("Unknown parameter type: $type");
558 * Set a key in global configuration
560 * Set a key/value pair in both this session's {@link $CFG} global variable
561 * and in the 'config' database table for future sessions.
563 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
564 * In that case it doesn't affect $CFG.
566 * @param string $name the key to set
567 * @param string $value the value to set (without magic quotes)
568 * @param string $plugin (optional) the plugin scope
572 function set_config($name, $value, $plugin=NULL) {
573 /// No need for get_config because they are usually always available in $CFG
577 if (empty($plugin)) {
578 $CFG->$name = $value; // So it's defined for this invocation at least
580 if (get_field('config', 'name', 'name', $name)) {
581 return set_field('config', 'value', addslashes($value), 'name', $name);
583 $config = new object();
584 $config->name
= $name;
585 $config->value
= addslashes($value);
586 return insert_record('config', $config);
588 } else { // plugin scope
589 if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
590 return set_field('config_plugins', 'value', addslashes($value), 'id', $id);
592 $config = new object();
593 $config->plugin
= addslashes($plugin);
594 $config->name
= $name;
595 $config->value
= addslashes($value);
596 return insert_record('config_plugins', $config);
602 * Get configuration values from the global config table
603 * or the config_plugins table.
605 * If called with no parameters it will do the right thing
606 * generating $CFG safely from the database without overwriting
609 * If called with 2 parameters it will return a $string single
610 * value or false of the value is not found.
612 * @param string $plugin
613 * @param string $name
615 * @return hash-like object or single value
618 function get_config($plugin=NULL, $name=NULL) {
622 if (!empty($name)) { // the user is asking for a specific value
623 if (!empty($plugin)) {
624 return get_field('config_plugins', 'value', 'plugin' , $plugin, 'name', $name);
626 return get_field('config', 'value', 'name', $name);
630 // the user is after a recordset
631 if (!empty($plugin)) {
632 if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
633 $configs = (array)$configs;
635 foreach ($configs as $config) {
636 $localcfg[$config->name
] = $config->value
;
638 return (object)$localcfg;
643 // this was originally in setup.php
644 if ($configs = get_records('config')) {
645 $localcfg = (array)$CFG;
646 foreach ($configs as $config) {
647 if (!isset($localcfg[$config->name
])) {
648 $localcfg[$config->name
] = $config->value
;
650 if ($localcfg[$config->name
] != $config->value
) {
651 // complain if the DB has a different
652 // value than config.php does
653 error_log("\$CFG->{$config->name} in config.php ({$localcfg[$config->name]}) overrides database setting ({$config->value})");
658 $localcfg = (object)$localcfg;
661 // preserve $CFG if DB returns nothing or error
669 * Removes a key from global configuration
671 * @param string $name the key to set
672 * @param string $plugin (optional) the plugin scope
676 function unset_config($name, $plugin=NULL) {
682 if (empty($plugin)) {
683 return delete_records('config', 'name', $name);
685 return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
691 * Refresh current $USER session global variable with all their current preferences.
694 function reload_user_preferences() {
699 $USER->preference
= array();
701 if (!isloggedin() or isguestuser()) {
702 // no pernament storage for not-logged-in user and guest
704 } else if ($preferences = get_records('user_preferences', 'userid', $USER->id
)) {
705 foreach ($preferences as $preference) {
706 $USER->preference
[$preference->name
] = $preference->value
;
714 * Sets a preference for the current user
715 * Optionally, can set a preference for a different user object
717 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
719 * @param string $name The key to set as preference for the specified user
720 * @param string $value The value to set forthe $name key in the specified user's record
721 * @param int $otheruserid A moodle user ID
724 function set_user_preference($name, $value, $otheruserid=NULL) {
728 if (!isset($USER->preference
)) {
729 reload_user_preferences();
738 if (empty($otheruserid)){
739 if (!isloggedin() or isguestuser()) {
744 if (isguestuser($otheruserid)) {
747 $userid = $otheruserid;
752 // no pernament storage for not-logged-in user and guest
754 } else if ($preference = get_record('user_preferences', 'userid', $userid, 'name', addslashes($name))) {
755 if (!set_field('user_preferences', 'value', addslashes((string)$value), 'id', $preference->id
)) {
760 $preference = new object();
761 $preference->userid
= $userid;
762 $preference->name
= addslashes($name);
763 $preference->value
= addslashes((string)$value);
764 if (!insert_record('user_preferences', $preference)) {
769 // update value in USER session if needed
770 if ($userid == $USER->id
) {
771 $USER->preference
[$name] = (string)$value;
778 * Unsets a preference completely by deleting it from the database
779 * Optionally, can set a preference for a different user id
781 * @param string $name The key to unset as preference for the specified user
782 * @param int $otheruserid A moodle user ID
784 function unset_user_preference($name, $otheruserid=NULL) {
788 if (!isset($USER->preference
)) {
789 reload_user_preferences();
792 if (empty($otheruserid)){
795 $userid = $otheruserid;
798 //Delete the preference from $USER if needed
799 if ($userid == $USER->id
) {
800 unset($USER->preference
[$name]);
804 return delete_records('user_preferences', 'userid', $userid, 'name', addslashes($name));
809 * Sets a whole array of preferences for the current user
810 * @param array $prefarray An array of key/value pairs to be set
811 * @param int $otheruserid A moodle user ID
814 function set_user_preferences($prefarray, $otheruserid=NULL) {
816 if (!is_array($prefarray) or empty($prefarray)) {
821 foreach ($prefarray as $name => $value) {
822 // The order is important; test for return is done first
823 $return = (set_user_preference($name, $value, $otheruserid) && $return);
829 * If no arguments are supplied this function will return
830 * all of the current user preferences as an array.
831 * If a name is specified then this function
832 * attempts to return that particular preference value. If
833 * none is found, then the optional value $default is returned,
835 * @param string $name Name of the key to use in finding a preference value
836 * @param string $default Value to be returned if the $name key is not set in the user preferences
837 * @param int $otheruserid A moodle user ID
841 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
844 if (!isset($USER->preference
)) {
845 reload_user_preferences();
848 if (empty($otheruserid)){
851 $userid = $otheruserid;
854 if ($userid == $USER->id
) {
855 $preference = $USER->preference
;
858 $preference = array();
859 if ($prefdata = get_records('user_preferences', 'userid', $userid)) {
860 foreach ($prefdata as $pref) {
861 $preference[$pref->name
] = $pref->value
;
867 return $preference; // All values
869 } else if (array_key_exists($name, $preference)) {
870 return $preference[$name]; // The single value
873 return $default; // Default value (or NULL)
878 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
881 * Given date parts in user time produce a GMT timestamp.
883 * @param int $year The year part to create timestamp of
884 * @param int $month The month part to create timestamp of
885 * @param int $day The day part to create timestamp of
886 * @param int $hour The hour part to create timestamp of
887 * @param int $minute The minute part to create timestamp of
888 * @param int $second The second part to create timestamp of
889 * @param float $timezone ?
890 * @param bool $applydst ?
891 * @return int timestamp
892 * @todo Finish documenting this function
894 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
896 $timezone = get_user_timezone_offset($timezone);
898 if (abs($timezone) > 13) {
899 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
901 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
902 $time = usertime($time, $timezone);
904 $time -= dst_offset_on($time);
913 * Given an amount of time in seconds, returns string
914 * formatted nicely as weeks, days, hours etc as needed
920 * @param int $totalsecs ?
921 * @param array $str ?
924 function format_time($totalsecs, $str=NULL) {
926 $totalsecs = abs($totalsecs);
928 if (!$str) { // Create the str structure the slow way
929 $str->day
= get_string('day');
930 $str->days
= get_string('days');
931 $str->hour
= get_string('hour');
932 $str->hours
= get_string('hours');
933 $str->min
= get_string('min');
934 $str->mins
= get_string('mins');
935 $str->sec
= get_string('sec');
936 $str->secs
= get_string('secs');
937 $str->year
= get_string('year');
938 $str->years
= get_string('years');
942 $years = floor($totalsecs/YEARSECS
);
943 $remainder = $totalsecs - ($years*YEARSECS
);
944 $days = floor($remainder/DAYSECS
);
945 $remainder = $totalsecs - ($days*DAYSECS
);
946 $hours = floor($remainder/HOURSECS
);
947 $remainder = $remainder - ($hours*HOURSECS
);
948 $mins = floor($remainder/MINSECS
);
949 $secs = $remainder - ($mins*MINSECS
);
951 $ss = ($secs == 1) ?
$str->sec
: $str->secs
;
952 $sm = ($mins == 1) ?
$str->min
: $str->mins
;
953 $sh = ($hours == 1) ?
$str->hour
: $str->hours
;
954 $sd = ($days == 1) ?
$str->day
: $str->days
;
955 $sy = ($years == 1) ?
$str->year
: $str->years
;
963 if ($years) $oyears = $years .' '. $sy;
964 if ($days) $odays = $days .' '. $sd;
965 if ($hours) $ohours = $hours .' '. $sh;
966 if ($mins) $omins = $mins .' '. $sm;
967 if ($secs) $osecs = $secs .' '. $ss;
969 if ($years) return trim($oyears .' '. $odays);
970 if ($days) return trim($odays .' '. $ohours);
971 if ($hours) return trim($ohours .' '. $omins);
972 if ($mins) return trim($omins .' '. $osecs);
973 if ($secs) return $osecs;
974 return get_string('now');
978 * Returns a formatted string that represents a date in user time
979 * <b>WARNING: note that the format is for strftime(), not date().</b>
980 * Because of a bug in most Windows time libraries, we can't use
981 * the nicer %e, so we have to use %d which has leading zeroes.
982 * A lot of the fuss in the function is just getting rid of these leading
983 * zeroes as efficiently as possible.
985 * If parameter fixday = true (default), then take off leading
986 * zero from %d, else mantain it.
989 * @param int $date timestamp in GMT
990 * @param string $format strftime format
991 * @param float $timezone
992 * @param bool $fixday If true (default) then the leading
993 * zero from %d is removed. If false then the leading zero is mantained.
996 function userdate($date, $format='', $timezone=99, $fixday = true) {
1000 if (empty($format)) {
1001 $format = get_string('strftimedaydatetime');
1004 if (!empty($CFG->nofixday
)) { // Config.php can force %d not to be fixed.
1006 } else if ($fixday) {
1007 $formatnoday = str_replace('%d', 'DD', $format);
1008 $fixday = ($formatnoday != $format);
1011 $date +
= dst_offset_on($date);
1013 $timezone = get_user_timezone_offset($timezone);
1015 if (abs($timezone) > 13) { /// Server time
1017 $datestring = strftime($formatnoday, $date);
1018 $daystring = str_replace(' 0', '', strftime(' %d', $date));
1019 $datestring = str_replace('DD', $daystring, $datestring);
1021 $datestring = strftime($format, $date);
1024 $date +
= (int)($timezone * 3600);
1026 $datestring = gmstrftime($formatnoday, $date);
1027 $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
1028 $datestring = str_replace('DD', $daystring, $datestring);
1030 $datestring = gmstrftime($format, $date);
1034 /// If we are running under Windows convert from windows encoding to UTF-8
1035 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1037 if ($CFG->ostype
== 'WINDOWS') {
1038 if ($localewincharset = get_string('localewincharset')) {
1039 $textlib = textlib_get_instance();
1040 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1048 * Given a $time timestamp in GMT (seconds since epoch),
1049 * returns an array that represents the date in user time
1052 * @param int $time Timestamp in GMT
1053 * @param float $timezone ?
1054 * @return array An array that represents the date in user time
1055 * @todo Finish documenting this function
1057 function usergetdate($time, $timezone=99) {
1059 $timezone = get_user_timezone_offset($timezone);
1061 if (abs($timezone) > 13) { // Server time
1062 return getdate($time);
1065 // There is no gmgetdate so we use gmdate instead
1066 $time +
= dst_offset_on($time);
1067 $time +
= intval((float)$timezone * HOURSECS
);
1069 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
1072 $getdate['seconds'],
1073 $getdate['minutes'],
1080 $getdate['weekday'],
1082 ) = explode('_', $datestring);
1088 * Given a GMT timestamp (seconds since epoch), offsets it by
1089 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1092 * @param int $date Timestamp in GMT
1093 * @param float $timezone
1096 function usertime($date, $timezone=99) {
1098 $timezone = get_user_timezone_offset($timezone);
1100 if (abs($timezone) > 13) {
1103 return $date - (int)($timezone * HOURSECS
);
1107 * Given a time, return the GMT timestamp of the most recent midnight
1108 * for the current user.
1110 * @param int $date Timestamp in GMT
1111 * @param float $timezone ?
1114 function usergetmidnight($date, $timezone=99) {
1116 $timezone = get_user_timezone_offset($timezone);
1117 $userdate = usergetdate($date, $timezone);
1119 // Time of midnight of this user's day, in GMT
1120 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1125 * Returns a string that prints the user's timezone
1127 * @param float $timezone The user's timezone
1130 function usertimezone($timezone=99) {
1132 $tz = get_user_timezone($timezone);
1134 if (!is_float($tz)) {
1138 if(abs($tz) > 13) { // Server time
1139 return get_string('serverlocaltime');
1142 if($tz == intval($tz)) {
1143 // Don't show .0 for whole hours
1160 * Returns a float which represents the user's timezone difference from GMT in hours
1161 * Checks various settings and picks the most dominant of those which have a value
1165 * @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
1168 function get_user_timezone_offset($tz = 99) {
1172 $tz = get_user_timezone($tz);
1174 if (is_float($tz)) {
1177 $tzrecord = get_timezone_record($tz);
1178 if (empty($tzrecord)) {
1181 return (float)$tzrecord->gmtoff
/ HOURMINS
;
1186 * Returns a float or a string which denotes the user's timezone
1187 * 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)
1188 * means that for this timezone there are also DST rules to be taken into account
1189 * Checks various settings and picks the most dominant of those which have a value
1193 * @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
1196 function get_user_timezone($tz = 99) {
1201 isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: 99,
1202 isset($USER->timezone
) ?
$USER->timezone
: 99,
1203 isset($CFG->timezone
) ?
$CFG->timezone
: 99,
1208 while(($tz == '' ||
$tz == 99) && $next = each($timezones)) {
1209 $tz = $next['value'];
1212 return is_numeric($tz) ?
(float) $tz : $tz;
1220 * @param string $timezonename ?
1223 function get_timezone_record($timezonename) {
1225 static $cache = NULL;
1227 if ($cache === NULL) {
1231 if (isset($cache[$timezonename])) {
1232 return $cache[$timezonename];
1235 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix
.'timezone
1236 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
1244 * @param ? $fromyear ?
1245 * @param ? $to_year ?
1248 function calculate_user_dst_table($from_year = NULL, $to_year = NULL) {
1249 global $CFG, $SESSION;
1251 $usertz = get_user_timezone();
1253 if (is_float($usertz)) {
1254 // Trivial timezone, no DST
1258 if (!empty($SESSION->dst_offsettz
) && $SESSION->dst_offsettz
!= $usertz) {
1259 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1260 unset($SESSION->dst_offsets
);
1261 unset($SESSION->dst_range
);
1264 if (!empty($SESSION->dst_offsets
) && empty($from_year) && empty($to_year)) {
1265 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1266 // This will be the return path most of the time, pretty light computationally
1270 // Reaching here means we either need to extend our table or create it from scratch
1272 // Remember which TZ we calculated these changes for
1273 $SESSION->dst_offsettz
= $usertz;
1275 if(empty($SESSION->dst_offsets
)) {
1276 // If we 're creating from scratch, put the two guard elements in there
1277 $SESSION->dst_offsets
= array(1 => NULL, 0 => NULL);
1279 if(empty($SESSION->dst_range
)) {
1280 // If creating from scratch
1281 $from = max((empty($from_year) ?
intval(date('Y')) - 3 : $from_year), 1971);
1282 $to = min((empty($to_year) ?
intval(date('Y')) +
3 : $to_year), 2035);
1284 // Fill in the array with the extra years we need to process
1285 $yearstoprocess = array();
1286 for($i = $from; $i <= $to; ++
$i) {
1287 $yearstoprocess[] = $i;
1290 // Take note of which years we have processed for future calls
1291 $SESSION->dst_range
= array($from, $to);
1294 // If needing to extend the table, do the same
1295 $yearstoprocess = array();
1297 $from = max((empty($from_year) ?
$SESSION->dst_range
[0] : $from_year), 1971);
1298 $to = min((empty($to_year) ?
$SESSION->dst_range
[1] : $to_year), 2035);
1300 if($from < $SESSION->dst_range
[0]) {
1301 // Take note of which years we need to process and then note that we have processed them for future calls
1302 for($i = $from; $i < $SESSION->dst_range
[0]; ++
$i) {
1303 $yearstoprocess[] = $i;
1305 $SESSION->dst_range
[0] = $from;
1307 if($to > $SESSION->dst_range
[1]) {
1308 // Take note of which years we need to process and then note that we have processed them for future calls
1309 for($i = $SESSION->dst_range
[1] +
1; $i <= $to; ++
$i) {
1310 $yearstoprocess[] = $i;
1312 $SESSION->dst_range
[1] = $to;
1316 if(empty($yearstoprocess)) {
1317 // This means that there was a call requesting a SMALLER range than we have already calculated
1321 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1322 // Also, the array is sorted in descending timestamp order!
1325 $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');
1326 if(empty($presetrecords)) {
1330 // Remove ending guard (first element of the array)
1331 reset($SESSION->dst_offsets
);
1332 unset($SESSION->dst_offsets
[key($SESSION->dst_offsets
)]);
1334 // Add all required change timestamps
1335 foreach($yearstoprocess as $y) {
1336 // Find the record which is in effect for the year $y
1337 foreach($presetrecords as $year => $preset) {
1343 $changes = dst_changes_for_year($y, $preset);
1345 if($changes === NULL) {
1348 if($changes['dst'] != 0) {
1349 $SESSION->dst_offsets
[$changes['dst']] = $preset->dstoff
* MINSECS
;
1351 if($changes['std'] != 0) {
1352 $SESSION->dst_offsets
[$changes['std']] = 0;
1356 // Put in a guard element at the top
1357 $maxtimestamp = max(array_keys($SESSION->dst_offsets
));
1358 $SESSION->dst_offsets
[($maxtimestamp + DAYSECS
)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1361 krsort($SESSION->dst_offsets
);
1366 function dst_changes_for_year($year, $timezone) {
1368 if($timezone->dst_startday
== 0 && $timezone->dst_weekday
== 0 && $timezone->std_startday
== 0 && $timezone->std_weekday
== 0) {
1372 $monthdaydst = find_day_in_month($timezone->dst_startday
, $timezone->dst_weekday
, $timezone->dst_month
, $year);
1373 $monthdaystd = find_day_in_month($timezone->std_startday
, $timezone->std_weekday
, $timezone->std_month
, $year);
1375 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time
);
1376 list($std_hour, $std_min) = explode(':', $timezone->std_time
);
1378 $timedst = make_timestamp($year, $timezone->dst_month
, $monthdaydst, 0, 0, 0, 99, false);
1379 $timestd = make_timestamp($year, $timezone->std_month
, $monthdaystd, 0, 0, 0, 99, false);
1381 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1382 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1383 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1385 $timedst +
= $dst_hour * HOURSECS +
$dst_min * MINSECS
;
1386 $timestd +
= $std_hour * HOURSECS +
$std_min * MINSECS
;
1388 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1391 // $time must NOT be compensated at all, it has to be a pure timestamp
1392 function dst_offset_on($time) {
1395 if(!calculate_user_dst_table() ||
empty($SESSION->dst_offsets
)) {
1399 reset($SESSION->dst_offsets
);
1400 while(list($from, $offset) = each($SESSION->dst_offsets
)) {
1401 if($from <= $time) {
1406 // This is the normal return path
1407 if($offset !== NULL) {
1411 // Reaching this point means we haven't calculated far enough, do it now:
1412 // Calculate extra DST changes if needed and recurse. The recursion always
1413 // moves toward the stopping condition, so will always end.
1416 // We need a year smaller than $SESSION->dst_range[0]
1417 if($SESSION->dst_range
[0] == 1971) {
1420 calculate_user_dst_table($SESSION->dst_range
[0] - 5, NULL);
1421 return dst_offset_on($time);
1424 // We need a year larger than $SESSION->dst_range[1]
1425 if($SESSION->dst_range
[1] == 2035) {
1428 calculate_user_dst_table(NULL, $SESSION->dst_range
[1] +
5);
1429 return dst_offset_on($time);
1433 function find_day_in_month($startday, $weekday, $month, $year) {
1435 $daysinmonth = days_in_month($month, $year);
1437 if($weekday == -1) {
1438 // Don't care about weekday, so return:
1439 // abs($startday) if $startday != -1
1440 // $daysinmonth otherwise
1441 return ($startday == -1) ?
$daysinmonth : abs($startday);
1444 // From now on we 're looking for a specific weekday
1446 // Give "end of month" its actual value, since we know it
1447 if($startday == -1) {
1448 $startday = -1 * $daysinmonth;
1451 // Starting from day $startday, the sign is the direction
1455 $startday = abs($startday);
1456 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1458 // This is the last such weekday of the month
1459 $lastinmonth = $daysinmonth +
$weekday - $lastmonthweekday;
1460 if($lastinmonth > $daysinmonth) {
1464 // Find the first such weekday <= $startday
1465 while($lastinmonth > $startday) {
1469 return $lastinmonth;
1474 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
1476 $diff = $weekday - $indexweekday;
1481 // This is the first such weekday of the month equal to or after $startday
1482 $firstfromindex = $startday +
$diff;
1484 return $firstfromindex;
1490 * Calculate the number of days in a given month
1492 * @param int $month The month whose day count is sought
1493 * @param int $year The year of the month whose day count is sought
1496 function days_in_month($month, $year) {
1497 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1501 * Calculate the position in the week of a specific calendar day
1503 * @param int $day The day of the date whose position in the week is sought
1504 * @param int $month The month of the date whose position in the week is sought
1505 * @param int $year The year of the date whose position in the week is sought
1508 function dayofweek($day, $month, $year) {
1509 // I wonder if this is any different from
1510 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1511 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1514 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
1517 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1518 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1519 * sesskey string if $USER exists, or boolean false if not.
1524 function sesskey() {
1531 if (empty($USER->sesskey
)) {
1532 $USER->sesskey
= random_string(10);
1535 return $USER->sesskey
;
1540 * For security purposes, this function will check that the currently
1541 * given sesskey (passed as a parameter to the script or this function)
1542 * matches that of the current user.
1544 * @param string $sesskey optionally provided sesskey
1547 function confirm_sesskey($sesskey=NULL) {
1550 if (!empty($USER->ignoresesskey
) ||
!empty($CFG->ignoresesskey
)) {
1554 if (empty($sesskey)) {
1555 $sesskey = required_param('sesskey', PARAM_RAW
); // Check script parameters
1558 if (!isset($USER->sesskey
)) {
1562 return ($USER->sesskey
=== $sesskey);
1566 * Setup all global $CFG course variables, set locale and also themes
1567 * This function can be used on pages that do not require login instead of require_login()
1569 * @param mixed $courseorid id of the course or course object
1571 function course_setup($courseorid=0) {
1572 global $COURSE, $CFG, $SITE;
1574 /// Redefine global $COURSE if needed
1575 if (empty($courseorid)) {
1576 // no change in global $COURSE - for backwards compatibiltiy
1577 // if require_rogin() used after require_login($courseid);
1578 } else if (is_object($courseorid)) {
1579 $COURSE = clone($courseorid);
1581 global $course; // used here only to prevent repeated fetching from DB - may be removed later
1582 if (!empty($course->id
) and $course->id
== SITEID
) {
1583 $COURSE = clone($SITE);
1584 } else if (!empty($course->id
) and $course->id
== $courseorid) {
1585 $COURSE = clone($course);
1587 if (!$COURSE = get_record('course', 'id', $courseorid)) {
1588 error('Invalid course ID');
1593 /// set locale and themes
1600 * This function checks that the current user is logged in and has the
1601 * required privileges
1603 * This function checks that the current user is logged in, and optionally
1604 * whether they are allowed to be in a particular course and view a particular
1606 * If they are not logged in, then it redirects them to the site login unless
1607 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
1608 * case they are automatically logged in as guests.
1609 * If $courseid is given and the user is not enrolled in that course then the
1610 * user is redirected to the course enrolment page.
1611 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1612 * in the course then the user is redirected to the course home page.
1620 * @param mixed $courseorid id of the course or course object
1621 * @param bool $autologinguest
1622 * @param object $cm course module object
1624 function require_login($courseorid=0, $autologinguest=true, $cm=null) {
1626 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
1628 /// setup global $COURSE, themes, language and locale
1629 course_setup($courseorid);
1631 /// If the user is not even logged in yet then make sure they are
1632 if (!isloggedin()) {
1633 //NOTE: $USER->site check was obsoleted by session test cookie,
1634 // $USER->confirmed test is in login/index.php
1635 $SESSION->wantsurl
= $FULLME;
1636 if (!empty($_SERVER['HTTP_REFERER'])) {
1637 $SESSION->fromurl
= $_SERVER['HTTP_REFERER'];
1639 if ($autologinguest and !empty($CFG->guestloginbutton
) and !empty($CFG->autologinguests
) and ($COURSE->id
== SITEID
or $COURSE->guest
) ) {
1640 $loginguest = '?loginguest=true';
1644 if (empty($CFG->loginhttps
) or $loginguest) { //do not require https for guest logins
1645 redirect($CFG->wwwroot
.'/login/index.php'. $loginguest);
1647 $wwwroot = str_replace('http:','https:', $CFG->wwwroot
);
1648 redirect($wwwroot .'/login/index.php');
1653 /// loginas as redirection if needed
1654 if ($COURSE->id
!= SITEID
and !empty($USER->realuser
)) {
1655 if ($USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
1656 if ($USER->loginascontext
->instanceid
!= $COURSE->id
) {
1657 print_error('loginasonecourse', '', $CFG->wwwroot
.'/course/view.php?id='.$USER->loginascontext
->instanceid
);
1663 /// check whether the user should be changing password (but only if it is REALLY them)
1664 $userauth = get_auth_plugin($USER->auth
);
1665 if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser
)) {
1666 if ($userauth->can_change_password()) {
1667 $SESSION->wantsurl
= $FULLME;
1668 if ($changeurl = $userauth->change_password_url()) {
1669 //use plugin custom url
1670 redirect($changeurl);
1672 //use moodle internal method
1673 if (empty($CFG->loginhttps
)) {
1674 redirect($CFG->wwwroot
.'/login/change_password.php');
1676 $wwwroot = str_replace('http:','https:', $CFG->wwwroot
);
1677 redirect($wwwroot .'/login/change_password.php');
1681 error(get_string('nopasswordchangeforced', 'auth'));
1685 /// Check that the user account is properly set up
1686 if (user_not_fully_set_up($USER)) {
1687 $SESSION->wantsurl
= $FULLME;
1688 redirect($CFG->wwwroot
.'/user/edit.php?id='. $USER->id
.'&course='. SITEID
);
1691 /// Make sure current IP matches the one for this session (if required)
1692 if (!empty($CFG->tracksessionip
)) {
1693 if ($USER->sessionIP
!= md5(getremoteaddr())) {
1694 error(get_string('sessionipnomatch', 'error'));
1698 /// Make sure the USER has a sesskey set up. Used for checking script parameters.
1701 // Check that the user has agreed to a site policy if there is one
1702 if (!empty($CFG->sitepolicy
)) {
1703 if (!$USER->policyagreed
) {
1704 $SESSION->wantsurl
= $FULLME;
1705 redirect($CFG->wwwroot
.'/user/policy.php');
1709 /// If the site is currently under maintenance, then print a message
1710 if (!has_capability('moodle/site:config',get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
1711 if (file_exists($CFG->dataroot
.'/'.SITEID
.'/maintenance.html')) {
1712 print_maintenance_message();
1718 if ($COURSE->id
== SITEID
) {
1719 /// We can eliminate hidden site activities straight away
1720 if (!empty($cm) && !$cm->visible
and !has_capability('moodle/course:viewhiddenactivities',
1721 get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
1722 redirect($CFG->wwwroot
, get_string('activityiscurrentlyhidden'));
1727 /// Check if the user can be in a particular course
1728 if (!$context = get_context_instance(CONTEXT_COURSE
, $COURSE->id
)) {
1729 print_error('nocontext');
1732 if (empty($USER->switchrole
[$context->id
]) &&
1733 !($COURSE->visible
&& course_parent_visible($COURSE)) &&
1734 !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $COURSE->id
)) ){
1735 print_header_simple();
1736 notice(get_string('coursehidden'), $CFG->wwwroot
.'/');
1739 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1741 if ($USER->username
!= 'guest' and !has_capability('moodle/course:view', $context)) {
1742 if ($COURSE->guest
== 1) {
1743 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
1744 has_capability('clearcache'); // Must clear cache
1745 $guestcaps = get_role_context_caps($CFG->guestroleid
, $context);
1746 $USER->capabilities
= merge_role_caps($USER->capabilities
, $guestcaps);
1750 /// If the user is a guest then treat them according to the course policy about guests
1752 if (has_capability('moodle/legacy:guest', $context, NULL, false)) {
1753 switch ($COURSE->guest
) { /// Check course policy about guest access
1755 case 1: /// Guests always allowed
1756 if (!has_capability('moodle/course:view', $context)) { // Prohibited by capability
1757 print_header_simple();
1758 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)), "$CFG->wwwroot/login/index.php");
1760 if (!empty($cm) and !$cm->visible
) { // Not allowed to see module, send to course page
1761 redirect($CFG->wwwroot
.'/course/view.php?id='.$cm->course
,
1762 get_string('activityiscurrentlyhidden'));
1765 return; // User is allowed to see this course
1769 case 2: /// Guests allowed with key
1770 if (!empty($USER->enrolkey
[$COURSE->id
])) { // Set by enrol/manual/enrol.php
1773 // otherwise drop through to logic below (--> enrol.php)
1776 default: /// Guests not allowed
1777 print_header_simple('', '', get_string('loggedinasguest'));
1778 if (empty($USER->switchrole
[$context->id
])) { // Normal guest
1779 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)), "$CFG->wwwroot/login/index.php");
1781 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname
)));
1782 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id
).'</div>';
1783 print_footer($COURSE);
1789 /// For non-guests, check if they have course view access
1791 } else if (has_capability('moodle/course:view', $context)) {
1792 if (!empty($USER->realuser
)) { // Make sure the REAL person can also access this course
1793 if (!has_capability('moodle/course:view', $context, $USER->realuser
)) {
1794 print_header_simple();
1795 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot
.'/');
1799 /// Make sure they can read this activity too, if specified
1801 if (!empty($cm) and !$cm->visible
and !has_capability('moodle/course:viewhiddenactivities', $context)) {
1802 redirect($CFG->wwwroot
.'/course/view.php?id='.$cm->course
, get_string('activityiscurrentlyhidden'));
1804 return; // User is allowed to see this course
1809 /// Currently not enrolled in the course, so see if they want to enrol
1810 $SESSION->wantsurl
= $FULLME;
1811 redirect($CFG->wwwroot
.'/course/enrol.php?id='. $COURSE->id
);
1819 * This function just makes sure a user is logged out.
1824 function require_logout() {
1826 global $USER, $CFG, $SESSION;
1829 add_to_log(SITEID
, "user", "logout", "view.php?id=$USER->id&course=".SITEID
, $USER->id
, 0, $USER->id
);
1831 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
1832 foreach($authsequence as $authname) {
1833 $authplugin = get_auth_plugin($authname);
1834 $authplugin->prelogout_hook();
1838 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
1839 // This method is just to try to avoid silly warnings from PHP 4.3.0
1840 session_unregister("USER");
1841 session_unregister("SESSION");
1844 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
1845 $file = $line = null;
1846 if (headers_sent($file, $line)) {
1847 error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__
);
1848 error_log('Headers were already sent in file: '.$file.' on line '.$line);
1850 setcookie('MoodleSessionTest'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
1853 unset($_SESSION['USER']);
1854 unset($_SESSION['SESSION']);
1862 * This is a weaker version of {@link require_login()} which only requires login
1863 * when called from within a course rather than the site page, unless
1864 * the forcelogin option is turned on.
1867 * @param mixed $courseorid The course object or id in question
1868 * @param bool $autologinguest Allow autologin guests if that is wanted
1869 * @param object $cm Course activity module if known
1871 function require_course_login($courseorid, $autologinguest=true, $cm=null) {
1873 if (!empty($CFG->forcelogin
)) {
1874 // login required for both SITE and courses
1875 require_login($courseorid, $autologinguest, $cm);
1877 } else if (!empty($cm) and !$cm->visible
) {
1878 // always login for hidden activities
1879 require_login($courseorid, $autologinguest, $cm);
1881 } else if ((is_object($courseorid) and $courseorid->id
== SITEID
)
1882 or (!is_object($courseorid) and $courseorid == SITEID
)) {
1883 //login for SITE not required
1887 // course login always required
1888 require_login($courseorid, $autologinguest, $cm);
1893 * Modify the user table by setting the currently logged in user's
1894 * last login to now.
1899 function update_user_login_times() {
1902 $user = new object();
1903 $USER->lastlogin
= $user->lastlogin
= $USER->currentlogin
;
1904 $USER->currentlogin
= $user->lastaccess
= $user->currentlogin
= time();
1906 $user->id
= $USER->id
;
1908 return update_record('user', $user);
1912 * Determines if a user has completed setting up their account.
1914 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
1917 function user_not_fully_set_up($user) {
1918 return ($user->username
!= 'guest' and (empty($user->firstname
) or empty($user->lastname
) or empty($user->email
) or over_bounce_threshold($user)));
1921 function over_bounce_threshold($user) {
1925 if (empty($CFG->handlebounces
)) {
1928 // set sensible defaults
1929 if (empty($CFG->minbounces
)) {
1930 $CFG->minbounces
= 10;
1932 if (empty($CFG->bounceratio
)) {
1933 $CFG->bounceratio
= .20;
1937 if ($bounce = get_record('user_preferences','userid',$user->id
,'name','email_bounce_count')) {
1938 $bouncecount = $bounce->value
;
1940 if ($send = get_record('user_preferences','userid',$user->id
,'name','email_send_count')) {
1941 $sendcount = $send->value
;
1943 return ($bouncecount >= $CFG->minbounces
&& $bouncecount/$sendcount >= $CFG->bounceratio
);
1947 * @param $user - object containing an id
1948 * @param $reset - will reset the count to 0
1950 function set_send_count($user,$reset=false) {
1951 if ($pref = get_record('user_preferences','userid',$user->id
,'name','email_send_count')) {
1952 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
1953 update_record('user_preferences',$pref);
1955 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1957 $pref->name
= 'email_send_count';
1959 $pref->userid
= $user->id
;
1960 insert_record('user_preferences',$pref, false);
1965 * @param $user - object containing an id
1966 * @param $reset - will reset the count to 0
1968 function set_bounce_count($user,$reset=false) {
1969 if ($pref = get_record('user_preferences','userid',$user->id
,'name','email_bounce_count')) {
1970 $pref->value
= (!empty($reset)) ?
0 : $pref->value+
1;
1971 update_record('user_preferences',$pref);
1973 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1975 $pref->name
= 'email_bounce_count';
1977 $pref->userid
= $user->id
;
1978 insert_record('user_preferences',$pref, false);
1983 * Keeps track of login attempts
1987 function update_login_count() {
1993 if (empty($SESSION->logincount
)) {
1994 $SESSION->logincount
= 1;
1996 $SESSION->logincount++
;
1999 if ($SESSION->logincount
> $max_logins) {
2000 unset($SESSION->wantsurl
);
2001 error(get_string('errortoomanylogins'));
2006 * Resets login attempts
2010 function reset_login_count() {
2013 $SESSION->logincount
= 0;
2016 function sync_metacourses() {
2020 if (!$courses = get_records('course', 'metacourse', 1)) {
2024 foreach ($courses as $course) {
2025 sync_metacourse($course);
2030 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
2032 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
2034 function sync_metacourse($course) {
2037 // Check the course is valid.
2038 if (!is_object($course)) {
2039 if (!$course = get_record('course', 'id', $course)) {
2040 return false; // invalid course id
2044 // Check that we actually have a metacourse.
2045 if (empty($course->metacourse
)) {
2049 // Get a list of roles that should not be synced.
2050 if (!empty($CFG->nonmetacoursesyncroleids
)) {
2051 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids
. ') AND';
2053 $roleexclusions = '';
2056 // Get the context of the metacourse.
2057 $context = get_context_instance(CONTEXT_COURSE
, $course->id
); // SITEID can not be a metacourse
2059 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
2060 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
2061 $managers = array_keys($users);
2063 $managers = array();
2066 // Get assignments of a user to a role that exist in a child course, but
2067 // not in the meta coure. That is, get a list of the assignments that need to be made.
2068 if (!$assignments = get_records_sql("
2070 ra.id, ra.roleid, ra.userid
2072 {$CFG->prefix}role_assignments ra,
2073 {$CFG->prefix}context con,
2074 {$CFG->prefix}course_meta cm
2076 ra.contextid = con.id AND
2077 con.contextlevel = " . CONTEXT_COURSE
. " AND
2078 con.instanceid = cm.child_course AND
2079 cm.parent_course = {$course->id} AND
2083 {$CFG->prefix}role_assignments ra2
2085 ra2.userid = ra.userid AND
2086 ra2.roleid = ra.roleid AND
2087 ra2.contextid = {$context->id}
2090 $assignments = array();
2093 // Get assignments of a user to a role that exist in the meta course, but
2094 // not in any child courses. That is, get a list of the unassignments that need to be made.
2095 if (!$unassignments = get_records_sql("
2097 ra.id, ra.roleid, ra.userid
2099 {$CFG->prefix}role_assignments ra
2101 ra.contextid = {$context->id} AND
2105 {$CFG->prefix}role_assignments ra2,
2106 {$CFG->prefix}context con2,
2107 {$CFG->prefix}course_meta cm
2109 ra2.userid = ra.userid AND
2110 ra2.roleid = ra.roleid AND
2111 ra2.contextid = con2.id AND
2112 con2.contextlevel = " . CONTEXT_COURSE
. " AND
2113 con2.instanceid = cm.child_course AND
2114 cm.parent_course = {$course->id}
2117 $unassignments = array();
2122 // Make the unassignments, if they are not managers.
2123 foreach ($unassignments as $unassignment) {
2124 if (!in_array($unassignment->userid
, $managers)) {
2125 $success = role_unassign($unassignment->roleid
, $unassignment->userid
, 0, $context->id
) && $success;
2129 // Make the assignments.
2130 foreach ($assignments as $assignment) {
2131 $success = role_assign($assignment->roleid
, $assignment->userid
, 0, $context->id
) && $success;
2136 // TODO: finish timeend and timestart
2137 // maybe we could rely on cron job to do the cleaning from time to time
2141 * Adds a record to the metacourse table and calls sync_metacoures
2143 function add_to_metacourse ($metacourseid, $courseid) {
2145 if (!$metacourse = get_record("course","id",$metacourseid)) {
2149 if (!$course = get_record("course","id",$courseid)) {
2153 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
2154 $rec = new object();
2155 $rec->parent_course
= $metacourseid;
2156 $rec->child_course
= $courseid;
2157 if (!insert_record('course_meta',$rec)) {
2160 return sync_metacourse($metacourseid);
2167 * Removes the record from the metacourse table and calls sync_metacourse
2169 function remove_from_metacourse($metacourseid, $courseid) {
2171 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
2172 return sync_metacourse($metacourseid);
2179 * Determines if a user is currently logged in
2184 function isloggedin() {
2187 return (!empty($USER->id
));
2191 * Determines if a user is logged in as real guest user with username 'guest'.
2192 * This function is similar to original isguest() in 1.6 and earlier.
2193 * Current isguest() is deprecated - do not use it anymore.
2195 * @param $user mixed user object or id, $USER if not specified
2196 * @return bool true if user is the real guest user, false if not logged in or other user
2198 function isguestuser($user=NULL) {
2200 if ($user === NULL) {
2202 } else if (is_numeric($user)) {
2203 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2206 if (empty($user->id
)) {
2207 return false; // not logged in, can not be guest
2210 return ($user->username
== 'guest');
2214 * Determines if the currently logged in user is in editing mode
2217 * @param int $courseid The id of the course being tested
2218 * @param user $user A {@link $USER} object. If null then the currently logged in user is used.
2221 function isediting($courseid, $user=NULL) {
2226 if (empty($user->editing
)) {
2231 $coursecontext = get_context_instance(CONTEXT_COURSE
, $courseid);
2233 if (has_capability('moodle/course:manageactivities', $coursecontext) ||
2234 has_capability('moodle/site:manageblocks', $coursecontext)) {
2237 // loop through all child context, see if user has moodle/course:manageactivities or moodle/site:manageblocks
2238 if ($children = get_child_contexts($coursecontext)) {
2239 foreach ($children as $child) {
2240 $childcontext = get_record('context', 'id', $child);
2241 if (has_capability('moodle/course:manageactivities', $childcontext) ||
2242 has_capability('moodle/site:manageblocks', $childcontext)) {
2250 return ($user->editing
&& $capcheck);
2251 //return ($user->editing and has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $courseid)));
2255 * Determines if the logged in user is currently moving an activity
2258 * @param int $courseid The id of the course being tested
2261 function ismoving($courseid) {
2264 if (!empty($USER->activitycopy
)) {
2265 return ($USER->activitycopycourse
== $courseid);
2271 * Given an object containing firstname and lastname
2272 * values, this function returns a string with the
2273 * full name of the person.
2274 * The result may depend on system settings
2275 * or language. 'override' will force both names
2276 * to be used even if system settings specify one.
2280 * @param object $user A {@link $USER} object to get full name of
2281 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
2283 function fullname($user, $override=false) {
2285 global $CFG, $SESSION;
2287 if (!isset($user->firstname
) and !isset($user->lastname
)) {
2292 if (!empty($CFG->forcefirstname
)) {
2293 $user->firstname
= $CFG->forcefirstname
;
2295 if (!empty($CFG->forcelastname
)) {
2296 $user->lastname
= $CFG->forcelastname
;
2300 if (!empty($SESSION->fullnamedisplay
)) {
2301 $CFG->fullnamedisplay
= $SESSION->fullnamedisplay
;
2304 if ($CFG->fullnamedisplay
== 'firstname lastname') {
2305 return $user->firstname
.' '. $user->lastname
;
2307 } else if ($CFG->fullnamedisplay
== 'lastname firstname') {
2308 return $user->lastname
.' '. $user->firstname
;
2310 } else if ($CFG->fullnamedisplay
== 'firstname') {
2312 return get_string('fullnamedisplay', '', $user);
2314 return $user->firstname
;
2318 return get_string('fullnamedisplay', '', $user);
2322 * Sets a moodle cookie with an encrypted string
2327 * @param string $thing The string to encrypt and place in a cookie
2329 function set_moodle_cookie($thing) {
2332 if ($thing == 'guest') { // Ignore guest account
2336 $cookiename = 'MOODLEID_'.$CFG->sessioncookie
;
2339 $seconds = DAYSECS
*$days;
2341 setCookie($cookiename, '', time() - HOURSECS
, '/');
2342 setCookie($cookiename, rc4encrypt($thing), time()+
$seconds, '/');
2346 * Gets a moodle cookie with an encrypted string
2351 function get_moodle_cookie() {
2354 $cookiename = 'MOODLEID_'.$CFG->sessioncookie
;
2356 if (empty($_COOKIE[$cookiename])) {
2359 $thing = rc4decrypt($_COOKIE[$cookiename]);
2360 return ($thing == 'guest') ?
'': $thing; // Ignore guest account
2365 * Returns whether a given authentication plugin exists.
2368 * @param string $auth Form of authentication to check for. Defaults to the
2369 * global setting in {@link $CFG}.
2370 * @return boolean Whether the plugin is available.
2372 function exists_auth_plugin($auth) {
2375 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2376 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2382 * Checks if a given plugin is in the list of enabled authentication plugins.
2384 * @param string $auth Authentication plugin.
2385 * @return boolean Whether the plugin is enabled.
2387 function is_enabled_auth($auth) {
2392 $enabled = get_enabled_auth_plugins();
2394 return in_array($auth, $enabled);
2398 * Returns an authentication plugin instance.
2401 * @param string $auth name of authentication plugin
2402 * @return object An instance of the required authentication plugin.
2404 function get_auth_plugin($auth) {
2407 // check the plugin exists first
2408 if (! exists_auth_plugin($auth)) {
2409 error("Authentication plugin '$auth' not found.");
2412 // return auth plugin instance
2413 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2414 $class = "auth_plugin_$auth";
2419 * Returns array of active auth plugins.
2421 * @param bool $fix fix $CFG->auth if needed
2424 function get_enabled_auth_plugins($fix=false) {
2427 $default = array('manual', 'nologin');
2429 if (empty($CFG->auth
)) {
2432 $auths = explode(',', $CFG->auth
);
2436 $auths = array_unique($auths);
2437 foreach($auths as $k=>$authname) {
2438 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
2442 $newconfig = implode(',', $auths);
2443 if (!isset($CFG->auth
) or $newconfig != $CFG->auth
) {
2444 set_config('auth', $newconfig);
2448 return (array_merge($default, $auths));
2452 * Returns true if an internal authentication method is being used.
2453 * if method not specified then, global default is assumed
2456 * @param string $auth Form of authentication required
2459 function is_internal_auth($auth) {
2460 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2461 return $authplugin->is_internal();
2465 * Returns an array of user fields
2469 * @return array User field/column names
2471 function get_user_fieldnames() {
2475 $fieldarray = $db->MetaColumnNames($CFG->prefix
.'user');
2476 unset($fieldarray['ID']);
2482 * Creates the default "guest" user. Used both from
2483 * admin/index.php and login/index.php
2484 * @return mixed user object created or boolean false if the creation has failed
2486 function create_guest_record() {
2490 $guest->auth
= 'manual';
2491 $guest->username
= 'guest';
2492 $guest->password
= hash_internal_user_password('guest');
2493 $guest->firstname
= addslashes(get_string('guestuser'));
2494 $guest->lastname
= ' ';
2495 $guest->email
= 'root@localhost';
2496 $guest->description
= addslashes(get_string('guestuserinfo'));
2497 $guest->mnethostid
= $CFG->mnet_localhost_id
;
2498 $guest->confirmed
= 1;
2499 $guest->lang
= $CFG->lang
;
2500 $guest->timemodified
= time();
2502 if (! $guest->id
= insert_record("user", $guest)) {
2510 * Creates a bare-bones user record
2513 * @param string $username New user's username to add to record
2514 * @param string $password New user's password to add to record
2515 * @param string $auth Form of authentication required
2516 * @return object A {@link $USER} object
2517 * @todo Outline auth types and provide code example
2519 function create_user_record($username, $password, $auth='manual') {
2522 //just in case check text case
2523 $username = trim(moodle_strtolower($username));
2525 $authplugin = get_auth_plugin($auth);
2527 if ($newinfo = $authplugin->get_userinfo($username)) {
2528 $newinfo = truncate_userinfo($newinfo);
2529 foreach ($newinfo as $key => $value){
2530 $newuser->$key = addslashes($value);
2534 if (!empty($newuser->email
)) {
2535 if (email_is_not_allowed($newuser->email
)) {
2536 unset($newuser->email
);
2540 $newuser->auth
= $auth;
2541 $newuser->username
= $username;
2544 // user CFG lang for user if $newuser->lang is empty
2545 // or $user->lang is not an installed language
2546 $sitelangs = array_keys(get_list_of_languages());
2547 if (empty($newuser->lang
) ||
!in_array($newuser->lang
, $sitelangs)) {
2548 $newuser -> lang
= $CFG->lang
;
2550 $newuser->confirmed
= 1;
2551 $newuser->lastip
= getremoteaddr();
2552 $newuser->timemodified
= time();
2553 $newuser->mnethostid
= $CFG->mnet_localhost_id
;
2555 if (insert_record('user', $newuser)) {
2556 $user = get_complete_user_data('username', $newuser->username
);
2557 if(!empty($CFG->{'auth_'.$newuser->auth
.'_forcechangepassword'})){
2558 set_user_preference('auth_forcepasswordchange', 1, $user->id
);
2560 update_internal_user_password($user, $password);
2567 * Will update a local user record from an external source
2570 * @param string $username New user's username to add to record
2571 * @return user A {@link $USER} object
2573 function update_user_record($username, $authplugin) {
2574 $username = trim(moodle_strtolower($username)); /// just in case check text case
2576 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2577 $userauth = get_auth_plugin($oldinfo->auth
);
2579 if ($newinfo = $userauth->get_userinfo($username)) {
2580 $newinfo = truncate_userinfo($newinfo);
2581 foreach ($newinfo as $key => $value){
2582 $confkey = 'field_updatelocal_' . $key;
2583 if (!empty($userauth->config
->$confkey) and $userauth->config
->$confkey === 'onlogin') {
2584 $value = addslashes(stripslashes($value)); // Just in case
2585 set_field('user', $key, $value, 'username', $username)
2586 or error_log("Error updating $key for $username");
2591 return get_complete_user_data('username', $username);
2594 function truncate_userinfo($info) {
2595 /// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2596 /// which may have large fields
2598 // define the limits
2608 'institution' => 40,
2616 // apply where needed
2617 foreach (array_keys($info) as $key) {
2618 if (!empty($limit[$key])) {
2619 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
2627 * Retrieve the guest user object
2630 * @return user A {@link $USER} object
2632 function guest_user() {
2635 if ($newuser = get_record('user', 'username', 'guest', 'mnethostid', $CFG->mnet_localhost_id
)) {
2636 $newuser->confirmed
= 1;
2637 $newuser->lang
= $CFG->lang
;
2638 $newuser->lastip
= getremoteaddr();
2645 * Given a username and password, this function looks them
2646 * up using the currently selected authentication mechanism,
2647 * and if the authentication is successful, it returns a
2648 * valid $user object from the 'user' table.
2650 * Uses auth_ functions from the currently active auth module
2653 * @param string $username User's username (with system magic quotes)
2654 * @param string $password User's password (with system magic quotes)
2655 * @return user|flase A {@link $USER} object or false if error
2657 function authenticate_user_login($username, $password) {
2661 $authsenabled = get_enabled_auth_plugins();
2663 if ($user = get_complete_user_data('username', $username)) {
2664 $auth = empty($user->auth
) ?
'manual' : $user->auth
; // use manual if auth not set
2665 if ($auth=='nologin' or !is_enabled_auth($auth)) {
2666 add_to_log(0, 'login', 'error', 'index.php', $username);
2667 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2670 if (!empty($user->deleted
)) {
2671 add_to_log(0, 'login', 'error', 'index.php', $username);
2672 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2675 $auths = array($auth);
2678 $auths = $authsenabled;
2679 $user = new object();
2680 $user->id
= 0; // User does not exist
2683 foreach ($auths as $auth) {
2684 $authplugin = get_auth_plugin($auth);
2686 // on auth fail fall through to the next plugin
2687 if (!$authplugin->user_login($username, $password)) {
2691 // successful authentication
2692 if ($user->id
) { // User already exists in database
2693 if (empty($user->auth
)) { // For some reason auth isn't set yet
2694 set_field('user', 'auth', $auth, 'username', $username);
2695 $user->auth
= $auth;
2698 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
2700 if (!$authplugin->is_internal()) { // update user record from external DB
2701 $user = update_user_record($username, get_auth_plugin($user->auth
));
2704 // if user not found, create him
2705 $user = create_user_record($username, $password, $auth);
2708 $authplugin->sync_roles($user);
2710 foreach ($authsenabled as $hau) {
2711 $hauth = get_auth_plugin($hau);
2712 $hauth->user_authenticated_hook($user, $username, $password);
2715 /// Log in to a second system if necessary
2716 /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
2717 if (!empty($CFG->sso
)) {
2718 include_once($CFG->dirroot
.'/sso/'. $CFG->sso
.'/lib.php');
2719 if (function_exists('sso_user_login')) {
2720 if (!sso_user_login($username, $password)) { // Perform the signon process
2721 notify('Second sign-on failed');
2730 // failed if all the plugins have failed
2731 add_to_log(0, 'login', 'error', 'index.php', $username);
2732 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2737 * Compare password against hash stored in internal user table.
2738 * If necessary it also updates the stored hash to new format.
2740 * @param object user
2741 * @param string plain text password
2742 * @return bool is password valid?
2744 function validate_internal_user_password(&$user, $password) {
2747 if (!isset($CFG->passwordsaltmain
)) {
2748 $CFG->passwordsaltmain
= '';
2753 // get password original encoding in case it was not updated to unicode yet
2754 $textlib = textlib_get_instance();
2755 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
2757 if ($user->password
== md5($password.$CFG->passwordsaltmain
) or $user->password
== md5($password)
2758 or $user->password
== md5($convpassword.$CFG->passwordsaltmain
) or $user->password
== md5($convpassword)) {
2761 for ($i=1; $i<=20; $i++
) { //20 alternative salts should be enough, right?
2762 $alt = 'passwordsaltalt'.$i;
2763 if (!empty($CFG->$alt)) {
2764 if ($user->password
== md5($password.$CFG->$alt) or $user->password
== md5($convpassword.$CFG->$alt)) {
2773 // force update of password hash using latest main password salt and encoding if needed
2774 update_internal_user_password($user, $password);
2781 * Calculate hashed value from password using current hash mechanism.
2783 * @param string password
2784 * @return string password hash
2786 function hash_internal_user_password($password) {
2789 if (isset($CFG->passwordsaltmain
)) {
2790 return md5($password.$CFG->passwordsaltmain
);
2792 return md5($password);
2797 * Update pssword hash in user object.
2799 * @param object user
2800 * @param string plain text password
2801 * @param bool store changes also in db, default true
2802 * @return true if hash changed
2804 function update_internal_user_password(&$user, $password) {
2807 $authplugin = get_auth_plugin($user->auth
);
2808 if (!empty($authplugin->config
->preventpassindb
)) {
2809 $hashedpassword = 'not cached';
2811 $hashedpassword = hash_internal_user_password($password);
2814 return set_field('user', 'password', $hashedpassword, 'id', $user->id
);
2818 * Get a complete user record, which includes all the info
2819 * in the user record
2820 * Intended for setting as $USER session variable
2824 * @param string $field The user field to be checked for a given value.
2825 * @param string $value The value to match for $field.
2826 * @return user A {@link $USER} object.
2828 function get_complete_user_data($field, $value, $mnethostid=null) {
2832 if (!$field ||
!$value) {
2836 /// Build the WHERE clause for an SQL query
2838 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
2840 if (is_null($mnethostid)) {
2841 // if null, we restrict to local users
2842 // ** testing for local user can be done with
2843 // mnethostid = $CFG->mnet_localhost_id
2846 // but the first one is FAST with our indexes
2847 $mnethostid = $CFG->mnet_localhost_id
;
2849 $mnethostid = (int)$mnethostid;
2850 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
2852 /// Get all the basic user data
2854 if (! $user = get_record_select('user', $constraints)) {
2858 /// Get various settings and preferences
2860 if ($displays = get_records('course_display', 'userid', $user->id
)) {
2861 foreach ($displays as $display) {
2862 $user->display
[$display->course
] = $display->display
;
2866 $user->preference
= get_user_preferences(null, null, $user->id
);
2868 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id
)) {
2869 foreach ($lastaccesses as $lastaccess) {
2870 $user->lastcourseaccess
[$lastaccess->courseid
] = $lastaccess->timeaccess
;
2874 if ($groupids = groups_get_all_groups_for_user($user->id
)) { //TODO:check.
2875 foreach ($groupids as $groupid) {
2876 $courseid = groups_get_course($groupid);
2877 //change this to 2D array so we can put multiple groups in a course
2878 $user->groupmember
[$courseid][] = $groupid;
2882 /// Rewrite some variables if necessary
2883 if (!empty($user->description
)) {
2884 $user->description
= true; // No need to cart all of it around
2886 if ($user->username
== 'guest') {
2887 $user->lang
= $CFG->lang
; // Guest language always same as site
2888 $user->firstname
= get_string('guestuser'); // Name always in current language
2889 $user->lastname
= ' ';
2892 $user->sesskey
= random_string(10);
2893 $user->sessionIP
= md5(getremoteaddr()); // Store the current IP in the session
2900 * @param string $password the password to be checked agains the password policy
2901 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
2902 * @return bool true if the password is valid according to the policy. false otherwise.
2904 function check_password_policy($password, &$errmsg) {
2907 if (empty($CFG->passwordpolicy
)) {
2911 $textlib = new textlib();
2913 if ($textlib->strlen($password) < $CFG->minpasswordlength
) {
2914 $errmsg = get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength
);
2916 } else if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits
) {
2917 $errmsg = get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits
);
2919 } else if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower
) {
2920 $errmsg = get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower
);
2922 } else if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper
) {
2923 $errmsg = get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper
);
2925 } else if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum
) {
2926 $errmsg = get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum
);
2928 } else if ($password == 'admin' or $password == 'password') {
2929 $errmsg = get_string('unsafepassword');
2932 if ($errmsg == '') {
2941 * When logging in, this function is run to set certain preferences
2942 * for the current SESSION
2944 function set_login_session_preferences() {
2945 global $SESSION, $CFG;
2947 $SESSION->justloggedin
= true;
2949 unset($SESSION->lang
);
2951 // Restore the calendar filters, if saved
2952 if (intval(get_user_preferences('calendar_persistflt', 0))) {
2953 include_once($CFG->dirroot
.'/calendar/lib.php');
2954 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
2960 * Delete a course, including all related data from the database,
2961 * and any associated files from the moodledata folder.
2963 * @param int $courseid The id of the course to delete.
2964 * @param bool $showfeedback Whether to display notifications of each action the function performs.
2965 * @return bool true if all the removals succeeded. false if there were any failures. If this
2966 * method returns false, some of the removals will probably have succeeded, and others
2967 * failed, but you have no way of knowing which.
2969 function delete_course($courseid, $showfeedback = true) {
2971 require_once($CFG->libdir
.'/gradelib.php');
2974 if (!remove_course_contents($courseid, $showfeedback)) {
2975 if ($showfeedback) {
2976 notify("An error occurred while deleting some of the course contents.");
2981 remove_course_grades($courseid, $showfeedback);
2983 if (!delete_records("course", "id", $courseid)) {
2984 if ($showfeedback) {
2985 notify("An error occurred while deleting the main course record.");
2990 if (!delete_records('context', 'contextlevel', CONTEXT_COURSE
, 'instanceid', $courseid)) {
2991 if ($showfeedback) {
2992 notify("An error occurred while deleting the main context record.");
2997 if (!fulldelete($CFG->dataroot
.'/'.$courseid)) {
2998 if ($showfeedback) {
2999 notify("An error occurred while deleting the course files.");
3008 * Clear a course out completely, deleting all content
3009 * but don't delete the course itself
3012 * @param int $courseid The id of the course that is being deleted
3013 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3014 * @return bool true if all the removals succeeded. false if there were any failures. If this
3015 * method returns false, some of the removals will probably have succeeded, and others
3016 * failed, but you have no way of knowing which.
3018 function remove_course_contents($courseid, $showfeedback=true) {
3024 if (! $course = get_record('course', 'id', $courseid)) {
3025 error('Course ID was incorrect (can\'t find it)');
3028 $strdeleted = get_string('deleted');
3030 /// First delete every instance of every module
3032 if ($allmods = get_records('modules') ) {
3033 foreach ($allmods as $mod) {
3034 $modname = $mod->name
;
3035 $modfile = $CFG->dirroot
.'/mod/'. $modname .'/lib.php';
3036 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
3037 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
3039 if (file_exists($modfile)) {
3040 include_once($modfile);
3041 if (function_exists($moddelete)) {
3042 if ($instances = get_records($modname, 'course', $course->id
)) {
3043 foreach ($instances as $instance) {
3044 if ($cm = get_coursemodule_from_instance($modname, $instance->id
, $course->id
)) {
3045 delete_context(CONTEXT_MODULE
, $cm->id
);
3047 if ($moddelete($instance->id
)) {
3051 notify('Could not delete '. $modname .' instance '. $instance->id
.' ('. format_string($instance->name
) .')');
3057 notify('Function '. $moddelete() .'doesn\'t exist!');
3061 if (function_exists($moddeletecourse)) {
3062 $moddeletecourse($course, $showfeedback);
3065 if ($showfeedback) {
3066 notify($strdeleted .' '. $count .' x '. $modname);
3070 error('No modules are installed!');
3073 /// Give local code a chance to delete its references to this course.
3074 require_once('locallib.php');
3075 notify_local_delete_course($courseid, $showfeedback);
3077 /// Delete course blocks
3079 if ($blocks = get_records_sql("SELECT *
3080 FROM {$CFG->prefix}block_instance
3081 WHERE pagetype = '".PAGE_COURSE_VIEW
."'
3082 AND pageid = $course->id")) {
3083 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW
, 'pageid', $course->id
)) {
3084 if ($showfeedback) {
3085 notify($strdeleted .' block_instance');
3088 require_once($CFG->libdir
.'/blocklib.php');
3089 foreach ($blocks as $block) { /// Delete any associated contexts for this block
3091 // Block instances are rarely created. Since the block instance is gone from the above delete
3092 // statement, calling delete_context() will generate a warning as get_context_instance could
3093 // no longer create the context as the block is already gone.
3094 if (record_exists('context', 'contextlevel', CONTEXT_BLOCK
, 'instanceid', $block->id
)) {
3095 delete_context(CONTEXT_BLOCK
, $block->id
);
3099 // Get the block object and call instance_delete()
3100 if (!$record = blocks_get_record($block->blockid
)) {
3104 if (!$obj = block_instance($record->name
, $block)) {
3108 // Return value ignored, in core mods this does not do anything, but just in case
3109 // third party blocks might have stuff to clean up
3110 // we execute this anyway
3111 $obj->instance_delete();
3118 /// Delete any groups, removing members and grouping/course links first.
3119 //TODO: If groups or groupings are to be shared between courses, think again!
3120 if ($groupids = groups_get_groups($course->id
)) {
3121 foreach ($groupids as $groupid) {
3122 if (groups_remove_all_members($groupid)) {
3123 if ($showfeedback) {
3124 notify($strdeleted .' groups_members');
3129 /// Delete any associated context for this group ??
3130 delete_context(CONTEXT_GROUP
, $groupid);
3132 if (groups_delete_group($groupid)) {
3133 if ($showfeedback) {
3134 notify($strdeleted .' groups');
3141 /// Delete any groupings.
3142 $result = groups_delete_all_groupings($course->id
);
3143 if ($result && $showfeedback) {
3144 notify($strdeleted .' groupings');
3147 /// Delete all related records in other tables that may have a courseid
3148 /// This array stores the tables that need to be cleared, as
3149 /// table_name => column_name that contains the course id.
3151 $tablestoclear = array(
3152 'event' => 'courseid', // Delete events
3153 'log' => 'course', // Delete logs
3154 'course_sections' => 'course', // Delete any course stuff
3155 'course_modules' => 'course',
3156 'backup_courses' => 'courseid', // Delete scheduled backup stuff
3157 'backup_log' => 'courseid'
3159 foreach ($tablestoclear as $table => $col) {
3160 if (delete_records($table, $col, $course->id
)) {
3161 if ($showfeedback) {
3162 notify($strdeleted . ' ' . $table);
3170 /// Clean up metacourse stuff
3172 if ($course->metacourse
) {
3173 delete_records("course_meta","parent_course",$course->id
);
3174 sync_metacourse($course->id
); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
3175 if ($showfeedback) {
3176 notify("$strdeleted course_meta");
3179 if ($parents = get_records("course_meta","child_course",$course->id
)) {
3180 foreach ($parents as $parent) {
3181 remove_from_metacourse($parent->parent_course
,$parent->child_course
); // this will do the unenrolments as well.
3183 if ($showfeedback) {
3184 notify("$strdeleted course_meta");
3189 /// Delete questions and question categories
3190 include_once($CFG->libdir
.'/questionlib.php');
3191 question_delete_course($course, $showfeedback);
3193 /// Delete all roles and overiddes in the course context (but keep the course context)
3194 if ($courseid != SITEID
) {
3195 delete_context(CONTEXT_COURSE
, $course->id
);
3199 // clear the cache because the course context is deleted, and
3200 // we don't want to write assignment, overrides and context_rel table
3201 // with this old context id!
3202 get_context_instance('clearcache');
3208 * This function will empty a course of USER data as much as
3209 /// possible. It will retain the activities and the structure
3215 * @param object $data an object containing all the boolean settings and courseid
3216 * @param bool $showfeedback if false then do it all silently
3218 * @todo Finish documenting this function
3220 function reset_course_userdata($data, $showfeedback=true) {
3222 global $CFG, $USER, $SESSION;
3226 $strdeleted = get_string('deleted');
3228 // Look in every instance of every module for data to delete
3230 if ($allmods = get_records('modules') ) {
3231 foreach ($allmods as $mod) {
3232 $modname = $mod->name
;
3233 $modfile = $CFG->dirroot
.'/mod/'. $modname .'/lib.php';
3234 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3235 if (file_exists($modfile)) {
3236 @include_once
($modfile);
3237 if (function_exists($moddeleteuserdata)) {
3238 $moddeleteuserdata($data, $showfeedback);
3243 error('No modules are installed!');
3246 // Delete other stuff
3247 $coursecontext = get_context_instance(CONTEXT_COURSE
, $data->courseid
);
3249 if (!empty($data->reset_students
) or !empty($data->reset_teachers
)) {
3250 $teachers = array_keys(get_users_by_capability($coursecontext, 'moodle/course:update'));
3251 $participants = array_keys(get_users_by_capability($coursecontext, 'moodle/course:view'));
3252 $students = array_diff($participants, $teachers);
3254 if (!empty($data->reset_students
)) {
3255 foreach ($students as $studentid) {
3256 role_unassign(0, $studentid, 0, $coursecontext->id
);
3258 if ($showfeedback) {
3259 notify($strdeleted .' '.get_string('students'), 'notifysuccess');
3262 /// Delete group members (but keep the groups) TODO:check.
3263 if ($groupids = groups_get_groups($data->courseid
)) {
3264 foreach ($groupids as $groupid) {
3265 if (groups_remove_all_group_members($groupid)) {
3266 if ($showfeedback) {
3267 notify($strdeleted .' groups_members', 'notifysuccess');
3276 if (!empty($data->reset_teachers
)) {
3277 foreach ($teachers as $teacherid) {
3278 role_unassign(0, $teacherid, 0, $coursecontext->id
);
3280 if ($showfeedback) {
3281 notify($strdeleted .' '.get_string('teachers'), 'notifysuccess');
3286 if (!empty($data->reset_groups
)) {
3287 if ($groupids = groups_get_groups($data->courseid
)) {
3288 foreach ($groupids as $groupid) {
3289 if (groups_delete_group($groupid)) {
3290 if ($showfeedback) {
3291 notify($strdeleted .' groups', 'notifysuccess');
3300 if (!empty($data->reset_events
)) {
3301 if (delete_records('event', 'courseid', $data->courseid
)) {
3302 if ($showfeedback) {
3303 notify($strdeleted .' event', 'notifysuccess');
3310 if (!empty($data->reset_logs
)) {
3311 if (delete_records('log', 'course', $data->courseid
)) {
3312 if ($showfeedback) {
3313 notify($strdeleted .' log', 'notifysuccess');
3320 // deletes all role assignments, and local override, these have no courseid in table and needs separate process
3321 $context = get_context_instance(CONTEXT_COURSE
, $data->courseid
);
3322 delete_records('role_capabilities', 'contextid', $context->id
);
3328 require_once($CFG->dirroot
.'/group/lib.php');
3329 /*TODO: functions moved to /group/lib/legacylib.php
3339 function generate_email_processing_address($modid,$modargs) {
3342 if (empty($CFG->siteidentifier
)) { // Unique site identification code
3343 set_config('siteidentifier', random_string(32));
3346 $header = $CFG->mailprefix
. substr(base64_encode(pack('C',$modid)),0,2).$modargs;
3347 return $header . substr(md5($header.$CFG->siteidentifier
),0,16).'@'.$CFG->maildomain
;
3351 function moodle_process_email($modargs,$body) {
3352 // the first char should be an unencoded letter. We'll take this as an action
3353 switch ($modargs{0}) {
3354 case 'B': { // bounce
3355 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
3356 if ($user = get_record_select("user","id=$userid","id,email")) {
3357 // check the half md5 of their email
3358 $md5check = substr(md5($user->email
),0,16);
3359 if ($md5check == substr($modargs, -16)) {
3360 set_bounce_count($user);
3362 // else maybe they've already changed it?
3366 // maybe more later?
3370 /// CORRESPONDENCE ////////////////////////////////////////////////
3373 * Send an email to a specified user
3378 * @param user $user A {@link $USER} object
3379 * @param user $from A {@link $USER} object
3380 * @param string $subject plain text subject line of the email
3381 * @param string $messagetext plain text version of the message
3382 * @param string $messagehtml complete html version of the message (optional)
3383 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
3384 * @param string $attachname the name of the file (extension indicates MIME)
3385 * @param bool $usetrueaddress determines whether $from email address should
3386 * be sent out. Will be overruled by user profile setting for maildisplay
3387 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3388 * was blocked by user and "false" if there was another sort of error.
3390 function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='') {
3392 global $CFG, $FULLME;
3394 include_once($CFG->libdir
.'/phpmailer/class.phpmailer.php');
3396 /// We are going to use textlib services here
3397 $textlib = textlib_get_instance();
3403 // skip mail to suspended users
3404 if (isset($user->auth
) && $user->auth
=='nologin') {
3408 if (!empty($user->emailstop
)) {
3412 if (over_bounce_threshold($user)) {
3413 error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
3417 $mail = new phpmailer
;
3419 $mail->Version
= 'Moodle '. $CFG->version
; // mailer version
3420 $mail->PluginDir
= $CFG->libdir
.'/phpmailer/'; // plugin directory (eg smtp plugin)
3422 $mail->CharSet
= 'UTF-8';
3424 if ($CFG->smtphosts
== 'qmail') {
3425 $mail->IsQmail(); // use Qmail system
3427 } else if (empty($CFG->smtphosts
)) {
3428 $mail->IsMail(); // use PHP mail() = sendmail
3431 $mail->IsSMTP(); // use SMTP directly
3432 if (!empty($CFG->debugsmtp
)) {
3433 echo '<pre>' . "\n";
3434 $mail->SMTPDebug
= true;
3436 $mail->Host
= $CFG->smtphosts
; // specify main and backup servers
3438 if ($CFG->smtpuser
) { // Use SMTP authentication
3439 $mail->SMTPAuth
= true;
3440 $mail->Username
= $CFG->smtpuser
;
3441 $mail->Password
= $CFG->smtppass
;
3445 $supportuser = generate_email_supportuser();
3448 // make up an email address for handling bounces
3449 if (!empty($CFG->handlebounces
)) {
3450 $modargs = 'B'.base64_encode(pack('V',$user->id
)).substr(md5($user->email
),0,16);
3451 $mail->Sender
= generate_email_processing_address(0,$modargs);
3453 $mail->Sender
= $supportuser->email
;
3456 if (is_string($from)) { // So we can pass whatever we want if there is need
3457 $mail->From
= $CFG->noreplyaddress
;
3458 $mail->FromName
= $from;
3459 } else if ($usetrueaddress and $from->maildisplay
) {
3460 $mail->From
= $from->email
;
3461 $mail->FromName
= fullname($from);
3463 $mail->From
= $CFG->noreplyaddress
;
3464 $mail->FromName
= fullname($from);
3465 if (empty($replyto)) {
3466 $mail->AddReplyTo($CFG->noreplyaddress
,get_string('noreplyname'));
3470 if (!empty($replyto)) {
3471 $mail->AddReplyTo($replyto,$replytoname);
3474 $mail->Subject
= substr(stripslashes($subject), 0, 900);
3476 $mail->AddAddress($user->email
, fullname($user) );
3478 $mail->WordWrap
= 79; // set word wrap
3480 if (!empty($from->customheaders
)) { // Add custom headers
3481 if (is_array($from->customheaders
)) {
3482 foreach ($from->customheaders
as $customheader) {
3483 $mail->AddCustomHeader($customheader);
3486 $mail->AddCustomHeader($from->customheaders
);
3490 if (!empty($from->priority
)) {
3491 $mail->Priority
= $from->priority
;
3494 if ($messagehtml && $user->mailformat
== 1) { // Don't ever send HTML to users who don't want it
3495 $mail->IsHTML(true);
3496 $mail->Encoding
= 'quoted-printable'; // Encoding to use
3497 $mail->Body
= $messagehtml;
3498 $mail->AltBody
= "\n$messagetext\n";
3500 $mail->IsHTML(false);
3501 $mail->Body
= "\n$messagetext\n";
3504 if ($attachment && $attachname) {
3505 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
3506 $mail->AddAddress($supportuser->email
, fullname($supportuser, true) );
3507 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
3509 require_once($CFG->libdir
.'/filelib.php');
3510 $mimetype = mimeinfo('type', $attachname);
3511 $mail->AddAttachment($CFG->dataroot
.'/'. $attachment, $attachname, 'base64', $mimetype);
3517 /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
3518 /// encoding to the specified one
3519 if ((!empty($CFG->sitemailcharset
) ||
!empty($CFG->allowusermailcharset
))) {
3520 /// Set it to site mail charset
3521 $charset = $CFG->sitemailcharset
;
3522 /// Overwrite it with the user mail charset
3523 if (!empty($CFG->allowusermailcharset
)) {
3524 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id
)) {
3525 $charset = $useremailcharset;
3528 /// If it has changed, convert all the necessary strings
3529 $charsets = get_list_of_charsets();
3530 unset($charsets['UTF-8']);
3531 if (in_array($charset, $charsets)) {
3532 /// Save the new mail charset
3533 $mail->CharSet
= $charset;
3534 /// And convert some strings
3535 $mail->FromName
= $textlib->convert($mail->FromName
, 'utf-8', $mail->CharSet
); //From Name
3536 foreach ($mail->ReplyTo
as $key => $rt) { //ReplyTo Names
3537 $mail->ReplyTo
[$key][1] = $textlib->convert($rt, 'utf-8', $mail->CharSet
);
3539 $mail->Subject
= $textlib->convert($mail->Subject
, 'utf-8', $mail->CharSet
); //Subject
3540 foreach ($mail->to
as $key => $to) {
3541 $mail->to
[$key][1] = $textlib->convert($to, 'utf-8', $mail->CharSet
); //To Names
3543 $mail->Body
= $textlib->convert($mail->Body
, 'utf-8', $mail->CharSet
); //Body
3544 $mail->AltBody
= $textlib->convert($mail->AltBody
, 'utf-8', $mail->CharSet
); //Subject
3548 if ($mail->Send()) {
3549 set_send_count($user);
3550 $mail->IsSMTP(); // use SMTP directly
3551 if (!empty($CFG->debugsmtp
)) {
3556 mtrace('ERROR: '. $mail->ErrorInfo
);
3557 add_to_log(SITEID
, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo
);
3558 if (!empty($CFG->debugsmtp
)) {
3566 * Generate a signoff for emails based on support settings
3569 function generate_email_signoff() {
3573 if (!empty($CFG->supportname
)) {
3574 $signoff .= $CFG->supportname
."\n";
3576 if (!empty($CFG->supportemail
)) {
3577 $signoff .= $CFG->supportemail
."\n";
3579 if (!empty($CFG->supportpage
)) {
3580 $signoff .= $CFG->supportpage
."\n";
3586 * Generate a fake user for emails based on support settings
3589 function generate_email_supportuser() {
3593 static $supportuser;
3595 if (!empty($supportuser)) {
3596 return $supportuser;
3599 $supportuser = new object;
3600 $supportuser->email
= $CFG->supportemail ?
$CFG->supportemail
: $CFG->noreplyaddress
;
3601 $supportuser->firstname
= $CFG->supportname ?
$CFG->supportname
: get_string('noreplyname');
3602 $supportuser->lastname
= '';
3604 return $supportuser;
3609 * Sets specified user's password and send the new password to the user via email.
3612 * @param user $user A {@link $USER} object
3613 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
3614 * was blocked by user and "false" if there was another sort of error.
3616 function setnew_password_and_mail($user) {
3622 $supportuser = generate_email_supportuser();
3624 $newpassword = generate_password();
3626 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id
) ) {
3627 trigger_error('Could not set user password!');
3632 $a->firstname
= fullname($user, true);
3633 $a->sitename
= format_string($site->fullname
);
3634 $a->username
= $user->username
;
3635 $a->newpassword
= $newpassword;
3636 $a->link
= $CFG->wwwroot
.'/login/';
3637 $a->signoff
= generate_email_signoff();
3639 $message = get_string('newusernewpasswordtext', '', $a);
3641 $subject = format_string($site->fullname
) .': '. get_string('newusernewpasswordsubj');
3643 return email_to_user($user, $supportuser, $subject, $message);
3648 * Resets specified user's password and send the new password to the user via email.
3651 * @param user $user A {@link $USER} object
3652 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3653 * was blocked by user and "false" if there was another sort of error.
3655 function reset_password_and_mail($user) {
3660 $supportuser = generate_email_supportuser();
3662 $userauth = get_auth_plugin($user->auth
);
3663 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth
)) {
3664 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
3668 $newpassword = generate_password();
3670 if (!$userauth->user_update_password(addslashes_recursive($user), addslashes($newpassword))) {
3671 error("Could not set user password!");
3675 $a->firstname
= $user->firstname
;
3676 $a->sitename
= format_string($site->fullname
);
3677 $a->username
= $user->username
;
3678 $a->newpassword
= $newpassword;
3679 $a->link
= $CFG->httpswwwroot
.'/login/change_password.php';
3680 $a->signoff
= generate_email_signoff();
3682 $message = get_string('newpasswordtext', '', $a);
3684 $subject = format_string($site->fullname
) .': '. get_string('changedpassword');
3686 return email_to_user($user, $supportuser, $subject, $message);
3691 * Send email to specified user with confirmation text and activation link.
3694 * @param user $user A {@link $USER} object
3695 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3696 * was blocked by user and "false" if there was another sort of error.
3698 function send_confirmation_email($user) {
3703 $supportuser = generate_email_supportuser();
3705 $data = new object();
3706 $data->firstname
= fullname($user);
3707 $data->sitename
= format_string($site->fullname
);
3708 $data->admin
= generate_email_signoff();
3710 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname
));
3712 $data->link
= $CFG->wwwroot
.'/login/confirm.php?data='. $user->secret
.'/'. urlencode($user->username
);
3713 $message = get_string('emailconfirmation', '', $data);
3714 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
3716 $user->mailformat
= 1; // Always send HTML version as well
3718 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
3723 * send_password_change_confirmation_email.
3726 * @param user $user A {@link $USER} object
3727 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3728 * was blocked by user and "false" if there was another sort of error.
3730 function send_password_change_confirmation_email($user) {
3735 $supportuser = generate_email_supportuser();
3737 $data = new object();
3738 $data->firstname
= $user->firstname
;
3739 $data->sitename
= format_string($site->fullname
);
3740 $data->link
= $CFG->httpswwwroot
.'/login/forgot_password.php?p='. $user->secret
.'&s='. urlencode($user->username
);
3741 $data->admin
= generate_email_signoff();
3743 $message = get_string('emailpasswordconfirmation', '', $data);
3744 $subject = get_string('emailpasswordconfirmationsubject', '', format_string($site->fullname
));
3746 return email_to_user($user, $supportuser, $subject, $message);
3751 * send_password_change_info.
3754 * @param user $user A {@link $USER} object
3755 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3756 * was blocked by user and "false" if there was another sort of error.
3758 function send_password_change_info($user) {
3763 $supportuser = generate_email_supportuser();
3764 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
3766 $data = new object();
3767 $data->firstname
= $user->firstname
;
3768 $data->sitename
= format_string($site->fullname
);
3769 $data->admin
= generate_email_signoff();
3771 $userauth = get_auth_plugin($user->auth
);
3773 if (!is_enabled_auth($user->auth
) or $user->auth
== 'nologin') {
3774 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
3775 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
3776 return email_to_user($user, $supportuser, $subject, $message);
3779 if ($userauth->can_change_password() and $userauth->change_password_url()) {
3780 // we have some external url for password changing
3781 $data->link
.= $userauth->change_password_url();
3784 //no way to change password, sorry
3788 if (!empty($data->link
) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id
)) {
3789 $message = get_string('emailpasswordchangeinfo', '', $data);
3790 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
3792 $message = get_string('emailpasswordchangeinfofail', '', $data);
3793 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname
));
3796 return email_to_user($user, $supportuser, $subject, $message);
3801 * Check that an email is allowed. It returns an error message if there
3805 * @param string $email Content of email
3806 * @return string|false
3808 function email_is_not_allowed($email) {
3812 if (!empty($CFG->allowemailaddresses
)) {
3813 $allowed = explode(' ', $CFG->allowemailaddresses
);
3814 foreach ($allowed as $allowedpattern) {
3815 $allowedpattern = trim($allowedpattern);
3816 if (!$allowedpattern) {
3819 if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) { // Match! (bug 5250)
3823 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses
);
3825 } else if (!empty($CFG->denyemailaddresses
)) {
3826 $denied = explode(' ', $CFG->denyemailaddresses
);
3827 foreach ($denied as $deniedpattern) {
3828 $deniedpattern = trim($deniedpattern);
3829 if (!$deniedpattern) {
3832 if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) { // Match! (bug 5250)
3833 return get_string('emailnotallowed', '', $CFG->denyemailaddresses
);
3841 function email_welcome_message_to_user($course, $user=NULL) {
3845 if (!isloggedin()) {
3851 if (!empty($course->welcomemessage
)) {
3852 $subject = get_string('welcometocourse', '', format_string($course->fullname
));
3854 $a->coursename
= $course->fullname
;
3855 $a->profileurl
= "$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id";
3856 //$message = get_string("welcometocoursetext", "", $a);
3857 $message = $course->welcomemessage
;
3859 if (! $teacher = get_teacher($course->id
)) {
3860 $teacher = get_admin();
3862 email_to_user($user, $teacher, $subject, $message);
3866 /// FILE HANDLING /////////////////////////////////////////////
3870 * Makes an upload directory for a particular module.
3873 * @param int $courseid The id of the course in question - maps to id field of 'course' table.
3874 * @return string|false Returns full path to directory if successful, false if not
3876 function make_mod_upload_directory($courseid) {
3879 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata
)) {
3883 $strreadme = get_string('readme');
3885 if (file_exists($CFG->dirroot
.'/lang/'. $CFG->lang
.'/docs/module_files.txt')) {
3886 copy($CFG->dirroot
.'/lang/'. $CFG->lang
.'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
3888 copy($CFG->dirroot
.'/lang/en_utf8/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
3894 * Returns current name of file on disk if it exists.
3896 * @param string $newfile File to be verified
3897 * @return string Current name of file on disk if true
3899 function valid_uploaded_file($newfile) {
3900 if (empty($newfile)) {
3903 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
3904 return $newfile['tmp_name'];
3911 * Returns the maximum size for uploading files.
3913 * There are seven possible upload limits:
3914 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
3915 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
3916 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
3917 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
3918 * 5. by the Moodle admin in $CFG->maxbytes
3919 * 6. by the teacher in the current course $course->maxbytes
3920 * 7. by the teacher for the current module, eg $assignment->maxbytes
3922 * These last two are passed to this function as arguments (in bytes).
3923 * Anything defined as 0 is ignored.
3924 * The smallest of all the non-zero numbers is returned.
3926 * @param int $sizebytes ?
3927 * @param int $coursebytes Current course $course->maxbytes (in bytes)
3928 * @param int $modulebytes Current module ->maxbytes (in bytes)
3929 * @return int The maximum size for uploading files.
3930 * @todo Finish documenting this function
3932 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
3934 if (! $filesize = ini_get('upload_max_filesize')) {
3937 $minimumsize = get_real_size($filesize);
3939 if ($postsize = ini_get('post_max_size')) {
3940 $postsize = get_real_size($postsize);
3941 if ($postsize < $minimumsize) {
3942 $minimumsize = $postsize;
3946 if ($sitebytes and $sitebytes < $minimumsize) {
3947 $minimumsize = $sitebytes;
3950 if ($coursebytes and $coursebytes < $minimumsize) {
3951 $minimumsize = $coursebytes;
3954 if ($modulebytes and $modulebytes < $minimumsize) {
3955 $minimumsize = $modulebytes;
3958 return $minimumsize;
3962 * Related to {@link get_max_upload_file_size()} - this function returns an
3963 * array of possible sizes in an array, translated to the
3966 * @uses SORT_NUMERIC
3967 * @param int $sizebytes ?
3968 * @param int $coursebytes Current course $course->maxbytes (in bytes)
3969 * @param int $modulebytes Current module ->maxbytes (in bytes)
3971 * @todo Finish documenting this function
3973 function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
3976 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
3980 $filesize[$maxsize] = display_size($maxsize);
3982 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
3983 5242880, 10485760, 20971520, 52428800, 104857600);
3985 // Allow maxbytes to be selected if it falls outside the above boundaries
3986 if( isset($CFG->maxbytes
) && !in_array($CFG->maxbytes
, $sizelist) ){
3987 $sizelist[] = $CFG->maxbytes
;
3990 foreach ($sizelist as $sizebytes) {
3991 if ($sizebytes < $maxsize) {
3992 $filesize[$sizebytes] = display_size($sizebytes);
3996 krsort($filesize, SORT_NUMERIC
);
4002 * If there has been an error uploading a file, print the appropriate error message
4003 * Numerical constants used as constant definitions not added until PHP version 4.2.0
4005 * $filearray is a 1-dimensional sub-array of the $_FILES array
4006 * eg $filearray = $_FILES['userfile1']
4007 * If left empty then the first element of the $_FILES array will be used
4010 * @param array $filearray A 1-dimensional sub-array of the $_FILES array
4011 * @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.
4012 * @return bool|string
4014 function print_file_upload_error($filearray = '', $returnerror = false) {
4016 if ($filearray == '' or !isset($filearray['error'])) {
4018 if (empty($_FILES)) return false;
4020 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
4021 $filearray = array_shift($files); /// use first element of array
4024 switch ($filearray['error']) {
4026 case 0: // UPLOAD_ERR_OK
4027 if ($filearray['size'] > 0) {
4028 $errmessage = get_string('uploadproblem', $filearray['name']);
4030 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
4034 case 1: // UPLOAD_ERR_INI_SIZE
4035 $errmessage = get_string('uploadserverlimit');
4038 case 2: // UPLOAD_ERR_FORM_SIZE
4039 $errmessage = get_string('uploadformlimit');
4042 case 3: // UPLOAD_ERR_PARTIAL
4043 $errmessage = get_string('uploadpartialfile');
4046 case 4: // UPLOAD_ERR_NO_FILE
4047 $errmessage = get_string('uploadnofilefound');
4051 $errmessage = get_string('uploadproblem', $filearray['name']);
4057 notify($errmessage);
4064 * handy function to loop through an array of files and resolve any filename conflicts
4065 * both in the array of filenames and for what is already on disk.
4066 * not really compatible with the similar function in uploadlib.php
4067 * but this could be used for files/index.php for moving files around.
4070 function resolve_filename_collisions($destination,$files,$format='%s_%d.%s') {
4071 foreach ($files as $k => $f) {
4072 if (check_potential_filename($destination,$f,$files)) {
4073 $bits = explode('.', $f);
4074 for ($i = 1; true; $i++
) {
4075 $try = sprintf($format, $bits[0], $i, $bits[1]);
4076 if (!check_potential_filename($destination,$try,$files)) {
4087 * @used by resolve_filename_collisions
4089 function check_potential_filename($destination,$filename,$files) {
4090 if (file_exists($destination.'/'.$filename)) {
4093 if (count(array_keys($files,$filename)) > 1) {
4101 * Returns an array with all the filenames in
4102 * all subdirectories, relative to the given rootdir.
4103 * If excludefile is defined, then that file/directory is ignored
4104 * If getdirs is true, then (sub)directories are included in the output
4105 * If getfiles is true, then files are included in the output
4106 * (at least one of these must be true!)
4108 * @param string $rootdir ?
4109 * @param string $excludefile If defined then the specified file/directory is ignored
4110 * @param bool $descend ?
4111 * @param bool $getdirs If true then (sub)directories are included in the output
4112 * @param bool $getfiles If true then files are included in the output
4113 * @return array An array with all the filenames in
4114 * all subdirectories, relative to the given rootdir
4115 * @todo Finish documenting this function. Add examples of $excludefile usage.
4117 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
4121 if (!$getdirs and !$getfiles) { // Nothing to show
4125 if (!is_dir($rootdir)) { // Must be a directory
4129 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
4133 if (!is_array($excludefiles)) {
4134 $excludefiles = array($excludefiles);
4137 while (false !== ($file = readdir($dir))) {
4138 $firstchar = substr($file, 0, 1);
4139 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
4142 $fullfile = $rootdir .'/'. $file;
4143 if (filetype($fullfile) == 'dir') {
4148 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
4149 foreach ($subdirs as $subdir) {
4150 $dirs[] = $file .'/'. $subdir;
4153 } else if ($getfiles) {
4166 * Adds up all the files in a directory and works out the size.
4168 * @param string $rootdir ?
4169 * @param string $excludefile ?
4171 * @todo Finish documenting this function
4173 function get_directory_size($rootdir, $excludefile='') {
4177 // do it this way if we can, it's much faster
4178 if (!empty($CFG->pathtodu
) && is_executable(trim($CFG->pathtodu
))) {
4179 $command = trim($CFG->pathtodu
).' -sk --apparent-size '.escapeshellarg($rootdir);
4182 exec($command,$output,$return);
4183 if (is_array($output)) {
4184 return get_real_size(intval($output[0]).'k'); // we told it to return k.
4188 if (!is_dir($rootdir)) { // Must be a directory
4192 if (!$dir = @opendir
($rootdir)) { // Can't open it for some reason
4198 while (false !== ($file = readdir($dir))) {
4199 $firstchar = substr($file, 0, 1);
4200 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
4203 $fullfile = $rootdir .'/'. $file;
4204 if (filetype($fullfile) == 'dir') {
4205 $size +
= get_directory_size($fullfile, $excludefile);
4207 $size +
= filesize($fullfile);
4216 * Converts bytes into display form
4218 * @param string $size ?
4220 * @staticvar string $gb Localized string for size in gigabytes
4221 * @staticvar string $mb Localized string for size in megabytes
4222 * @staticvar string $kb Localized string for size in kilobytes
4223 * @staticvar string $b Localized string for size in bytes
4224 * @todo Finish documenting this function. Verify return type.
4226 function display_size($size) {
4228 static $gb, $mb, $kb, $b;
4231 $gb = get_string('sizegb');
4232 $mb = get_string('sizemb');
4233 $kb = get_string('sizekb');
4234 $b = get_string('sizeb');
4237 if ($size >= 1073741824) {
4238 $size = round($size / 1073741824 * 10) / 10 . $gb;
4239 } else if ($size >= 1048576) {
4240 $size = round($size / 1048576 * 10) / 10 . $mb;
4241 } else if ($size >= 1024) {
4242 $size = round($size / 1024 * 10) / 10 . $kb;
4244 $size = $size .' '. $b;
4250 * Cleans a given filename by removing suspicious or troublesome characters
4251 * Only these are allowed: alphanumeric _ - .
4252 * Unicode characters can be enabled by setting $CFG->unicodecleanfilename = true in config.php
4254 * WARNING: unicode characters may not be compatible with zip compression in backup/restore,
4255 * because native zip binaries do weird character conversions. Use PHP zipping instead.
4257 * @param string $string file name
4258 * @return string cleaned file name
4260 function clean_filename($string) {
4262 if (empty($CFG->unicodecleanfilename
)) {
4263 $textlib = textlib_get_instance();
4264 $string = $textlib->specialtoascii($string);
4265 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
4267 //clean only ascii range
4268 $string = preg_replace("/[\\000-\\x2c\\x2f\\x3a-\\x40\\x5b-\\x5e\\x60\\x7b-\\177]/s", '_', $string);
4270 $string = preg_replace("/_+/", '_', $string);
4271 $string = preg_replace("/\.\.+/", '.', $string);
4276 /// STRING TRANSLATION ////////////////////////////////////////
4279 * Returns the code for the current language
4286 function current_language() {
4287 global $CFG, $USER, $SESSION, $COURSE;
4289 if (!empty($COURSE->id
) and $COURSE->id
!= SITEID
and !empty($COURSE->lang
)) { // Course language can override all other settings for this page
4290 $return = $COURSE->lang
;
4292 } else if (!empty($SESSION->lang
)) { // Session language can override other settings
4293 $return = $SESSION->lang
;
4295 } else if (!empty($USER->lang
)) {
4296 $return = $USER->lang
;
4299 $return = $CFG->lang
;
4302 if ($return == 'en') {
4303 $return = 'en_utf8';
4310 * Prints out a translated string.
4312 * Prints out a translated string using the return value from the {@link get_string()} function.
4314 * Example usage of this function when the string is in the moodle.php file:<br/>
4317 * print_string('wordforstudent');
4321 * Example usage of this function when the string is not in the moodle.php file:<br/>
4324 * print_string('typecourse', 'calendar');
4328 * @param string $identifier The key identifier for the localized string
4329 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4330 * @param mixed $a An object, string or number that can be used
4331 * within translation strings
4333 function print_string($identifier, $module='', $a=NULL) {
4334 echo get_string($identifier, $module, $a);
4338 * fix up the optional data in get_string()/print_string() etc
4339 * ensure possible sprintf() format characters are escaped correctly
4340 * needs to handle arbitrary strings and objects
4341 * @param mixed $a An object, string or number that can be used
4342 * @return mixed the supplied parameter 'cleaned'
4344 function clean_getstring_data( $a ) {
4345 if (is_string($a)) {
4346 return str_replace( '%','%%',$a );
4348 elseif (is_object($a)) {
4349 $a_vars = get_object_vars( $a );
4350 $new_a_vars = array();
4351 foreach ($a_vars as $fname => $a_var) {
4352 $new_a_vars[$fname] = clean_getstring_data( $a_var );
4354 return (object)$new_a_vars;
4362 * @return array places to look for lang strings based on the prefix to the
4363 * module name. For example qtype_ in question/type. Used by get_string and
4366 function places_to_search_for_lang_strings() {
4370 '__exceptions' => array('moodle', 'langconfig'),
4371 'assignment_' => array('mod/assignment/type'),
4372 'auth_' => array('auth'),
4373 'block_' => array('blocks'),
4374 'datafield_' => array('mod/data/field'),
4375 'datapreset_' => array('mod/data/preset'),
4376 'enrol_' => array('enrol'),
4377 'format_' => array('course/format'),
4378 'qtype_' => array('question/type'),
4379 'report_' => array($CFG->admin
.'/report', 'course/report', 'mod/quiz/report'),
4380 'resource_' => array('mod/resource/type'),
4386 * Returns a localized string.
4388 * Returns the translated string specified by $identifier as
4389 * for $module. Uses the same format files as STphp.
4390 * $a is an object, string or number that can be used
4391 * within translation strings
4393 * eg "hello \$a->firstname \$a->lastname"
4396 * If you would like to directly echo the localized string use
4397 * the function {@link print_string()}
4399 * Example usage of this function involves finding the string you would
4400 * like a local equivalent of and using its identifier and module information
4401 * to retrive it.<br/>
4402 * If you open moodle/lang/en/moodle.php and look near line 1031
4403 * you will find a string to prompt a user for their word for student
4405 * $string['wordforstudent'] = 'Your word for Student';
4407 * So if you want to display the string 'Your word for student'
4408 * in any language that supports it on your site
4409 * you just need to use the identifier 'wordforstudent'
4411 * $mystring = '<strong>'. get_string('wordforstudent') .'</strong>';
4414 * If the string you want is in another file you'd take a slightly
4415 * different approach. Looking in moodle/lang/en/calendar.php you find
4418 * $string['typecourse'] = 'Course event';
4420 * If you want to display the string "Course event" in any language
4421 * supported you would use the identifier 'typecourse' and the module 'calendar'
4422 * (because it is in the file calendar.php):
4424 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
4427 * As a last resort, should the identifier fail to map to a string
4428 * the returned string will be [[ $identifier ]]
4431 * @param string $identifier The key identifier for the localized string
4432 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4433 * @param mixed $a An object, string or number that can be used
4434 * within translation strings
4435 * @param array $extralocations An array of strings with other locations to look for string files
4436 * @return string The localized string.
4438 function get_string($identifier, $module='', $a=NULL, $extralocations=NULL) {
4442 /// originally these special strings were stored in moodle.php now we are only in langconfig.php
4443 $langconfigstrs = array('alphabet', 'backupnameformat', 'firstdayofweek', 'locale',
4444 'localewin', 'localewincharset', 'oldcharset',
4445 'parentlanguage', 'strftimedate', 'strftimedateshort', 'strftimedatetime',
4446 'strftimedaydate', 'strftimedaydatetime', 'strftimedayshort', 'strftimedaytime',
4447 'strftimemonthyear', 'strftimerecent', 'strftimerecentfull', 'strftimetime',
4448 'thischarset', 'thisdirection', 'thislanguage');
4450 $filetocheck = 'langconfig.php';
4451 $defaultlang = 'en_utf8';
4452 if (in_array($identifier, $langconfigstrs)) {
4453 $module = 'langconfig'; //This strings are under langconfig.php for 1.6 lang packs
4456 $lang = current_language();
4458 if ($module == '') {
4462 // if $a happens to have % in it, double it so sprintf() doesn't break
4464 $a = clean_getstring_data( $a );
4467 /// Define the two or three major locations of language strings for this module
4468 $locations = array();
4470 if (!empty($extralocations)) { // Calling code has a good idea where to look
4471 if (is_array($extralocations)) {
4472 $locations +
= $extralocations;
4473 } else if (is_string($extralocations)) {
4474 $locations[] = $extralocations;
4476 debugging('Bad lang path provided');
4480 if (isset($CFG->running_installer
)) {
4481 $module = 'installer';
4482 $filetocheck = 'installer.php';
4483 $locations +
= array( $CFG->dirroot
.'/install/lang/', $CFG->dataroot
.'/lang/', $CFG->dirroot
.'/lang/' );
4484 $defaultlang = 'en_utf8';
4486 $locations +
= array( $CFG->dataroot
.'/lang/', $CFG->dirroot
.'/lang/' );
4489 /// Add extra places to look for strings for particular plugin types.
4490 $rules = places_to_search_for_lang_strings();
4491 $exceptions = $rules['__exceptions'];
4492 unset($rules['__exceptions']);
4494 if (!in_array($module, $exceptions)) {
4495 $dividerpos = strpos($module, '_');
4496 if ($dividerpos === false) {
4500 $type = substr($module, 0, $dividerpos +
1);
4501 $plugin = substr($module, $dividerpos +
1);
4503 if (!empty($rules[$type])) {
4504 foreach ($rules[$type] as $location) {
4505 $locations[] = $CFG->dirroot
. "/$location/$plugin/lang/";
4510 /// First check all the normal locations for the string in the current language
4512 foreach ($locations as $location) {
4513 $locallangfile = $location.$lang.'_local'.'/'.$module.'.php'; //first, see if there's a local file
4514 if (file_exists($locallangfile)) {
4515 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4517 return $resultstring;
4520 //if local directory not found, or particular string does not exist in local direcotry
4521 $langfile = $location.$lang.'/'.$module.'.php';
4522 if (file_exists($langfile)) {
4523 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4525 return $resultstring;
4530 /// If the preferred language was English (utf8) we can abort now
4531 /// saving some checks beacuse it's the only "root" lang
4532 if ($lang == 'en_utf8') {
4533 return '[['. $identifier .']]';
4536 /// Is a parent language defined? If so, try to find this string in a parent language file
4538 foreach ($locations as $location) {
4539 $langfile = $location.$lang.'/'.$filetocheck;
4540 if (file_exists($langfile)) {
4541 if ($result = get_string_from_file('parentlanguage', $langfile, "\$parentlang")) {
4543 if (!empty($parentlang)) { // found it!
4545 //first, see if there's a local file for parent
4546 $locallangfile = $location.$parentlang.'_local'.'/'.$module.'.php';
4547 if (file_exists($locallangfile)) {
4548 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4550 return $resultstring;
4554 //if local directory not found, or particular string does not exist in local direcotry
4555 $langfile = $location.$parentlang.'/'.$module.'.php';
4556 if (file_exists($langfile)) {
4557 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4559 return $resultstring;
4567 /// Our only remaining option is to try English
4569 foreach ($locations as $location) {
4570 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4571 if (file_exists($locallangfile)) {
4572 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4574 return $resultstring;
4578 //if local_en not found, or string not found in local_en
4579 $langfile = $location.$defaultlang.'/'.$module.'.php';
4581 if (file_exists($langfile)) {
4582 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4584 return $resultstring;
4589 /// And, because under 1.6 en is defined as en_utf8 child, me must try
4590 /// if it hasn't been queried before.
4591 if ($defaultlang == 'en') {
4592 $defaultlang = 'en_utf8';
4593 foreach ($locations as $location) {
4594 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4595 if (file_exists($locallangfile)) {
4596 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4598 return $resultstring;
4602 //if local_en not found, or string not found in local_en
4603 $langfile = $location.$defaultlang.'/'.$module.'.php';
4605 if (file_exists($langfile)) {
4606 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4608 return $resultstring;
4614 return '[['.$identifier.']]'; // Last resort
4618 * This function is only used from {@link get_string()}.
4620 * @internal Only used from get_string, not meant to be public API
4621 * @param string $identifier ?
4622 * @param string $langfile ?
4623 * @param string $destination ?
4624 * @return string|false ?
4625 * @staticvar array $strings Localized strings
4627 * @todo Finish documenting this function.
4629 function get_string_from_file($identifier, $langfile, $destination) {
4631 static $strings; // Keep the strings cached in memory.
4633 if (empty($strings[$langfile])) {
4635 include ($langfile);
4636 $strings[$langfile] = $string;
4638 $string = &$strings[$langfile];
4641 if (!isset ($string[$identifier])) {
4645 return $destination .'= sprintf("'. $string[$identifier] .'");';
4649 * Converts an array of strings to their localized value.
4651 * @param array $array An array of strings
4652 * @param string $module The language module that these strings can be found in.
4655 function get_strings($array, $module='') {
4658 foreach ($array as $item) {
4659 $string->$item = get_string($item, $module);
4665 * Returns a list of language codes and their full names
4666 * hides the _local files from everyone.
4667 * @param bool refreshcache force refreshing of lang cache
4668 * @param bool returnall ignore langlist, return all languages available
4669 * @return array An associative array with contents in the form of LanguageCode => LanguageName
4671 function get_list_of_languages($refreshcache=false, $returnall=false) {
4675 $languages = array();
4677 $filetocheck = 'langconfig.php';
4679 if (!$refreshcache && !$returnall && !empty($CFG->langcache
) && file_exists($CFG->dataroot
.'/cache/languages')) {
4680 /// read available langs from cache
4682 $lines = file($CFG->dataroot
.'/cache/languages');
4683 foreach ($lines as $line) {
4684 $line = trim($line);
4685 if (preg_match('/^(\w+)\s+(.+)/', $line, $matches)) {
4686 $languages[$matches[1]] = $matches[2];
4689 unset($lines); unset($line); unset($matches);
4693 if (!$returnall && !empty($CFG->langlist
)) {
4694 /// return only languages allowed in langlist admin setting
4696 $langlist = explode(',', $CFG->langlist
);
4697 // fix short lang names first - non existing langs are skipped anyway...
4698 foreach ($langlist as $lang) {
4699 if (strpos($lang, '_utf8') === false) {
4700 $langlist[] = $lang.'_utf8';
4703 // find existing langs from langlist
4704 foreach ($langlist as $lang) {
4705 $lang = trim($lang); //Just trim spaces to be a bit more permissive
4706 if (strstr($lang, '_local')!==false) {
4709 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4710 $shortlang = substr($lang, 0, -5);
4714 /// Search under dirroot/lang
4715 if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4716 include($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck);
4717 if (!empty($string['thislanguage'])) {
4718 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4722 /// And moodledata/lang
4723 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4724 include($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck);
4725 if (!empty($string['thislanguage'])) {
4726 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4733 /// return all languages available in system
4734 /// Fetch langs from moodle/lang directory
4735 $langdirs = get_list_of_plugins('lang');
4736 /// Fetch langs from moodledata/lang directory
4737 $langdirs2 = get_list_of_plugins('lang', '', $CFG->dataroot
);
4738 /// Merge both lists of langs
4739 $langdirs = array_merge($langdirs, $langdirs2);
4742 /// Get some info from each lang (first from moodledata, then from moodle)
4743 foreach ($langdirs as $lang) {
4744 if (strstr($lang, '_local')!==false) {
4747 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4748 $shortlang = substr($lang, 0, -5);
4752 /// Search under moodledata/lang
4753 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4754 include($CFG->dataroot
.'/lang/'. $lang .'/'. $filetocheck);
4755 if (!empty($string['thislanguage'])) {
4756 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4760 /// And dirroot/lang
4761 if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck)) {
4762 include($CFG->dirroot
.'/lang/'. $lang .'/'. $filetocheck);
4763 if (!empty($string['thislanguage'])) {
4764 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4771 if ($refreshcache && !empty($CFG->langcache
)) {
4773 // we have a list of all langs only, just delete old cache
4774 @unlink
($CFG->dataroot
.'/cache/languages');
4777 // store the list of allowed languages
4778 if ($file = fopen($CFG->dataroot
.'/cache/languages', 'w')) {
4779 foreach ($languages as $key => $value) {
4780 fwrite($file, "$key $value\n");
4791 * Returns a list of charset codes. It's hardcoded, so they should be added manually
4792 * (cheking that such charset is supported by the texlib library!)
4794 * @return array And associative array with contents in the form of charset => charset
4796 function get_list_of_charsets() {
4799 'EUC-JP' => 'EUC-JP',
4800 'ISO-2022-JP'=> 'ISO-2022-JP',
4801 'ISO-8859-1' => 'ISO-8859-1',
4802 'SHIFT-JIS' => 'SHIFT-JIS',
4803 'GB2312' => 'GB2312',
4804 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
4805 'UTF-8' => 'UTF-8');
4813 * Returns a list of country names in the current language
4819 function get_list_of_countries() {
4822 $lang = current_language();
4824 if (!file_exists($CFG->dirroot
.'/lang/'. $lang .'/countries.php') &&
4825 !file_exists($CFG->dataroot
.'/lang/'. $lang .'/countries.php')) {
4826 if ($parentlang = get_string('parentlanguage')) {
4827 if (file_exists($CFG->dirroot
.'/lang/'. $parentlang .'/countries.php') ||
4828 file_exists($CFG->dataroot
.'/lang/'. $parentlang .'/countries.php')) {
4829 $lang = $parentlang;
4831 $lang = 'en_utf8'; // countries.php must exist in this pack
4834 $lang = 'en_utf8'; // countries.php must exist in this pack
4838 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/countries.php')) {
4839 include($CFG->dataroot
.'/lang/'. $lang .'/countries.php');
4840 } else if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/countries.php')) {
4841 include($CFG->dirroot
.'/lang/'. $lang .'/countries.php');
4844 if (!empty($string)) {
4852 * Returns a list of valid and compatible themes
4857 function get_list_of_themes() {
4863 if (!empty($CFG->themelist
)) { // use admin's list of themes
4864 $themelist = explode(',', $CFG->themelist
);
4866 $themelist = get_list_of_plugins("theme");
4869 foreach ($themelist as $key => $theme) {
4870 if (!file_exists("$CFG->themedir/$theme/config.php")) { // bad folder
4873 $THEME = new object(); // Note this is not the global one!! :-)
4874 include("$CFG->themedir/$theme/config.php");
4875 if (!isset($THEME->sheets
)) { // Not a valid 1.5 theme
4878 $themes[$theme] = $theme;
4887 * Returns a list of picture names in the current or specified language
4892 function get_list_of_pixnames($lang = '') {
4896 $lang = current_language();
4901 $path = $CFG->dirroot
.'/lang/en_utf8/pix.php'; // always exists
4903 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'_local/pix.php')) {
4904 $path = $CFG->dataroot
.'/lang/'. $lang .'_local/pix.php';
4906 } else if (file_exists($CFG->dirroot
.'/lang/'. $lang .'/pix.php')) {
4907 $path = $CFG->dirroot
.'/lang/'. $lang .'/pix.php';
4909 } else if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/pix.php')) {
4910 $path = $CFG->dataroot
.'/lang/'. $lang .'/pix.php';
4912 } else if ($parentlang = get_string('parentlanguage') and $parentlang != '[[parentlanguage]]') {
4913 return get_list_of_pixnames($parentlang); //return pixnames from parent language instead
4922 * Returns a list of timezones in the current language
4927 function get_list_of_timezones() {
4932 if (!empty($timezones)) { // This function has been called recently
4936 $timezones = array();
4938 if ($rawtimezones = get_records_sql('SELECT MAX(id), name FROM '.$CFG->prefix
.'timezone GROUP BY name')) {
4939 foreach($rawtimezones as $timezone) {
4940 if (!empty($timezone->name
)) {
4941 $timezones[$timezone->name
] = get_string(strtolower($timezone->name
), 'timezones');
4942 if (substr($timezones[$timezone->name
], 0, 1) == '[') { // No translation found
4943 $timezones[$timezone->name
] = $timezone->name
;
4951 for ($i = -13; $i <= 13; $i +
= .5) {
4954 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
4955 } else if ($i > 0) {
4956 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
4958 $timezones[sprintf("%.1f", $i)] = $tzstring;
4966 * Returns a list of currencies in the current language
4972 function get_list_of_currencies() {
4975 $lang = current_language();
4977 if (!file_exists($CFG->dataroot
.'/lang/'. $lang .'/currencies.php')) {
4978 if ($parentlang = get_string('parentlanguage')) {
4979 if (file_exists($CFG->dataroot
.'/lang/'. $parentlang .'/currencies.php')) {
4980 $lang = $parentlang;
4982 $lang = 'en_utf8'; // currencies.php must exist in this pack
4985 $lang = 'en_utf8'; // currencies.php must exist in this pack
4989 if (file_exists($CFG->dataroot
.'/lang/'. $lang .'/currencies.php')) {
4990 include_once($CFG->dataroot
.'/lang/'. $lang .'/currencies.php');
4991 } else { //if en_utf8 is not installed in dataroot
4992 include_once($CFG->dirroot
.'/lang/'. $lang .'/currencies.php');
4995 if (!empty($string)) {
5005 * Can include a given document file (depends on second
5006 * parameter) or just return info about it.
5009 * @param string $file ?
5010 * @param bool $include ?
5012 * @todo Finish documenting this function
5014 function document_file($file, $include=true) {
5017 $file = clean_filename($file);
5023 $langs = array(current_language(), get_string('parentlanguage'), 'en');
5025 foreach ($langs as $lang) {
5026 $info = new object();
5027 $info->filepath
= $CFG->dirroot
.'/lang/'. $lang .'/docs/'. $file;
5028 $info->urlpath
= $CFG->wwwroot
.'/lang/'. $lang .'/docs/'. $file;
5030 if (file_exists($info->filepath
)) {
5032 include($info->filepath
);
5041 /// ENCRYPTION ////////////////////////////////////////////////
5046 * @param string $data ?
5048 * @todo Finish documenting this function
5050 function rc4encrypt($data) {
5051 $password = 'nfgjeingjk';
5052 return endecrypt($password, $data, '');
5058 * @param string $data ?
5060 * @todo Finish documenting this function
5062 function rc4decrypt($data) {
5063 $password = 'nfgjeingjk';
5064 return endecrypt($password, $data, 'de');
5068 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
5070 * @param string $pwd ?
5071 * @param string $data ?
5072 * @param string $case ?
5074 * @todo Finish documenting this function
5076 function endecrypt ($pwd, $data, $case) {
5078 if ($case == 'de') {
5079 $data = urldecode($data);
5087 $pwd_length = strlen($pwd);
5089 for ($i = 0; $i <= 255; $i++
) {
5090 $key[$i] = ord(substr($pwd, ($i %
$pwd_length), 1));
5096 for ($i = 0; $i <= 255; $i++
) {
5097 $x = ($x +
$box[$i] +
$key[$i]) %
256;
5098 $temp_swap = $box[$i];
5099 $box[$i] = $box[$x];
5100 $box[$x] = $temp_swap;
5112 for ($i = 0; $i < strlen($data); $i++
) {
5113 $a = ($a +
1) %
256;
5114 $j = ($j +
$box[$a]) %
256;
5116 $box[$a] = $box[$j];
5118 $k = $box[(($box[$a] +
$box[$j]) %
256)];
5119 $cipherby = ord(substr($data, $i, 1)) ^
$k;
5120 $cipher .= chr($cipherby);
5123 if ($case == 'de') {
5124 $cipher = urldecode(urlencode($cipher));
5126 $cipher = urlencode($cipher);
5133 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
5137 * Call this function to add an event to the calendar table
5138 * and to call any calendar plugins
5141 * @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:
5143 * <li><b>$event->name</b> - Name for the event
5144 * <li><b>$event->description</b> - Description of the event (defaults to '')
5145 * <li><b>$event->format</b> - Format for the description (using formatting types defined at the top of weblib.php)
5146 * <li><b>$event->courseid</b> - The id of the course this event belongs to (0 = all courses)
5147 * <li><b>$event->groupid</b> - The id of the group this event belongs to (0 = no group)
5148 * <li><b>$event->userid</b> - The id of the user this event belongs to (0 = no user)
5149 * <li><b>$event->modulename</b> - Name of the module that creates this event
5150 * <li><b>$event->instance</b> - Instance of the module that owns this event
5151 * <li><b>$event->eventtype</b> - The type info together with the module info could
5152 * be used by calendar plugins to decide how to display event
5153 * <li><b>$event->timestart</b>- Timestamp for start of event
5154 * <li><b>$event->timeduration</b> - Duration (defaults to zero)
5155 * <li><b>$event->visible</b> - 0 if the event should be hidden (e.g. because the activity that created it is hidden)
5157 * @return int The id number of the resulting record
5159 function add_event($event) {
5163 $event->timemodified
= time();
5165 if (!$event->id
= insert_record('event', $event)) {
5169 if (!empty($CFG->calendar
)) { // call the add_event function of the selected calendar
5170 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5171 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5172 $calendar_add_event = $CFG->calendar
.'_add_event';
5173 if (function_exists($calendar_add_event)) {
5174 $calendar_add_event($event);
5183 * Call this function to update an event in the calendar table
5184 * the event will be identified by the id field of the $event object.
5187 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5190 function update_event($event) {
5194 $event->timemodified
= time();
5196 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
5197 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5198 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5199 $calendar_update_event = $CFG->calendar
.'_update_event';
5200 if (function_exists($calendar_update_event)) {
5201 $calendar_update_event($event);
5205 return update_record('event', $event);
5209 * Call this function to delete the event with id $id from calendar table.
5212 * @param int $id The id of an event from the 'calendar' table.
5213 * @return array An associative array with the results from the SQL call.
5214 * @todo Verify return type
5216 function delete_event($id) {
5220 if (!empty($CFG->calendar
)) { // call the delete_event function of the selected calendar
5221 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5222 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5223 $calendar_delete_event = $CFG->calendar
.'_delete_event';
5224 if (function_exists($calendar_delete_event)) {
5225 $calendar_delete_event($id);
5229 return delete_records('event', 'id', $id);
5233 * Call this function to hide an event in the calendar table
5234 * the event will be identified by the id field of the $event object.
5237 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5238 * @return array An associative array with the results from the SQL call.
5239 * @todo Verify return type
5241 function hide_event($event) {
5244 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
5245 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5246 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5247 $calendar_hide_event = $CFG->calendar
.'_hide_event';
5248 if (function_exists($calendar_hide_event)) {
5249 $calendar_hide_event($event);
5253 return set_field('event', 'visible', 0, 'id', $event->id
);
5257 * Call this function to unhide an event in the calendar table
5258 * the event will be identified by the id field of the $event object.
5261 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5262 * @return array An associative array with the results from the SQL call.
5263 * @todo Verify return type
5265 function show_event($event) {
5268 if (!empty($CFG->calendar
)) { // call the update_event function of the selected calendar
5269 if (file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
5270 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
5271 $calendar_show_event = $CFG->calendar
.'_show_event';
5272 if (function_exists($calendar_show_event)) {
5273 $calendar_show_event($event);
5277 return set_field('event', 'visible', 1, 'id', $event->id
);
5281 /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
5284 * Lists plugin directories within some directory
5287 * @param string $plugin dir under we'll look for plugins (defaults to 'mod')
5288 * @param string $exclude dir name to exclude from the list (defaults to none)
5289 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
5290 * @return array of plugins found under the requested parameters
5292 function get_list_of_plugins($plugin='mod', $exclude='', $basedir='') {
5298 if (empty($basedir)) {
5300 # This switch allows us to use the appropiate theme directory - and potentialy alternatives for other plugins
5303 $basedir = $CFG->themedir
;
5307 $basedir = $CFG->dirroot
.'/'. $plugin;
5311 $basedir = $basedir .'/'. $plugin;
5314 if (file_exists($basedir) && filetype($basedir) == 'dir') {
5315 $dirhandle = opendir($basedir);
5316 while (false !== ($dir = readdir($dirhandle))) {
5317 $firstchar = substr($dir, 0, 1);
5318 if ($firstchar == '.' or $dir == 'CVS' or $dir == '_vti_cnf' or $dir == $exclude) {
5321 if (filetype($basedir .'/'. $dir) != 'dir') {
5326 closedir($dirhandle);
5335 * Returns true if the current version of PHP is greater that the specified one.
5337 * @param string $version The version of php being tested.
5340 function check_php_version($version='4.1.0') {
5341 return (version_compare(phpversion(), $version) >= 0);
5346 * Checks to see if is a browser matches the specified
5347 * brand and is equal or better version.
5350 * @param string $brand The browser identifier being tested
5351 * @param int $version The version of the browser
5352 * @return bool true if the given version is below that of the detected browser
5354 function check_browser_version($brand='MSIE', $version=5.5) {
5355 if (empty($_SERVER['HTTP_USER_AGENT'])) {
5359 $agent = $_SERVER['HTTP_USER_AGENT'];
5363 case 'Camino': /// Mozilla Firefox browsers
5365 if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
5366 if (version_compare($match[1], $version) >= 0) {
5373 case 'Firefox': /// Mozilla Firefox browsers
5375 if (preg_match("/Firefox\/([0-9\.]+)/i", $agent, $match)) {
5376 if (version_compare($match[1], $version) >= 0) {
5383 case 'Gecko': /// Gecko based browsers
5385 if (substr_count($agent, 'Camino')) {
5386 // MacOS X Camino support
5387 $version = 20041110;
5390 // the proper string - Gecko/CCYYMMDD Vendor/Version
5391 // Faster version and work-a-round No IDN problem.
5392 if (preg_match("/Gecko\/([0-9]+)/i", $agent, $match)) {
5393 if ($match[1] > $version) {
5400 case 'MSIE': /// Internet Explorer
5402 if (strpos($agent, 'Opera')) { // Reject Opera
5405 $string = explode(';', $agent);
5406 if (!isset($string[1])) {
5409 $string = explode(' ', trim($string[1]));
5410 if (!isset($string[0]) and !isset($string[1])) {
5413 if ($string[0] == $brand and (float)$string[1] >= $version ) {
5418 case 'Opera': /// Opera
5420 if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
5421 if (version_compare($match[1], $version) >= 0) {
5427 case 'Safari': /// Safari
5428 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SimbianOS
5429 if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
5431 } elseif (strpos($agent, 'Shiira')) { // Reject Shiira
5433 } elseif (strpos($agent, 'SimbianOS')) { // Reject SimbianOS
5437 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
5438 if (version_compare($match[1], $version) >= 0) {
5451 * This function makes the return value of ini_get consistent if you are
5452 * setting server directives through the .htaccess file in apache.
5453 * Current behavior for value set from php.ini On = 1, Off = [blank]
5454 * Current behavior for value set from .htaccess On = On, Off = Off
5455 * Contributed by jdell @ unr.edu
5457 * @param string $ini_get_arg ?
5459 * @todo Finish documenting this function
5461 function ini_get_bool($ini_get_arg) {
5462 $temp = ini_get($ini_get_arg);
5464 if ($temp == '1' or strtolower($temp) == 'on') {
5471 * Compatibility stub to provide backward compatibility
5473 * Determines if the HTML editor is enabled.
5474 * @deprecated Use {@link can_use_html_editor()} instead.
5476 function can_use_richtext_editor() {
5477 return can_use_html_editor();
5481 * Determines if the HTML editor is enabled.
5483 * This depends on site and user
5484 * settings, as well as the current browser being used.
5486 * @return string|false Returns false if editor is not being used, otherwise
5487 * returns 'MSIE' or 'Gecko'.
5489 function can_use_html_editor() {
5492 if (!empty($USER->htmleditor
) and !empty($CFG->htmleditor
)) {
5493 if (check_browser_version('MSIE', 5.5)) {
5495 } else if (check_browser_version('Gecko', 20030516)) {
5503 * Hack to find out the GD version by parsing phpinfo output
5505 * @return int GD version (1, 2, or 0)
5507 function check_gd_version() {
5510 if (function_exists('gd_info')){
5511 $gd_info = gd_info();
5512 if (substr_count($gd_info['GD Version'], '2.')) {
5514 } else if (substr_count($gd_info['GD Version'], '1.')) {
5521 $phpinfo = ob_get_contents();
5524 $phpinfo = explode("\n", $phpinfo);
5527 foreach ($phpinfo as $text) {
5528 $parts = explode('</td>', $text);
5529 foreach ($parts as $key => $val) {
5530 $parts[$key] = trim(strip_tags($val));
5532 if ($parts[0] == 'GD Version') {
5533 if (substr_count($parts[1], '2.0')) {
5536 $gdversion = intval($parts[1]);
5541 return $gdversion; // 1, 2 or 0
5545 * Determine if moodle installation requires update
5547 * Checks version numbers of main code and all modules to see
5548 * if there are any mismatches
5553 function moodle_needs_upgrading() {
5557 include_once($CFG->dirroot
.'/version.php'); # defines $version and upgrades
5558 if ($CFG->version
) {
5559 if ($version > $CFG->version
) {
5562 if ($mods = get_list_of_plugins('mod')) {
5563 foreach ($mods as $mod) {
5564 $fullmod = $CFG->dirroot
.'/mod/'. $mod;
5565 $module = new object();
5566 if (!is_readable($fullmod .'/version.php')) {
5567 notify('Module "'. $mod .'" is not readable - check permissions');
5570 include_once($fullmod .'/version.php'); # defines $module with version etc
5571 if ($currmodule = get_record('modules', 'name', $mod)) {
5572 if ($module->version
> $currmodule->version
) {
5585 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
5588 * Notify admin users or admin user of any failed logins (since last notification).
5594 function notify_login_failures() {
5597 switch ($CFG->notifyloginfailures
) {
5599 $recip = array(get_admin());
5602 $recip = get_admins();
5606 if (empty($CFG->lastnotifyfailure
)) {
5607 $CFG->lastnotifyfailure
=0;
5610 // we need to deal with the threshold stuff first.
5611 if (empty($CFG->notifyloginthreshold
)) {
5612 $CFG->notifyloginthreshold
= 10; // default to something sensible.
5615 $notifyipsrs = $db->Execute('SELECT ip FROM '. $CFG->prefix
.'log WHERE time > '. $CFG->lastnotifyfailure
.'
5616 AND module=\'login\' AND action=\'error\' GROUP BY ip HAVING count(*) > '. $CFG->notifyloginthreshold
);
5618 $notifyusersrs = $db->Execute('SELECT info FROM '. $CFG->prefix
.'log WHERE time > '. $CFG->lastnotifyfailure
.'
5619 AND module=\'login\' AND action=\'error\' GROUP BY info HAVING count(*) > '. $CFG->notifyloginthreshold
);
5623 while ($row = rs_fetch_next_record($notifyipsrs)) {
5624 $ipstr .= "'". $row->ip
."',";
5626 rs_close($notifyipsrs);
5627 $ipstr = substr($ipstr,0,strlen($ipstr)-1);
5629 if ($notifyusersrs) {
5631 while ($row = rs_fetch_next_record($notifyusersrs)) {
5632 $userstr .= "'". $row->info
."',";
5634 rs_close($notifyusersrs);
5635 $userstr = substr($userstr,0,strlen($userstr)-1);
5638 if (strlen($userstr) > 0 ||
strlen($ipstr) > 0) {
5640 $logs = get_logs('time > '. $CFG->lastnotifyfailure
.' AND module=\'login\' AND action=\'error\' '
5641 .((strlen($ipstr) > 0 && strlen($userstr) > 0) ?
' AND ( ip IN ('. $ipstr .') OR info IN ('. $userstr .') ) '
5642 : ((strlen($ipstr) != 0) ?
' AND ip IN ('. $ipstr .') ' : ' AND info IN ('. $userstr .') ')), 'l.time DESC', '', '', $count);
5644 // 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
5645 if (is_array($recip) and count($recip) > 0 and ((time() - HOURSECS
) > $CFG->lastnotifyfailure
)
5646 and is_array($logs) and count($logs) > 0) {
5650 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname
));
5651 $message .= get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot
)
5652 .(($CFG->lastnotifyfailure
!= 0) ?
'('.userdate($CFG->lastnotifyfailure
).')' : '')."\n\n";
5653 foreach ($logs as $log) {
5654 $log->time
= userdate($log->time
);
5655 $message .= get_string('notifyloginfailuresmessage','',$log)."\n";
5657 $message .= "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot
)."\n\n";
5658 foreach ($recip as $admin) {
5659 mtrace('Emailing '. $admin->username
.' about '. count($logs) .' failed login attempts');
5660 email_to_user($admin,get_admin(),$subject,$message);
5662 $conf = new object();
5663 $conf->name
= 'lastnotifyfailure';
5664 $conf->value
= time();
5665 if ($current = get_record('config', 'name', 'lastnotifyfailure')) {
5666 $conf->id
= $current->id
;
5667 if (! update_record('config', $conf)) {
5668 mtrace('Could not update last notify time');
5671 } else if (! insert_record('config', $conf)) {
5672 mtrace('Could not set last notify time');
5682 * @param string $locale ?
5683 * @todo Finish documenting this function
5685 function moodle_setlocale($locale='') {
5689 static $currentlocale = ''; // last locale caching
5691 $oldlocale = $currentlocale;
5693 /// Fetch the correct locale based on ostype
5694 if($CFG->ostype
== 'WINDOWS') {
5695 $stringtofetch = 'localewin';
5697 $stringtofetch = 'locale';
5700 /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
5701 if (!empty($locale)) {
5702 $currentlocale = $locale;
5703 } else if (!empty($CFG->locale
)) { // override locale for all language packs
5704 $currentlocale = $CFG->locale
;
5706 $currentlocale = get_string($stringtofetch);
5709 /// do nothing if locale already set up
5710 if ($oldlocale == $currentlocale) {
5714 /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
5715 /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
5716 /// Some day, numeric, monetary and other categories should be set too, I think. :-/
5718 /// Get current values
5719 $monetary= setlocale (LC_MONETARY
, 0);
5720 $numeric = setlocale (LC_NUMERIC
, 0);
5721 $ctype = setlocale (LC_CTYPE
, 0);
5722 if ($CFG->ostype
!= 'WINDOWS') {
5723 $messages= setlocale (LC_MESSAGES
, 0);
5725 /// Set locale to all
5726 setlocale (LC_ALL
, $currentlocale);
5728 setlocale (LC_MONETARY
, $monetary);
5729 setlocale (LC_NUMERIC
, $numeric);
5730 if ($CFG->ostype
!= 'WINDOWS') {
5731 setlocale (LC_MESSAGES
, $messages);
5733 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
5734 setlocale (LC_CTYPE
, $ctype);
5739 * Converts string to lowercase using most compatible function available.
5741 * @param string $string The string to convert to all lowercase characters.
5742 * @param string $encoding The encoding on the string.
5744 * @todo Add examples of calling this function with/without encoding types
5745 * @deprecated Use textlib->strtolower($text) instead.
5747 function moodle_strtolower ($string, $encoding='') {
5749 //If not specified use utf8
5750 if (empty($encoding)) {
5751 $encoding = 'UTF-8';
5754 $textlib = textlib_get_instance();
5756 return $textlib->strtolower($string, $encoding);
5760 * Count words in a string.
5762 * Words are defined as things between whitespace.
5764 * @param string $string The text to be searched for words.
5765 * @return int The count of words in the specified string
5767 function count_words($string) {
5768 $string = strip_tags($string);
5769 return count(preg_split("/\w\b/", $string)) - 1;
5772 /** Count letters in a string.
5774 * Letters are defined as chars not in tags and different from whitespace.
5776 * @param string $string The text to be searched for letters.
5777 * @return int The count of letters in the specified text.
5779 function count_letters($string) {
5780 /// Loading the textlib singleton instance. We are going to need it.
5781 $textlib = textlib_get_instance();
5783 $string = strip_tags($string); // Tags are out now
5784 $string = ereg_replace('[[:space:]]*','',$string); //Whitespace are out now
5786 return $textlib->strlen($string);
5790 * Generate and return a random string of the specified length.
5792 * @param int $length The length of the string to be created.
5795 function random_string ($length=15) {
5796 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
5797 $pool .= 'abcdefghijklmnopqrstuvwxyz';
5798 $pool .= '0123456789';
5799 $poollen = strlen($pool);
5800 mt_srand ((double) microtime() * 1000000);
5802 for ($i = 0; $i < $length; $i++
) {
5803 $string .= substr($pool, (mt_rand()%
($poollen)), 1);
5809 * Given some text (which may contain HTML) and an ideal length,
5810 * this function truncates the text neatly on a word boundary if possible
5812 function shorten_text($text, $ideal=30) {
5819 $length = strlen($text);
5824 if ($length <= $ideal) {
5828 for ($i=0; $i<$length; $i++
) {
5841 if ($char == '.' or $char == ' ') {
5844 } else if (ord($char) >= 0xE0) { // Chinese/Japanese/Korean text
5845 $truncate = $i; // can be truncated at any UTF-8
5846 break 2; // character boundary.
5854 if ($count > $ideal) {
5864 $ellipse = ($truncate < $length) ?
'...' : '';
5866 return substr($text, 0, $truncate).$ellipse;
5871 * Given dates in seconds, how many weeks is the date from startdate
5872 * The first week is 1, the second 2 etc ...
5875 * @param ? $startdate ?
5876 * @param ? $thedate ?
5878 * @todo Finish documenting this function
5880 function getweek ($startdate, $thedate) {
5881 if ($thedate < $startdate) { // error
5885 return floor(($thedate - $startdate) / WEEKSECS
) +
1;
5889 * returns a randomly generated password of length $maxlen. inspired by
5890 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3}
5892 * @param int $maxlength The maximum size of the password being generated.
5895 function generate_password($maxlen=10) {
5898 $fillers = '1234567890!$-+';
5899 $wordlist = file($CFG->wordlist
);
5901 srand((double) microtime() * 1000000);
5902 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
5903 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
5904 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
5906 return substr($word1 . $filler1 . $word2, 0, $maxlen);
5910 * Given a float, prints it nicely
5912 * @param float $num The float to print
5913 * @param int $places The number of decimal places to print.
5916 function format_float($num, $places=1) {
5917 return sprintf("%.$places"."f", $num);
5921 * Given a simple array, this shuffles it up just like shuffle()
5922 * Unlike PHP's shuffle() ihis function works on any machine.
5924 * @param array $array The array to be rearranged
5927 function swapshuffle($array) {
5929 srand ((double) microtime() * 10000000);
5930 $last = count($array) - 1;
5931 for ($i=0;$i<=$last;$i++
) {
5932 $from = rand(0,$last);
5934 $array[$i] = $array[$from];
5935 $array[$from] = $curr;
5941 * Like {@link swapshuffle()}, but works on associative arrays
5943 * @param array $array The associative array to be rearranged
5946 function swapshuffle_assoc($array) {
5949 $newkeys = swapshuffle(array_keys($array));
5950 foreach ($newkeys as $newkey) {
5951 $newarray[$newkey] = $array[$newkey];
5957 * Given an arbitrary array, and a number of draws,
5958 * this function returns an array with that amount
5959 * of items. The indexes are retained.
5961 * @param array $array ?
5964 * @todo Finish documenting this function
5966 function draw_rand_array($array, $draws) {
5967 srand ((double) microtime() * 10000000);
5971 $last = count($array);
5973 if ($draws > $last) {
5977 while ($draws > 0) {
5980 $keys = array_keys($array);
5981 $rand = rand(0, $last);
5983 $return[$keys[$rand]] = $array[$keys[$rand]];
5984 unset($array[$keys[$rand]]);
5995 * @param string $a ?
5996 * @param string $b ?
5998 * @todo Finish documenting this function
6000 function microtime_diff($a, $b) {
6001 list($a_dec, $a_sec) = explode(' ', $a);
6002 list($b_dec, $b_sec) = explode(' ', $b);
6003 return $b_sec - $a_sec +
$b_dec - $a_dec;
6007 * Given a list (eg a,b,c,d,e) this function returns
6008 * an array of 1->a, 2->b, 3->c etc
6010 * @param array $list ?
6011 * @param string $separator ?
6012 * @todo Finish documenting this function
6014 function make_menu_from_list($list, $separator=',') {
6016 $array = array_reverse(explode($separator, $list), true);
6017 foreach ($array as $key => $item) {
6018 $outarray[$key+
1] = trim($item);
6024 * Creates an array that represents all the current grades that
6025 * can be chosen using the given grading type. Negative numbers
6026 * are scales, zero is no grade, and positive numbers are maximum
6029 * @param int $gradingtype ?
6031 * @todo Finish documenting this function
6033 function make_grades_menu($gradingtype) {
6035 if ($gradingtype < 0) {
6036 if ($scale = get_record('scale', 'id', - $gradingtype)) {
6037 return make_menu_from_list($scale->scale
);
6039 } else if ($gradingtype > 0) {
6040 for ($i=$gradingtype; $i>=0; $i--) {
6041 $grades[$i] = $i .' / '. $gradingtype;
6049 * This function returns the nummber of activities
6050 * using scaleid in a courseid
6052 * @param int $courseid ?
6053 * @param int $scaleid ?
6055 * @todo Finish documenting this function
6057 function course_scale_used($courseid, $scaleid) {
6063 if (!empty($scaleid)) {
6064 if ($cms = get_course_mods($courseid)) {
6065 foreach ($cms as $cm) {
6066 //Check cm->name/lib.php exists
6067 if (file_exists($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php')) {
6068 include_once($CFG->dirroot
.'/mod/'.$cm->modname
.'/lib.php');
6069 $function_name = $cm->modname
.'_scale_used';
6070 if (function_exists($function_name)) {
6071 if ($function_name($cm->instance
,$scaleid)) {
6079 // check if any course grade item makes use of the scale
6080 $return +
= count_records('grade_items', 'courseid', $courseid, 'scaleid', $scaleid);
6086 * This function returns the nummber of activities
6087 * using scaleid in the entire site
6089 * @param int $scaleid ?
6091 * @todo Finish documenting this function. Is return type correct?
6093 function site_scale_used($scaleid,&$courses) {
6099 if (!is_array($courses) ||
count($courses) == 0) {
6100 $courses = get_courses("all",false,"c.id,c.shortname");
6103 if (!empty($scaleid)) {
6104 if (is_array($courses) && count($courses) > 0) {
6105 foreach ($courses as $course) {
6106 $return +
= course_scale_used($course->id
,$scaleid);
6114 * make_unique_id_code
6116 * @param string $extra ?
6118 * @todo Finish documenting this function
6120 function make_unique_id_code($extra='') {
6122 $hostname = 'unknownhost';
6123 if (!empty($_SERVER['HTTP_HOST'])) {
6124 $hostname = $_SERVER['HTTP_HOST'];
6125 } else if (!empty($_ENV['HTTP_HOST'])) {
6126 $hostname = $_ENV['HTTP_HOST'];
6127 } else if (!empty($_SERVER['SERVER_NAME'])) {
6128 $hostname = $_SERVER['SERVER_NAME'];
6129 } else if (!empty($_ENV['SERVER_NAME'])) {
6130 $hostname = $_ENV['SERVER_NAME'];
6133 $date = gmdate("ymdHis");
6135 $random = random_string(6);
6138 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
6140 return $hostname .'+'. $date .'+'. $random;
6146 * Function to check the passed address is within the passed subnet
6148 * The parameter is a comma separated string of subnet definitions.
6149 * Subnet strings can be in one of three formats:
6150 * 1: xxx.xxx.xxx.xxx/xx
6152 * 3: xxx.xxx.xxx.xxx-xxx //a range of IP addresses in the last group.
6153 * Code for type 1 modified from user posted comments by mediator at
6154 * {@link http://au.php.net/manual/en/function.ip2long.php}
6156 * @param string $addr The address you are checking
6157 * @param string $subnetstr The string of subnet addresses
6160 function address_in_subnet($addr, $subnetstr) {
6162 $subnets = explode(',', $subnetstr);
6164 $addr = trim($addr);
6166 foreach ($subnets as $subnet) {
6167 $subnet = trim($subnet);
6168 if (strpos($subnet, '/') !== false) { /// type 1
6169 list($ip, $mask) = explode('/', $subnet);
6170 $mask = 0xffffffff << (32 - $mask);
6171 $found = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
6172 } else if (strpos($subnet, '-') !== false) {/// type 3
6173 $subnetparts = explode('.', $subnet);
6174 $addrparts = explode('.', $addr);
6175 $subnetrange = explode('-', array_pop($subnetparts));
6176 if (count($subnetrange) == 2) {
6177 $lastaddrpart = array_pop($addrparts);
6178 $found = ($subnetparts == $addrparts &&
6179 $subnetrange[0] <= $lastaddrpart && $lastaddrpart <= $subnetrange[1]);
6182 $found = (strpos($addr, $subnet) === 0);
6193 * This function sets the $HTTPSPAGEREQUIRED global
6194 * (used in some parts of moodle to change some links)
6195 * and calculate the proper wwwroot to be used
6197 * By using this function properly, we can ensure 100% https-ized pages
6198 * at our entire discretion (login, forgot_password, change_password)
6200 function httpsrequired() {
6202 global $CFG, $HTTPSPAGEREQUIRED;
6204 if (!empty($CFG->loginhttps
)) {
6205 $HTTPSPAGEREQUIRED = true;
6206 $CFG->httpswwwroot
= str_replace('http:', 'https:', $CFG->wwwroot
);
6207 $CFG->httpsthemewww
= str_replace('http:', 'https:', $CFG->themewww
);
6209 // change theme URLs to https
6213 $CFG->httpswwwroot
= $CFG->wwwroot
;
6214 $CFG->httpsthemewww
= $CFG->themewww
;
6219 * For outputting debugging info
6222 * @param string $string ?
6223 * @param string $eol ?
6224 * @todo Finish documenting this function
6226 function mtrace($string, $eol="\n", $sleep=0) {
6228 if (defined('STDOUT')) {
6229 fwrite(STDOUT
, $string.$eol);
6231 echo $string . $eol;
6236 //delay to keep message on user's screen in case of subsequent redirect
6242 //Replace 1 or more slashes or backslashes to 1 slash
6243 function cleardoubleslashes ($path) {
6244 return preg_replace('/(\/|\\\){1,}/','/',$path);
6247 function zip_files ($originalfiles, $destination) {
6248 //Zip an array of files/dirs to a destination zip file
6249 //Both parameters must be FULL paths to the files/dirs
6253 //Extract everything from destination
6254 $path_parts = pathinfo(cleardoubleslashes($destination));
6255 $destpath = $path_parts["dirname"]; //The path of the zip file
6256 $destfilename = $path_parts["basename"]; //The name of the zip file
6257 $extension = $path_parts["extension"]; //The extension of the file
6260 if (empty($destfilename)) {
6264 //If no extension, add it
6265 if (empty($extension)) {
6267 $destfilename = $destfilename.'.'.$extension;
6270 //Check destination path exists
6271 if (!is_dir($destpath)) {
6275 //Check destination path is writable. TODO!!
6277 //Clean destination filename
6278 $destfilename = clean_filename($destfilename);
6280 //Now check and prepare every file
6284 foreach ($originalfiles as $file) { //Iterate over each file
6285 //Check for every file
6286 $tempfile = cleardoubleslashes($file); // no doubleslashes!
6287 //Calculate the base path for all files if it isn't set
6288 if ($origpath === NULL) {
6289 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
6291 //See if the file is readable
6292 if (!is_readable($tempfile)) { //Is readable
6295 //See if the file/dir is in the same directory than the rest
6296 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
6299 //Add the file to the array
6300 $files[] = $tempfile;
6303 //Everything is ready:
6304 // -$origpath is the path where ALL the files to be compressed reside (dir).
6305 // -$destpath is the destination path where the zip file will go (dir).
6306 // -$files is an array of files/dirs to compress (fullpath)
6307 // -$destfilename is the name of the zip file (without path)
6309 //print_object($files); //Debug
6311 if (empty($CFG->zip
)) { // Use built-in php-based zip function
6313 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6314 //rewrite filenames because the old method with PCLZIP_OPT_REMOVE_PATH does not work under win32
6315 $zipfiles = array();
6316 $start = strlen($origpath)+
1;
6317 foreach($files as $file) {
6319 $tf[PCLZIP_ATT_FILE_NAME
] = $file;
6320 $tf[PCLZIP_ATT_FILE_NEW_FULL_NAME
] = substr($file, $start);
6323 //create the archive
6324 $archive = new PclZip(cleardoubleslashes("$destpath/$destfilename"));
6325 if (($list = $archive->create($zipfiles) == 0)) {
6326 notice($archive->errorInfo(true));
6330 } else { // Use external zip program
6333 foreach ($files as $filetozip) {
6334 $filestozip .= escapeshellarg(basename($filetozip));
6337 //Construct the command
6338 $separator = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
' &' : ' ;';
6339 $command = 'cd '.escapeshellarg($origpath).$separator.
6340 escapeshellarg($CFG->zip
).' -r '.
6341 escapeshellarg(cleardoubleslashes("$destpath/$destfilename")).' '.$filestozip;
6342 //All converted to backslashes in WIN
6343 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6344 $command = str_replace('/','\\',$command);
6351 function unzip_file ($zipfile, $destination = '', $showstatus = true) {
6352 //Unzip one zip file to a destination dir
6353 //Both parameters must be FULL paths
6354 //If destination isn't specified, it will be the
6355 //SAME directory where the zip file resides.
6359 //Extract everything from zipfile
6360 $path_parts = pathinfo(cleardoubleslashes($zipfile));
6361 $zippath = $path_parts["dirname"]; //The path of the zip file
6362 $zipfilename = $path_parts["basename"]; //The name of the zip file
6363 $extension = $path_parts["extension"]; //The extension of the file
6366 if (empty($zipfilename)) {
6370 //If no extension, error
6371 if (empty($extension)) {
6376 $zipfile = cleardoubleslashes($zipfile);
6378 //Check zipfile exists
6379 if (!file_exists($zipfile)) {
6383 //If no destination, passed let's go with the same directory
6384 if (empty($destination)) {
6385 $destination = $zippath;
6388 //Clear $destination
6389 $destpath = rtrim(cleardoubleslashes($destination), "/");
6391 //Check destination path exists
6392 if (!is_dir($destpath)) {
6396 //Check destination path is writable. TODO!!
6398 //Everything is ready:
6399 // -$zippath is the path where the zip file resides (dir)
6400 // -$zipfilename is the name of the zip file (without path)
6401 // -$destpath is the destination path where the zip file will uncompressed (dir)
6405 if (empty($CFG->unzip
)) { // Use built-in php-based unzip function
6407 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6408 $archive = new PclZip(cleardoubleslashes("$zippath/$zipfilename"));
6409 if (!$list = $archive->extract(PCLZIP_OPT_PATH
, $destpath,
6410 PCLZIP_CB_PRE_EXTRACT
, 'unzip_cleanfilename',
6411 PCLZIP_OPT_EXTRACT_DIR_RESTRICTION
, $destpath)) {
6412 notice($archive->errorInfo(true));
6416 } else { // Use external unzip program
6418 $separator = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
' &' : ' ;';
6419 $redirection = strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' ?
'' : ' 2>&1';
6421 $command = 'cd '.escapeshellarg($zippath).$separator.
6422 escapeshellarg($CFG->unzip
).' -o '.
6423 escapeshellarg(cleardoubleslashes("$zippath/$zipfilename")).' -d '.
6424 escapeshellarg($destpath).$redirection;
6425 //All converted to backslashes in WIN
6426 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6427 $command = str_replace('/','\\',$command);
6429 Exec($command,$list);
6432 //Display some info about the unzip execution
6434 unzip_show_status($list,$destpath);
6440 function unzip_cleanfilename ($p_event, &$p_header) {
6441 //This function is used as callback in unzip_file() function
6442 //to clean illegal characters for given platform and to prevent directory traversal.
6443 //Produces the same result as info-zip unzip.
6444 $p_header['filename'] = ereg_replace('[[:cntrl:]]', '', $p_header['filename']); //strip control chars first!
6445 $p_header['filename'] = ereg_replace('\.\.+', '', $p_header['filename']); //directory traversal protection
6446 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
6447 $p_header['filename'] = ereg_replace('[:*"?<>|]', '_', $p_header['filename']); //replace illegal chars
6448 $p_header['filename'] = ereg_replace('^([a-zA-Z])_', '\1:', $p_header['filename']); //repair drive letter
6450 //Add filtering for other systems here
6451 // BSD: none (tested)
6455 $p_header['filename'] = cleardoubleslashes($p_header['filename']); //normalize the slashes/backslashes
6459 function unzip_show_status ($list,$removepath) {
6460 //This function shows the results of the unzip execution
6461 //depending of the value of the $CFG->zip, results will be
6462 //text or an array of files.
6466 if (empty($CFG->unzip
)) { // Use built-in php-based zip function
6467 $strname = get_string("name");
6468 $strsize = get_string("size");
6469 $strmodified = get_string("modified");
6470 $strstatus = get_string("status");
6471 echo "<table width=\"640\">";
6472 echo "<tr><th class=\"header\" scope=\"col\">$strname</th>";
6473 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strsize</th>";
6474 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strmodified</th>";
6475 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strstatus</th></tr>";
6476 foreach ($list as $item) {
6478 $item['filename'] = str_replace(cleardoubleslashes($removepath).'/', "", $item['filename']);
6479 print_cell("left", s($item['filename']));
6480 if (! $item['folder']) {
6481 print_cell("right", display_size($item['size']));
6483 echo "<td> </td>";
6485 $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
6486 print_cell("right", $filedate);
6487 print_cell("right", $item['status']);
6492 } else { // Use external zip program
6493 print_simple_box_start("center");
6495 foreach ($list as $item) {
6496 echo s(str_replace(cleardoubleslashes($removepath.'/'), '', $item)).'<br />';
6499 print_simple_box_end();
6504 * Returns most reliable client address
6506 * @return string The remote IP address
6508 function getremoteaddr() {
6509 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
6510 return cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
6512 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
6513 return cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
6515 if (!empty($_SERVER['REMOTE_ADDR'])) {
6516 return cleanremoteaddr($_SERVER['REMOTE_ADDR']);
6522 * Cleans a remote address ready to put into the log table
6524 function cleanremoteaddr($addr) {
6525 $originaladdr = $addr;
6527 // first get all things that look like IP addresses.
6528 if (!preg_match_all('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/',$addr,$matches,PREG_SET_ORDER
)) {
6531 $goodmatches = array();
6532 $lanmatches = array();
6533 foreach ($matches as $match) {
6535 // check to make sure it's not an internal address.
6536 // the following are reserved for private lans...
6537 // 10.0.0.0 - 10.255.255.255
6538 // 172.16.0.0 - 172.31.255.255
6539 // 192.168.0.0 - 192.168.255.255
6540 // 169.254.0.0 -169.254.255.255
6541 $bits = explode('.',$match[0]);
6542 if (count($bits) != 4) {
6543 // weird, preg match shouldn't give us it.
6546 if (($bits[0] == 10)
6547 ||
($bits[0] == 172 && $bits[1] >= 16 && $bits[1] <= 31)
6548 ||
($bits[0] == 192 && $bits[1] == 168)
6549 ||
($bits[0] == 169 && $bits[1] == 254)) {
6550 $lanmatches[] = $match[0];
6554 $goodmatches[] = $match[0];
6556 if (!count($goodmatches)) {
6557 // perhaps we have a lan match, it's probably better to return that.
6558 if (!count($lanmatches)) {
6561 return array_pop($lanmatches);
6564 if (count($goodmatches) == 1) {
6565 return $goodmatches[0];
6567 error_log("NOTICE: cleanremoteaddr gives us something funny: $originaladdr had ".count($goodmatches)." matches");
6568 // we need to return something, so
6569 return array_pop($goodmatches);
6573 * file_put_contents is only supported by php 5.0 and higher
6574 * so if it is not predefined, define it here
6576 * @param $file full path of the file to write
6577 * @param $contents contents to be sent
6578 * @return number of bytes written (false on error)
6580 if(!function_exists('file_put_contents')) {
6581 function file_put_contents($file, $contents) {
6583 if ($f = fopen($file, 'w')) {
6584 $result = fwrite($f, $contents);
6592 * The clone keyword is only supported from PHP 5 onwards.
6593 * The behaviour of $obj2 = $obj1 differs fundamentally
6594 * between PHP 4 and PHP 5. In PHP 4 a copy of $obj1 was
6595 * created, in PHP 5 $obj1 is referenced. To create a copy
6596 * in PHP 5 the clone keyword was introduced. This function
6597 * simulates this behaviour for PHP < 5.0.0.
6598 * See also: http://mjtsai.com/blog/2004/07/15/php-5-object-references/
6600 * Modified 2005-09-29 by Eloy (from Julian Sedding proposal)
6601 * Found a better implementation (more checks and possibilities) from PEAR:
6602 * http://cvs.php.net/co.php/pear/PHP_Compat/Compat/Function/clone.php
6604 * @param object $obj
6607 if(!check_php_version('5.0.0')) {
6608 // the eval is needed to prevent PHP 5 from getting a parse error!
6610 function clone($obj) {
6612 if (!is_object($obj)) {
6613 user_error(\'clone() __clone method called on non-object\', E_USER_WARNING);
6617 /// Use serialize/unserialize trick to deep copy the object
6618 $obj = unserialize(serialize($obj));
6620 /// If there is a __clone method call it on the "new" class
6621 if (method_exists($obj, \'__clone\')) {
6628 // Supply the PHP5 function scandir() to older versions.
6629 function scandir($directory) {
6631 if ($dh = opendir($directory)) {
6632 while (($file = readdir($dh)) !== false) {
6640 // Supply the PHP5 function array_combine() to older versions.
6641 function array_combine($keys, $values) {
6642 if (!is_array($keys) || !is_array($values) || count($keys) != count($values)) {
6647 foreach ($keys as $key) {
6648 $result[$key] = current($values);
6657 * This function will make a complete copy of anything it's given,
6658 * regardless of whether it's an object or not.
6659 * @param mixed $thing
6662 function fullclone($thing) {
6663 return unserialize(serialize($thing));
6668 * This function expects to called during shutdown
6669 * should be set via register_shutdown_function()
6670 * in lib/setup.php .
6672 * Right now we do it only if we are under apache, to
6673 * make sure apache children that hog too much mem are
6677 function moodle_request_shutdown() {
6681 // initially, we are only ever called under apache
6682 // but check just in case
6683 if (function_exists('apache_child_terminate')
6684 && function_exists('memory_get_usage')
6685 && ini_get_bool('child_terminate')) {
6686 if (empty($CFG->apachemaxmem
)) {
6687 $CFG->apachemaxmem
= 25000000; // default 25MiB
6689 if (memory_get_usage() > (int)$CFG->apachemaxmem
) {
6690 trigger_error('Mem usage over $CFG->apachemaxmem: marking child for reaping.');
6691 @apache_child_terminate
();
6697 * If new messages are waiting for the current user, then return
6698 * Javascript code to create a popup window
6700 * @return string Javascript code
6702 function message_popup_window() {
6705 $popuplimit = 30; // Minimum seconds between popups
6707 if (!defined('MESSAGE_WINDOW')) {
6708 if (isset($USER->id
)) {
6709 if (!isset($USER->message_lastpopup
)) {
6710 $USER->message_lastpopup
= 0;
6712 if ((time() - $USER->message_lastpopup
) > $popuplimit) { /// It's been long enough
6713 if (get_user_preferences('message_showmessagewindow', 1) == 1) {
6714 if (count_records_select('message', 'useridto = \''.$USER->id
.'\' AND timecreated > \''.$USER->message_lastpopup
.'\'')) {
6715 $USER->message_lastpopup
= time();
6716 return '<script type="text/javascript">'."\n//<![CDATA[\n openpopup('/message/index.php', 'message',
6717 'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500', 0);\n//]]>\n</script>";
6727 // Used to make sure that $min <= $value <= $max
6728 function bounded_number($min, $value, $max) {
6738 function array_is_nested($array) {
6739 foreach ($array as $value) {
6740 if (is_array($value)) {
6748 *** get_performance_info() pairs up with init_performance_info()
6749 *** loaded in setup.php. Returns an array with 'html' and 'txt'
6750 *** values ready for use, and each of the individual stats provided
6751 *** separately as well.
6754 function get_performance_info() {
6755 global $CFG, $PERF, $rcache;
6758 $info['html'] = ''; // holds userfriendly HTML representation
6759 $info['txt'] = me() . ' '; // holds log-friendly representation
6761 $info['realtime'] = microtime_diff($PERF->starttime
, microtime());
6763 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
6764 $info['txt'] .= 'time: '.$info['realtime'].'s ';
6766 if (function_exists('memory_get_usage')) {
6767 $info['memory_total'] = memory_get_usage();
6768 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory
;
6769 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
6770 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
6773 $inc = get_included_files();
6774 //error_log(print_r($inc,1));
6775 $info['includecount'] = count($inc);
6776 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
6777 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
6779 if (!empty($PERF->dbqueries
)) {
6780 $info['dbqueries'] = $PERF->dbqueries
;
6781 $info['html'] .= '<span class="dbqueries">DB queries '.$info['dbqueries'].'</span> ';
6782 $info['txt'] .= 'dbqueries: '.$info['dbqueries'].' ';
6785 if (!empty($PERF->logwrites
)) {
6786 $info['logwrites'] = $PERF->logwrites
;
6787 $info['html'] .= '<span class="logwrites">Log writes '.$info['logwrites'].'</span> ';
6788 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
6791 if (!empty($PERF->profiling
) && $PERF->profiling
) {
6792 require_once($CFG->dirroot
.'/lib/profilerlib.php');
6793 $info['html'] .= '<span class="profilinginfo">'.Profiler
::get_profiling(array('-R')).'</span>';
6796 if (function_exists('posix_times')) {
6797 $ptimes = posix_times();
6798 if (is_array($ptimes)) {
6799 foreach ($ptimes as $key => $val) {
6800 $info[$key] = $ptimes[$key] - $PERF->startposixtimes
[$key];
6802 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
6803 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
6807 // Grab the load average for the last minute
6808 // /proc will only work under some linux configurations
6809 // while uptime is there under MacOSX/Darwin and other unices
6810 if (is_readable('/proc/loadavg') && $loadavg = @file
('/proc/loadavg')) {
6811 list($server_load) = explode(' ', $loadavg[0]);
6813 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `
/usr
/bin
/uptime`
) {
6814 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
6815 $server_load = $matches[1];
6817 trigger_error('Could not parse uptime output!');
6820 if (!empty($server_load)) {
6821 $info['serverload'] = $server_load;
6822 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
6823 $info['txt'] .= "serverload: {$info['serverload']} ";
6826 if (isset($rcache->hits
) && isset($rcache->misses
)) {
6827 $info['rcachehits'] = $rcache->hits
;
6828 $info['rcachemisses'] = $rcache->misses
;
6829 $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
6830 "{$rcache->hits}/{$rcache->misses}</span> ";
6831 $info['txt'] .= 'rcache: '.
6832 "{$rcache->hits}/{$rcache->misses} ";
6834 $info['html'] = '<div class="performanceinfo">'.$info['html'].'</div>';
6838 function apd_get_profiling() {
6839 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
6842 function remove_dir($dir, $content_only=false) {
6843 // if content_only=true then delete all but
6844 // the directory itself
6846 $handle = opendir($dir);
6847 while (false!==($item = readdir($handle))) {
6848 if($item != '.' && $item != '..') {
6849 if(is_dir($dir.'/'.$item)) {
6850 remove_dir($dir.'/'.$item);
6852 unlink($dir.'/'.$item);
6857 if ($content_only) {
6864 * Function to check if a directory exists and optionally create it.
6866 * @param string absolute directory path
6867 * @param boolean create directory if does not exist
6868 * @param boolean create directory recursively
6870 * @return boolean true if directory exists or created
6872 function check_dir_exists($dir, $create=false, $recursive=false) {
6884 // PHP 5.0 has recursive mkdir parameter, but 4.x does not :-(
6885 $dir = str_replace('\\', '/', $dir); //windows compatibility
6886 $dirs = explode('/', $dir);
6887 $dir = array_shift($dirs).'/'; //skip root or drive letter
6888 foreach ($dirs as $part) {
6893 if (!is_dir($dir)) {
6894 if (!mkdir($dir, $CFG->directorypermissions
)) {
6901 $status = mkdir($dir, $CFG->directorypermissions
);
6908 function report_session_error() {
6909 global $CFG, $FULLME;
6911 if (empty($CFG->lang
)) {
6914 // Set up default theme and locale
6918 //clear session cookies
6919 setcookie('MoodleSession'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
6920 setcookie('MoodleSessionTest'.$CFG->sessioncookie
, '', time() - 3600, $CFG->sessioncookiepath
);
6921 //increment database error counters
6922 if (isset($CFG->session_error_counter
)) {
6923 set_config('session_error_counter', 1 +
$CFG->session_error_counter
);
6925 set_config('session_error_counter', 1);
6927 redirect($FULLME, get_string('sessionerroruser2', 'error'), 5);
6932 * Detect if an object or a class contains a given property
6933 * will take an actual object or the name of a class
6934 * @param mix $obj Name of class or real object to test
6935 * @param string $property name of property to find
6936 * @return bool true if property exists
6938 function object_property_exists( $obj, $property ) {
6939 if (is_string( $obj )) {
6940 $properties = get_class_vars( $obj );
6943 $properties = get_object_vars( $obj );
6945 return array_key_exists( $property, $properties );
6950 * Detect a custom script replacement in the data directory that will
6951 * replace an existing moodle script
6952 * @param string $urlpath path to the original script
6953 * @return string full path name if a custom script exists
6954 * @return bool false if no custom script exists
6956 function custom_script_path($urlpath='') {
6959 // set default $urlpath, if necessary
6960 if (empty($urlpath)) {
6961 $urlpath = qualified_me(); // e.g. http://www.this-server.com/moodle/this-script.php
6964 // $urlpath is invalid if it is empty or does not start with the Moodle wwwroot
6965 if (empty($urlpath) or (strpos($urlpath, $CFG->wwwroot
) === false )) {
6969 // replace wwwroot with the path to the customscripts folder and clean path
6970 $scriptpath = $CFG->customscripts
. clean_param(substr($urlpath, strlen($CFG->wwwroot
)), PARAM_PATH
);
6972 // remove the query string, if any
6973 if (($strpos = strpos($scriptpath, '?')) !== false) {
6974 $scriptpath = substr($scriptpath, 0, $strpos);
6977 // remove trailing slashes, if any
6978 $scriptpath = rtrim($scriptpath, '/\\');
6980 // append index.php, if necessary
6981 if (is_dir($scriptpath)) {
6982 $scriptpath .= '/index.php';
6985 // check the custom script exists
6986 if (file_exists($scriptpath)) {
6994 * Wrapper function to load necessary editor scripts
6995 * to $CFG->editorsrc array. Params can be coursei id
6996 * or associative array('courseid' => value, 'name' => 'editorname').
6998 * @param mixed $args Courseid or associative array.
7000 function loadeditor($args) {
7002 include($CFG->libdir
.'/editorlib.php');
7003 return editorObject
::loadeditor($args);
7007 * Returns whether or not the user object is a remote MNET user. This function
7008 * is in moodlelib because it does not rely on loading any of the MNET code.
7010 * @param object $user A valid user object
7011 * @return bool True if the user is from a remote Moodle.
7013 function is_mnet_remote_user($user) {
7016 if (!isset($CFG->mnet_localhost_id
)) {
7017 include_once $CFG->dirroot
. '/mnet/lib.php';
7018 $env = new mnet_environment();
7023 return (!empty($user->mnethostid
) && $user->mnethostid
!= $CFG->mnet_localhost_id
);
7027 * Checks if a given plugin is in the list of enabled enrolment plugins.
7029 * @param string $auth Enrolment plugin.
7030 * @return boolean Whether the plugin is enabled.
7032 function is_enabled_enrol($enrol='') {
7035 // use the global default if not specified
7037 $enrol = $CFG->enrol
;
7039 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled
));
7043 * This function will search for browser prefereed languages, setting Moodle
7044 * to use the best one available if $SESSION->lang is undefined
7046 function setup_lang_from_browser() {
7048 global $CFG, $SESSION, $USER;
7050 if (!empty($SESSION->lang
) or !empty($USER->lang
)) {
7051 // Lang is defined in session or user profile, nothing to do
7055 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
7059 /// Extract and clean langs from headers
7060 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
7061 $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
7062 $rawlangs = explode(',', $rawlangs); // Convert to array
7066 foreach ($rawlangs as $lang) {
7067 if (strpos($lang, ';') === false) {
7068 $langs[(string)$order] = $lang;
7069 $order = $order-0.01;
7071 $parts = explode(';', $lang);
7072 $pos = strpos($parts[1], '=');
7073 $langs[substr($parts[1], $pos+
1)] = $parts[0];
7076 krsort($langs, SORT_NUMERIC
);
7078 $langlist = get_list_of_languages();
7080 /// Look for such langs under standard locations
7081 foreach ($langs as $lang) {
7082 $lang = strtolower(clean_param($lang.'_utf8', PARAM_SAFEDIR
)); // clean it properly for include
7083 if (!array_key_exists($lang, $langlist)) {
7084 continue; // language not allowed, try next one
7086 if (file_exists($CFG->dataroot
.'/lang/'. $lang) or file_exists($CFG->dirroot
.'/lang/'. $lang)) {
7087 $SESSION->lang
= $lang; /// Lang exists, set it in session
7088 break; /// We have finished. Go out
7095 ////////////////////////////////////////////////////////////////////////////////
7097 * This function will build the navigation string to be used by print_header
7101 * @param $extranavlinks - array of associative arrays, keys: name, link, type
7102 * @return $navigation as an object so it can be differentiated from old style
7103 * navigation strings.
7105 function build_navigation($extranavlinks) {
7106 global $CFG, $COURSE;
7109 $navlinks = array();
7112 if ($site = get_site()) {
7113 $navlinks[] = array('name' => format_string($site->shortname
), 'link' => "$CFG->wwwroot/", 'type' => 'home');
7118 if ($COURSE->id
!= SITEID
) {
7120 $navlinks[] = array('name' => format_string($COURSE->shortname
), 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",'type' => 'course');
7124 //Merge in extra navigation links
7125 $navlinks = array_merge($navlinks, $extranavlinks);
7127 //Construct an unordered list from $navlinks
7128 //Accessibility: heading hidden from visual browsers by default.
7129 $navigation = '<h2 class="accesshide">'.get_string('youarehere','access')."</h2> <ul>\n";
7130 $countlinks = count($navlinks);
7132 for($i=0;$i<$countlinks;$i++
) {
7134 // Check the link type to see if this link should appear in the trail
7135 if ($navlinks[$i]['type'] == 'activity' && $i+
1 < $countlinks && ($CFG->hideactivitytypenavlink
== 2 ||
($CFG->hideactivitytypenavlink
== 1 && !has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE
, $course->id
))))) {
7138 $navigation .= '<li class="first">';
7140 $navigation .= get_separator();
7142 if ($navlinks[$i]['link'] && $i+
1 < $countlinks) {
7143 $navigation .= "<a onclick=\"this.target='$CFG->framename'\" href=\"{$navlinks[$i]['link']}\">";
7145 $navigation .= "{$navlinks[$i]['name']}";
7146 if ($navlinks[$i]['link'] && $i+
1 < $countlinks) {
7147 $navigation .= "</a>";
7150 $navigation .= "</li>";
7153 $navigation .= "</ul>";
7155 return(array('newnav' => true, 'navlinks' => $navigation));
7158 function is_newnav($navigation) {
7159 if (is_array($navigation) && $navigation['newnav']) {
7167 * Checks whether the given variable name is defined as a variable within the given object.
7168 * @note This will NOT work with stdClass objects, which have no class variables.
7169 * @param string $var The variable name
7170 * @param object $object The object to check
7173 function in_object_vars($var, $object)
7175 $class_vars = get_class_vars(get_class($object));
7176 $class_vars = array_keys($class_vars);
7177 return in_array($var, $class_vars);
7181 * Returns an array without repeated objects.
7182 * This function is similar to array_unique, but for arrays that have objects as values
7184 * @param unknown_type $array
7185 * @param unknown_type $keep_key_assoc
7188 function object_array_unique($array, $keep_key_assoc = true) {
7189 $duplicate_keys = array();
7192 foreach ($array as $key=>$val) {
7193 // convert objects to arrays, in_array() does not support objects
7194 if (is_object($val)) {
7198 if (!in_array($val, $tmp)) {
7201 $duplicate_keys[] = $key;
7205 foreach ($duplicate_keys as $key) {
7206 unset($array[$key]);
7209 return $keep_key_assoc ?
$array : array_values($array);
7212 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: