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