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