Adding test for empty db password.
[moodle.git] / lib / moodlelib.php
CommitLineData
ef1e97c7 1<?php // $Id$
f9903ed0 2
9fa49e22 3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
abc3b857 8// http://moodle.org //
9fa49e22 9// //
abc3b857 10// Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
9fa49e22 11// //
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. //
16// //
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: //
21// //
22// http://www.gnu.org/copyleft/gpl.html //
23// //
24///////////////////////////////////////////////////////////////////////////
65ccdd8c 25
7cf1c7bd 26/**
89dcb99d 27 * moodlelib.php - Moodle main library
7cf1c7bd 28 *
29 * Main library file of miscellaneous general-purpose Moodle functions.
30 * Other main libraries:
8c3dba73 31 * - weblib.php - functions that produce web output
32 * - datalib.php - functions that access the database
7cf1c7bd 33 * @author Martin Dougiamas
34 * @version $Id$
89dcb99d 35 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7cf1c7bd 36 * @package moodlecore
37 */
f374fb10 38/// CONSTANTS /////////////////////////////////////////////////////////////
39
6b94a807 40/**
41 * Used by some scripts to check they are being called by Moodle
42 */
43define('MOODLE_INTERNAL', true);
44
45
7cf1c7bd 46/**
47 * No groups used?
48 */
d8ba183c 49define('NOGROUPS', 0);
7cf1c7bd 50
51/**
52 * Groups used?
53 */
f374fb10 54define('SEPARATEGROUPS', 1);
7cf1c7bd 55
56/**
57 * Groups visible?
58 */
f374fb10 59define('VISIBLEGROUPS', 2);
60
7a5672c9 61/**
2f87145b 62 * Time constant - the number of seconds in a week
7a5672c9 63 */
361855e6 64define('WEEKSECS', 604800);
2f87145b 65
66/**
67 * Time constant - the number of seconds in a day
68 */
7a5672c9 69define('DAYSECS', 86400);
2f87145b 70
71/**
72 * Time constant - the number of seconds in an hour
73 */
7a5672c9 74define('HOURSECS', 3600);
2f87145b 75
76/**
77 * Time constant - the number of seconds in a minute
78 */
7a5672c9 79define('MINSECS', 60);
2f87145b 80
81/**
82 * Time constant - the number of minutes in a day
83 */
7a5672c9 84define('DAYMINS', 1440);
2f87145b 85
86/**
87 * Time constant - the number of minutes in an hour
88 */
7a5672c9 89define('HOURMINS', 60);
f9903ed0 90
e0d346ff 91/**
3af57507 92 * Parameter constants - if set then the parameter is cleaned of scripts etc
e0d346ff 93 */
bb8bbc74 94define('PARAM_RAW', 0x0000);
95define('PARAM_CLEAN', 0x0001);
96define('PARAM_INT', 0x0002);
97define('PARAM_INTEGER', 0x0002); // Alias for PARAM_INT
98define('PARAM_ALPHA', 0x0004);
99define('PARAM_ACTION', 0x0004); // Alias for PARAM_ALPHA
100define('PARAM_FORMAT', 0x0004); // Alias for PARAM_ALPHA
101define('PARAM_NOTAGS', 0x0008);
102define('PARAM_FILE', 0x0010);
103define('PARAM_PATH', 0x0020);
104define('PARAM_HOST', 0x0040); // FQDN or IPv4 dotted quad
105define('PARAM_URL', 0x0080);
106define('PARAM_LOCALURL',0x0180); // NOT orthogonal to the others! Implies PARAM_URL!
14d6c233 107define('PARAM_CLEANFILE',0x0200);
f24148ef 108define('PARAM_ALPHANUM',0x0400); //numbers or letters only
109define('PARAM_BOOL', 0x0800); //convert to value 1 or 0 using empty()
e0d346ff 110
8bd3fad3 111/**
112 * Definition of page types
113 */
114define('PAGE_COURSE_VIEW', 'course-view');
115define('PAGE_QUIZ_VIEW', 'mod-quiz-view');
116
9fa49e22 117/// PARAMETER HANDLING ////////////////////////////////////////////////////
6b174680 118
e0d346ff 119/**
361855e6 120 * Returns a particular value for the named variable, taken from
121 * POST or GET. If the parameter doesn't exist then an error is
e0d346ff 122 * thrown because we require this variable.
123 *
361855e6 124 * This function should be used to initialise all required values
125 * in a script that are based on parameters. Usually it will be
e0d346ff 126 * used like this:
127 * $id = required_param('id');
128 *
129 * @param string $varname the name of the parameter variable we want
130 * @param integer $options a bit field that specifies any cleaning needed
131 * @return mixed
132 */
133function required_param($varname, $options=PARAM_CLEAN) {
e0d346ff 134
135 if (isset($_POST[$varname])) { // POST has precedence
136 $param = $_POST[$varname];
137 } else if (isset($_GET[$varname])) {
138 $param = $_GET[$varname];
139 } else {
3af57507 140 error('A required parameter ('.$varname.') was missing');
e0d346ff 141 }
142
143 return clean_param($param, $options);
144}
145
146/**
361855e6 147 * Returns a particular value for the named variable, taken from
e0d346ff 148 * POST or GET, otherwise returning a given default.
149 *
361855e6 150 * This function should be used to initialise all optional values
151 * in a script that are based on parameters. Usually it will be
e0d346ff 152 * used like this:
153 * $name = optional_param('name', 'Fred');
154 *
155 * @param string $varname the name of the parameter variable we want
156 * @param mixed $default the default value to return if nothing is found
157 * @param integer $options a bit field that specifies any cleaning needed
158 * @return mixed
159 */
160function optional_param($varname, $default=NULL, $options=PARAM_CLEAN) {
e0d346ff 161
162 if (isset($_POST[$varname])) { // POST has precedence
163 $param = $_POST[$varname];
164 } else if (isset($_GET[$varname])) {
165 $param = $_GET[$varname];
166 } else {
167 return $default;
168 }
169
170 return clean_param($param, $options);
171}
172
173/**
361855e6 174 * Used by {@link optional_param()} and {@link required_param()} to
175 * clean the variables and/or cast to specific types, based on
e0d346ff 176 * an options field.
177 *
178 * @param mixed $param the variable we are cleaning
179 * @param integer $options a bit field that specifies the cleaning needed
180 * @return mixed
181 */
182function clean_param($param, $options) {
e0d346ff 183
7744ea12 184 global $CFG;
185
3af57507 186 if (!$options) {
187 return $param; // Return raw value
188 }
189
7228f796 190 if ((string)$param == (string)(int)$param) { // It's just an integer
e0d346ff 191 return (int)$param;
192 }
193
194 if ($options & PARAM_CLEAN) {
195 $param = clean_text($param); // Sweep for scripts, etc
196 }
197
198 if ($options & PARAM_INT) {
199 $param = (int)$param; // Convert to integer
200 }
201
3af57507 202 if ($options & PARAM_ALPHA) { // Remove everything not a-z
01accf3e 203 $param = eregi_replace('[^a-zA-Z]', '', $param);
3af57507 204 }
205
f24148ef 206 if ($options & PARAM_ALPHANUM) { // Remove everything not a-zA-Z0-9
207 $param = eregi_replace('[^A-Za-z0-9]', '', $param);
208 }
209
210 if ($options & PARAM_BOOL) { // Convert to 1 or 0
211 $param = empty($param) ? 0 : 1;
212 }
213
3af57507 214 if ($options & PARAM_NOTAGS) { // Strip all tags completely
215 $param = strip_tags($param);
216 }
217
14d6c233 218 if ($options & PARAM_CLEANFILE) { // allow only safe characters
219 $param = clean_filename($param);
220 }
221
3af57507 222 if ($options & PARAM_FILE) { // Strip all suspicious characters from filename
14d6c233 223 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':\\/]', '', $param);
224 $param = ereg_replace('\.\.+', '', $param);
3af57507 225 }
226
227 if ($options & PARAM_PATH) { // Strip all suspicious characters from file path
d52d5a8e 228 $param = str_replace('\\\'', '\'', $param);
229 $param = str_replace('\\"', '"', $param);
7e6b7f8d 230 $param = str_replace('\\', '/', $param);
14d6c233 231 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':]', '', $param);
7e6b7f8d 232 $param = ereg_replace('\.\.+', '', $param);
d52d5a8e 233 $param = ereg_replace('//+', '/', $param);
3af57507 234 }
235
371a2ed0 236 if ($options & PARAM_HOST) { // allow FQDN or IPv4 dotted quad
237 preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
238 // match ipv4 dotted quad
239 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
240 // confirm values are ok
241 if ( $match[0] > 255
242 || $match[1] > 255
243 || $match[3] > 255
244 || $match[4] > 255 ) {
245 // hmmm, what kind of dotted quad is this?
246 $param = '';
247 }
248 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
249 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
250 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
251 ) {
252 // all is ok - $param is respected
253 } else {
254 // all is not ok...
255 $param='';
256 }
257 }
258
7744ea12 259 if ($options & PARAM_URL) { // allow safe ftp, http, mailto urls
260
261 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
262
263 //
264 // Parameters to validateurlsyntax()
265 //
266 // s? scheme is optional
267 // H? http optional
268 // S? https optional
269 // F? ftp optional
270 // E? mailto optional
271 // u- user section not allowed
272 // P- password not allowed
273 // a? address optional
274 // I? Numeric IP address optional (can use IP or domain)
275 // p- port not allowed -- restrict to default port
276 // f? "file" path section optional
277 // q? query section optional
278 // r? fragment (anchor) optional
279 //
280 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p-f?q?r?')) {
281 // all is ok, param is respected
282 } else {
283 $param =''; // not really ok
284 }
31686aea 285 $options ^= PARAM_URL; // Turn off the URL bit so that simple PARAM_URLs don't test true for PARAM_LOCALURL
7744ea12 286 }
287
7744ea12 288 if ($options & PARAM_LOCALURL) {
289 // assume we passed the PARAM_URL test...
290 // allow http absolute, root relative and relative URLs within wwwroot
291 if (!empty($param)) {
292 if (preg_match(':^/:', $param)) {
293 // root-relative, ok!
60ecca3a 294 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
7744ea12 295 // absolute, and matches our wwwroot
296 } else {
297 // relative - let's make sure there are no tricks
298 if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
299 // looks ok.
300 } else {
301 $param = '';
302 }
303 }
304 }
305 }
7744ea12 306
e0d346ff 307 return $param;
308}
309
7cf1c7bd 310/**
7228f796 311 * For security purposes, this function will check that the currently
312 * given sesskey (passed as a parameter to the script or this function)
313 * matches that of the current user.
7cf1c7bd 314 *
7228f796 315 * @param string $sesskey optionally provided sesskey
316 * @return boolean
317 */
318function confirm_sesskey($sesskey=NULL) {
319 global $USER;
320
089e9eae 321 if (!empty($USER->ignoresesskey)) {
322 return true;
323 }
324
7228f796 325 if (empty($sesskey)) {
326 $sesskey = required_param('sesskey'); // Check script parameters
327 }
328
329 if (!isset($USER->sesskey)) {
330 return false;
331 }
332
333 return ($USER->sesskey === $sesskey);
334}
335
336
337/**
338 * Ensure that a variable is set
339 *
340 * If $var is undefined throw an error, otherwise return $var.
341 * This function will soon be made obsolete by {@link required_param()}
7cf1c7bd 342 *
7228f796 343 * @param mixed $var the variable which may be unset
344 * @param mixed $default the value to return if $var is unset
7cf1c7bd 345 */
9fa49e22 346function require_variable($var) {
9fa49e22 347 if (! isset($var)) {
b0ccd3fb 348 error('A required parameter was missing');
6b174680 349 }
350}
351
7cf1c7bd 352
353/**
354 * Ensure that a variable is set
355 *
356 * If $var is undefined set it (by reference), otherwise return $var.
7228f796 357 * This function will soon be made obsolete by {@link optional_param()}
7cf1c7bd 358 *
359 * @param mixed $var the variable which may be unset
360 * @param mixed $default the value to return if $var is unset
361 */
9fa49e22 362function optional_variable(&$var, $default=0) {
9fa49e22 363 if (! isset($var)) {
364 $var = $default;
6b174680 365 }
366}
367
7cf1c7bd 368/**
369 * Set a key in global configuration
370 *
89dcb99d 371 * Set a key/value pair in both this session's {@link $CFG} global variable
7cf1c7bd 372 * and in the 'config' database table for future sessions.
373 *
374 * @param string $name the key to set
375 * @param string $value the value to set
376 * @uses $CFG
377 * @return bool
378 */
9fa49e22 379function set_config($name, $value) {
380/// No need for get_config because they are usually always available in $CFG
70812e39 381
42282810 382 global $CFG;
383
7cf1c7bd 384
42282810 385 $CFG->$name = $value; // So it's defined for this invocation at least
dfc9ba9b 386
b0ccd3fb 387 if (get_field('config', 'name', 'name', $name)) {
388 return set_field('config', 'value', $value, 'name', $name);
d897cae4 389 } else {
9fa49e22 390 $config->name = $name;
391 $config->value = $value;
b0ccd3fb 392 return insert_record('config', $config);
39917a09 393 }
39917a09 394}
395
7cf1c7bd 396/**
397 * Refresh current $USER session global variable with all their current preferences.
398 * @uses $USER
399 */
70812e39 400function reload_user_preferences() {
70812e39 401
402 global $USER;
403
070e2616 404 if(empty($USER) || empty($USER->id)) {
405 return false;
406 }
407
d8ba183c 408 unset($USER->preference);
70812e39 409
410 if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
411 foreach ($preferences as $preference) {
412 $USER->preference[$preference->name] = $preference->value;
413 }
4586d60c 414 } else {
415 //return empty preference array to hold new values
416 $USER->preference = array();
c6d15803 417 }
70812e39 418}
419
7cf1c7bd 420/**
421 * Sets a preference for the current user
422 * Optionally, can set a preference for a different user object
423 * @uses $USER
424 * @todo Add a better description and include usage examples.
425 * @param string $name The key to set as preference for the specified user
426 * @param string $value The value to set forthe $name key in the specified user's record
c6d15803 427 * @param int $userid A moodle user ID
7cf1c7bd 428 * @todo Add inline links to $USER and user functions in above line.
429 * @return boolean
430 */
13af52a6 431function set_user_preference($name, $value, $otheruser=NULL) {
70812e39 432
433 global $USER;
434
13af52a6 435 if (empty($otheruser)){
436 if (!empty($USER) && !empty($USER->id)) {
070e2616 437 $userid = $USER->id;
13af52a6 438 } else {
070e2616 439 return false;
440 }
13af52a6 441 } else {
442 $userid = $otheruser;
d35757eb 443 }
444
70812e39 445 if (empty($name)) {
446 return false;
447 }
448
a3f1f815 449 if ($preference = get_record('user_preferences', 'userid', $userid, 'name', $name)) {
b0ccd3fb 450 if (set_field('user_preferences', 'value', $value, 'id', $preference->id)) {
13af52a6 451 if (empty($otheruser) and !empty($USER)) {
070e2616 452 $USER->preference[$name] = $value;
453 }
066af654 454 return true;
455 } else {
456 return false;
457 }
70812e39 458
459 } else {
a3f1f815 460 $preference->userid = $userid;
70812e39 461 $preference->name = $name;
462 $preference->value = (string)$value;
066af654 463 if (insert_record('user_preferences', $preference)) {
13af52a6 464 if (empty($otheruser) and !empty($USER)) {
070e2616 465 $USER->preference[$name] = $value;
466 }
70812e39 467 return true;
468 } else {
469 return false;
470 }
471 }
472}
473
6eb3e776 474/**
475 * Unsets a preference completely by deleting it from the database
476 * Optionally, can set a preference for a different user id
477 * @uses $USER
478 * @param string $name The key to unset as preference for the specified user
c6d15803 479 * @param int $userid A moodle user ID
6eb3e776 480 * @return boolean
481 */
482function unset_user_preference($name, $userid=NULL) {
483
484 global $USER;
485
361855e6 486 if (empty($userid)){
070e2616 487 if(!empty($USER) && !empty($USER->id)) {
488 $userid = $USER->id;
489 }
490 else {
491 return false;
492 }
6eb3e776 493 }
494
495 return delete_records('user_preferences', 'userid', $userid, 'name', $name);
496}
497
498
7cf1c7bd 499/**
500 * Sets a whole array of preferences for the current user
501 * @param array $prefarray An array of key/value pairs to be set
c6d15803 502 * @param int $userid A moodle user ID
7cf1c7bd 503 * @return boolean
504 */
a3f1f815 505function set_user_preferences($prefarray, $userid=NULL) {
506
507 global $USER;
70812e39 508
509 if (!is_array($prefarray) or empty($prefarray)) {
510 return false;
511 }
512
361855e6 513 if (empty($userid)){
108adee2 514 if (!empty($USER) && !empty($USER->id)) {
515 $userid = NULL; // Continue with the current user below
516 } else {
517 return false; // No-one to set!
070e2616 518 }
a3f1f815 519 }
520
70812e39 521 $return = true;
522 foreach ($prefarray as $name => $value) {
070e2616 523 // The order is important; if the test for return is done first, then
524 // if one function call fails all the remaining ones will be "optimized away"
a3f1f815 525 $return = set_user_preference($name, $value, $userid) and $return;
70812e39 526 }
527 return $return;
528}
529
7cf1c7bd 530/**
531 * If no arguments are supplied this function will return
361855e6 532 * all of the current user preferences as an array.
7cf1c7bd 533 * If a name is specified then this function
534 * attempts to return that particular preference value. If
535 * none is found, then the optional value $default is returned,
536 * otherwise NULL.
537 * @param string $name Name of the key to use in finding a preference value
538 * @param string $default Value to be returned if the $name key is not set in the user preferences
c6d15803 539 * @param int $userid A moodle user ID
7cf1c7bd 540 * @uses $USER
541 * @return string
542 */
a3f1f815 543function get_user_preferences($name=NULL, $default=NULL, $userid=NULL) {
70812e39 544
545 global $USER;
546
a3f1f815 547 if (empty($userid)) { // assume current user
548 if (empty($USER->preference)) {
549 return $default; // Default value (or NULL)
550 }
551 if (empty($name)) {
552 return $USER->preference; // Whole array
553 }
554 if (!isset($USER->preference[$name])) {
555 return $default; // Default value (or NULL)
556 }
557 return $USER->preference[$name]; // The single value
558
559 } else {
560 $preference = get_records_menu('user_preferences', 'userid', $userid, 'name', 'name,value');
561
562 if (empty($name)) {
563 return $preference;
564 }
565 if (!isset($preference[$name])) {
566 return $default; // Default value (or NULL)
567 }
568 return $preference[$name]; // The single value
70812e39 569 }
70812e39 570}
571
572
9fa49e22 573/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 574
7cf1c7bd 575/**
c6d15803 576 * Given date parts in user time produce a GMT timestamp.
7cf1c7bd 577 *
c6d15803 578 * @param int $year The year part to create timestamp of.
579 * @param int $month The month part to create timestamp of.
580 * @param int $day The day part to create timestamp of.
581 * @param int $hour The hour part to create timestamp of.
582 * @param int $minute The minute part to create timestamp of.
583 * @param int $second The second part to create timestamp of.
584 * @param int $timezone ?
585 * @return ?
7cf1c7bd 586 * @todo Finish documenting this function
587 */
9f1f6daf 588function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
39917a09 589
f30fe8d0 590 $timezone = get_user_timezone($timezone);
94e34118 591
592 if (abs($timezone) > 13) {
9f1f6daf 593 $time = mktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year, 0);
03c17ddf 594 } else {
86f092d2 595 $time = gmmktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year, 0);
9f1f6daf 596 $time = usertime($time, $timezone); // This is GMT
03c17ddf 597 }
9f1f6daf 598
599 if(!$applydst) {
600 return $time;
601 }
602
603 return $time;
604
605 /*
606 // WARNING: BUG: TODO: This is buggy, but it will do for testing purposes
607 if(($dstid = get_user_preferences('calendar_dstpreset')) !== NULL) {
608 $preset = get_record('dst_preset', 'id', $dstid);
609 if($time > $preset->last_change && $time < $preset->next_change) {
610 return $time;
611 }
612
613 // We need to find out what's going on...
614 $nowuserdate = usergetdate($time);
615
616 $changes = calendar_dst_changes_for_year($year, $preset);
617 if($time < $changes['activate'] || $time > $changes['deactivate']) {
618 // DST will be off at that time
619 if($preset->current_offset != 0) {
620 print_object('Uncompensated time was:');
621 print_object(usergetdate($time));
622 $time += $preset->apply_offset * 60;
623 print_object('Compensated time is:');
624 print_object(usergetdate($time));
625 }
626 }
627 else {
628 // DST will be on at that time
629 if($preset->current_offset == 0) {
630 print_object('Uncompensated time was:');
631 print_object(usergetdate($time));
632 $time -= $preset->apply_offset * 60;
633 print_object('Compensated time is:');
634 print_object(usergetdate($time));
635 }
636 }
637
638 return $time;
639 }
640 */
39917a09 641}
642
7cf1c7bd 643/**
644 * Given an amount of time in seconds, returns string
645 * formatted nicely as months, days, hours etc as needed
646 *
2f87145b 647 * @uses MINSECS
648 * @uses HOURSECS
649 * @uses DAYSECS
c6d15803 650 * @param int $totalsecs ?
651 * @param array $str ?
89dcb99d 652 * @return string
7cf1c7bd 653 * @todo Finish documenting this function
654 */
655 function format_time($totalsecs, $str=NULL) {
c7e3ac2a 656
6b174680 657 $totalsecs = abs($totalsecs);
c7e3ac2a 658
8dbed6be 659 if (!$str) { // Create the str structure the slow way
b0ccd3fb 660 $str->day = get_string('day');
661 $str->days = get_string('days');
662 $str->hour = get_string('hour');
663 $str->hours = get_string('hours');
664 $str->min = get_string('min');
665 $str->mins = get_string('mins');
666 $str->sec = get_string('sec');
667 $str->secs = get_string('secs');
8dbed6be 668 }
669
7a5672c9 670 $days = floor($totalsecs/DAYSECS);
671 $remainder = $totalsecs - ($days*DAYSECS);
672 $hours = floor($remainder/HOURSECS);
673 $remainder = $remainder - ($hours*HOURSECS);
674 $mins = floor($remainder/MINSECS);
675 $secs = $remainder - ($mins*MINSECS);
8dbed6be 676
677 $ss = ($secs == 1) ? $str->sec : $str->secs;
678 $sm = ($mins == 1) ? $str->min : $str->mins;
679 $sh = ($hours == 1) ? $str->hour : $str->hours;
680 $sd = ($days == 1) ? $str->day : $str->days;
681
b0ccd3fb 682 $odays = '';
683 $ohours = '';
684 $omins = '';
685 $osecs = '';
9c9f7d77 686
b0ccd3fb 687 if ($days) $odays = $days .' '. $sd;
688 if ($hours) $ohours = $hours .' '. $sh;
689 if ($mins) $omins = $mins .' '. $sm;
690 if ($secs) $osecs = $secs .' '. $ss;
6b174680 691
b0ccd3fb 692 if ($days) return $odays .' '. $ohours;
693 if ($hours) return $ohours .' '. $omins;
694 if ($mins) return $omins .' '. $osecs;
695 if ($secs) return $osecs;
696 return get_string('now');
6b174680 697}
f9903ed0 698
7cf1c7bd 699/**
700 * Returns a formatted string that represents a date in user time
701 * <b>WARNING: note that the format is for strftime(), not date().</b>
702 * Because of a bug in most Windows time libraries, we can't use
703 * the nicer %e, so we have to use %d which has leading zeroes.
704 * A lot of the fuss in the function is just getting rid of these leading
705 * zeroes as efficiently as possible.
361855e6 706 *
8c3dba73 707 * If parameter fixday = true (default), then take off leading
7cf1c7bd 708 * zero from %d, else mantain it.
709 *
2f87145b 710 * @uses HOURSECS
c6d15803 711 * @param int $date ?
712 * @param string $format ?
713 * @param int $timezone ?
714 * @param boolean $fixday If true (default) then the leading
715 * zero from %d is removed. If false then the leading zero is mantained.
716 * @return string
7cf1c7bd 717 * @todo Finish documenting this function
718 */
b0ccd3fb 719function userdate($date, $format='', $timezone=99, $fixday = true) {
7a302afc 720
b0ccd3fb 721 if ($format == '') {
722 $format = get_string('strftimedaydatetime');
5fa51a39 723 }
035cdbff 724
b0ccd3fb 725 $formatnoday = str_replace('%d', 'DD', $format);
61ae5d36 726 if ($fixday) {
727 $fixday = ($formatnoday != $format);
728 }
dcde9f02 729
f30fe8d0 730 $timezone = get_user_timezone($timezone);
90207a06 731
0431bd7c 732 if (abs($timezone) > 13) {
035cdbff 733 if ($fixday) {
734 $datestring = strftime($formatnoday, $date);
b0ccd3fb 735 $daystring = str_replace(' 0', '', strftime(" %d", $date));
736 $datestring = str_replace('DD', $daystring, $datestring);
035cdbff 737 } else {
738 $datestring = strftime($format, $date);
739 }
bea7a51e 740 } else {
7a5672c9 741 $date = $date + (int)($timezone * HOURSECS);
035cdbff 742 if ($fixday) {
70d4cf82 743 $datestring = gmstrftime($formatnoday, $date);
b0ccd3fb 744 $daystring = str_replace(' 0', '', gmstrftime(" %d", $date));
745 $datestring = str_replace('DD', $daystring, $datestring);
035cdbff 746 } else {
70d4cf82 747 $datestring = gmstrftime($format, $date);
035cdbff 748 }
873960de 749 }
bea7a51e 750
035cdbff 751 return $datestring;
873960de 752}
753
7cf1c7bd 754/**
361855e6 755 * Given a $date timestamp in GMT (seconds since epoch),
c6d15803 756 * returns an array that represents the date in user time
7cf1c7bd 757 *
2f87145b 758 * @uses HOURSECS
c6d15803 759 * @param int $date Timestamp in GMT
760 * @param int $timezone ?
761 * @return array An array that represents the date in user time
7cf1c7bd 762 * @todo Finish documenting this function
763 */
5fa51a39 764function usergetdate($date, $timezone=99) {
6b174680 765
f30fe8d0 766 $timezone = get_user_timezone($timezone);
a36166d3 767
0431bd7c 768 if (abs($timezone) > 13) {
873960de 769 return getdate($date);
770 }
d2d6171f 771 //There is no gmgetdate so I have to fake it...
7a5672c9 772 $date = $date + (int)($timezone * HOURSECS);
9f1f6daf 773
774 // This is independent of the server's TZ settings,
775 // unlike gmstrftime. It's also a bit faster this way.
776 list(
777 $getdate['seconds'],
778 $getdate['minutes'],
779 $getdate['hours'],
780 $getdate['mday'],
781 $getdate['mon'],
782 $getdate['year'],
783 $getdate['wday'],
784 $getdate['yday'],
785 $getdate['weekday'],
786 $getdate['month']
787 ) = explode(' ', gmdate('s i H d m Y w z l F', $date));
788
d2d6171f 789 return $getdate;
d552ead0 790}
791
7cf1c7bd 792/**
793 * Given a GMT timestamp (seconds since epoch), offsets it by
794 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
795 *
2f87145b 796 * @uses HOURSECS
c6d15803 797 * @param int $date Timestamp in GMT
798 * @param int $timezone ?
799 * @return int
7cf1c7bd 800 * @todo Finish documenting this function
801 */
d552ead0 802function usertime($date, $timezone=99) {
a36166d3 803
f30fe8d0 804 $timezone = get_user_timezone($timezone);
0431bd7c 805 if (abs($timezone) > 13) {
d552ead0 806 return $date;
807 }
7a5672c9 808 return $date - (int)($timezone * HOURSECS);
d552ead0 809}
810
8c3dba73 811/**
812 * Given a time, return the GMT timestamp of the most recent midnight
813 * for the current user.
814 *
c6d15803 815 * @param int $date Timestamp in GMT
816 * @param int $timezone ?
817 * @return ?
818 * @todo Finish documenting this function. Is timezone an int or float?
8c3dba73 819 */
edf7fe8c 820function usergetmidnight($date, $timezone=99) {
edf7fe8c 821
f30fe8d0 822 $timezone = get_user_timezone($timezone);
edf7fe8c 823 $userdate = usergetdate($date, $timezone);
4606d9bb 824
0431bd7c 825 if (abs($timezone) > 13) {
b0ccd3fb 826 return mktime(0, 0, 0, $userdate['mon'], $userdate['mday'], $userdate['year']);
4606d9bb 827 }
828
b0ccd3fb 829 $timemidnight = gmmktime (0, 0, 0, $userdate['mon'], $userdate['mday'], $userdate['year']);
edf7fe8c 830 return usertime($timemidnight, $timezone); // Time of midnight of this user's day, in GMT
831
832}
833
7cf1c7bd 834/**
835 * Returns a string that prints the user's timezone
836 *
837 * @param float $timezone The user's timezone
838 * @return string
c6d15803 839 * @todo is $timezone an int or a float?
7cf1c7bd 840 */
d552ead0 841function usertimezone($timezone=99) {
d552ead0 842
f30fe8d0 843 $timezone = get_user_timezone($timezone);
844
0431bd7c 845 if (abs($timezone) > 13) {
b0ccd3fb 846 return 'server time';
d552ead0 847 }
848 if (abs($timezone) < 0.5) {
b0ccd3fb 849 return 'GMT';
d552ead0 850 }
851 if ($timezone > 0) {
b0ccd3fb 852 return 'GMT+'. $timezone;
d552ead0 853 } else {
b0ccd3fb 854 return 'GMT'. $timezone;
d552ead0 855 }
f9903ed0 856}
857
7cf1c7bd 858/**
859 * Returns a float which represents the user's timezone difference from GMT in hours
860 * Checks various settings and picks the most dominant of those which have a value
861 *
7cf1c7bd 862 * @uses $CFG
863 * @uses $USER
c6d15803 864 * @param int $tz The user's timezone
865 * @return int
866 * @todo is $tz an int or a float?
7cf1c7bd 867 */
f30fe8d0 868function get_user_timezone($tz = 99) {
f30fe8d0 869
870 // Variables declared explicitly global here so that if we add
871 // something later we won't forget to global it...
872 $timezones = array(
873 isset($GLOBALS['USER']->timezone) ? $GLOBALS['USER']->timezone : 99,
874 isset($GLOBALS['CFG']->timezone) ? $GLOBALS['CFG']->timezone : 99,
875 );
876 while($tz == 99 && $next = each($timezones)) {
877 $tz = (float)$next['value'];
878 }
879
880 return $tz;
881}
f9903ed0 882
9fa49e22 883/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 884
1a33f699 885// Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
886// if one does not already exist, but does not overwrite existing sesskeys. Returns the
887// sesskey string if $USER exists, or boolean false if not.
04280e85 888function sesskey() {
1a33f699 889 global $USER;
890
891 if(!isset($USER)) {
892 return false;
893 }
894
895 if (empty($USER->sesskey)) {
896 $USER->sesskey = random_string(10);
897 }
898
899 return $USER->sesskey;
900}
901
7cf1c7bd 902/**
903 * This function checks that the current user is logged in, and optionally
904 * whether they are "logged in" or allowed to be in a particular course.
905 * If not, then it redirects them to the site login or course enrolment.
906 * $autologinguest determines whether visitors should automatically be
89dcb99d 907 * logged in as guests provide {@link $CFG}->autologinguests is set to 1
7cf1c7bd 908 *
7cf1c7bd 909 * @uses $CFG
c6d15803 910 * @uses $SESSION
7cf1c7bd 911 * @uses $USER
912 * @uses $FULLME
c6d15803 913 * @uses SITEID
7cf1c7bd 914 * @uses $MoodleSession
c6d15803 915 * @param int $courseid The course in question
916 * @param boolean $autologinguest ?
7cf1c7bd 917 * @todo Finish documenting this function
918 */
8e8d0524 919function require_login($courseid=0, $autologinguest=true) {
f9903ed0 920
73047f2f 921 global $CFG, $SESSION, $USER, $FULLME, $MoodleSession;
d8ba183c 922
da5c172a 923 // First check that the user is logged in to the site.
c21c671d 924 if (! (isset($USER->loggedin) and $USER->confirmed and ($USER->site == $CFG->wwwroot)) ) { // They're not
f9903ed0 925 $SESSION->wantsurl = $FULLME;
b0ccd3fb 926 if (!empty($_SERVER['HTTP_REFERER'])) {
927 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
9f44d972 928 }
c21c671d 929 $USER = NULL;
8e8d0524 930 if ($autologinguest and $CFG->autologinguests and $courseid and get_field('course','guest','id',$courseid)) {
931 $loginguest = '?loginguest=true';
932 } else {
933 $loginguest = '';
a2ebe6a5 934 }
8a33e371 935 if (empty($CFG->loginhttps)) {
b0ccd3fb 936 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
8a33e371 937 } else {
b0ccd3fb 938 $wwwroot = str_replace('http','https', $CFG->wwwroot);
939 redirect($wwwroot .'/login/index.php'. $loginguest);
8a33e371 940 }
f9903ed0 941 die;
f9903ed0 942 }
808a3baa 943
d35757eb 944 // check whether the user should be changing password
027a1604 945 // reload_user_preferences(); // Why is this necessary? Seems wasteful. - MD
a3f1f815 946 if (!empty($USER->preference['auth_forcepasswordchange'])){
d35757eb 947 if (is_internal_auth() || $CFG->{'auth_'.$USER->auth.'_stdchangepassword'}){
b0ccd3fb 948 redirect($CFG->wwwroot .'/login/change_password.php');
d35757eb 949 } elseif($CFG->changepassword) {
950 redirect($CFG->changepassword);
951 } else {
361855e6 952 error('You cannot proceed without changing your password.
d35757eb 953 However there is no available page for changing it.
b0ccd3fb 954 Please contact your Moodle Administrator.');
d35757eb 955 }
956 }
957
808a3baa 958 // Check that the user account is properly set up
959 if (user_not_fully_set_up($USER)) {
b0ccd3fb 960 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 961 die;
962 }
d8ba183c 963
366dfa60 964 // Make sure current IP matches the one for this session (if required)
361855e6 965 if (!empty($CFG->tracksessionip)) {
366dfa60 966 if ($USER->sessionIP != md5(getremoteaddr())) {
967 error(get_string('sessionipnomatch', 'error'));
968 }
969 }
6d8f47d6 970
971 // Make sure the USER has a sesskey set up. Used for checking script parameters.
04280e85 972 sesskey();
366dfa60 973
027a1604 974 // Check that the user has agreed to a site policy if there is one
975 if (!empty($CFG->sitepolicy)) {
976 if (!$USER->policyagreed) {
957b5198 977 $SESSION->wantsurl = $FULLME;
027a1604 978 redirect($CFG->wwwroot .'/user/policy.php');
979 die;
980 }
981 }
982
da5c172a 983 // Next, check if the user can be in a particular course
984 if ($courseid) {
361855e6 985 if ($courseid == SITEID) {
e3512050 986 return; // Anyone can be in the site course
987 }
9c9f7d77 988 if (!empty($USER->student[$courseid]) or !empty($USER->teacher[$courseid]) or !empty($USER->admin)) {
cb909d74 989 if (isset($USER->realuser)) { // Make sure the REAL person can also access this course
990 if (!isteacher($courseid, $USER->realuser)) {
991 print_header();
b0ccd3fb 992 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
cb909d74 993 }
3ce2f1e0 994 }
da5c172a 995 return; // user is a member of this course.
996 }
b0ccd3fb 997 if (! $course = get_record('course', 'id', $courseid)) {
998 error('That course doesn\'t exist');
da5c172a 999 }
1efa27fd 1000 if (!$course->visible) {
1001 print_header();
b0ccd3fb 1002 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
1efa27fd 1003 }
b0ccd3fb 1004 if ($USER->username == 'guest') {
7363ff91 1005 switch ($course->guest) {
1006 case 0: // Guests not allowed
1007 print_header();
b0ccd3fb 1008 notice(get_string('guestsnotallowed', '', $course->fullname));
7363ff91 1009 break;
1010 case 1: // Guests allowed
7363ff91 1011 return;
1012 case 2: // Guests allowed with key (drop through)
1013 break;
1014 }
da5c172a 1015 }
f9903ed0 1016
9ca3b4f3 1017 //User is not enrolled in the course, wants to access course content
1018 //as a guest, and course setting allow unlimited guest access
1019 //Code cribbed from course/loginas.php
1020 if (strstr($FULLME,"username=guest") && ($course->guest==1)) {
1021 $realuser = $USER->id;
1022 $realname = fullname($USER, true);
1023 $USER = guest_user();
1024 $USER->loggedin = true;
1025 $USER->site = $CFG->wwwroot;
1026 $USER->realuser = $realuser;
1027 if (isset($SESSION->currentgroup[$course->id])) { // Remember current setting for later
1028 $SESSION->oldcurrentgroup = $SESSION->currentgroup[$course->id];
1029 unset($SESSION->currentgroup[$course->id]);
1030 }
1031 $guest_name = fullname($USER, true);
1032 add_to_log($course->id, "course", "loginas", "../user/view.php?id=$course->id&$USER->id$", "$realname -> $guest_name");
1033 return;
1034 }
1035
7363ff91 1036 // Currently not enrolled in the course, so see if they want to enrol
da5c172a 1037 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1038 redirect($CFG->wwwroot .'/course/enrol.php?id='. $courseid);
da5c172a 1039 die;
1040 }
f9903ed0 1041}
1042
7cf1c7bd 1043/**
1044 * This is a weaker version of {@link require_login()} which only requires login
1045 * when called from within a course rather than the site page, unless
1046 * the forcelogin option is turned on.
1047 *
1048 * @uses $CFG
c6d15803 1049 * @param int $courseid The course in question
1050 * @param boolean $autologinguest ?
7cf1c7bd 1051 * @todo Finish documenting this function
1052 */
f950af3c 1053function require_course_login($course, $autologinguest=true) {
f950af3c 1054 global $CFG;
1055 if ($CFG->forcelogin) {
1056 require_login();
1057 }
1058 if ($course->category) {
1059 require_login($course->id, $autologinguest);
1060 }
1061}
1062
7cf1c7bd 1063/**
1064 * Modify the user table by setting the currently logged in user's
1065 * last login to now.
1066 *
1067 * @uses $USER
1068 * @return boolean
1069 */
1d881d92 1070function update_user_login_times() {
1071 global $USER;
1072
1073 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2a2f5f11 1074 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1d881d92 1075
1076 $user->id = $USER->id;
1077
b0ccd3fb 1078 return update_record('user', $user);
1d881d92 1079}
1080
7cf1c7bd 1081/**
1082 * Determines if a user has completed setting up their account.
1083 *
89dcb99d 1084 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
7cf1c7bd 1085 * @return boolean
1086 */
808a3baa 1087function user_not_fully_set_up($user) {
b0ccd3fb 1088 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email)));
808a3baa 1089}
f9903ed0 1090
7cf1c7bd 1091/**
1092 * Keeps track of login attempts
1093 *
1094 * @uses $SESSION
1095 */
f9903ed0 1096function update_login_count() {
9fa49e22 1097
f9903ed0 1098 global $SESSION;
1099
1100 $max_logins = 10;
1101
1102 if (empty($SESSION->logincount)) {
1103 $SESSION->logincount = 1;
1104 } else {
1105 $SESSION->logincount++;
1106 }
1107
1108 if ($SESSION->logincount > $max_logins) {
9fa49e22 1109 unset($SESSION->wantsurl);
b0ccd3fb 1110 error(get_string('errortoomanylogins'));
d578afc8 1111 }
1112}
1113
7cf1c7bd 1114/**
1115 * Resets login attempts
1116 *
1117 * @uses $SESSION
1118 */
9fa49e22 1119function reset_login_count() {
9fa49e22 1120 global $SESSION;
d578afc8 1121
9fa49e22 1122 $SESSION->logincount = 0;
d578afc8 1123}
1124
7cf1c7bd 1125/**
1126 * check_for_restricted_user
1127 *
89dcb99d 1128 * @uses $CFG
1129 * @uses $USER
1130 * @param string $username ?
1131 * @param string $redirect ?
7cf1c7bd 1132 * @todo Finish documenting this function
1133 */
b0ccd3fb 1134function check_for_restricted_user($username=NULL, $redirect='') {
cb98d312 1135 global $CFG, $USER;
1136
1137 if (!$username) {
1138 if (!empty($USER->username)) {
1139 $username = $USER->username;
1140 } else {
1141 return false;
1142 }
1143 }
1144
1145 if (!empty($CFG->restrictusers)) {
1146 $names = explode(',', $CFG->restrictusers);
1147 if (in_array($username, $names)) {
b0ccd3fb 1148 error(get_string('restricteduser', 'error', fullname($USER)), $redirect);
cb98d312 1149 }
1150 }
1151}
1152
b61efafb 1153function sync_metacourses() {
1154
1155 global $CFG;
1156
5f37b628 1157 if (!$courses = get_records_sql("SELECT DISTINCT parent_course,1 FROM {$CFG->prefix}course_meta")) {
b61efafb 1158 return;
1159 }
1160
1161 foreach ($courses as $course) {
1162 sync_metacourse($course->parent_course);
1163 }
1164}
1165
1166
1167/**
1168 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
1169 */
1170
1171function sync_metacourse($metacourseid) {
1172
1173 global $CFG;
1174
1175 if (!$metacourse = get_record("course","id",$metacourseid)) {
1176 return false;
1177 }
1178
1179
5f37b628 1180 if (count_records('course_meta','parent_course',$metacourseid) == 0) { // if there are no child courses for this meta course, nuke the enrolments
b61efafb 1181 if ($enrolments = get_records('user_students','course',$metacourseid,'','userid,1')) {
1182 foreach ($enrolments as $enrolment) {
1183 unenrol_student($enrolment->userid,$metacourseid);
1184 }
1185 }
1186 return true;
1187 }
1188
1189
1190 // this will return a list of userids from user_student for enrolments in the metacourse that shouldn't be there.
1191 $sql = "SELECT DISTINCT parent.userid,1
5f37b628 1192 FROM {$CFG->prefix}course_meta meta
b61efafb 1193 JOIN {$CFG->prefix}user_students parent
1194 ON meta.parent_course = parent.course
ee1bef90 1195 LEFT OUTER JOIN {$CFG->prefix}user_students child
b61efafb 1196 ON meta.child_course = child.course
ee1bef90 1197 AND child.userid = parent.userid
1198 WHERE child.course IS NULL
1199 AND meta.parent_course = $metacourseid";
b61efafb 1200
1201 if ($enrolmentstodelete = get_records_sql($sql)) {
1202 foreach ($enrolmentstodelete as $enrolment) {
1203 unenrol_student($enrolment->userid,$metacourseid); // doing it this way for forum subscriptions etc.
1204 }
1205 }
1206
1207
1208 // this will return a list of userids that need to be enrolled in the metacourse
1209 $sql = "SELECT DISTINCT child.userid,1
5f37b628 1210 FROM {$CFG->prefix}course_meta meta
b61efafb 1211 JOIN {$CFG->prefix}user_students child
1212 ON meta.child_course = child.course
ee1bef90 1213 LEFT OUTER JOIN {$CFG->prefix}user_students parent
b61efafb 1214 ON meta.parent_course = parent.course
ee1bef90 1215 AND parent.userid = child.userid
1216 WHERE parent.course IS NULL
1217 AND meta.parent_course = $metacourseid";
b61efafb 1218
1219 if ($userstoadd = get_records_sql($sql)) {
1220 foreach ($userstoadd as $user) {
1221 enrol_student($user->userid,$metacourseid);
1222 }
1223 }
1224
1225 // and next make sure that we have the right start time and end time (ie max and min) for them all.
1226 if ($enrolments = get_records('user_students','course',$metacourseid,'','id,userid')) {
1227 foreach ($enrolments as $enrol) {
1228 if ($maxmin = get_record_sql("SELECT min(timestart) AS timestart, max(timeend) AS timeend
5f37b628 1229 FROM mdl_user_students u JOIN {$CFG->prefix}course_meta mc ON u.course = mc.child_course WHERE userid = $enrol->userid
b61efafb 1230 AND mc.parent_course = $metacourseid")) {
1231 $enrol->timestart = $maxmin->timestart;
1232 $enrol->timeend = $maxmin->timeend;
1233 update_record('user_students',$enrol);
1234 }
1235 }
1236 }
1237 return true;
1238}
1239
1240/**
1241 * Adds a record to the metacourse table and calls sync_metacoures
1242 */
1243function add_to_metacourse ($metacourseid, $courseid) {
1244
1245 if (!$metacourse = get_record("course","id",$metacourseid)) {
1246 return false;
1247 }
1248
1249 if (!$course = get_record("course","id",$courseid)) {
1250 return false;
1251 }
1252
5f37b628 1253 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
b61efafb 1254 $rec->parent_course = $metacourseid;
1255 $rec->child_course = $courseid;
5f37b628 1256 if (!insert_record('course_meta',$rec)) {
b61efafb 1257 return false;
1258 }
1259 return sync_metacourse($metacourseid);
1260 }
1261 return true;
1262
1263}
1264
1265/**
1266 * Removes the record from the metacourse table and calls sync_metacourse
1267 */
1268function remove_from_metacourse($metacourseid, $courseid) {
1269
5f37b628 1270 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
b61efafb 1271 return sync_metacourse($metacourseid);
1272 }
1273 return false;
1274}
1275
1276
7cf1c7bd 1277/**
1278 * Determines if a user an admin
1279 *
1280 * @uses $USER
c6d15803 1281 * @param int $userid The id of the user as is found in the 'user' table
89dcb99d 1282 * @staticvar array $admin ?
1283 * @staticvar array $nonadmins ?
7cf1c7bd 1284 * @return boolean
89dcb99d 1285 * @todo Complete documentation for this function
7cf1c7bd 1286 */
581d7b49 1287function isadmin($userid=0) {
f9903ed0 1288 global $USER;
aa095969 1289 static $admins = array();
1290 static $nonadmins = array();
f9903ed0 1291
581d7b49 1292 if (!$userid){
1293 if (empty($USER->id)) {
1294 return false;
1295 }
1296 $userid = $USER->id;
9bd2c874 1297 }
1298
581d7b49 1299 if (in_array($userid, $admins)) {
aa095969 1300 return true;
581d7b49 1301 } else if (in_array($userid, $nonadmins)) {
aa095969 1302 return false;
b0ccd3fb 1303 } else if (record_exists('user_admins', 'userid', $userid)){
581d7b49 1304 $admins[] = $userid;
aa095969 1305 return true;
1306 } else {
581d7b49 1307 $nonadmins[] = $userid;
aa095969 1308 return false;
f9903ed0 1309 }
f9903ed0 1310}
1311
7cf1c7bd 1312/**
1313 * Determines if a user is a teacher or an admin
1314 *
9407d456 1315 * @uses $USER
c6d15803 1316 * @param int $courseid The id of the course that is being viewed, if any
1317 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
7cf1c7bd 1318 * @param boolean $includeadmin If true this function will return true when it encounters an admin user.
1319 * @return boolean
1320 * @todo Finish documenting this function
1321 */
9407d456 1322function isteacher($courseid, $userid=0, $includeadmin=true) {
f9903ed0 1323 global $USER;
1324
9788367b 1325 if ($includeadmin and isadmin($userid)) { // admins can do anything the teacher can
d115a57f 1326 return true;
1327 }
1328
9407d456 1329 if (empty($courseid)) {
1330 notify('isteacher() should not be used without a valid course id as argument');
1331 return isteacherinanycourse($userid, $includeadmin);
1332 }
1333
f9903ed0 1334 if (!$userid) {
71f9abf9 1335 if ($courseid) {
1336 return !empty($USER->teacher[$courseid]);
1337 }
1338 if (!isset($USER->id)) {
1339 return false;
1340 }
1341 $userid = $USER->id;
f9903ed0 1342 }
1343
9407d456 1344 return record_exists('user_teachers', 'userid', $userid, 'course', $courseid);
1345}
1346
1347/**
1348 * Determines if a user is a teacher in any course, or an admin
1349 *
1350 * @uses $USER
1351 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
1352 * @param boolean $includeadmin If true this function will return true when it encounters an admin user.
1353 * @return boolean
1354 * @todo Finish documenting this function
1355 */
1356function isteacherinanycourse($userid = 0, $includeadmin = true) {
fddbcf9c 1357 global $USER;
1358
9407d456 1359 if(empty($userid)) {
1360 if(empty($USER) || empty($USER->id)) {
1361 return false;
1362 }
1363 $userid = $USER->id;
9d3c795c 1364 }
1365
fddbcf9c 1366 if (isadmin($userid) && $includeadmin) { // admins can do anything
1367 return true;
1368 }
1369
9407d456 1370 return record_exists('user_teachers', 'userid', $userid);
f9903ed0 1371}
1372
7cf1c7bd 1373/**
1374 * Determines if a user is allowed to edit a given course
1375 *
1376 * @uses $USER
c6d15803 1377 * @param int $courseid The id of the course that is being edited
1378 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
7cf1c7bd 1379 * @return boolean
1380 */
73047f2f 1381function isteacheredit($courseid, $userid=0) {
73047f2f 1382 global $USER;
1383
d8ba183c 1384 if (isadmin($userid)) { // admins can do anything
73047f2f 1385 return true;
1386 }
1387
1388 if (!$userid) {
1389 return !empty($USER->teacheredit[$courseid]);
1390 }
1391
b0ccd3fb 1392 return get_field('user_teachers', 'editall', 'userid', $userid, 'course', $courseid);
73047f2f 1393}
1394
7cf1c7bd 1395/**
1396 * Determines if a user can create new courses
1397 *
1398 * @uses $USER
361855e6 1399 * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
7cf1c7bd 1400 * @return boolean
1401 */
1924074c 1402function iscreator ($userid=0) {
1924074c 1403 global $USER;
8a205861 1404 if (empty($USER->id)) {
1405 return false;
1406 }
1924074c 1407 if (isadmin($userid)) { // admins can do anything
1408 return true;
1409 }
8a205861 1410 if (empty($userid)) {
b0ccd3fb 1411 return record_exists('user_coursecreators', 'userid', $USER->id);
1924074c 1412 }
1413
b0ccd3fb 1414 return record_exists('user_coursecreators', 'userid', $userid);
1924074c 1415}
1416
7cf1c7bd 1417/**
1418 * Determines if a user is a student in the specified course
361855e6 1419 *
7cf1c7bd 1420 * If the course id specifies the site then the function determines
1421 * if the user is a confirmed and valid user of this site.
1422 *
1423 * @uses $USER
1424 * @uses $CFG
c6d15803 1425 * @uses SITEID
1426 * @param int $courseid The id of the course being tested
361855e6 1427 * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
7cf1c7bd 1428 * @return boolean
1429 */
8a9e3fd7 1430function isstudent($courseid, $userid=0) {
71f9abf9 1431 global $USER, $CFG;
f9903ed0 1432
2700d113 1433 if (empty($USER->id) and !$userid) {
7064e18f 1434 return false;
1435 }
1436
222ac91b 1437 if ($courseid == SITEID) {
2cc72e84 1438 if (!$userid) {
1439 $userid = $USER->id;
1440 }
1441 if (isguest($userid)) {
1442 return false;
1443 }
71f9abf9 1444 // a site teacher can never be a site student
1445 if (isteacher($courseid, $userid)) {
1446 return false;
1447 }
2700d113 1448 if ($CFG->allusersaresitestudents) {
1449 return record_exists('user', 'id', $userid);
1450 } else {
1451 return (record_exists('user_students', 'userid', $userid)
71f9abf9 1452 or record_exists('user_teachers', 'userid', $userid));
2700d113 1453 }
8f0cd6ef 1454 }
2cc72e84 1455
f9903ed0 1456 if (!$userid) {
346b1a24 1457 return !empty($USER->student[$courseid]);
f9903ed0 1458 }
1459
ebc3bd2b 1460 // $timenow = time(); // todo: add time check below
f9903ed0 1461
b0ccd3fb 1462 return record_exists('user_students', 'userid', $userid, 'course', $courseid);
f9903ed0 1463}
1464
7cf1c7bd 1465/**
1466 * Determines if the specified user is logged in as guest.
1467 *
1468 * @uses $USER
361855e6 1469 * @param int $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
7cf1c7bd 1470 * @return boolean
1471 */
da5c172a 1472function isguest($userid=0) {
1473 global $USER;
1474
1475 if (!$userid) {
b35e8568 1476 if (empty($USER->username)) {
1477 return false;
1478 }
b0ccd3fb 1479 return ($USER->username == 'guest');
da5c172a 1480 }
1481
b0ccd3fb 1482 return record_exists('user', 'id', $userid, 'username', 'guest');
da5c172a 1483}
1484
7cf1c7bd 1485/**
1486 * Determines if the currently logged in user is in editing mode
1487 *
1488 * @uses $USER
c6d15803 1489 * @param int $courseid The id of the course being tested
89dcb99d 1490 * @param user $user A {@link $USER} object. If null then the currently logged in user is used.
7cf1c7bd 1491 * @return boolean
1492 */
2c309dc2 1493function isediting($courseid, $user=NULL) {
1494 global $USER;
1495 if (!$user){
1496 $user = $USER;
1497 }
9c9f7d77 1498 if (empty($user->editing)) {
1499 return false;
1500 }
2c309dc2 1501 return ($user->editing and isteacher($courseid, $user->id));
1502}
1503
7cf1c7bd 1504/**
1505 * Determines if the logged in user is currently moving an activity
1506 *
1507 * @uses $USER
c6d15803 1508 * @param int $courseid The id of the course being tested
7cf1c7bd 1509 * @return boolean
1510 */
7977cffd 1511function ismoving($courseid) {
7977cffd 1512 global $USER;
1513
1514 if (!empty($USER->activitycopy)) {
1515 return ($USER->activitycopycourse == $courseid);
1516 }
1517 return false;
1518}
1519
7cf1c7bd 1520/**
1521 * Given an object containing firstname and lastname
1522 * values, this function returns a string with the
1523 * full name of the person.
1524 * The result may depend on system settings
1525 * or language. 'override' will force both names
361855e6 1526 * to be used even if system settings specify one.
7cf1c7bd 1527 * @uses $CFG
1528 * @uses $SESSION
1529 * @param type description
1530 * @todo Finish documenting this function
1531 */
e2cd5065 1532function fullname($user, $override=false) {
b5cbb64d 1533
f374fb10 1534 global $CFG, $SESSION;
1535
6527c077 1536 if (!isset($user->firstname) and !isset($user->lastname)) {
1537 return '';
1538 }
1539
f374fb10 1540 if (!empty($SESSION->fullnamedisplay)) {
1541 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
1542 }
e2cd5065 1543
b5cbb64d 1544 if ($CFG->fullnamedisplay == 'firstname lastname') {
b0ccd3fb 1545 return $user->firstname .' '. $user->lastname;
b5cbb64d 1546
1547 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 1548 return $user->lastname .' '. $user->firstname;
e2cd5065 1549
b5cbb64d 1550 } else if ($CFG->fullnamedisplay == 'firstname') {
1551 if ($override) {
1552 return get_string('fullnamedisplay', '', $user);
1553 } else {
1554 return $user->firstname;
1555 }
1556 }
e2cd5065 1557
b5cbb64d 1558 return get_string('fullnamedisplay', '', $user);
e2cd5065 1559}
1560
7cf1c7bd 1561/**
1562 * Sets a moodle cookie with an encrypted string
1563 *
1564 * @uses $CFG
2f87145b 1565 * @uses DAYSECS
1566 * @uses HOURSECS
7cf1c7bd 1567 * @param string $thing The string to encrypt and place in a cookie
1568 */
f9903ed0 1569function set_moodle_cookie($thing) {
7185e073 1570 global $CFG;
482b6e6e 1571
1572 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
f9903ed0 1573
1574 $days = 60;
7a5672c9 1575 $seconds = DAYSECS*$days;
f9903ed0 1576
7a5672c9 1577 setCookie($cookiename, '', time() - HOURSECS, '/');
b0ccd3fb 1578 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, '/');
f9903ed0 1579}
1580
7cf1c7bd 1581/**
1582 * Gets a moodle cookie with an encrypted string
1583 *
1584 * @uses $CFG
1585 * @return string
1586 */
f9903ed0 1587function get_moodle_cookie() {
7185e073 1588 global $CFG;
1589
482b6e6e 1590 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
7185e073 1591
1079c8a8 1592 if (empty($_COOKIE[$cookiename])) {
b0ccd3fb 1593 return '';
1079c8a8 1594 } else {
1595 return rc4decrypt($_COOKIE[$cookiename]);
1596 }
f9903ed0 1597}
1598
7cf1c7bd 1599/**
1600 * Returns true if an internal authentication method is being used.
1601 * if method not specified then, global default is assumed
1602 *
1603 * @uses $CFG
1604 * @param string $auth Form of authentication required
1605 * @return boolean
1606 * @todo Outline auth types and provide code example
1607 */
39a5a35d 1608function is_internal_auth($auth='') {
ba7166c3 1609/// Returns true if an internal authentication method is being used.
a3f1f815 1610/// If auth not specified then global default is assumed
ba7166c3 1611
1612 global $CFG;
1613
a3f1f815 1614 if (empty($auth)) {
1615 $auth = $CFG->auth;
39a5a35d 1616 }
1617
a3f1f815 1618 return ($auth == "email" || $auth == "none" || $auth == "manual");
1619}
1620
8c3dba73 1621/**
1622 * Returns an array of user fields
1623 *
c6d15803 1624 * @uses $CFG
1625 * @uses $db
1626 * @return array User field/column names
8c3dba73 1627 * @todo Finish documenting this function
1628 */
a3f1f815 1629function get_user_fieldnames() {
a3f1f815 1630
1631 global $CFG, $db;
1632
1633 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
1634 unset($fieldarray['ID']);
1635
1636 return $fieldarray;
ba7166c3 1637}
f9903ed0 1638
7cf1c7bd 1639/**
1640 * Creates a bare-bones user record
1641 *
1642 * @uses $CFG
7cf1c7bd 1643 * @param string $username New user's username to add to record
1644 * @param string $password New user's password to add to record
1645 * @param string $auth Form of authentication required
89dcb99d 1646 * @return user A {@link $USER} object
7cf1c7bd 1647 * @todo Outline auth types and provide code example
1648 */
71f9abf9 1649function create_user_record($username, $password, $auth='') {
366dfa60 1650 global $CFG;
71f9abf9 1651
1e22bc9c 1652 //just in case check text case
1653 $username = trim(moodle_strtolower($username));
71f9abf9 1654
3271b70f 1655 if (function_exists('auth_get_userinfo')) {
e858f9da 1656 if ($newinfo = auth_get_userinfo($username)) {
b36a8fc4 1657 $newinfo = truncate_userinfo($newinfo);
34daec9b 1658 foreach ($newinfo as $key => $value){
9f44d972 1659 $newuser->$key = addslashes(stripslashes($value)); // Just in case
e858f9da 1660 }
1661 }
1662 }
f9903ed0 1663
85a1d4c9 1664 if (!empty($newuser->email)) {
1665 if (email_is_not_allowed($newuser->email)) {
1666 unset($newuser->email);
1667 }
1668 }
1669
71f9abf9 1670 $newuser->auth = (empty($auth)) ? $CFG->auth : $auth;
faebaf0f 1671 $newuser->username = $username;
1672 $newuser->password = md5($password);
a0bac19d 1673 $newuser->lang = $CFG->lang;
faebaf0f 1674 $newuser->confirmed = 1;
59619427 1675 $newuser->lastIP = getremoteaddr();
faebaf0f 1676 $newuser->timemodified = time();
f9903ed0 1677
b0ccd3fb 1678 if (insert_record('user', $newuser)) {
1679 $user = get_user_info_from_db('username', $newuser->username);
d35757eb 1680 if($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'}){
1681 set_user_preference('auth_forcepasswordchange', 1, $user);
1682 }
1683 return $user;
faebaf0f 1684 }
1685 return false;
1686}
1687
7cf1c7bd 1688/**
1689 * Will update a local user record from an external source
1690 *
1691 * @uses $CFG
1692 * @param string $username New user's username to add to record
89dcb99d 1693 * @return user A {@link $USER} object
7cf1c7bd 1694 */
d35757eb 1695function update_user_record($username) {
d35757eb 1696 global $CFG;
1697
1698 if (function_exists('auth_get_userinfo')) {
1699 $username = trim(moodle_strtolower($username)); /// just in case check text case
1700
1701 if ($newinfo = auth_get_userinfo($username)) {
1702 foreach ($newinfo as $key => $value){
1703 if (!empty($CFG->{'auth_user_' . $key. '_updatelocal'})) {
1704 $value = addslashes(stripslashes($value)); // Just in case
1705 set_field('user', $key, $value, 'username', $username);
1706 }
1707 }
1708 }
1709 }
b0ccd3fb 1710 return get_user_info_from_db('username', $username);
d35757eb 1711}
0609562b 1712
b36a8fc4 1713function truncate_userinfo($info) {
1714/// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
1715/// which may have large fields
1716
1717 // define the limits
1718 $limit = array(
1719 'username' => 100,
1720 'idnumber' => 12,
1721 'firstname' => 20,
1722 'lastname' => 20,
1723 'email' => 100,
1724 'icq' => 15,
1725 'phone1' => 20,
1726 'phone2' => 20,
1727 'institution' => 40,
1728 'department' => 30,
1729 'address' => 70,
1730 'city' => 20,
1731 'country' => 2,
1732 'url' => 255,
1733 );
361855e6 1734
b36a8fc4 1735 // apply where needed
1736 foreach (array_keys($info) as $key) {
1737 if (!empty($limit[$key])) {
1738 $info[$key] = substr($info[$key],0, $limit[$key]);
361855e6 1739 }
b36a8fc4 1740 }
361855e6 1741
b36a8fc4 1742 return $info;
1743}
1744
7cf1c7bd 1745/**
1746 * Retrieve the guest user object
1747 *
1748 * @uses $CFG
89dcb99d 1749 * @return user A {@link $USER} object
7cf1c7bd 1750 */
0609562b 1751function guest_user() {
1752 global $CFG;
1753
b0ccd3fb 1754 if ($newuser = get_record('user', 'username', 'guest')) {
0609562b 1755 $newuser->loggedin = true;
1756 $newuser->confirmed = 1;
1757 $newuser->site = $CFG->wwwroot;
1758 $newuser->lang = $CFG->lang;
366dfa60 1759 $newuser->lastIP = getremoteaddr();
0609562b 1760 }
1761
1762 return $newuser;
1763}
1764
7cf1c7bd 1765/**
1766 * Given a username and password, this function looks them
1767 * up using the currently selected authentication mechanism,
1768 * and if the authentication is successful, it returns a
1769 * valid $user object from the 'user' table.
361855e6 1770 *
7cf1c7bd 1771 * Uses auth_ functions from the currently active auth module
1772 *
1773 * @uses $CFG
361855e6 1774 * @param string $username User's username
1775 * @param string $password User's password
89dcb99d 1776 * @return user|flase A {@link $USER} object or false if error
7cf1c7bd 1777 */
faebaf0f 1778function authenticate_user_login($username, $password) {
faebaf0f 1779
1780 global $CFG;
1781
466558e3 1782 $md5password = md5($password);
1783
27286aeb 1784 // First try to find the user in the database
466558e3 1785
18f16d61 1786 if (!$user = get_user_info_from_db('username', $username)) {
1787 $user->id = 0; // Not a user
1788 $user->auth = $CFG->auth;
1789 }
39a5a35d 1790
27286aeb 1791 // Sort out the authentication method we are using.
39a5a35d 1792
27286aeb 1793 if (empty($CFG->auth)) {
b0ccd3fb 1794 $CFG->auth = 'manual'; // Default authentication module
27286aeb 1795 }
39a5a35d 1796
27286aeb 1797 if (empty($user->auth)) { // For some reason it isn't set yet
1798 if (isadmin($user->id) or isguest($user->id)) {
71f9abf9 1799 $auth = 'manual'; // Always assume these guys are internal
27286aeb 1800 } else {
71f9abf9 1801 $auth = $CFG->auth; // Normal users default to site method
27286aeb 1802 }
d35757eb 1803 // update user record from external DB
1804 if ($user->auth != 'manual' && $user->auth != 'email') {
1805 $user = update_user_record($username);
1806 }
71f9abf9 1807 } else {
1808 $auth = $user->auth;
27286aeb 1809 }
8f0cd6ef 1810
ce791f88 1811 if (detect_munged_arguments($auth, 0)) { // For safety on the next require
1812 return false;
1813 }
1814
b0ccd3fb 1815 if (!file_exists($CFG->dirroot .'/auth/'. $auth .'/lib.php')) {
1816 $auth = 'manual'; // Can't find auth module, default to internal
466558e3 1817 }
1818
b0ccd3fb 1819 require_once($CFG->dirroot .'/auth/'. $auth .'/lib.php');
faebaf0f 1820
1821 if (auth_user_login($username, $password)) { // Successful authentication
71f9abf9 1822 if ($user) { // User already exists in database
1823 if (empty($user->auth)) { // For some reason auth isn't set yet
1824 set_field('user', 'auth', $auth, 'username', $username);
1825 }
92710226 1826 if ($md5password <> $user->password) { // Update local copy of password for reference
71f9abf9 1827 set_field('user', 'password', $md5password, 'username', $username);
faebaf0f 1828 }
366dfa60 1829 if (!is_internal_auth()) { // update user record from external DB
d35757eb 1830 $user = update_user_record($username);
1831 }
faebaf0f 1832 } else {
71f9abf9 1833 $user = create_user_record($username, $password, $auth);
faebaf0f 1834 }
89b54325 1835
e582b65e 1836 if (function_exists('auth_iscreator')) { // Check if the user is a creator
f894a791 1837 $useriscreator = auth_iscreator($username);
1838 if (!is_null($useriscreator)) {
1839 if ($useriscreator) {
1840 if (! record_exists('user_coursecreators', 'userid', $user->id)) {
1841 $cdata->userid = $user->id;
1842 if (! insert_record('user_coursecreators', $cdata)) {
1843 error('Cannot add user to course creators.');
1844 }
39a5a35d 1845 }
f894a791 1846 } else {
1847 if (record_exists('user_coursecreators', 'userid', $user->id)) {
1848 if (! delete_records('user_coursecreators', 'userid', $user->id)) {
1849 error('Cannot remove user from course creators.');
1850 }
39a5a35d 1851 }
1852 }
361855e6 1853 }
39a5a35d 1854 }
366dfa60 1855 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
e582b65e 1856 return $user;
9d3c795c 1857
e582b65e 1858 } else {
b0ccd3fb 1859 add_to_log(0, 'login', 'error', $_SERVER['HTTP_REFERER'], $username);
3af57507 1860 error_log('[client '.$_SERVER['REMOTE_ADDR']."]\t$CFG->wwwroot\tFailed Login:\t$username\t".$_SERVER['HTTP_USER_AGENT']);
e582b65e 1861 return false;
1862 }
f9903ed0 1863}
1864
7cf1c7bd 1865/**
1866 * Enrols (or re-enrols) a student in a given course
1867 *
c6d15803 1868 * @param int $courseid The id of the course that is being viewed
1869 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
1870 * @param int $timestart ?
1871 * @param int $timeend ?
7cf1c7bd 1872 * @return boolean
1873 * @todo Finish documenting this function
1874 */
92318548 1875function enrol_student($userid, $courseid, $timestart=0, $timeend=0, $enrol='') {
b40bc478 1876
75169b06 1877 global $CFG;
1878
b0ccd3fb 1879 if (!$course = get_record('course', 'id', $courseid)) { // Check course
3041b0f8 1880 return false;
4d312bbe 1881 }
b0ccd3fb 1882 if (!$user = get_record('user', 'id', $userid)) { // Check user
631cf796 1883 return false;
1884 }
b61efafb 1885 // enrol the student in any parent meta courses...
5f37b628 1886 if ($parents = get_records('course_meta','child_course',$courseid)) {
b61efafb 1887 foreach ($parents as $parent) {
1888 enrol_student($userid, $parent->parent_course,$timestart,$timeend,$enrol);
1889 }
1890 }
92318548 1891
1892 if (empty($enrol)) {
1893 $enrol = $CFG->enrol; // Default current method
1894 }
b0ccd3fb 1895 if ($student = get_record('user_students', 'userid', $userid, 'course', $courseid)) {
631cf796 1896 $student->timestart = $timestart;
1897 $student->timeend = $timeend;
1898 $student->time = time();
6e8ca983 1899 $student->enrol = $enrol;
b0ccd3fb 1900 return update_record('user_students', $student);
361855e6 1901
631cf796 1902 } else {
75169b06 1903 require_once("$CFG->dirroot/mod/forum/lib.php");
2f3b54ae 1904 forum_add_user($userid, $courseid);
1905
631cf796 1906 $student->userid = $userid;
1907 $student->course = $courseid;
1908 $student->timestart = $timestart;
1909 $student->timeend = $timeend;
1910 $student->time = time();
6e8ca983 1911 $student->enrol = $enrol;
b0ccd3fb 1912 return insert_record('user_students', $student);
631cf796 1913 }
d7facad8 1914}
1915
7cf1c7bd 1916/**
1917 * Unenrols a student from a given course
1918 *
c6d15803 1919 * @param int $courseid The id of the course that is being viewed, if any
1920 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 1921 * @return boolean
1922 */
9fa62805 1923function unenrol_student($userid, $courseid=0) {
d7facad8 1924
9fa62805 1925 if ($courseid) {
9fa49e22 1926 /// First delete any crucial stuff that might still send mail
b0ccd3fb 1927 if ($forums = get_records('forum', 'course', $courseid)) {
9fa49e22 1928 foreach ($forums as $forum) {
b0ccd3fb 1929 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
9fa62805 1930 }
1931 }
1932 if ($groups = get_groups($courseid, $userid)) {
1933 foreach ($groups as $group) {
b0ccd3fb 1934 delete_records('groups_members', 'groupid', $group->id, 'userid', $userid);
bb09fb11 1935 }
f9903ed0 1936 }
b61efafb 1937 // enrol the student in any parent meta courses...
5f37b628 1938 if ($parents = get_records('course_meta','child_course',$courseid)) {
b61efafb 1939 foreach ($parents as $parent) {
1940 unenrol_student($userid, $parent->parent_course);
1941 }
1942 }
b0ccd3fb 1943 return delete_records('user_students', 'userid', $userid, 'course', $courseid);
9fa49e22 1944
f9903ed0 1945 } else {
b0ccd3fb 1946 delete_records('forum_subscriptions', 'userid', $userid);
1947 delete_records('groups_members', 'userid', $userid);
1948 return delete_records('user_students', 'userid', $userid);
f9903ed0 1949 }
1950}
1951
7cf1c7bd 1952/**
1953 * Add a teacher to a given course
1954 *
1955 * @uses $USER
c6d15803 1956 * @param int $courseid The id of the course that is being viewed, if any
1957 * @param int $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
1958 * @param int $editall ?
7cf1c7bd 1959 * @param string $role ?
c6d15803 1960 * @param int $timestart ?
1961 * @param int $timeend ?
7cf1c7bd 1962 * @return boolean
1963 * @todo Finish documenting this function
1964 */
6e8ca983 1965function add_teacher($userid, $courseid, $editall=1, $role='', $timestart=0, $timeend=0, $enrol='manual') {
7b5944cd 1966 global $CFG;
3041b0f8 1967
61451a36 1968 if ($teacher = get_record('user_teachers', 'userid', $userid, 'course', $courseid)) {
b40bc478 1969 $newteacher = NULL;
1970 $newteacher->id = $teacher->id;
1971 $newteacher->editall = $editall;
6e8ca983 1972 $newteacher->enrol = $enrol;
b40bc478 1973 if ($role) {
1974 $newteacher->role = $role;
1975 }
1976 if ($timestart) {
1977 $newteacher->timestart = $timestart;
3041b0f8 1978 }
b40bc478 1979 if ($timeend) {
1980 $newteacher->timeend = $timeend;
1981 }
1982 return update_record('user_teachers', $newteacher);
3041b0f8 1983 }
61451a36 1984
b0ccd3fb 1985 if (!record_exists('user', 'id', $userid)) {
61451a36 1986 return false; // no such user
1987 }
1988
b0ccd3fb 1989 if (!record_exists('course', 'id', $courseid)) {
61451a36 1990 return false; // no such course
1991 }
1992
1993 $teacher = NULL;
1994 $teacher->userid = $userid;
1995 $teacher->course = $courseid;
1996 $teacher->editall = $editall;
1997 $teacher->role = $role;
5a2dea02 1998 $teacher->timemodified = time();
1999 $newteacher->timestart = $timestart;
2000 $newteacher->timeend = $timeend;
b0ccd3fb 2001 if ($student = get_record('user_students', 'userid', $userid, 'course', $courseid)) {
5a2dea02 2002 $teacher->timestart = $student->timestart;
2003 $teacher->timeend = $student->timeend;
2004 $teacher->timeaccess = $student->timeaccess;
2005 }
61451a36 2006
b0ccd3fb 2007 if (record_exists('user_teachers', 'course', $courseid)) {
61451a36 2008 $teacher->authority = 2;
2009 } else {
2010 $teacher->authority = 1;
2011 }
b0ccd3fb 2012 delete_records('user_students', 'userid', $userid, 'course', $courseid); // Unenrol as student
8f0cd6ef 2013
709f0ec8 2014 /// Add forum subscriptions for new users
7b5944cd 2015 require_once('../mod/forum/lib.php');
2016 forum_add_user($userid, $courseid);
61451a36 2017
b0ccd3fb 2018 return insert_record('user_teachers', $teacher);
61451a36 2019
3041b0f8 2020}
2021
7cf1c7bd 2022/**
2023 * Removes a teacher from a given course (or ALL courses)
2024 * Does not delete the user account
2025 *
c6d15803 2026 * @param int $courseid The id of the course that is being viewed, if any
361855e6 2027 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 2028 * @return boolean
2029 */
3041b0f8 2030function remove_teacher($userid, $courseid=0) {
3041b0f8 2031 if ($courseid) {
9fa49e22 2032 /// First delete any crucial stuff that might still send mail
b0ccd3fb 2033 if ($forums = get_records('forum', 'course', $courseid)) {
9fa49e22 2034 foreach ($forums as $forum) {
b0ccd3fb 2035 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
9fa49e22 2036 }
2037 }
b02193e6 2038
2039 /// Next if the teacher is not registered as a student, but is
2040 /// a member of a group, remove them from the group.
2041 if (!isstudent($courseid, $userid)) {
2042 if ($groups = get_groups($courseid, $userid)) {
2043 foreach ($groups as $group) {
b0ccd3fb 2044 delete_records('groups_members', 'groupid', $group->id, 'userid', $userid);
b02193e6 2045 }
2046 }
2047 }
2048
b0ccd3fb 2049 return delete_records('user_teachers', 'userid', $userid, 'course', $courseid);
57507290 2050 } else {
b0ccd3fb 2051 delete_records('forum_subscriptions', 'userid', $userid);
2052 return delete_records('user_teachers', 'userid', $userid);
57507290 2053 }
f9903ed0 2054}
2055
7cf1c7bd 2056/**
2057 * Add a creator to the site
2058 *
361855e6 2059 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 2060 * @return boolean
2061 */
3041b0f8 2062function add_creator($userid) {
3041b0f8 2063
b0ccd3fb 2064 if (!record_exists('user_admins', 'userid', $userid)) {
2065 if (record_exists('user', 'id', $userid)) {
3041b0f8 2066 $creator->userid = $userid;
b0ccd3fb 2067 return insert_record('user_coursecreators', $creator);
3041b0f8 2068 }
2069 return false;
2070 }
2071 return true;
2072}
2073
7cf1c7bd 2074/**
2075 * Remove a creator from a site
2076 *
2077 * @uses $db
c6d15803 2078 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 2079 * @return boolean
2080 */
3041b0f8 2081function remove_creator($userid) {
3041b0f8 2082 global $db;
2083
b0ccd3fb 2084 return delete_records('user_coursecreators', 'userid', $userid);
3041b0f8 2085}
2086
7cf1c7bd 2087/**
2088 * Add an admin to a site
2089 *
2090 * @uses SITEID
c6d15803 2091 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 2092 * @return boolean
2093 */
3041b0f8 2094function add_admin($userid) {
3041b0f8 2095
b0ccd3fb 2096 if (!record_exists('user_admins', 'userid', $userid)) {
2097 if (record_exists('user', 'id', $userid)) {
3041b0f8 2098 $admin->userid = $userid;
361855e6 2099
f950af3c 2100 // any admin is also a teacher on the site course
222ac91b 2101 if (!record_exists('user_teachers', 'course', SITEID, 'userid', $userid)) {
2102 if (!add_teacher($userid, SITEID)) {
f950af3c 2103 return false;
2104 }
2105 }
361855e6 2106
b0ccd3fb 2107 return insert_record('user_admins', $admin);
3041b0f8 2108 }
2109 return false;
2110 }
2111 return true;
2112}
2113
7cf1c7bd 2114/**
2115 * Removes an admin from a site
2116 *
2117 * @uses $db
2118 * @uses SITEID
c6d15803 2119 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 2120 * @return boolean
2121 */
3041b0f8 2122function remove_admin($userid) {
9fa49e22 2123 global $db;
f9903ed0 2124
f950af3c 2125 // remove also from the list of site teachers
222ac91b 2126 remove_teacher($userid, SITEID);
f950af3c 2127
b0ccd3fb 2128 return delete_records('user_admins', 'userid', $userid);
f9903ed0 2129}
2130
7cf1c7bd 2131/**
2132 * Clear a course out completely, deleting all content
2133 * but don't delete the course itself
2134 *
2135 * @uses $USER
2136 * @uses $SESSION
2137 * @uses $CFG
c6d15803 2138 * @param int $courseid The id of the course that is being viewed
7cf1c7bd 2139 * @param boolean $showfeedback Set this to false to suppress notifications from being printed as the functions performs its steps.
2140 * @return boolean
2141 */
07aeb7b0 2142function remove_course_contents($courseid, $showfeedback=true) {
07aeb7b0 2143
538a2210 2144 global $CFG, $USER, $SESSION;
07aeb7b0 2145
2146 $result = true;
2147
b0ccd3fb 2148 if (! $course = get_record('course', 'id', $courseid)) {
2149 error('Course ID was incorrect (can\'t find it)');
07aeb7b0 2150 }
2151
b0ccd3fb 2152 $strdeleted = get_string('deleted');
07aeb7b0 2153
2154 // First delete every instance of every module
d8ba183c 2155
b0ccd3fb 2156 if ($allmods = get_records('modules') ) {
07aeb7b0 2157 foreach ($allmods as $mod) {
2158 $modname = $mod->name;
b0ccd3fb 2159 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
2160 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
2161 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
07aeb7b0 2162 $count=0;
2163 if (file_exists($modfile)) {
2164 include_once($modfile);
2165 if (function_exists($moddelete)) {
b0ccd3fb 2166 if ($instances = get_records($modname, 'course', $course->id)) {
07aeb7b0 2167 foreach ($instances as $instance) {
2168 if ($moddelete($instance->id)) {
2169 $count++;
2170 } else {
b0ccd3fb 2171 notify('Could not delete '. $modname .' instance '. $instance->id .' ('. $instance->name .')');
07aeb7b0 2172 $result = false;
2173 }
2174 }
2175 }
2176 } else {
b0ccd3fb 2177 notify('Function '. $moddelete() .'doesn\'t exist!');
07aeb7b0 2178 $result = false;
2179 }
2180
ca952b03 2181 if (function_exists($moddeletecourse)) {
2182 $moddeletecourse($course);
2183 }
07aeb7b0 2184 }
2185 if ($showfeedback) {
b0ccd3fb 2186 notify($strdeleted .' '. $count .' x '. $modname);
07aeb7b0 2187 }
2188 }
2189 } else {
b0ccd3fb 2190 error('No modules are installed!');
07aeb7b0 2191 }
2192
2193 // Delete any user stuff
2194
b0ccd3fb 2195 if (delete_records('user_students', 'course', $course->id)) {
07aeb7b0 2196 if ($showfeedback) {
b0ccd3fb 2197 notify($strdeleted .' user_students');
07aeb7b0 2198 }
2199 } else {
2200 $result = false;
2201 }
2202
b0ccd3fb 2203 if (delete_records('user_teachers', 'course', $course->id)) {
07aeb7b0 2204 if ($showfeedback) {
b0ccd3fb 2205 notify($strdeleted .' user_teachers');
07aeb7b0 2206 }
2207 } else {
2208 $result = false;
2209 }
2210
082e3ebc 2211 // Delete any groups
2212
b0ccd3fb 2213 if ($groups = get_records('groups', 'courseid', $course->id)) {
082e3ebc 2214 foreach ($groups as $group) {
b0ccd3fb 2215 if (delete_records('groups_members', 'groupid', $group->id)) {
082e3ebc 2216 if ($showfeedback) {
b0ccd3fb 2217 notify($strdeleted .' groups_members');
082e3ebc 2218 }
2219 } else {
2220 $result = false;
2221 }
b0ccd3fb 2222 if (delete_records('groups', 'id', $group->id)) {
082e3ebc 2223 if ($showfeedback) {
b0ccd3fb 2224 notify($strdeleted .' groups');
082e3ebc 2225 }
2226 } else {
2227 $result = false;
2228 }
2229 }
2230 }
2231
2232 // Delete events
2233
b0ccd3fb 2234 if (delete_records('event', 'courseid', $course->id)) {
082e3ebc 2235 if ($showfeedback) {
b0ccd3fb 2236 notify($strdeleted .' event');
082e3ebc 2237 }
2238 } else {
2239 $result = false;
2240 }
2241
07aeb7b0 2242 // Delete logs
2243
b0ccd3fb 2244 if (delete_records('log', 'course', $course->id)) {
07aeb7b0 2245 if ($showfeedback) {
b0ccd3fb 2246 notify($strdeleted .' log');
07aeb7b0 2247 }
2248 } else {
2249 $result = false;
2250 }
2251
2252 // Delete any course stuff
2253
b0ccd3fb 2254 if (delete_records('course_sections', 'course', $course->id)) {
07aeb7b0 2255 if ($showfeedback) {
b0ccd3fb 2256 notify($strdeleted .' course_sections');
07aeb7b0 2257 }
2258 } else {
2259 $result = false;
2260 }
2261
b0ccd3fb 2262 if (delete_records('course_modules', 'course', $course->id)) {
07aeb7b0 2263 if ($showfeedback) {
b0ccd3fb 2264 notify($strdeleted .' course_modules');
07aeb7b0 2265 }
2266 } else {
2267 $result = false;
2268 }
2269
5f37b628 2270 if ($course->metacourse) {
2271 delete_records("course_meta","parent_course",$course->id);
b61efafb 2272 sync_metacourse($course->id); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
2273 if ($showfeedback) {
5f37b628 2274 notify("$strdeleted course_meta");
b61efafb 2275 }
2276 }
2277 else {
5f37b628 2278 if ($parents = get_records("course_meta","child_course",$course->id)) {
b61efafb 2279 foreach ($parents as $parent) {
2280 remove_from_metacourse($parent->parent_course,$parent->child_course); // this will do the unenrolments as well.
2281 }
2282 if ($showfeedback) {
5f37b628 2283 notify("$strdeleted course_meta");
b61efafb 2284 }
2285 }
2286 }
2287
07aeb7b0 2288 return $result;
2289
2290}
2291
7cf1c7bd 2292/**
2293 * This function will empty a course of USER data as much as
2294/// possible. It will retain the activities and the structure
2295/// of the course.
2296 *
2297 * @uses $USER
7cf1c7bd 2298 * @uses $SESSION
2299 * @uses $CFG
c6d15803 2300 * @param int $courseid The id of the course that is being viewed
7cf1c7bd 2301 * @param boolean $showfeedback Set this to false to suppress notifications from being printed as the functions performs its steps.
2302 * @param boolean $removestudents ?
2303 * @param boolean $removeteachers ?
2304 * @param boolean $removegroups ?
2305 * @param boolean $removeevents ?
2306 * @param boolean $removelogs ?
2307 * @return boolean
2308 * @todo Finish documenting this function
2309 */
3831de52 2310function remove_course_userdata($courseid, $showfeedback=true,
2311 $removestudents=true, $removeteachers=false, $removegroups=true,
2312 $removeevents=true, $removelogs=false) {
3831de52 2313
538a2210 2314 global $CFG, $USER, $SESSION;
3831de52 2315
2316 $result = true;
2317
b0ccd3fb 2318 if (! $course = get_record('course', 'id', $courseid)) {
2319 error('Course ID was incorrect (can\'t find it)');
3831de52 2320 }
2321
b0ccd3fb 2322 $strdeleted = get_string('deleted');
3831de52 2323
2324 // Look in every instance of every module for data to delete
2325
b0ccd3fb 2326 if ($allmods = get_records('modules') ) {
3831de52 2327 foreach ($allmods as $mod) {
2328 $modname = $mod->name;
b0ccd3fb 2329 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
2330 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3831de52 2331 $count=0;
2332 if (file_exists($modfile)) {
2333 @include_once($modfile);
2334 if (function_exists($moddeleteuserdata)) {
2335 $moddeleteuserdata($course, $showfeedback);
2336 }
2337 }
2338 }
2339 } else {
b0ccd3fb 2340 error('No modules are installed!');
3831de52 2341 }
2342
2343 // Delete other stuff
2344
2345 if ($removestudents) {
2346 /// Delete student enrolments
b0ccd3fb 2347 if (delete_records('user_students', 'course', $course->id)) {
3831de52 2348 if ($showfeedback) {
b0ccd3fb 2349 notify($strdeleted .' user_students');
3831de52 2350 }
2351 } else {
2352 $result = false;
2353 }
2354 /// Delete group members (but keep the groups)
b0ccd3fb 2355 if ($groups = get_records('groups', 'courseid', $course->id)) {
3831de52 2356 foreach ($groups as $group) {
b0ccd3fb 2357 if (delete_records('groups_members', 'groupid', $group->id)) {
3831de52 2358 if ($showfeedback) {
b0ccd3fb 2359 notify($strdeleted .' groups_members');
3831de52 2360 }
2361 } else {
2362 $result = false;
2363 }
2364 }
2365 }
2366 }
2367
2368 if ($removeteachers) {
b0ccd3fb 2369 if (delete_records('user_teachers', 'course', $course->id)) {
3831de52 2370 if ($showfeedback) {
b0ccd3fb 2371 notify($strdeleted .' user_teachers');
3831de52 2372 }
2373 } else {
2374 $result = false;
2375 }
2376 }
2377
2378 if ($removegroups) {
b0ccd3fb 2379 if ($groups = get_records('groups', 'courseid', $course->id)) {
3831de52 2380 foreach ($groups as $group) {
b0ccd3fb 2381 if (delete_records('groups', 'id', $group->id)) {
3831de52 2382 if ($showfeedback) {
b0ccd3fb 2383 notify($strdeleted .' groups');
3831de52 2384 }
2385 } else {
2386 $result = false;
2387 }
2388 }
2389 }
2390 }
2391
2392 if ($removeevents) {
b0ccd3fb 2393 if (delete_records('event', 'courseid', $course->id)) {
3831de52 2394 if ($showfeedback) {
b0ccd3fb 2395 notify($strdeleted .' event');
3831de52 2396 }
2397 } else {
2398 $result = false;
2399 }
2400 }
2401
2402 if ($removelogs) {
b0ccd3fb 2403 if (delete_records('log', 'course', $course->id)) {
3831de52 2404 if ($showfeedback) {
b0ccd3fb 2405 notify($strdeleted .' log');
3831de52 2406 }
2407 } else {
2408 $result = false;
2409 }
2410 }
2411
2412 return $result;
2413
2414}
2415
2416
f9903ed0 2417
f374fb10 2418/// GROUPS /////////////////////////////////////////////////////////
d8ba183c 2419
f374fb10 2420
2421/**
2422* Returns a boolean: is the user a member of the given group?
d8ba183c 2423*
dcd338ff 2424* @param type description
7cf1c7bd 2425 * @todo Finish documenting this function
f374fb10 2426*/
2427function ismember($groupid, $userid=0) {
2428 global $USER;
2429
8a2c9076 2430 if (!$groupid) { // No point doing further checks
2431 return false;
2432 }
2433
f374fb10 2434 if (!$userid) {
0d67c514 2435 if (empty($USER->groupmember)) {
2436 return false;
2437 }
2438 foreach ($USER->groupmember as $courseid => $mgroupid) {
2439 if ($mgroupid == $groupid) {
2440 return true;
2441 }
2442 }
2443 return false;
f374fb10 2444 }
2445
b0ccd3fb 2446 return record_exists('groups_members', 'groupid', $groupid, 'userid', $userid);
f374fb10 2447}
2448
4ed533df 2449/**
2450 * Add a user to a group, return true upon success or if user already a group member
2451 *
2452 * @param groupid The group id
2453 * @param userid The user id
2454 * @todo Finish documenting this function
2455 */
2456function add_user_to_group ($groupid, $userid) {
2457 if (ismember($groupid, $userid)) return true;
2458 $record->groupid = $groupid;
2459 $record->userid = $userid;
2460 $record->timeadded = time();
2461 return (insert_record('groups_members', $record) !== false);
2462}
2463
2464
0d67c514 2465/**
c6d15803 2466 * Returns the group ID of the current user in the given course
2467 *
2468 * @uses $USER
2469 * @param int $courseid The course being examined - relates to id field in 'course' table.
7cf1c7bd 2470 * @todo Finish documenting this function
c6d15803 2471 */
0d67c514 2472function mygroupid($courseid) {
2473 global $USER;
2474
2475 if (empty($USER->groupmember[$courseid])) {
2476 return 0;
2477 } else {
2478 return $USER->groupmember[$courseid];
2479 }
2480}
2481
f374fb10 2482/**
c6d15803 2483 * For a given course, and possibly course module, determine
2484 * what the current default groupmode is:
2485 * NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
2486 *
89dcb99d 2487 * @param course $course A {@link $COURSE} object
2488 * @param array? $cm A course module object
c6d15803 2489 * @return int A group mode (NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS)
2490 */
f374fb10 2491function groupmode($course, $cm=null) {
2492
2493 if ($cm and !$course->groupmodeforce) {
2494 return $cm->groupmode;
2495 }
2496 return $course->groupmode;
2497}
2498
2499
2500/**
c6d15803 2501 * Sets the current group in the session variable
2502 *
2503 * @uses $SESSION
2504 * @param int $courseid The course being examined - relates to id field in 'course' table.
2505 * @param int $groupid The group being examined.
2506 * @return int Current group id which was set by this function
7cf1c7bd 2507 * @todo Finish documenting this function
c6d15803 2508 */
f374fb10 2509function set_current_group($courseid, $groupid) {
2510 global $SESSION;
2511
2512 return $SESSION->currentgroup[$courseid] = $groupid;
2513}
2514
2515
2516/**
c6d15803 2517 * Gets the current group for the current user as an id or an object
2518 *
2519 * @uses $CFG
2520 * @uses $SESSION
2521 * @param int $courseid The course being examined - relates to id field in 'course' table.
9f1f6daf 2522 * @param boolean $full If true, the return value is a full record object. If false, just the id of the record.
7cf1c7bd 2523 * @todo Finish documenting this function
c6d15803 2524 */
f374fb10 2525function get_current_group($courseid, $full=false) {
2526 global $SESSION, $USER;
2527
ce04df6b 2528 if (!isset($SESSION->currentgroup[$courseid])) {
f374fb10 2529 if (empty($USER->groupmember[$courseid])) {
8a2c9076 2530 return 0;
f374fb10 2531 } else {
2532 $SESSION->currentgroup[$courseid] = $USER->groupmember[$courseid];
2533 }
2534 }
2535
2536 if ($full) {
0da33e07 2537 return get_record('groups', 'id', $SESSION->currentgroup[$courseid]);
f374fb10 2538 } else {
2539 return $SESSION->currentgroup[$courseid];
2540 }
2541}
2542
0d67c514 2543/**
c6d15803 2544 * A combination function to make it easier for modules
2545 * to set up groups.
2546 *
2547 * It will use a given "groupid" parameter and try to use
2548 * that to reset the current group for the user.
2549 *
2550 * @uses VISIBLEGROUPS
89dcb99d 2551 * @param course $course A {@link $COURSE} object
c6d15803 2552 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
2553 * @param int $groupid Will try to use this optional parameter to
2554 * reset the current group for the user
89dcb99d 2555 * @return int|false Returns the current group id or false if error.
7cf1c7bd 2556 * @todo Finish documenting this function
c6d15803 2557 */
eb6147a8 2558function get_and_set_current_group($course, $groupmode, $groupid=-1) {
0d67c514 2559
2560 if (!$groupmode) { // Groups don't even apply
d8ba183c 2561 return false;
0d67c514 2562 }
2563
2564 $currentgroupid = get_current_group($course->id);
2565
eb6147a8 2566 if ($groupid < 0) { // No change was specified
2567 return $currentgroupid;
2568 }
2569
2570 if ($groupid) { // Try to change the current group to this groupid
0d67c514 2571 if ($group = get_record('groups', 'id', $groupid, 'courseid', $course->id)) { // Exists
2572 if (isteacheredit($course->id)) { // Sets current default group
2573 $currentgroupid = set_current_group($course->id, $group->id);
2574
2575 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
2576 $currentgroupid = $group->id;
2577 }
2578 }
eb6147a8 2579 } else { // When groupid = 0 it means show ALL groups
2580 if (isteacheredit($course->id)) { // Sets current default group
2581 $currentgroupid = set_current_group($course->id, 0);
2582
2583 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
2584 $currentgroupid = 0;
2585 }
0d67c514 2586 }
2587
2588 return $currentgroupid;
2589}
2590
2591
c3cbfe7f 2592/**
c6d15803 2593 * A big combination function to make it easier for modules
2594 * to set up groups.
2595 *
2596 * Terminates if the current user shouldn't be looking at this group
2597 * Otherwise returns the current group if there is one
2598 * Otherwise returns false if groups aren't relevant
2599 *
2600 * @uses SEPARATEGROUPS
2601 * @uses VISIBLEGROUPS
89dcb99d 2602 * @param course $course A {@link $COURSE} object
c6d15803 2603 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
2604 * @param string $urlroot ?
7cf1c7bd 2605 * @todo Finish documenting this function
c6d15803 2606 */
c3cbfe7f 2607function setup_and_print_groups($course, $groupmode, $urlroot) {
2608
eb6147a8 2609 if (isset($_GET['group'])) {
2610 $changegroup = $_GET['group']; /// 0 or higher
2611 } else {
2612 $changegroup = -1; /// This means no group change was specified
2613 }
2614
2615 $currentgroup = get_and_set_current_group($course, $groupmode, $changegroup);
c3cbfe7f 2616
eb6147a8 2617 if ($currentgroup === false) {
c3cbfe7f 2618 return false;
2619 }
2620
4b6d8dd5 2621 if ($groupmode == SEPARATEGROUPS and !isteacheredit($course->id) and !$currentgroup) {
2622 print_heading(get_string('notingroup'));
c3cbfe7f 2623 print_footer($course);
2624 exit;
2625 }
2626
2627 if ($groupmode == VISIBLEGROUPS or ($groupmode and isteacheredit($course->id))) {
b0ccd3fb 2628 if ($groups = get_records_menu('groups', 'courseid', $course->id, 'name ASC', 'id,name')) {
eb6147a8 2629 echo '<div align="center">';
c3cbfe7f 2630 print_group_menu($groups, $groupmode, $currentgroup, $urlroot);
eb6147a8 2631 echo '</div>';
c3cbfe7f 2632 }
2633 }
2634
2635 return $currentgroup;
2636}
0d67c514 2637
f374fb10 2638
2639
f9903ed0 2640/// CORRESPONDENCE ////////////////////////////////////////////////
2641
7cf1c7bd 2642/**
2643 * Send an email to a specified user
2644 *
7cf1c7bd 2645 * @uses $CFG
2646 * @uses $_SERVER
c6d15803 2647 * @uses SITEID
89dcb99d 2648 * @param user $user A {@link $USER} object
2649 * @param user $from A {@link $USER} object
7cf1c7bd 2650 * @param string $subject plain text subject line of the email
2651 * @param string $messagetext plain text version of the message
2652 * @param string $messagehtml complete html version of the message (optional)
2653 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
2654 * @param string $attachname the name of the file (extension indicates MIME)
361855e6 2655 * @param boolean $usetrueaddress determines whether $from email address should
c6d15803 2656 * be sent out. Will be overruled by user profile setting for maildisplay
361855e6 2657 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 2658 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 2659 */
b0ccd3fb 2660function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true) {
f9903ed0 2661
f9f4d999 2662 global $CFG, $FULLME;
f9903ed0 2663
0cc6fa6a 2664 global $course; // This is a bit of an ugly hack to be gotten rid of later
2665 if (!empty($course->lang)) { // Course language is defined
2666 $CFG->courselang = $course->lang;
2667 }
2668
b0ccd3fb 2669 include_once($CFG->libdir .'/phpmailer/class.phpmailer.php');
f9903ed0 2670
cadb96f2 2671 if (empty($user)) {
2672 return false;
2673 }
2674
2675 if (!empty($user->emailstop)) {
579dcca4 2676 return 'emailstop';
f9903ed0 2677 }
d8ba183c 2678
f9903ed0 2679 $mail = new phpmailer;
2680
b0ccd3fb 2681 $mail->Version = 'Moodle '. $CFG->version; // mailer version
2682 $mail->PluginDir = $CFG->libdir .'/phpmailer/'; // plugin directory (eg smtp plugin)
562bbe90 2683
98c4eae3 2684
b0ccd3fb 2685 if (current_language() != 'en') {
2686 $mail->CharSet = get_string('thischarset');
98c4eae3 2687 }
2688
b0ccd3fb 2689 if ($CFG->smtphosts == 'qmail') {
62740736 2690 $mail->IsQmail(); // use Qmail system
2691
2692 } else if (empty($CFG->smtphosts)) {
2693 $mail->IsMail(); // use PHP mail() = sendmail
2694
2695 } else {
1e411ffc 2696 $mail->IsSMTP(); // use SMTP directly
57ef3480 2697 if ($CFG->debug > 7) {
b0ccd3fb 2698 echo '<pre>' . "\n";
57ef3480 2699 $mail->SMTPDebug = true;
2700 }
b0ccd3fb 2701 $mail->Host = $CFG->smtphosts; // specify main and backup servers
9f58537a 2702
2703 if ($CFG->smtpuser) { // Use SMTP authentication
2704 $mail->SMTPAuth = true;
2705 $mail->Username = $CFG->smtpuser;
2706 $mail->Password = $CFG->smtppass;
2707 }
7f86ce17 2708 }
f9903ed0 2709
2b97bd71 2710 $adminuser = get_admin();
2711
b0ccd3fb 2712 $mail->Sender = $adminuser->email;
2b97bd71 2713
a402bdcb 2714 if (is_string($from)) { // So we can pass whatever we want if there is need
2715 $mail->From = $CFG->noreplyaddress;
0d8a590a 2716 $mail->FromName = $from;
a402bdcb 2717 } else if ($usetrueaddress and $from->maildisplay) {
b0ccd3fb 2718 $mail->From = $from->email;
6e506bf9 2719 $mail->FromName = fullname($from);
2720 } else {
b0ccd3fb 2721 $mail->From = $CFG->noreplyaddress;
0d8a590a 2722 $mail->FromName = fullname($from);
6e506bf9 2723 }
136dabd8 2724 $mail->Subject = stripslashes($subject);
f9903ed0 2725
b0ccd3fb 2726 $mail->AddAddress($user->email, fullname($user) );
f9903ed0 2727
58d24720 2728 $mail->WordWrap = 79; // set word wrap
f9903ed0 2729
857b798b 2730 if (!empty($from->customheaders)) { // Add custom headers
2731 if (is_array($from->customheaders)) {
2732 foreach ($from->customheaders as $customheader) {
2733 $mail->AddCustomHeader($customheader);
2734 }
2735 } else {
2736 $mail->AddCustomHeader($from->customheaders);
2737 }
b68dca19 2738 }
8f0cd6ef 2739
756e1823 2740 if ($messagehtml && $user->mailformat == 1) { // Don't ever send HTML to users who don't want it
136dabd8 2741 $mail->IsHTML(true);
b0ccd3fb 2742 $mail->Encoding = 'quoted-printable'; // Encoding to use
136dabd8 2743 $mail->Body = $messagehtml;
78681899 2744 $mail->AltBody = "\n$messagetext\n";
136dabd8 2745 } else {
2746 $mail->IsHTML(false);
78681899 2747 $mail->Body = "\n$messagetext\n";
f9903ed0 2748 }
2749
136dabd8 2750 if ($attachment && $attachname) {
2751 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
b0ccd3fb 2752 $mail->AddAddress($adminuser->email, fullname($adminuser) );
2753 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
136dabd8 2754 } else {
b0ccd3fb 2755 include_once($CFG->dirroot .'/files/mimetypes.php');
2756 $mimetype = mimeinfo('type', $attachname);
2757 $mail->AddAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
136dabd8 2758 }
f9903ed0 2759 }
2760
136dabd8 2761 if ($mail->Send()) {
2762 return true;
2763 } else {
b0ccd3fb 2764 mtrace('ERROR: '. $mail->ErrorInfo);
f9f4d999 2765 add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo);
f9903ed0 2766 return false;
2767 }
f9903ed0 2768}
2769
7cf1c7bd 2770/**
2771 * Resets specified user's password and send the new password to the user via email.
2772 *
2773 * @uses $CFG
89dcb99d 2774 * @param user $user A {@link $USER} object
361855e6 2775 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 2776 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 2777 */
1d881d92 2778function reset_password_and_mail($user) {
2779
2780 global $CFG;
2781
2782 $site = get_site();
2783 $from = get_admin();
2784
2785 $newpassword = generate_password();
2786
b0ccd3fb 2787 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id) ) {
2788 error('Could not set user password!');
1d881d92 2789 }
2790
2791 $a->firstname = $user->firstname;
2792 $a->sitename = $site->fullname;
2793 $a->username = $user->username;
2794 $a->newpassword = $newpassword;
b0ccd3fb 2795 $a->link = $CFG->wwwroot .'/login/change_password.php';
2796 $a->signoff = fullname($from, true).' ('. $from->email .')';
1d881d92 2797
b0ccd3fb 2798 $message = get_string('newpasswordtext', '', $a);
1d881d92 2799
b0ccd3fb 2800 $subject = $site->fullname .': '. get_string('changedpassword');
1d881d92 2801
2802 return email_to_user($user, $from, $subject, $message);
2803
2804}
2805
7cf1c7bd 2806/**
2807 * Send email to specified user with confirmation text and activation link.
2808 *
2809 * @uses $CFG
89dcb99d 2810 * @param user $user A {@link $USER} object
361855e6 2811 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 2812 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 2813 */
2814 function send_confirmation_email($user) {
1d881d92 2815
2816 global $CFG;
2817
2818 $site = get_site();
2819 $from = get_admin();
2820
865a6f26 2821 $data->firstname = fullname($user);
1d881d92 2822 $data->sitename = $site->fullname;
b0ccd3fb 2823 $data->link = $CFG->wwwroot .'/login/confirm.php?p='. $user->secret .'&amp;s='. $user->username;
2824 $data->admin = fullname($from) .' ('. $from->email .')';
1d881d92 2825
b0ccd3fb 2826 $message = get_string('emailconfirmation', '', $data);
2827 $subject = get_string('emailconfirmationsubject', '', $site->fullname);
1d881d92 2828
58d24720 2829 $messagehtml = text_to_html($message, false, false, true);
2830
2831 return email_to_user($user, $from, $subject, $message, $messagehtml);
1d881d92 2832
2833}
2834
7cf1c7bd 2835/**
2836 * send_password_change_confirmation_email.
2837 *
c6d15803 2838 * @uses $CFG
89dcb99d 2839 * @param user $user A {@link $USER} object
361855e6 2840 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 2841 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 2842 * @todo Finish documenting this function
2843 */
eb347b6b 2844function send_password_change_confirmation_email($user) {
2845
2846 global $CFG;
2847
2848 $site = get_site();
2849 $from = get_admin();
2850
2851 $data->firstname = $user->firstname;
2852 $data->sitename = $site->fullname;
b0ccd3fb 2853 $data->link = $CFG->wwwroot .'/login/forgot_password.php?p='. $user->secret .'&amp;s='. $user->username;
2854 $data->admin = fullname($from).' ('. $from->email .')';
eb347b6b 2855
b0ccd3fb 2856 $message = get_string('emailpasswordconfirmation', '', $data);
2857 $subject = get_string('emailpasswordconfirmationsubject', '', $site->fullname);
eb347b6b 2858
2859 return email_to_user($user, $from, $subject, $message);
2860
2861}
2862
7cf1c7bd 2863/**
2864 * Check that an email is allowed. It returns an error message if there
2865 * was a problem.
2866 *
2867 * @param type description
2868 * @todo Finish documenting this function
2869 */
85a1d4c9 2870function email_is_not_allowed($email) {
85a1d4c9 2871
2872 global $CFG;
2873
2874 if (!empty($CFG->allowemailaddresses)) {
2875 $allowed = explode(' ', $CFG->allowemailaddresses);
2876 foreach ($allowed as $allowedpattern) {
2877 $allowedpattern = trim($allowedpattern);
2878 if (!$allowedpattern) {
2879 continue;
2880 }
2881 if (strpos($email, $allowedpattern) !== false) { // Match!
2882 return false;
2883 }
2884 }
b0ccd3fb 2885 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
85a1d4c9 2886
2887 } else if (!empty($CFG->denyemailaddresses)) {
2888 $denied = explode(' ', $CFG->denyemailaddresses);
2889 foreach ($denied as $deniedpattern) {
2890 $deniedpattern = trim($deniedpattern);
2891 if (!$deniedpattern) {
2892 continue;
2893 }
2894 if (strpos($email, $deniedpattern) !== false) { // Match!
b0ccd3fb 2895 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
85a1d4c9 2896 }
2897 }
2898 }
2899
2900 return false;
2901}
1d881d92 2902
136dabd8 2903
f9903ed0 2904/// FILE HANDLING /////////////////////////////////////////////
2905
7cf1c7bd 2906/**
c6d15803 2907 * Create a directory.
7cf1c7bd 2908 *
2909 * @uses $CFG
8c3dba73 2910 * @param string $directory a string of directory names under $CFG->dataroot eg stuff/assignment/1
c6d15803 2911 * param boolean $shownotices If true then notification messages will be printed out on error.
2912 * @return string|false Returns full path to directory if successful, false if not
7cf1c7bd 2913 */
66f9a82c 2914function make_upload_directory($directory, $shownotices=true) {
6b174680 2915
2916 global $CFG;
2917
2918 $currdir = $CFG->dataroot;
fe287429 2919
2e6d4273 2920 umask(0000);
2921
6b174680 2922 if (!file_exists($currdir)) {
2e6d4273 2923 if (! mkdir($currdir, $CFG->directorypermissions)) {
66f9a82c 2924 if ($shownotices) {
b0ccd3fb 2925 notify('ERROR: You need to create the directory '. $currdir .' with web server write access');
66f9a82c 2926 }
6b174680 2927 return false;
2928 }
2765411a 2929 if ($handle = fopen($currdir.'/.htaccess', 'w')) { // For safety
2930 @fwrite($handle, "deny from all\r\n");
2931 @fclose($handle);
2932 }
6b174680 2933 }
2934
b0ccd3fb 2935 $dirarray = explode('/', $directory);
6b174680 2936
2937 foreach ($dirarray as $dir) {
b0ccd3fb 2938 $currdir = $currdir .'/'. $dir;
6b174680 2939 if (! file_exists($currdir)) {
2e6d4273 2940 if (! mkdir($currdir, $CFG->directorypermissions)) {
66f9a82c 2941 if ($shownotices) {
b0ccd3fb 2942 notify('ERROR: Could not find or create a directory ('. $currdir .')');
66f9a82c 2943 }
6b174680 2944 return false;
2945 }
d99bab2d 2946 //@chmod($currdir, $CFG->directorypermissions); // Just in case mkdir didn't do it
6b174680 2947 }
2948 }
2949
2950 return $currdir;
2951}
1e03c552 2952
7cf1c7bd 2953/**
2954 * Makes an upload directory for a particular module.
2955 *
2956 * @uses $CFG
c6d15803 2957 * @param int $courseid The id of the course in question - maps to id field of 'course' table.
2958 * @return string|false Returns full path to directory if successful, false if not
7cf1c7bd 2959 * @todo Finish documenting this function
2960 */
ca4f8eb8 2961function make_mod_upload_directory($courseid) {
2962 global $CFG;
2963
b0ccd3fb 2964 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata)) {
ca4f8eb8 2965 return false;
2966 }
2967
b0ccd3fb 2968 $strreadme = get_string('readme');
ca4f8eb8 2969
b0ccd3fb 2970 if (file_exists($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt')) {
2971 copy($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
ca4f8eb8 2972 } else {
b0ccd3fb 2973 copy($CFG->dirroot .'/lang/en/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
ca4f8eb8 2974 }
2975 return $moddata;
2976}
2977
7cf1c7bd 2978/**
c6d15803 2979 * Returns current name of file on disk if it exists.
7cf1c7bd 2980 *
c6d15803 2981 * @param string $newfile File to be verified
2982 * @return string Current name of file on disk if true
7cf1c7bd 2983 * @todo Finish documenting this function
2984 */
44e2d2bb 2985function valid_uploaded_file($newfile) {
9c9f7d77 2986 if (empty($newfile)) {
b0ccd3fb 2987 return '';
9c9f7d77 2988 }
44e2d2bb 2989 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
2990 return $newfile['tmp_name'];
2991 } else {
b0ccd3fb 2992 return '';
44e2d2bb 2993 }
2994}
2995
7cf1c7bd 2996/**
2997 * Returns the maximum size for uploading files.
2998 *
2999 * There are seven possible upload limits:
3000 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
3001 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
3002 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
3003 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
3004 * 5. by the Moodle admin in $CFG->maxbytes
3005 * 6. by the teacher in the current course $course->maxbytes
3006 * 7. by the teacher for the current module, eg $assignment->maxbytes
3007 *
3008 * These last two are passed to this function as arguments (in bytes).
3009 * Anything defined as 0 is ignored.
3010 * The smallest of all the non-zero numbers is returned.
3011 *
c6d15803 3012 * @param int $sizebytes ?
3013 * @param int $coursebytes Current course $course->maxbytes (in bytes)
3014 * @param int $modulebytes Current module ->maxbytes (in bytes)
3015 * @return int The maximum size for uploading files.
7cf1c7bd 3016 * @todo Finish documenting this function
3017 */
4909e176 3018function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4909e176 3019
b0ccd3fb 3020 if (! $filesize = ini_get('upload_max_filesize')) {
3021 $filesize = '5M';
44e2d2bb 3022 }
4909e176 3023 $minimumsize = get_real_size($filesize);
3024
b0ccd3fb 3025 if ($postsize = ini_get('post_max_size')) {
316ebf78 3026 $postsize = get_real_size($postsize);
3027 if ($postsize < $minimumsize) {
3028 $minimumsize = $postsize;
3029 }
3030 }
3031
4909e176 3032 if ($sitebytes and $sitebytes < $minimumsize) {
3033 $minimumsize = $sitebytes;
3034 }
3035
3036 if ($coursebytes and $coursebytes < $minimumsize) {
3037 $minimumsize = $coursebytes;
3038 }
3039
3040 if ($modulebytes and $modulebytes < $minimumsize) {
3041 $minimumsize = $modulebytes;
3042 }
3043
3044 return $minimumsize;
3045}
3046
7cf1c7bd 3047/**
3048 * Related to the above function - this function returns an
3049 * array of possible sizes in an array, translated to the
3050 * local language.
3051 *
c6d15803 3052 * @uses SORT_NUMERIC
3053 * @param int $sizebytes ?
3054 * @param int $coursebytes Current course $course->maxbytes (in bytes)
3055 * @param int $modulebytes Current module ->maxbytes (in bytes)
3056 * @return int
7cf1c7bd 3057 * @todo Finish documenting this function
3058 */
4909e176 3059function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4909e176 3060
3061 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
3062 return array();
3063 }
3064
3065 $filesize[$maxsize] = display_size($maxsize);
3066
d8ba183c 3067 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
4909e176 3068 5242880, 10485760, 20971520, 52428800, 104857600);
3069
3070 foreach ($sizelist as $sizebytes) {
3071 if ($sizebytes < $maxsize) {
3072 $filesize[$sizebytes] = display_size($sizebytes);
3073 }
3074 }
3075
3076 krsort($filesize, SORT_NUMERIC);
3077
3078 return $filesize;
44e2d2bb 3079}
3080
7cf1c7bd 3081/**
3082 * If there has been an error uploading a file, print the appropriate error message
3083 * Numerical constants used as constant definitions not added until PHP version 4.2.0
3084 *
c6d15803 3085 * $filearray is a 1-dimensional sub-array of the $_FILES array
7cf1c7bd 3086 * eg $filearray = $_FILES['userfile1']
361855e6 3087 * If left empty then the first element of the $_FILES array will be used
8c3dba73 3088 *
c6d15803 3089 * @uses $_FILES
3090 * @param array $filearray A 1-dimensional sub-array of the $_FILES array
3091 * @param boolean $returnerror ?
7cf1c7bd 3092 * @return boolean
3093 * @todo Finish documenting this function
3094 */
ebd52396 3095function print_file_upload_error($filearray = '', $returnerror = false) {
ebd52396 3096
3097 if ($filearray == '' or !isset($filearray['error'])) {
3098
3099 if (empty($_FILES)) return false;
3100
3101 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
3102 $filearray = array_shift($files); /// use first element of array
3103 }
3104
3105 switch ($filearray['error']) {
3106
3107 case 0: // UPLOAD_ERR_OK
3108 if ($filearray['size'] > 0) {
3109 $errmessage = get_string('uploadproblem', $filearray['name']);
3110 } else {
3111 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
3112 }
3113 break;
3114
3115 case 1: // UPLOAD_ERR_INI_SIZE
3116 $errmessage = get_string('uploadserverlimit');
3117 break;
3118
3119 case 2: // UPLOAD_ERR_FORM_SIZE
3120 $errmessage = get_string('uploadformlimit');
3121 break;
3122
3123 case 3: // UPLOAD_ERR_PARTIAL
3124 $errmessage = get_string('uploadpartialfile');
3125 break;
3126
3127 case 4: // UPLOAD_ERR_NO_FILE
3128 $errmessage = get_string('uploadnofilefound');
3129 break;
3130
3131 default:
3132 $errmessage = get_string('uploadproblem', $filearray['name']);
3133 }
3134
3135 if ($returnerror) {
3136 return $errmessage;
3137 } else {
3138 notify($errmessage);
3139 return true;
3140 }
3141
3142}
3143
7cf1c7bd 3144/**
3145 * Returns an array with all the filenames in
3146 * all subdirectories, relative to the given rootdir.
3147 * If excludefile is defined, then that file/directory is ignored
3148 * If getdirs is true, then (sub)directories are included in the output
3149 * If getfiles is true, then files are included in the output
3150 * (at least one of these must be true!)
3151 *
c6d15803 3152 * @param string $rootdir ?
3153 * @param string $excludefile If defined then the specified file/directory is ignored
3154 * @param boolean $descend ?
3155 * @param boolean $getdirs If true then (sub)directories are included in the output
3156 * @param boolean $getfiles If true then files are included in the output
3157 * @return array An array with all the filenames in
3158 * all subdirectories, relative to the given rootdir
3159 * @todo Finish documenting this function. Add examples of $excludefile usage.
7cf1c7bd 3160 */
b0ccd3fb 3161function get_directory_list($rootdir, $excludefile='', $descend=true, $getdirs=false, $getfiles=true) {
f9903ed0 3162
3163 $dirs = array();
f9903ed0 3164
16a5602c 3165 if (!$getdirs and !$getfiles) { // Nothing to show
12407705 3166 return $dirs;
3167 }
3168
16a5602c 3169 if (!is_dir($rootdir)) { // Must be a directory
3170 return $dirs;
3171 }
3172
3173 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
d897cae4 3174 return $dirs;
3175 }
3176
81fcd0f0 3177 while (false !== ($file = readdir($dir))) {
b35e8568 3178 $firstchar = substr($file, 0, 1);
b0ccd3fb 3179 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
b35e8568 3180 continue;
3181 }
b0ccd3fb 3182 $fullfile = $rootdir .'/'. $file;
3183 if (filetype($fullfile) == 'dir') {
16a5602c 3184 if ($getdirs) {
55fd8177 3185 $dirs[] = $file;
3186 }
bf5c2e84 3187 if ($descend) {
16a5602c 3188 $subdirs = get_directory_list($fullfile, $excludefile, $descend, $getdirs, $getfiles);
bf5c2e84 3189 foreach ($subdirs as $subdir) {
b0ccd3fb 3190 $dirs[] = $file .'/'. $subdir;
bf5c2e84 3191 }
f9903ed0 3192 }
16a5602c 3193 } else if ($getfiles) {
b35e8568 3194 $dirs[] = $file;
f9903ed0 3195 }
3196 }
44e2d2bb 3197 closedir($dir);
f9903ed0 3198
774ab660 3199 asort($dirs);
3200
f9903ed0 3201 return $dirs;
3202}
3203
7cf1c7bd 3204/**
3205 * Adds up all the files in a directory and works out the size.
3206 *
3207 * @param string $rootdir ?
3208 * @param string $excludefile ?
c6d15803 3209 * @return array
7cf1c7bd 3210 * @todo Finish documenting this function
3211 */
b0ccd3fb 3212function get_directory_size($rootdir, $excludefile='') {
16a5602c 3213
3214 $size = 0;
3215
3216 if (!is_dir($rootdir)) { // Must be a directory
3217 return $dirs;
3218 }
3219
b5b90f26 3220 if (!$dir = @opendir($rootdir)) { // Can't open it for some reason
16a5602c 3221 return $dirs;
3222 }
3223
3224 while (false !== ($file = readdir($dir))) {
3225 $firstchar = substr($file, 0, 1);
b0ccd3fb 3226 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
16a5602c 3227 continue;
3228 }
b0ccd3fb 3229 $fullfile = $rootdir .'/'. $file;
3230 if (filetype($fullfile) == 'dir') {
16a5602c 3231 $size += get_directory_size($fullfile, $excludefile);
3232 } else {
3233 $size += filesize($fullfile);
3234 }
3235 }
3236 closedir($dir);
3237
3238 return $size;
3239}
3240
7cf1c7bd 3241/**
3242 * Converts numbers like 10M into bytes.
3243 *
7cf1c7bd 3244 * @param mixed $size The size to be converted
3245 * @return mixed
3246 */
989bfa9d 3247function get_real_size($size=0) {
989bfa9d 3248 if (!$size) {
d8ba183c 3249 return 0;
989bfa9d 3250 }
3251 $scan['MB'] = 1048576;
64efda84 3252 $scan['Mb'] = 1048576;
989bfa9d 3253 $scan['M'] = 1048576;
266a416e 3254 $scan['m'] = 1048576;
989bfa9d 3255 $scan['KB'] = 1024;
64efda84 3256 $scan['Kb'] = 1024;
989bfa9d 3257 $scan['K'] = 1024;
266a416e 3258 $scan['k'] = 1024;
989bfa9d 3259
3260 while (list($key) = each($scan)) {
3261 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
3262 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
3263 break;
3264 }
3265 }
3266 return $size;
3267}
3268
7cf1c7bd 3269/**
3270 * Converts bytes into display form
3271 *
c6d15803 3272 * @param string $size ?
3273 * @return string
89dcb99d 3274 * @staticvar string $gb Localized string for size in gigabytes
3275 * @staticvar string $mb Localized string for size in megabytes
3276 * @staticvar string $kb Localized string for size in kilobytes
3277 * @staticvar string $b Localized string for size in bytes
c6d15803 3278 * @todo Finish documenting this function. Verify return type.
7cf1c7bd 3279 */
44e2d2bb 3280function display_size($size) {
4909e176 3281
7cf1c7bd 3282 static $gb, $mb, $kb, $b;
4909e176 3283
3284 if (empty($gb)) {
3285 $gb = get_string('sizegb');
3286 $mb = get_string('sizemb');
3287 $kb = get_string('sizekb');
3288 $b = get_string('sizeb');
3289 }
3290
44e2d2bb 3291 if ($size >= 1073741824) {
4909e176 3292 $size = round($size / 1073741824 * 10) / 10 . $gb;
44e2d2bb 3293 } else if ($size >= 1048576) {
4909e176 3294 $size = round($size / 1048576 * 10) / 10 . $mb;
44e2d2bb