polished.
[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
f30fe8d0 605 $timezone = get_user_timezone($timezone);
94e34118 606
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
102dc313 717 $timezone = get_user_timezone($timezone);
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
f30fe8d0 753 $timezone = get_user_timezone($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
f30fe8d0 792 $timezone = get_user_timezone($timezone);
0431bd7c 793 if (abs($timezone) > 13) {
d552ead0 794 return $date;
795 }
7a5672c9 796 return $date - (int)($timezone * HOURSECS);
d552ead0 797}
798
8c3dba73 799/**
800 * Given a time, return the GMT timestamp of the most recent midnight
801 * for the current user.
802 *
e34d817e 803 * @param int $date Timestamp in GMT
804 * @param float $timezone ?
c6d15803 805 * @return ?
8c3dba73 806 */
edf7fe8c 807function usergetmidnight($date, $timezone=99) {
edf7fe8c 808
f30fe8d0 809 $timezone = get_user_timezone($timezone);
edf7fe8c 810 $userdate = usergetdate($date, $timezone);
4606d9bb 811
02f0527d 812 // Time of midnight of this user's day, in GMT
813 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
edf7fe8c 814
815}
816
7cf1c7bd 817/**
818 * Returns a string that prints the user's timezone
819 *
820 * @param float $timezone The user's timezone
821 * @return string
822 */
d552ead0 823function usertimezone($timezone=99) {
d552ead0 824
f30fe8d0 825 $timezone = get_user_timezone($timezone);
826
0431bd7c 827 if (abs($timezone) > 13) {
b0ccd3fb 828 return 'server time';
d552ead0 829 }
830 if (abs($timezone) < 0.5) {
b0ccd3fb 831 return 'GMT';
d552ead0 832 }
833 if ($timezone > 0) {
b0ccd3fb 834 return 'GMT+'. $timezone;
d552ead0 835 } else {
b0ccd3fb 836 return 'GMT'. $timezone;
d552ead0 837 }
f9903ed0 838}
839
7cf1c7bd 840/**
841 * Returns a float which represents the user's timezone difference from GMT in hours
842 * Checks various settings and picks the most dominant of those which have a value
843 *
7cf1c7bd 844 * @uses $CFG
845 * @uses $USER
e34d817e 846 * @param float $tz The user's timezone
c6d15803 847 * @return int
7cf1c7bd 848 */
f30fe8d0 849function get_user_timezone($tz = 99) {
f30fe8d0 850
851 // Variables declared explicitly global here so that if we add
852 // something later we won't forget to global it...
853 $timezones = array(
854 isset($GLOBALS['USER']->timezone) ? $GLOBALS['USER']->timezone : 99,
855 isset($GLOBALS['CFG']->timezone) ? $GLOBALS['CFG']->timezone : 99,
856 );
857 while($tz == 99 && $next = each($timezones)) {
858 $tz = (float)$next['value'];
859 }
860
861 return $tz;
862}
f9903ed0 863
830a2bbd 864function calculate_user_dst_table($from_year = NULL, $to_year = NULL) {
85cafb3e 865 global $CFG, $USER;
85cafb3e 866
830a2bbd 867 if (empty($USER)) {
868 return false;
85cafb3e 869 }
870
0ed442f8 871 if (empty($CFG->forcetimezone)) {
872 if (empty($USER->timezonename)) {
e789650d 873 return false;
85cafb3e 874 }
830a2bbd 875 $timezonename = $USER->timezonename;
7cb29a3d 876
877 } else {
830a2bbd 878 $timezonename = $CFG->forcetimezone;
879 }
880
881 if (!empty($USER->dstoffsets) && empty($from_year) && empty($to_year)) {
882 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
883 // This will be the return path most of the time, pretty light computationally
884 return true;
85cafb3e 885 }
886
830a2bbd 887 // Reaching here means we either need to extend our table or create it from scratch
888 if(empty($USER->dstoffsets)) {
889 // If we 're creating from scratch, put the two guard elements in there
890 $USER->dstoffsets = array(1 => NULL, 0 => NULL);
891 }
892 if(empty($USER->dstrange)) {
893 // If creating from scratch
894 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
895 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
896
897 // Fill in the array with the extra years we need to process
898 $yearstoprocess = array();
899 for($i = $from; $i <= $to; ++$i) {
900 $yearstoprocess[] = $i;
901 }
902
903 // Take note of which years we have processed for future calls
904 $USER->dstrange = array($from, $to);
905 }
906 else {
907 // If needing to extend the table, do the same
908 $yearstoprocess = array();
909
910 $from = max((empty($from_year) ? $USER->dstrange[0] : $from_year), 1971);
911 $to = min((empty($to_year) ? $USER->dstrange[1] : $to_year), 2035);
912
913 if($from < $USER->dstrange[0]) {
914 // Take note of which years we need to process and then note that we have processed them for future calls
915 for($i = $from; $i < $USER->dstrange[0]; ++$i) {
916 $yearstoprocess[] = $i;
917 }
918 $USER->dstrange[0] = $from;
919 }
920 if($to > $USER->dstrange[1]) {
921 // Take note of which years we need to process and then note that we have processed them for future calls
922 for($i = $USER->dstrange[1] + 1; $i <= $to; ++$i) {
923 $yearstoprocess[] = $i;
924 }
925 $USER->dstrange[1] = $to;
926 }
927 }
928
929 if(empty($yearstoprocess)) {
930 // This means that there was a call requesting a SMALLER range than we have already calculated
931 return true;
932 }
933
934 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
935 // Also, the array is sorted in descending timestamp order!
936
937 // Get DB data
938 $presetrecords = get_records('timezone', 'name', $timezonename, '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 939 if(empty($presetrecords)) {
940 return false;
941 }
57f1191c 942
830a2bbd 943 // Remove ending guard (first element of the array)
944 reset($USER->dstoffsets);
945 unset($USER->dstoffsets[key($USER->dstoffsets)]);
946
947 // Add all required change timestamps
948 foreach($yearstoprocess as $y) {
949 // Find the record which is in effect for the year $y
950 foreach($presetrecords as $year => $preset) {
951 if($year <= $y) {
952 break;
c9e72798 953 }
830a2bbd 954 }
955
956 $changes = dst_changes_for_year($y, $preset);
957
958 if($changes === NULL) {
959 continue;
960 }
961 if($changes['dst'] != 0) {
962 $USER->dstoffsets[$changes['dst']] = $preset->dstoff * MINSECS;
963 }
964 if($changes['std'] != 0) {
965 $USER->dstoffsets[$changes['std']] = 0;
c9e72798 966 }
85cafb3e 967 }
42d36497 968
830a2bbd 969 // Put in a guard element at the top
970 $maxtimestamp = max(array_keys($USER->dstoffsets));
971 $USER->dstoffsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
972
973 // Sort again
974 krsort($USER->dstoffsets);
975
e789650d 976 return true;
977}
42d36497 978
e789650d 979function dst_changes_for_year($year, $timezone) {
7cb29a3d 980
e789650d 981 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
982 return NULL;
42d36497 983 }
7cb29a3d 984
e789650d 985 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
986 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
987
988 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
989 list($std_hour, $std_min) = explode(':', $timezone->std_time);
d2a9f7cc 990
e789650d 991 $tz = get_user_timezone(99);
830a2bbd 992 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, $tz, false);
993 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, $tz, false);
994
995 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
996 // This has the advantage of being able to have negative values for hour, i.e. for timezones
997 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
998
999 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1000 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
42d36497 1001
e789650d 1002 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
42d36497 1003}
1004
02f0527d 1005// $time must NOT be compensated at all, it has to be a pure timestamp
1006function dst_offset_on($time) {
830a2bbd 1007 global $USER;
1008
e789650d 1009 if(!calculate_user_dst_table()) {
85cafb3e 1010 return 0;
1011 }
02f0527d 1012
0bd7322e 1013 if(empty($USER) || empty($USER->dstoffsets)) {
c9e72798 1014 return 0;
85cafb3e 1015 }
1016
830a2bbd 1017 reset($USER->dstoffsets);
1018 while(list($from, $offset) = each($USER->dstoffsets)) {
59556d48 1019 if($from <= $time) {
c9e72798 1020 break;
1021 }
1022 }
1023
830a2bbd 1024 // This is the normal return path
1025 if($offset !== NULL) {
1026 return $offset;
02f0527d 1027 }
02f0527d 1028
830a2bbd 1029 // Reaching this point means we haven't calculated far enough, do it now:
1030 // Calculate extra DST changes if needed and recurse. The recursion always
1031 // moves toward the stopping condition, so will always end.
1032
1033 if($from == 0) {
1034 // We need a year smaller than $USER->dstrange[0]
1035 if($USER->dstrange[0] == 1971) {
1036 return 0;
1037 }
1038 calculate_user_dst_table($USER->dstrange[0] - 5, NULL);
1039 return dst_offset_on($time);
1040 }
1041 else {
1042 // We need a year larger than $USER->dstrange[1]
1043 if($USER->dstrange[1] == 2035) {
1044 return 0;
1045 }
1046 calculate_user_dst_table(NULL, $USER->dstrange[1] + 5);
1047 return dst_offset_on($time);
1048 }
85cafb3e 1049}
02f0527d 1050
28902d99 1051function find_day_in_month($startday, $weekday, $month, $year) {
8dc3f6cf 1052
1053 $daysinmonth = days_in_month($month, $year);
1054
42d36497 1055 if($weekday == -1) {
28902d99 1056 // Don't care about weekday, so return:
1057 // abs($startday) if $startday != -1
1058 // $daysinmonth otherwise
1059 return ($startday == -1) ? $daysinmonth : abs($startday);
8dc3f6cf 1060 }
1061
1062 // From now on we 're looking for a specific weekday
8dc3f6cf 1063
28902d99 1064 // Give "end of month" its actual value, since we know it
1065 if($startday == -1) {
1066 $startday = -1 * $daysinmonth;
1067 }
1068
1069 // Starting from day $startday, the sign is the direction
8dc3f6cf 1070
28902d99 1071 if($startday < 1) {
8dc3f6cf 1072
28902d99 1073 $startday = abs($startday);
8dc3f6cf 1074 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1075
1076 // This is the last such weekday of the month
1077 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
1078 if($lastinmonth > $daysinmonth) {
1079 $lastinmonth -= 7;
42d36497 1080 }
8dc3f6cf 1081
28902d99 1082 // Find the first such weekday <= $startday
1083 while($lastinmonth > $startday) {
8dc3f6cf 1084 $lastinmonth -= 7;
42d36497 1085 }
8dc3f6cf 1086
1087 return $lastinmonth;
1088
42d36497 1089 }
1090 else {
42d36497 1091
28902d99 1092 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
42d36497 1093
8dc3f6cf 1094 $diff = $weekday - $indexweekday;
1095 if($diff < 0) {
1096 $diff += 7;
42d36497 1097 }
42d36497 1098
28902d99 1099 // This is the first such weekday of the month equal to or after $startday
1100 $firstfromindex = $startday + $diff;
42d36497 1101
8dc3f6cf 1102 return $firstfromindex;
1103
1104 }
42d36497 1105}
1106
1107function days_in_month($month, $year) {
1108 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1109}
1110
8dc3f6cf 1111function dayofweek($day, $month, $year) {
1112 // I wonder if this is any different from
1113 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1114 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1115}
1116
9fa49e22 1117/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 1118
1a33f699 1119// Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1120// if one does not already exist, but does not overwrite existing sesskeys. Returns the
1121// sesskey string if $USER exists, or boolean false if not.
04280e85 1122function sesskey() {
1a33f699 1123 global $USER;
1124
1125 if(!isset($USER)) {
1126 return false;
1127 }
1128
1129 if (empty($USER->sesskey)) {
1130 $USER->sesskey = random_string(10);
1131 }
1132
1133 return $USER->sesskey;
1134}
1135
7cf1c7bd 1136/**
ec81373f 1137 * This function checks that the current user is logged in and has the
1138 * required privileges
1139 *
7cf1c7bd 1140 * This function checks that the current user is logged in, and optionally
ec81373f 1141 * whether they are allowed to be in a particular course and view a particular
1142 * course module.
1143 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 1144 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 1145 * case they are automatically logged in as guests.
1146 * If $courseid is given and the user is not enrolled in that course then the
1147 * user is redirected to the course enrolment page.
1148 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1149 * in the course then the user is redirected to the course home page.
7cf1c7bd 1150 *
7cf1c7bd 1151 * @uses $CFG
c6d15803 1152 * @uses $SESSION
7cf1c7bd 1153 * @uses $USER
1154 * @uses $FULLME
c6d15803 1155 * @uses SITEID
7cf1c7bd 1156 * @uses $MoodleSession
ec81373f 1157 * @param int $courseid id of the course
d2a9f7cc 1158 * @param boolean $autologinguest
ec81373f 1159 * @param $cm course module object
7cf1c7bd 1160 */
ec81373f 1161function require_login($courseid=0, $autologinguest=true, $cm=null) {
f9903ed0 1162
73047f2f 1163 global $CFG, $SESSION, $USER, $FULLME, $MoodleSession;
d8ba183c 1164
da5c172a 1165 // First check that the user is logged in to the site.
c21c671d 1166 if (! (isset($USER->loggedin) and $USER->confirmed and ($USER->site == $CFG->wwwroot)) ) { // They're not
f9903ed0 1167 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1168 if (!empty($_SERVER['HTTP_REFERER'])) {
1169 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
9f44d972 1170 }
c21c671d 1171 $USER = NULL;
8e8d0524 1172 if ($autologinguest and $CFG->autologinguests and $courseid and get_field('course','guest','id',$courseid)) {
1173 $loginguest = '?loginguest=true';
1174 } else {
1175 $loginguest = '';
a2ebe6a5 1176 }
8a33e371 1177 if (empty($CFG->loginhttps)) {
b0ccd3fb 1178 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
8a33e371 1179 } else {
b0ccd3fb 1180 $wwwroot = str_replace('http','https', $CFG->wwwroot);
1181 redirect($wwwroot .'/login/index.php'. $loginguest);
8a33e371 1182 }
20fde7b1 1183 exit;
f9903ed0 1184 }
808a3baa 1185
d35757eb 1186 // check whether the user should be changing password
027a1604 1187 // reload_user_preferences(); // Why is this necessary? Seems wasteful. - MD
a3f1f815 1188 if (!empty($USER->preference['auth_forcepasswordchange'])){
d35757eb 1189 if (is_internal_auth() || $CFG->{'auth_'.$USER->auth.'_stdchangepassword'}){
20fde7b1 1190 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1191 redirect($CFG->wwwroot .'/login/change_password.php');
d35757eb 1192 } elseif($CFG->changepassword) {
1193 redirect($CFG->changepassword);
1194 } else {
361855e6 1195 error('You cannot proceed without changing your password.
d35757eb 1196 However there is no available page for changing it.
b0ccd3fb 1197 Please contact your Moodle Administrator.');
d35757eb 1198 }
1199 }
808a3baa 1200 // Check that the user account is properly set up
1201 if (user_not_fully_set_up($USER)) {
20fde7b1 1202 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1203 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 1204 }
d8ba183c 1205
366dfa60 1206 // Make sure current IP matches the one for this session (if required)
361855e6 1207 if (!empty($CFG->tracksessionip)) {
366dfa60 1208 if ($USER->sessionIP != md5(getremoteaddr())) {
1209 error(get_string('sessionipnomatch', 'error'));
1210 }
1211 }
6d8f47d6 1212
1213 // Make sure the USER has a sesskey set up. Used for checking script parameters.
04280e85 1214 sesskey();
366dfa60 1215
027a1604 1216 // Check that the user has agreed to a site policy if there is one
1217 if (!empty($CFG->sitepolicy)) {
1218 if (!$USER->policyagreed) {
957b5198 1219 $SESSION->wantsurl = $FULLME;
027a1604 1220 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 1221 }
1695b680 1222 }
1223
1224 // If the site is currently under maintenance, then print a message
1225 if (!isadmin()) {
1226 if (file_exists($CFG->dataroot.'/1/maintenance.html')) {
1227 print_maintenance_message();
20fde7b1 1228 exit;
1695b680 1229 }
027a1604 1230 }
1231
da5c172a 1232 // Next, check if the user can be in a particular course
1233 if ($courseid) {
ec81373f 1234 if ($courseid == SITEID) { // Anyone can be in the site course
1235 if (isset($cm) and !$cm->visible and !isteacher(SITEID)) { // Not allowed to see module, send to course page
1236 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1237 }
d2a9f7cc 1238 return;
e3512050 1239 }
9c9f7d77 1240 if (!empty($USER->student[$courseid]) or !empty($USER->teacher[$courseid]) or !empty($USER->admin)) {
cb909d74 1241 if (isset($USER->realuser)) { // Make sure the REAL person can also access this course
1242 if (!isteacher($courseid, $USER->realuser)) {
1243 print_header();
b0ccd3fb 1244 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
cb909d74 1245 }
3ce2f1e0 1246 }
ec81373f 1247 if (isset($cm) and !$cm->visible and !isteacher($courseid)) { // Not allowed to see module, send to course page
1248 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1249 }
da5c172a 1250 return; // user is a member of this course.
1251 }
b0ccd3fb 1252 if (! $course = get_record('course', 'id', $courseid)) {
1253 error('That course doesn\'t exist');
da5c172a 1254 }
1efa27fd 1255 if (!$course->visible) {
1256 print_header();
4bd2e69a 1257 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
1efa27fd 1258 }
b0ccd3fb 1259 if ($USER->username == 'guest') {
7363ff91 1260 switch ($course->guest) {
1261 case 0: // Guests not allowed
1262 print_header();
ea971152 1263 notice(get_string('guestsnotallowed', '', $course->fullname), "$CFG->wwwroot/login/index.php");
7363ff91 1264 break;
1265 case 1: // Guests allowed
ec81373f 1266 if (isset($cm) and !$cm->visible) { // Not allowed to see module, send to course page
1267 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1268 }
7363ff91 1269 return;
1270 case 2: // Guests allowed with key (drop through)
1271 break;
1272 }
da5c172a 1273 }
f9903ed0 1274
9ca3b4f3 1275 //User is not enrolled in the course, wants to access course content
1276 //as a guest, and course setting allow unlimited guest access
1277 //Code cribbed from course/loginas.php
1278 if (strstr($FULLME,"username=guest") && ($course->guest==1)) {
b56ccdd9 1279 $realuser = $USER->id;
1280 $realname = fullname($USER, true);
1281 $USER = guest_user();
1282 $USER->loggedin = true;
1283 $USER->site = $CFG->wwwroot;
1284 $USER->realuser = $realuser;
5f357fb6 1285 $USER->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
1286 if (isset($SESSION->currentgroup)) { // Remember current cache setting for later
1287 $SESSION->oldcurrentgroup = $SESSION->currentgroup;
1288 unset($SESSION->currentgroup);
b56ccdd9 1289 }
1290 $guest_name = fullname($USER, true);
1291 add_to_log($course->id, "course", "loginas", "../user/view.php?id=$course->id&$USER->id$", "$realname -> $guest_name");
ec81373f 1292 if (isset($cm) and !$cm->visible) { // Not allowed to see module, send to course page
1293 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1294 }
b56ccdd9 1295 return;
9ca3b4f3 1296 }
1297
7363ff91 1298 // Currently not enrolled in the course, so see if they want to enrol
da5c172a 1299 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1300 redirect($CFG->wwwroot .'/course/enrol.php?id='. $courseid);
da5c172a 1301 die;
1302 }
f9903ed0 1303}
1304
7cf1c7bd 1305/**
1306 * This is a weaker version of {@link require_login()} which only requires login
1307 * when called from within a course rather than the site page, unless
1308 * the forcelogin option is turned on.
1309 *
1310 * @uses $CFG
c6d15803 1311 * @param int $courseid The course in question
b56ccdd9 1312 * @param boolean $autologinguest Allow autologin guests if that is wanted
7cf1c7bd 1313 */
ec81373f 1314function require_course_login($course, $autologinguest=true, $cm=null) {
f950af3c 1315 global $CFG;
1316 if ($CFG->forcelogin) {
b56ccdd9 1317 require_login();
f950af3c 1318 }
1319 if ($course->category) {
ec81373f 1320 require_login($course->id, $autologinguest, $cm);
f950af3c 1321 }
1322}
1323
7cf1c7bd 1324/**
1325 * Modify the user table by setting the currently logged in user's
1326 * last login to now.
1327 *
1328 * @uses $USER
1329 * @return boolean
1330 */
1d881d92 1331function update_user_login_times() {
1332 global $USER;
1333
1334 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2a2f5f11 1335 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1d881d92 1336
1337 $user->id = $USER->id;
1338
b0ccd3fb 1339 return update_record('user', $user);
1d881d92 1340}
1341
7cf1c7bd 1342/**
1343 * Determines if a user has completed setting up their account.
1344 *
89dcb99d 1345 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
7cf1c7bd 1346 * @return boolean
1347 */
808a3baa 1348function user_not_fully_set_up($user) {
bb64b51a 1349 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
1350}
1351
1352function over_bounce_threshold($user) {
d2a9f7cc 1353
bb64b51a 1354 global $CFG;
d2a9f7cc 1355
bb64b51a 1356 if (empty($CFG->handlebounces)) {
1357 return false;
1358 }
1359 // set sensible defaults
1360 if (empty($CFG->minbounces)) {
1361 $CFG->minbounces = 10;
1362 }
1363 if (empty($CFG->bounceratio)) {
1364 $CFG->bounceratio = .20;
1365 }
1366 $bouncecount = 0;
1367 $sendcount = 0;
1368 if ($bounce = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
1369 $bouncecount = $bounce->value;
1370 }
1371 if ($send = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
1372 $sendcount = $send->value;
1373 }
1374 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
1375}
1376
d2a9f7cc 1377/**
bb64b51a 1378 * @param $user - object containing an id
1379 * @param $reset - will reset the count to 0
1380 */
1381function set_send_count($user,$reset=false) {
d2a9f7cc 1382 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
bb64b51a 1383 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
1384 update_record('user_preferences',$pref);
1385 }
1386 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1387 // make a new one
1388 $pref->name = 'email_send_count';
1389 $pref->value = 1;
1390 $pref->userid = $user->id;
1391 insert_record('user_preferences',$pref);
1392 }
1393}
1394
d2a9f7cc 1395/**
bb64b51a 1396* @param $user - object containing an id
1397 * @param $reset - will reset the count to 0
1398 */
1399function set_bounce_count($user,$reset=false) {
d2a9f7cc 1400 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
bb64b51a 1401 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
1402 update_record('user_preferences',$pref);
1403 }
1404 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1405 // make a new one
1406 $pref->name = 'email_bounce_count';
1407 $pref->value = 1;
1408 $pref->userid = $user->id;
1409 insert_record('user_preferences',$pref);
1410 }
808a3baa 1411}
f9903ed0 1412
7cf1c7bd 1413/**
1414 * Keeps track of login attempts
1415 *
1416 * @uses $SESSION
1417 */
f9903ed0 1418function update_login_count() {
9fa49e22 1419
f9903ed0 1420 global $SESSION;
1421
1422 $max_logins = 10;
1423
1424 if (empty($SESSION->logincount)) {
1425 $SESSION->logincount = 1;
1426 } else {
1427 $SESSION->logincount++;
1428 }
1429
1430 if ($SESSION->logincount > $max_logins) {
9fa49e22 1431 unset($SESSION->wantsurl);
b0ccd3fb 1432 error(get_string('errortoomanylogins'));
d578afc8 1433 }
1434}
1435
7cf1c7bd 1436/**
1437 * Resets login attempts
1438 *
1439 * @uses $SESSION
1440 */
9fa49e22 1441function reset_login_count() {
9fa49e22 1442 global $SESSION;
d578afc8 1443
9fa49e22 1444 $SESSION->logincount = 0;
d578afc8 1445}
1446
7cf1c7bd 1447/**
1448 * check_for_restricted_user
1449 *
89dcb99d 1450 * @uses $CFG
1451 * @uses $USER
1452 * @param string $username ?
1453 * @param string $redirect ?
7cf1c7bd 1454 * @todo Finish documenting this function
1455 */
b0ccd3fb 1456function check_for_restricted_user($username=NULL, $redirect='') {
cb98d312 1457 global $CFG, $USER;
1458
1459 if (!$username) {
1460 if (!empty($USER->username)) {
1461 $username = $USER->username;
1462 } else {
1463 return false;
1464 }
1465 }
1466
1467 if (!empty($CFG->restrictusers)) {
1468 $names = explode(',', $CFG->restrictusers);
1469 if (in_array($username, $names)) {
b0ccd3fb 1470 error(get_string('restricteduser', 'error', fullname($USER)), $redirect);
cb98d312 1471 }
1472 }
1473}
1474
b61efafb 1475function sync_metacourses() {
1476
1477 global $CFG;
1478
5f37b628 1479 if (!$courses = get_records_sql("SELECT DISTINCT parent_course,1 FROM {$CFG->prefix}course_meta")) {
b61efafb 1480 return;
1481 }
d2a9f7cc 1482
b61efafb 1483 foreach ($courses as $course) {
1484 sync_metacourse($course->parent_course);
1485 }
1486}
1487
1488
1489/**
1490 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
d2a9f7cc 1491 */
b61efafb 1492
1493function sync_metacourse($metacourseid) {
1494
87671466 1495 global $CFG,$db;
b61efafb 1496
1497 if (!$metacourse = get_record("course","id",$metacourseid)) {
1498 return false;
1499 }
1500
1501
5f37b628 1502 if (count_records('course_meta','parent_course',$metacourseid) == 0) { // if there are no child courses for this meta course, nuke the enrolments
b61efafb 1503 if ($enrolments = get_records('user_students','course',$metacourseid,'','userid,1')) {
1504 foreach ($enrolments as $enrolment) {
1505 unenrol_student($enrolment->userid,$metacourseid);
1506 }
1507 }
1508 return true;
1509 }
1510
b61efafb 1511 // this will return a list of userids from user_student for enrolments in the metacourse that shouldn't be there.
d2a9f7cc 1512 $sql = "SELECT parent.userid,max(child.course) as course
87671466 1513 FROM {$CFG->prefix}course_meta meta
d2a9f7cc 1514 JOIN {$CFG->prefix}user_students parent
87671466 1515 ON meta.parent_course = parent.course
d2a9f7cc 1516 LEFT OUTER JOIN {$CFG->prefix}user_students child
1517 ON child.course = meta.child_course
ee1bef90 1518 AND child.userid = parent.userid
87671466 1519 WHERE meta.parent_course = $metacourseid
d2a9f7cc 1520 GROUP BY child.course,parent.userid
87671466 1521 ORDER BY parent.userid,child.course";
1522
1523 $res = $db->Execute($sql);
b61efafb 1524
87671466 1525 //iterate results
1526 $enrolmentstodelete = array();
1527 while( !$res->EOF && isset($res->fields) ) {
1528 $enrolmentstodelete[] = $res->fields;
1529 $res->MoveNext();
1530 }
1531
1532 if (!empty($enrolmentstodelete)) {
1533 $last->id = 0;
1534 $last->course = 0;
b61efafb 1535 foreach ($enrolmentstodelete as $enrolment) {
87671466 1536 $enrolment = (object)$enrolment;
1537 if (count($enrolmentstodelete) == 1 && empty($enrolment->course)) {
1538 unenrol_student($enrolment->userid,$metacourseid);
1539 break;
1540 }
1541 if ($last->id != $enrolment->userid) { // we've changed
1542 if (empty($last->course) && !empty($last->id)) {
1543 unenrol_student($last->id,$metacourseid); // doing it this way for forum subscriptions etc.
1544 }
1545 $last->course = 0;
1546 $last->id = $enrolment->userid;
1547 }
1548
1549 if (!empty($enrolment->course)) {
1550 $last->course = $enrolment->course;
1551 }
1552 }
1553 if (!empty($last->id) && empty($last->course)) {
1554 unenrol_student($last->id,$metacourseid); // doing it this way for forum subscriptions etc.
b61efafb 1555 }
1556 }
1557
1558
1559 // this will return a list of userids that need to be enrolled in the metacourse
d2a9f7cc 1560 $sql = "SELECT DISTINCT child.userid,1
1561 FROM {$CFG->prefix}course_meta meta
1562 JOIN {$CFG->prefix}user_students child
1563 ON meta.child_course = child.course
1564 LEFT OUTER JOIN {$CFG->prefix}user_students parent
1565 ON meta.parent_course = parent.course
ee1bef90 1566 AND parent.userid = child.userid
d2a9f7cc 1567 WHERE parent.course IS NULL
ee1bef90 1568 AND meta.parent_course = $metacourseid";
b61efafb 1569
1570 if ($userstoadd = get_records_sql($sql)) {
1571 foreach ($userstoadd as $user) {
1572 enrol_student($user->userid,$metacourseid);
1573 }
1574 }
d2a9f7cc 1575
b61efafb 1576 // and next make sure that we have the right start time and end time (ie max and min) for them all.
1577 if ($enrolments = get_records('user_students','course',$metacourseid,'','id,userid')) {
1578 foreach ($enrolments as $enrol) {
1579 if ($maxmin = get_record_sql("SELECT min(timestart) AS timestart, max(timeend) AS timeend
0bedb187 1580 FROM {$CFG->prefix}user_students u JOIN {$CFG->prefix}course_meta mc ON u.course = mc.child_course WHERE userid = $enrol->userid
b61efafb 1581 AND mc.parent_course = $metacourseid")) {
1582 $enrol->timestart = $maxmin->timestart;
1583 $enrol->timeend = $maxmin->timeend;
1584 update_record('user_students',$enrol);
1585 }
1586 }
1587 }
1588 return true;
1589}
1590
d2a9f7cc 1591/**
b61efafb 1592 * Adds a record to the metacourse table and calls sync_metacoures
1593 */
1594function add_to_metacourse ($metacourseid, $courseid) {
d2a9f7cc 1595
b61efafb 1596 if (!$metacourse = get_record("course","id",$metacourseid)) {
1597 return false;
1598 }
d2a9f7cc 1599
b61efafb 1600 if (!$course = get_record("course","id",$courseid)) {
1601 return false;
1602 }
1603
5f37b628 1604 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
b61efafb 1605 $rec->parent_course = $metacourseid;
1606 $rec->child_course = $courseid;
5f37b628 1607 if (!insert_record('course_meta',$rec)) {
b61efafb 1608 return false;
1609 }
1610 return sync_metacourse($metacourseid);
1611 }
1612 return true;
d2a9f7cc 1613
b61efafb 1614}
1615
d2a9f7cc 1616/**
b61efafb 1617 * Removes the record from the metacourse table and calls sync_metacourse
1618 */
1619function remove_from_metacourse($metacourseid, $courseid) {
1620
5f37b628 1621 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
b61efafb 1622 return sync_metacourse($metacourseid);
1623 }
1624 return false;
1625}
1626
1627
7cf1c7bd 1628/**
1629 * Determines if a user an admin
1630 *
1631 * @uses $USER
c6d15803 1632 * @param int $userid The id of the user as is found in the 'user' table
89dcb99d 1633 * @staticvar array $admin ?
1634 * @staticvar array $nonadmins ?
7cf1c7bd 1635 * @return boolean
89dcb99d 1636 * @todo Complete documentation for this function
7cf1c7bd 1637 */
581d7b49 1638function isadmin($userid=0) {
f9903ed0 1639 global $USER;
5e04ee0c 1640 static $admins, $nonadmins;
1641
1642 if (!isset($admins)) {
1643 $admins = array();
1644 $nonadmins = array();
1645 }
f9903ed0 1646
581d7b49 1647 if (!$userid){
1648 if (empty($USER->id)) {
1649 return false;
1650 }
1651 $userid = $USER->id;
9bd2c874 1652 }
1653
dcc17b63 1654 if (!empty($USER->id) and ($userid == $USER->id)) { // Check session cache
1655 return !empty($USER->admin);
1656 }
1657
581d7b49 1658 if (in_array($userid, $admins)) {
aa095969 1659 return true;
581d7b49 1660 } else if (in_array($userid, $nonadmins)) {
aa095969 1661 return false;
b0ccd3fb 1662 } else if (record_exists('user_admins', 'userid', $userid)){
581d7b49 1663 $admins[] = $userid;
aa095969 1664 return true;
1665 } else {
581d7b49 1666 $nonadmins[] = $userid;
aa095969 1667 return false;
f9903ed0 1668 }
f9903ed0 1669}
1670
7cf1c7bd 1671/**
5e04ee0c 1672 * Determines if a user is a teacher (or better)
7cf1c7bd 1673 *
9407d456 1674 * @uses $USER
c6d15803 1675 * @param int $courseid The id of the course that is being viewed, if any
1676 * @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 1677 * @param boolean $includeadmin If true this function will return true when it encounters an admin user.
1678 * @return boolean
1679 * @todo Finish documenting this function
1680 */
fb830a1b 1681function isteacher($courseid=0, $userid=0, $includeadmin=true) {
5e04ee0c 1682/// Is the user able to access this course as a teacher?
fb830a1b 1683 global $USER, $CFG;
f9903ed0 1684
5e04ee0c 1685 if (empty($userid)) { // we are relying on $USER
1686 if (empty($USER) or empty($USER->id)) { // not logged in so can't be a teacher
1687 return false;
1688 }
dcc17b63 1689 if (!empty($USER->teacher) and $courseid) { // look in session cache
1690 if (!empty($USER->teacher[$courseid])) { // Explicitly a teacher, good
1691 return true;
1692 }
5e04ee0c 1693 }
dcc17b63 1694 $userid = $USER->id; // we need to make further checks
5e04ee0c 1695 }
1696
dcc17b63 1697 if ($includeadmin and isadmin($userid)) { // admins can do anything the teacher can
d115a57f 1698 return true;
1699 }
1700
dcc17b63 1701 if (empty($courseid)) { // should not happen, but we handle it
fb830a1b 1702 if (isadmin() or $CFG->debug > 7) {
dcc17b63 1703 notify('Coding error: isteacher() should not be used without a valid course id '.
1704 'as argument. Please notify the developer for this module.');
fb830a1b 1705 }
9407d456 1706 return isteacherinanycourse($userid, $includeadmin);
1707 }
1708
dcc17b63 1709/// Last resort, check the database
1710
9407d456 1711 return record_exists('user_teachers', 'userid', $userid, 'course', $courseid);
1712}
1713
1714/**
1715 * Determines if a user is a teacher in any course, or an admin
1716 *
1717 * @uses $USER
1718 * @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.
1719 * @param boolean $includeadmin If true this function will return true when it encounters an admin user.
1720 * @return boolean
1721 * @todo Finish documenting this function
1722 */
5e04ee0c 1723function isteacherinanycourse($userid=0, $includeadmin=true) {
fddbcf9c 1724 global $USER;
1725
5e04ee0c 1726 if (empty($userid)) {
1727 if (empty($USER) or empty($USER->id)) {
9407d456 1728 return false;
1729 }
dcc17b63 1730 if (!empty($USER->teacher)) { // look in session cache
1731 return true;
1732 }
9407d456 1733 $userid = $USER->id;
9d3c795c 1734 }
1735
5e04ee0c 1736 if ($includeadmin and isadmin($userid)) { // admins can do anything
fddbcf9c 1737 return true;
1738 }
1739
9407d456 1740 return record_exists('user_teachers', 'userid', $userid);
f9903ed0 1741}
1742
7cf1c7bd 1743/**
1744 * Determines if a user is allowed to edit a given course
1745 *
1746 * @uses $USER
c6d15803 1747 * @param int $courseid The id of the course that is being edited
1748 * @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 1749 * @return boolean
1750 */
73047f2f 1751function isteacheredit($courseid, $userid=0) {
73047f2f 1752 global $USER;
1753
d8ba183c 1754 if (isadmin($userid)) { // admins can do anything
73047f2f 1755 return true;
1756 }
1757
1758 if (!$userid) {
ddd7a47a 1759 if (empty($USER) or empty($USER->id)) { // not logged in so can't be a teacher
1760 return false;
1761 }
1762 if (empty($USER->teacheredit)) { // we are relying on session cache
1763 return false;
1764 }
73047f2f 1765 return !empty($USER->teacheredit[$courseid]);
1766 }
1767
b0ccd3fb 1768 return get_field('user_teachers', 'editall', 'userid', $userid, 'course', $courseid);
73047f2f 1769}
1770
7cf1c7bd 1771/**
1772 * Determines if a user can create new courses
1773 *
1774 * @uses $USER
361855e6 1775 * @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 1776 * @return boolean
1777 */
1924074c 1778function iscreator ($userid=0) {
1924074c 1779 global $USER;
8a205861 1780 if (empty($USER->id)) {
1781 return false;
1782 }
1924074c 1783 if (isadmin($userid)) { // admins can do anything
1784 return true;
1785 }
8a205861 1786 if (empty($userid)) {
b0ccd3fb 1787 return record_exists('user_coursecreators', 'userid', $USER->id);
1924074c 1788 }
1789
b0ccd3fb 1790 return record_exists('user_coursecreators', 'userid', $userid);
1924074c 1791}
1792
7cf1c7bd 1793/**
1794 * Determines if a user is a student in the specified course
361855e6 1795 *
7cf1c7bd 1796 * If the course id specifies the site then the function determines
1797 * if the user is a confirmed and valid user of this site.
1798 *
1799 * @uses $USER
1800 * @uses $CFG
c6d15803 1801 * @uses SITEID
1802 * @param int $courseid The id of the course being tested
361855e6 1803 * @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 1804 * @return boolean
1805 */
8a9e3fd7 1806function isstudent($courseid, $userid=0) {
71f9abf9 1807 global $USER, $CFG;
f9903ed0 1808
2700d113 1809 if (empty($USER->id) and !$userid) {
7064e18f 1810 return false;
1811 }
1812
222ac91b 1813 if ($courseid == SITEID) {
2cc72e84 1814 if (!$userid) {
1815 $userid = $USER->id;
1816 }
1817 if (isguest($userid)) {
1818 return false;
1819 }
71f9abf9 1820 // a site teacher can never be a site student
1821 if (isteacher($courseid, $userid)) {
1822 return false;
1823 }
2700d113 1824 if ($CFG->allusersaresitestudents) {
1825 return record_exists('user', 'id', $userid);
1826 } else {
1827 return (record_exists('user_students', 'userid', $userid)
71f9abf9 1828 or record_exists('user_teachers', 'userid', $userid));
2700d113 1829 }
8f0cd6ef 1830 }
2cc72e84 1831
f9903ed0 1832 if (!$userid) {
346b1a24 1833 return !empty($USER->student[$courseid]);
f9903ed0 1834 }
1835
ebc3bd2b 1836 // $timenow = time(); // todo: add time check below
f9903ed0 1837
b0ccd3fb 1838 return record_exists('user_students', 'userid', $userid, 'course', $courseid);
f9903ed0 1839}
1840
7cf1c7bd 1841/**
1842 * Determines if the specified user is logged in as guest.
1843 *
1844 * @uses $USER
361855e6 1845 * @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 1846 * @return boolean
1847 */
da5c172a 1848function isguest($userid=0) {
1849 global $USER;
1850
1851 if (!$userid) {
b35e8568 1852 if (empty($USER->username)) {
1853 return false;
1854 }
b0ccd3fb 1855 return ($USER->username == 'guest');
da5c172a 1856 }
1857
b0ccd3fb 1858 return record_exists('user', 'id', $userid, 'username', 'guest');
da5c172a 1859}
1860
7cf1c7bd 1861/**
1862 * Determines if the currently logged in user is in editing mode
1863 *
1864 * @uses $USER
c6d15803 1865 * @param int $courseid The id of the course being tested
89dcb99d 1866 * @param user $user A {@link $USER} object. If null then the currently logged in user is used.
7cf1c7bd 1867 * @return boolean
1868 */
2c309dc2 1869function isediting($courseid, $user=NULL) {
1870 global $USER;
1871 if (!$user){
1872 $user = $USER;
1873 }
9c9f7d77 1874 if (empty($user->editing)) {
1875 return false;
1876 }
2c309dc2 1877 return ($user->editing and isteacher($courseid, $user->id));
1878}
1879
7cf1c7bd 1880/**
1881 * Determines if the logged in user is currently moving an activity
1882 *
1883 * @uses $USER
c6d15803 1884 * @param int $courseid The id of the course being tested
7cf1c7bd 1885 * @return boolean
1886 */
7977cffd 1887function ismoving($courseid) {
7977cffd 1888 global $USER;
1889
1890 if (!empty($USER->activitycopy)) {
1891 return ($USER->activitycopycourse == $courseid);
1892 }
1893 return false;
1894}
1895
7cf1c7bd 1896/**
1897 * Given an object containing firstname and lastname
1898 * values, this function returns a string with the
1899 * full name of the person.
1900 * The result may depend on system settings
1901 * or language. 'override' will force both names
361855e6 1902 * to be used even if system settings specify one.
7cf1c7bd 1903 * @uses $CFG
1904 * @uses $SESSION
1905 * @param type description
1906 * @todo Finish documenting this function
1907 */
e2cd5065 1908function fullname($user, $override=false) {
b5cbb64d 1909
f374fb10 1910 global $CFG, $SESSION;
1911
6527c077 1912 if (!isset($user->firstname) and !isset($user->lastname)) {
1913 return '';
1914 }
1915
f374fb10 1916 if (!empty($SESSION->fullnamedisplay)) {
1917 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
1918 }
e2cd5065 1919
b5cbb64d 1920 if ($CFG->fullnamedisplay == 'firstname lastname') {
b0ccd3fb 1921 return $user->firstname .' '. $user->lastname;
b5cbb64d 1922
1923 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 1924 return $user->lastname .' '. $user->firstname;
e2cd5065 1925
b5cbb64d 1926 } else if ($CFG->fullnamedisplay == 'firstname') {
1927 if ($override) {
1928 return get_string('fullnamedisplay', '', $user);
1929 } else {
1930 return $user->firstname;
1931 }
1932 }
e2cd5065 1933
b5cbb64d 1934 return get_string('fullnamedisplay', '', $user);
e2cd5065 1935}
1936
7cf1c7bd 1937/**
1938 * Sets a moodle cookie with an encrypted string
1939 *
1940 * @uses $CFG
2f87145b 1941 * @uses DAYSECS
1942 * @uses HOURSECS
7cf1c7bd 1943 * @param string $thing The string to encrypt and place in a cookie
1944 */
f9903ed0 1945function set_moodle_cookie($thing) {
7185e073 1946 global $CFG;
482b6e6e 1947
1948 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
f9903ed0 1949
1950 $days = 60;
7a5672c9 1951 $seconds = DAYSECS*$days;
f9903ed0 1952
7a5672c9 1953 setCookie($cookiename, '', time() - HOURSECS, '/');
b0ccd3fb 1954 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, '/');
f9903ed0 1955}
1956
7cf1c7bd 1957/**
1958 * Gets a moodle cookie with an encrypted string
1959 *
1960 * @uses $CFG
1961 * @return string
1962 */
f9903ed0 1963function get_moodle_cookie() {
7185e073 1964 global $CFG;
1965
482b6e6e 1966 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
7185e073 1967
1079c8a8 1968 if (empty($_COOKIE[$cookiename])) {
b0ccd3fb 1969 return '';
1079c8a8 1970 } else {
1971 return rc4decrypt($_COOKIE[$cookiename]);
1972 }
f9903ed0 1973}
1974
7cf1c7bd 1975/**
1976 * Returns true if an internal authentication method is being used.
1977 * if method not specified then, global default is assumed
1978 *
1979 * @uses $CFG
1980 * @param string $auth Form of authentication required
1981 * @return boolean
1982 * @todo Outline auth types and provide code example
1983 */
39a5a35d 1984function is_internal_auth($auth='') {
ba7166c3 1985/// Returns true if an internal authentication method is being used.
a3f1f815 1986/// If auth not specified then global default is assumed
ba7166c3 1987
1988 global $CFG;
1989
a3f1f815 1990 if (empty($auth)) {
1991 $auth = $CFG->auth;
39a5a35d 1992 }
1993
a3f1f815 1994 return ($auth == "email" || $auth == "none" || $auth == "manual");
1995}
1996
8c3dba73 1997/**
1998 * Returns an array of user fields
1999 *
c6d15803 2000 * @uses $CFG
2001 * @uses $db
2002 * @return array User field/column names
8c3dba73 2003 * @todo Finish documenting this function
2004 */
a3f1f815 2005function get_user_fieldnames() {
a3f1f815 2006
2007 global $CFG, $db;
2008
2009 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
2010 unset($fieldarray['ID']);
2011
2012 return $fieldarray;
ba7166c3 2013}
f9903ed0 2014
7cf1c7bd 2015/**
2016 * Creates a bare-bones user record
2017 *
2018 * @uses $CFG
7cf1c7bd 2019 * @param string $username New user's username to add to record
2020 * @param string $password New user's password to add to record
2021 * @param string $auth Form of authentication required
89dcb99d 2022 * @return user A {@link $USER} object
7cf1c7bd 2023 * @todo Outline auth types and provide code example
2024 */
71f9abf9 2025function create_user_record($username, $password, $auth='') {
366dfa60 2026 global $CFG;
71f9abf9 2027
1e22bc9c 2028 //just in case check text case
2029 $username = trim(moodle_strtolower($username));
71f9abf9 2030
3271b70f 2031 if (function_exists('auth_get_userinfo')) {
e858f9da 2032 if ($newinfo = auth_get_userinfo($username)) {
b36a8fc4 2033 $newinfo = truncate_userinfo($newinfo);
34daec9b 2034 foreach ($newinfo as $key => $value){
9f44d972 2035 $newuser->$key = addslashes(stripslashes($value)); // Just in case
e858f9da 2036 }
2037 }
2038 }
f9903ed0 2039
85a1d4c9 2040 if (!empty($newuser->email)) {
2041 if (email_is_not_allowed($newuser->email)) {
2042 unset($newuser->email);
2043 }
2044 }
2045
71f9abf9 2046 $newuser->auth = (empty($auth)) ? $CFG->auth : $auth;
faebaf0f 2047 $newuser->username = $username;
2048 $newuser->password = md5($password);
a0bac19d 2049 $newuser->lang = $CFG->lang;
faebaf0f 2050 $newuser->confirmed = 1;
59619427 2051 $newuser->lastIP = getremoteaddr();
faebaf0f 2052 $newuser->timemodified = time();
f9903ed0 2053
b0ccd3fb 2054 if (insert_record('user', $newuser)) {
2055 $user = get_user_info_from_db('username', $newuser->username);
d35757eb 2056 if($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'}){
2057 set_user_preference('auth_forcepasswordchange', 1, $user);
2058 }
2059 return $user;
faebaf0f 2060 }
2061 return false;
2062}
2063
7cf1c7bd 2064/**
2065 * Will update a local user record from an external source
2066 *
2067 * @uses $CFG
2068 * @param string $username New user's username to add to record
89dcb99d 2069 * @return user A {@link $USER} object
7cf1c7bd 2070 */
d35757eb 2071function update_user_record($username) {
d35757eb 2072 global $CFG;
2073
2074 if (function_exists('auth_get_userinfo')) {
2075 $username = trim(moodle_strtolower($username)); /// just in case check text case
2076
2077 if ($newinfo = auth_get_userinfo($username)) {
2078 foreach ($newinfo as $key => $value){
2079 if (!empty($CFG->{'auth_user_' . $key. '_updatelocal'})) {
2080 $value = addslashes(stripslashes($value)); // Just in case
2081 set_field('user', $key, $value, 'username', $username);
2082 }
2083 }
2084 }
2085 }
b0ccd3fb 2086 return get_user_info_from_db('username', $username);
d35757eb 2087}
0609562b 2088
b36a8fc4 2089function truncate_userinfo($info) {
2090/// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2091/// which may have large fields
2092
2093 // define the limits
2094 $limit = array(
2095 'username' => 100,
1c66bf59 2096 'idnumber' => 64,
b36a8fc4 2097 'firstname' => 20,
2098 'lastname' => 20,
2099 'email' => 100,
2100 'icq' => 15,
2101 'phone1' => 20,
2102 'phone2' => 20,
2103 'institution' => 40,
2104 'department' => 30,
2105 'address' => 70,
2106 'city' => 20,
2107 'country' => 2,
2108 'url' => 255,
2109 );
361855e6 2110
b36a8fc4 2111 // apply where needed
2112 foreach (array_keys($info) as $key) {
2113 if (!empty($limit[$key])) {
adfc03f9 2114 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
361855e6 2115 }
b36a8fc4 2116 }
361855e6 2117
b36a8fc4 2118 return $info;
2119}
2120
7cf1c7bd 2121/**
2122 * Retrieve the guest user object
2123 *
2124 * @uses $CFG
89dcb99d 2125 * @return user A {@link $USER} object
7cf1c7bd 2126 */
0609562b 2127function guest_user() {
2128 global $CFG;
2129
b0ccd3fb 2130 if ($newuser = get_record('user', 'username', 'guest')) {
0609562b 2131 $newuser->loggedin = true;
2132 $newuser->confirmed = 1;
2133 $newuser->site = $CFG->wwwroot;
2134 $newuser->lang = $CFG->lang;
366dfa60 2135 $newuser->lastIP = getremoteaddr();
0609562b 2136 }
2137
2138 return $newuser;
2139}
2140
7cf1c7bd 2141/**
2142 * Given a username and password, this function looks them
2143 * up using the currently selected authentication mechanism,
2144 * and if the authentication is successful, it returns a
2145 * valid $user object from the 'user' table.
361855e6 2146 *
7cf1c7bd 2147 * Uses auth_ functions from the currently active auth module
2148 *
2149 * @uses $CFG
361855e6 2150 * @param string $username User's username
2151 * @param string $password User's password
89dcb99d 2152 * @return user|flase A {@link $USER} object or false if error
7cf1c7bd 2153 */
faebaf0f 2154function authenticate_user_login($username, $password) {
faebaf0f 2155
2156 global $CFG;
2157
466558e3 2158 $md5password = md5($password);
2159
27286aeb 2160 // First try to find the user in the database
466558e3 2161
18f16d61 2162 if (!$user = get_user_info_from_db('username', $username)) {
2163 $user->id = 0; // Not a user
2164 $user->auth = $CFG->auth;
2165 }
39a5a35d 2166
27286aeb 2167 // Sort out the authentication method we are using.
39a5a35d 2168
27286aeb 2169 if (empty($CFG->auth)) {
b0ccd3fb 2170 $CFG->auth = 'manual'; // Default authentication module
27286aeb 2171 }
39a5a35d 2172
27286aeb 2173 if (empty($user->auth)) { // For some reason it isn't set yet
ccb3585f 2174 if (!empty($user->id) && (isadmin($user->id) || isguest($user->id))) {
71f9abf9 2175 $auth = 'manual'; // Always assume these guys are internal
27286aeb 2176 } else {
71f9abf9 2177 $auth = $CFG->auth; // Normal users default to site method
27286aeb 2178 }
d35757eb 2179 // update user record from external DB
2180 if ($user->auth != 'manual' && $user->auth != 'email') {
2181 $user = update_user_record($username);
2182 }
71f9abf9 2183 } else {
2184 $auth = $user->auth;
27286aeb 2185 }
8f0cd6ef 2186
ce791f88 2187 if (detect_munged_arguments($auth, 0)) { // For safety on the next require
2188 return false;
2189 }
2190
b0ccd3fb 2191 if (!file_exists($CFG->dirroot .'/auth/'. $auth .'/lib.php')) {
2192 $auth = 'manual'; // Can't find auth module, default to internal
466558e3 2193 }
2194
b0ccd3fb 2195 require_once($CFG->dirroot .'/auth/'. $auth .'/lib.php');
faebaf0f 2196
2197 if (auth_user_login($username, $password)) { // Successful authentication
d613daf0 2198 if ($user->id) { // User already exists in database
71f9abf9 2199 if (empty($user->auth)) { // For some reason auth isn't set yet
2200 set_field('user', 'auth', $auth, 'username', $username);
2201 }
92710226 2202 if ($md5password <> $user->password) { // Update local copy of password for reference
71f9abf9 2203 set_field('user', 'password', $md5password, 'username', $username);
faebaf0f 2204 }
366dfa60 2205 if (!is_internal_auth()) { // update user record from external DB
d35757eb 2206 $user = update_user_record($username);
2207 }
faebaf0f 2208 } else {
71f9abf9 2209 $user = create_user_record($username, $password, $auth);
faebaf0f 2210 }
89b54325 2211
e582b65e 2212 if (function_exists('auth_iscreator')) { // Check if the user is a creator
f894a791 2213 $useriscreator = auth_iscreator($username);
2214 if (!is_null($useriscreator)) {
2215 if ($useriscreator) {
2216 if (! record_exists('user_coursecreators', 'userid', $user->id)) {
2217 $cdata->userid = $user->id;
2218 if (! insert_record('user_coursecreators', $cdata)) {
2219 error('Cannot add user to course creators.');
2220 }
39a5a35d 2221 }
f894a791 2222 } else {
2223 if (record_exists('user_coursecreators', 'userid', $user->id)) {
2224 if (! delete_records('user_coursecreators', 'userid', $user->id)) {
2225 error('Cannot remove user from course creators.');
2226 }
39a5a35d 2227 }
2228 }
361855e6 2229 }
39a5a35d 2230 }
d613daf0 2231 if ($user) {
2232 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
2233 }
e582b65e 2234 return $user;
9d3c795c 2235
e582b65e 2236 } else {
b0ccd3fb 2237 add_to_log(0, 'login', 'error', $_SERVER['HTTP_REFERER'], $username);
f52d48db 2238 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
e582b65e 2239 return false;
2240 }
f9903ed0 2241}
2242
7cf1c7bd 2243/**
2244 * Enrols (or re-enrols) a student in a given course
2245 *
c6d15803 2246 * @param int $courseid The id of the course that is being viewed
2247 * @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.
2248 * @param int $timestart ?
2249 * @param int $timeend ?
7cf1c7bd 2250 * @return boolean
2251 * @todo Finish documenting this function
2252 */
92318548 2253function enrol_student($userid, $courseid, $timestart=0, $timeend=0, $enrol='') {
b40bc478 2254
75169b06 2255 global $CFG;
2256
b0ccd3fb 2257 if (!$course = get_record('course', 'id', $courseid)) { // Check course
3041b0f8 2258 return false;
4d312bbe 2259 }
b0ccd3fb 2260 if (!$user = get_record('user', 'id', $userid)) { // Check user
631cf796 2261 return false;
2262 }
b61efafb 2263 // enrol the student in any parent meta courses...
5f37b628 2264 if ($parents = get_records('course_meta','child_course',$courseid)) {
b61efafb 2265 foreach ($parents as $parent) {
2266 enrol_student($userid, $parent->parent_course,$timestart,$timeend,$enrol);
2267 }
2268 }
92318548 2269
2270 if (empty($enrol)) {
2271 $enrol = $CFG->enrol; // Default current method
2272 }
b0ccd3fb 2273 if ($student = get_record('user_students', 'userid', $userid, 'course', $courseid)) {
631cf796 2274 $student->timestart = $timestart;
2275 $student->timeend = $timeend;
2276 $student->time = time();
6e8ca983 2277 $student->enrol = $enrol;
b0ccd3fb 2278 return update_record('user_students', $student);
361855e6 2279
631cf796 2280 } else {
75169b06 2281 require_once("$CFG->dirroot/mod/forum/lib.php");
2f3b54ae 2282 forum_add_user($userid, $courseid);
2283
631cf796 2284 $student->userid = $userid;
2285 $student->course = $courseid;
2286 $student->timestart = $timestart;
2287 $student->timeend = $timeend;
2288 $student->time = time();
6e8ca983 2289 $student->enrol = $enrol;
b0ccd3fb 2290 return insert_record('user_students', $student);
631cf796 2291 }
d7facad8 2292}
2293
7cf1c7bd 2294/**
2295 * Unenrols a student from a given course
2296 *
c6d15803 2297 * @param int $courseid The id of the course that is being viewed, if any
2298 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 2299 * @return boolean
2300 */
9fa62805 2301function unenrol_student($userid, $courseid=0) {
d7facad8 2302
9fa62805 2303 if ($courseid) {
9fa49e22 2304 /// First delete any crucial stuff that might still send mail
b0ccd3fb 2305 if ($forums = get_records('forum', 'course', $courseid)) {
9fa49e22 2306 foreach ($forums as $forum) {
b0ccd3fb 2307 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
9fa62805 2308 }
2309 }
2310 if ($groups = get_groups($courseid, $userid)) {
2311 foreach ($groups as $group) {
b0ccd3fb 2312 delete_records('groups_members', 'groupid', $group->id, 'userid', $userid);
bb09fb11 2313 }
f9903ed0 2314 }
b61efafb 2315 // enrol the student in any parent meta courses...
5f37b628 2316 if ($parents = get_records('course_meta','child_course',$courseid)) {
b61efafb 2317 foreach ($parents as $parent) {
2318 unenrol_student($userid, $parent->parent_course);
2319 }
2320 }
b0ccd3fb 2321 return delete_records('user_students', 'userid', $userid, 'course', $courseid);
9fa49e22 2322
f9903ed0 2323 } else {
b0ccd3fb 2324 delete_records('forum_subscriptions', 'userid', $userid);
2325 delete_records('groups_members', 'userid', $userid);
2326 return delete_records('user_students', 'userid', $userid);
f9903ed0 2327 }
2328}
2329
7cf1c7bd 2330/**
2331 * Add a teacher to a given course
2332 *
2333 * @uses $USER
c6d15803 2334 * @param int $courseid The id of the course that is being viewed, if any
2335 * @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.
2336 * @param int $editall ?
7cf1c7bd 2337 * @param string $role ?
c6d15803 2338 * @param int $timestart ?
2339 * @param int $timeend ?
7cf1c7bd 2340 * @return boolean
2341 * @todo Finish documenting this function
2342 */
6e8ca983 2343function add_teacher($userid, $courseid, $editall=1, $role='', $timestart=0, $timeend=0, $enrol='manual') {
7b5944cd 2344 global $CFG;
3041b0f8 2345
61451a36 2346 if ($teacher = get_record('user_teachers', 'userid', $userid, 'course', $courseid)) {
b40bc478 2347 $newteacher = NULL;
2348 $newteacher->id = $teacher->id;
2349 $newteacher->editall = $editall;
6e8ca983 2350 $newteacher->enrol = $enrol;
b40bc478 2351 if ($role) {
2352 $newteacher->role = $role;
2353 }
2354 if ($timestart) {
2355 $newteacher->timestart = $timestart;
3041b0f8 2356 }
b40bc478 2357 if ($timeend) {
2358 $newteacher->timeend = $timeend;
2359 }
2360 return update_record('user_teachers', $newteacher);
3041b0f8 2361 }
61451a36 2362
b0ccd3fb 2363 if (!record_exists('user', 'id', $userid)) {
61451a36 2364 return false; // no such user
2365 }
2366
b0ccd3fb 2367 if (!record_exists('course', 'id', $courseid)) {
61451a36 2368 return false; // no such course
2369 }
2370
2371 $teacher = NULL;
2372 $teacher->userid = $userid;
2373 $teacher->course = $courseid;
2374 $teacher->editall = $editall;
2375 $teacher->role = $role;
5a2dea02 2376 $teacher->timemodified = time();
2377 $newteacher->timestart = $timestart;
2378 $newteacher->timeend = $timeend;
b0ccd3fb 2379 if ($student = get_record('user_students', 'userid', $userid, 'course', $courseid)) {
5a2dea02 2380 $teacher->timestart = $student->timestart;
2381 $teacher->timeend = $student->timeend;
2382 $teacher->timeaccess = $student->timeaccess;
2383 }
61451a36 2384
b0ccd3fb 2385 if (record_exists('user_teachers', 'course', $courseid)) {
61451a36 2386 $teacher->authority = 2;
2387 } else {
2388 $teacher->authority = 1;
2389 }
b0ccd3fb 2390 delete_records('user_students', 'userid', $userid, 'course', $courseid); // Unenrol as student
8f0cd6ef 2391
709f0ec8 2392 /// Add forum subscriptions for new users
7b5944cd 2393 require_once('../mod/forum/lib.php');
2394 forum_add_user($userid, $courseid);
61451a36 2395
b0ccd3fb 2396 return insert_record('user_teachers', $teacher);
61451a36 2397
3041b0f8 2398}
2399
7cf1c7bd 2400/**
2401 * Removes a teacher from a given course (or ALL courses)
2402 * Does not delete the user account
2403 *
c6d15803 2404 * @param int $courseid The id of the course that is being viewed, if any
361855e6 2405 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 2406 * @return boolean
2407 */
3041b0f8 2408function remove_teacher($userid, $courseid=0) {
3041b0f8 2409 if ($courseid) {
9fa49e22 2410 /// First delete any crucial stuff that might still send mail
b0ccd3fb 2411 if ($forums = get_records('forum', 'course', $courseid)) {
9fa49e22 2412 foreach ($forums as $forum) {
b0ccd3fb 2413 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
9fa49e22 2414 }
2415 }
b02193e6 2416
2417 /// Next if the teacher is not registered as a student, but is
2418 /// a member of a group, remove them from the group.
2419 if (!isstudent($courseid, $userid)) {
2420 if ($groups = get_groups($courseid, $userid)) {
2421 foreach ($groups as $group) {
b0ccd3fb 2422 delete_records('groups_members', 'groupid', $group->id, 'userid', $userid);
b02193e6 2423 }
2424 }
2425 }
2426
b0ccd3fb 2427 return delete_records('user_teachers', 'userid', $userid, 'course', $courseid);
57507290 2428 } else {
b0ccd3fb 2429 delete_records('forum_subscriptions', 'userid', $userid);
2430 return delete_records('user_teachers', 'userid', $userid);
57507290 2431 }
f9903ed0 2432}
2433
7cf1c7bd 2434/**
2435 * Add a creator to the site
2436 *
361855e6 2437 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 2438 * @return boolean
2439 */
3041b0f8 2440function add_creator($userid) {
3041b0f8 2441
b0ccd3fb 2442 if (!record_exists('user_admins', 'userid', $userid)) {
2443 if (record_exists('user', 'id', $userid)) {
3041b0f8 2444 $creator->userid = $userid;
b0ccd3fb 2445 return insert_record('user_coursecreators', $creator);
3041b0f8 2446 }
2447 return false;
2448 }
2449 return true;
2450}
2451
7cf1c7bd 2452/**
2453 * Remove a creator from a site
2454 *
2455 * @uses $db
c6d15803 2456 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 2457 * @return boolean
2458 */
3041b0f8 2459function remove_creator($userid) {
3041b0f8 2460 global $db;
2461
b0ccd3fb 2462 return delete_records('user_coursecreators', 'userid', $userid);
3041b0f8 2463}
2464
7cf1c7bd 2465/**
2466 * Add an admin to a site
2467 *
2468 * @uses SITEID
c6d15803 2469 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 2470 * @return boolean
2471 */
3041b0f8 2472function add_admin($userid) {
3041b0f8 2473
b0ccd3fb 2474 if (!record_exists('user_admins', 'userid', $userid)) {
2475 if (record_exists('user', 'id', $userid)) {
3041b0f8 2476 $admin->userid = $userid;
361855e6 2477
f950af3c 2478 // any admin is also a teacher on the site course
222ac91b 2479 if (!record_exists('user_teachers', 'course', SITEID, 'userid', $userid)) {
2480 if (!add_teacher($userid, SITEID)) {
f950af3c 2481 return false;
2482 }
2483 }
361855e6 2484
b0ccd3fb 2485 return insert_record('user_admins', $admin);
3041b0f8 2486 }
2487 return false;
2488 }
2489 return true;
2490}
2491
7cf1c7bd 2492/**
2493 * Removes an admin from a site
2494 *
2495 * @uses $db
2496 * @uses SITEID
c6d15803 2497 * @param int $userid The id of the user that is being tested against.
7cf1c7bd 2498 * @return boolean
2499 */
3041b0f8 2500function remove_admin($userid) {
9fa49e22 2501 global $db;
f9903ed0 2502
f950af3c 2503 // remove also from the list of site teachers
222ac91b 2504 remove_teacher($userid, SITEID);
f950af3c 2505
b0ccd3fb 2506 return delete_records('user_admins', 'userid', $userid);
f9903ed0 2507}
2508
7cf1c7bd 2509/**
2510 * Clear a course out completely, deleting all content
2511 * but don't delete the course itself
2512 *
2513 * @uses $USER
2514 * @uses $SESSION
2515 * @uses $CFG
c6d15803 2516 * @param int $courseid The id of the course that is being viewed
7cf1c7bd 2517 * @param boolean $showfeedback Set this to false to suppress notifications from being printed as the functions performs its steps.
2518 * @return boolean
2519 */
07aeb7b0 2520function remove_course_contents($courseid, $showfeedback=true) {
07aeb7b0 2521
538a2210 2522 global $CFG, $USER, $SESSION;
07aeb7b0 2523
2524 $result = true;
2525
b0ccd3fb 2526 if (! $course = get_record('course', 'id', $courseid)) {
2527 error('Course ID was incorrect (can\'t find it)');
07aeb7b0 2528 }
2529
b0ccd3fb 2530 $strdeleted = get_string('deleted');
07aeb7b0 2531
2532 // First delete every instance of every module
d8ba183c 2533
b0ccd3fb 2534 if ($allmods = get_records('modules') ) {
07aeb7b0 2535 foreach ($allmods as $mod) {
2536 $modname = $mod->name;
b0ccd3fb 2537 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
2538 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
2539 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
07aeb7b0 2540 $count=0;
2541 if (file_exists($modfile)) {
2542 include_once($modfile);
2543 if (function_exists($moddelete)) {
b0ccd3fb 2544 if ($instances = get_records($modname, 'course', $course->id)) {
07aeb7b0 2545 foreach ($instances as $instance) {
2546 if ($moddelete($instance->id)) {
2547 $count++;
2548 } else {
b0ccd3fb 2549 notify('Could not delete '. $modname .' instance '. $instance->id .' ('. $instance->name .')');
07aeb7b0 2550 $result = false;
2551 }
2552 }
2553 }
2554 } else {
b0ccd3fb 2555 notify('Function '. $moddelete() .'doesn\'t exist!');
07aeb7b0 2556 $result = false;
2557 }
2558
ca952b03 2559 if (function_exists($moddeletecourse)) {
2560 $moddeletecourse($course);
2561 }
07aeb7b0 2562 }
2563 if ($showfeedback) {
b0ccd3fb 2564 notify($strdeleted .' '. $count .' x '. $modname);
07aeb7b0 2565 }
2566 }
2567 } else {
b0ccd3fb 2568 error('No modules are installed!');
07aeb7b0 2569 }
2570
251af423 2571 // Delete course blocks
2572 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW, 'pageid', $course->id)) {
2573 if ($showfeedback) {
2574 notify($strdeleted .' block_instance');
2575 }
2576 } else {
2577 $result = false;
2578 }
2579
07aeb7b0 2580 // Delete any user stuff
2581
b0ccd3fb 2582 if (delete_records('user_students', 'course', $course->id)) {
07aeb7b0 2583 if ($showfeedback) {
b0ccd3fb 2584 notify($strdeleted .' user_students');
07aeb7b0 2585 }
2586 } else {
2587 $result = false;
2588 }
2589
b0ccd3fb 2590 if (delete_records('user_teachers', 'course', $course->id)) {
07aeb7b0 2591 if ($showfeedback) {
b0ccd3fb 2592 notify($strdeleted .' user_teachers');
07aeb7b0 2593 }
2594 } else {
2595 $result = false;
2596 }
2597
082e3ebc 2598 // Delete any groups
2599
b0ccd3fb 2600 if ($groups = get_records('groups', 'courseid', $course->id)) {
082e3ebc 2601 foreach ($groups as $group) {
b0ccd3fb 2602 if (delete_records('groups_members', 'groupid', $group->id)) {
082e3ebc 2603 if ($showfeedback) {
b0ccd3fb 2604 notify($strdeleted .' groups_members');
082e3ebc 2605 }
2606 } else {
2607 $result = false;
2608 }
b0ccd3fb 2609 if (delete_records('groups', 'id', $group->id)) {
082e3ebc 2610 if ($showfeedback) {
b0ccd3fb 2611 notify($strdeleted .' groups');
082e3ebc 2612 }
2613 } else {
2614 $result = false;
2615 }
2616 }
2617 }
2618
2619 // Delete events
2620
b0ccd3fb 2621 if (delete_records('event', 'courseid', $course->id)) {
082e3ebc 2622 if ($showfeedback) {
b0ccd3fb 2623 notify($strdeleted .' event');
082e3ebc 2624 }
2625 } else {
2626 $result = false;
2627 }
2628
07aeb7b0 2629 // Delete logs
2630
b0ccd3fb 2631 if (delete_records('log', 'course', $course->id)) {
07aeb7b0 2632 if ($showfeedback) {
b0ccd3fb 2633 notify($strdeleted .' log');
07aeb7b0 2634 }
2635 } else {
2636 $result = false;
2637 }
2638
2639 // Delete any course stuff
2640
b0ccd3fb 2641 if (delete_records('course_sections', 'course', $course->id)) {
07aeb7b0 2642 if ($showfeedback) {
b0ccd3fb 2643 notify($strdeleted .' course_sections');
07aeb7b0 2644 }
2645 } else {
2646 $result = false;
2647 }
2648
b0ccd3fb 2649 if (delete_records('course_modules', 'course', $course->id)) {
07aeb7b0 2650 if ($showfeedback) {
b0ccd3fb 2651 notify($strdeleted .' course_modules');
07aeb7b0 2652 }
2653 } else {
2654 $result = false;
2655 }
2656
7ff9860d 2657 // Delete gradebook stuff
2658
322344bb 2659 if (delete_records("grade_category", "course", $course->id)) {
7ff9860d 2660 if ($showfeedback) {
2661 notify("$strdeleted grade categories");
2662 } else {
2663 $result = false;
2664 }
2665 }
322344bb 2666 if (delete_records("grade_exceptions", "course", $course->id)) {
7ff9860d 2667 if ($showfeedback) {
2668 notify("$strdeleted grade exceptions");
2669 } else {
2670 $result = false;
2671 }
2672 }
322344bb 2673 if (delete_records("grade_item", "course", $course->id)) {
7ff9860d 2674 if ($showfeedback) {
2675 notify("$strdeleted grade items");
2676 } else {
2677 $result = false;
2678 }
2679 }
322344bb 2680 if (delete_records("grade_letter", "course", $course->id)) {
7ff9860d 2681 if ($showfeedback) {
2682 notify("$strdeleted grade letters");
2683 } else {
2684 $result = false;
2685 }
2686 }
322344bb 2687 if (delete_records("grade_preferences", "course", $course->id)) {
7ff9860d 2688 if ($showfeedback) {
2689 notify("$strdeleted grade preferences");
2690 } else {
2691 $result = false;
2692 }
2693 }
2694
2695
5f37b628 2696 if ($course->metacourse) {
2697 delete_records("course_meta","parent_course",$course->id);
b61efafb 2698 sync_metacourse($course->id); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
2699 if ($showfeedback) {
5f37b628 2700 notify("$strdeleted course_meta");
b61efafb 2701 }
7ff9860d 2702 } else {
5f37b628 2703 if ($parents = get_records("course_meta","child_course",$course->id)) {
b61efafb 2704 foreach ($parents as $parent) {
2705 remove_from_metacourse($parent->parent_course,$parent->child_course); // this will do the unenrolments as well.
2706 }
2707 if ($showfeedback) {
5f37b628 2708 notify("$strdeleted course_meta");
b61efafb 2709 }
2710 }
2711 }
2712
07aeb7b0 2713 return $result;
2714
2715}
2716
7cf1c7bd 2717/**
2718 * This function will empty a course of USER data as much as
2719/// possible. It will retain the activities and the structure
2720/// of the course.
2721 *
2722 * @uses $USER
7cf1c7bd 2723 * @uses $SESSION
2724 * @uses $CFG
c6d15803 2725 * @param int $courseid The id of the course that is being viewed
7cf1c7bd 2726 * @param boolean $showfeedback Set this to false to suppress notifications from being printed as the functions performs its steps.
2727 * @param boolean $removestudents ?
2728 * @param boolean $removeteachers ?
2729 * @param boolean $removegroups ?
2730 * @param boolean $removeevents ?
2731 * @param boolean $removelogs ?
2732 * @return boolean
2733 * @todo Finish documenting this function
2734 */
3831de52 2735function remove_course_userdata($courseid, $showfeedback=true,
2736 $removestudents=true, $removeteachers=false, $removegroups=true,
2737 $removeevents=true, $removelogs=false) {
3831de52 2738
538a2210 2739 global $CFG, $USER, $SESSION;
3831de52 2740
2741 $result = true;
2742
b0ccd3fb 2743 if (! $course = get_record('course', 'id', $courseid)) {
2744 error('Course ID was incorrect (can\'t find it)');
3831de52 2745 }
2746
b0ccd3fb 2747 $strdeleted = get_string('deleted');
3831de52 2748
2749 // Look in every instance of every module for data to delete
2750
b0ccd3fb 2751 if ($allmods = get_records('modules') ) {
3831de52 2752 foreach ($allmods as $mod) {
2753 $modname = $mod->name;
b0ccd3fb 2754 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
2755 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3831de52 2756 $count=0;
2757 if (file_exists($modfile)) {
2758 @include_once($modfile);
2759 if (function_exists($moddeleteuserdata)) {
2760 $moddeleteuserdata($course, $showfeedback);
2761 }
2762 }
2763 }
2764 } else {
b0ccd3fb 2765 error('No modules are installed!');
3831de52 2766 }
2767
2768 // Delete other stuff
2769
2770 if ($removestudents) {
2771 /// Delete student enrolments
b0ccd3fb 2772 if (delete_records('user_students', 'course', $course->id)) {
3831de52 2773 if ($showfeedback) {
b0ccd3fb 2774 notify($strdeleted .' user_students');
3831de52 2775 }
2776 } else {
2777 $result = false;
2778 }
2779 /// Delete group members (but keep the groups)
b0ccd3fb 2780 if ($groups = get_records('groups', 'courseid', $course->id)) {
3831de52 2781 foreach ($groups as $group) {
b0ccd3fb 2782 if (delete_records('groups_members', 'groupid', $group->id)) {
3831de52 2783 if ($showfeedback) {
b0ccd3fb 2784 notify($strdeleted .' groups_members');
3831de52 2785 }
2786 } else {
2787 $result = false;
2788 }
2789 }
2790 }
2791 }
2792
2793 if ($removeteachers) {
b0ccd3fb 2794 if (delete_records('user_teachers', 'course', $course->id)) {
3831de52 2795 if ($showfeedback) {
b0ccd3fb 2796 notify($strdeleted .' user_teachers');
3831de52 2797 }
2798 } else {
2799 $result = false;
2800 }
2801 }
2802
2803 if ($removegroups) {
b0ccd3fb 2804 if ($groups = get_records('groups', 'courseid', $course->id)) {
3831de52 2805 foreach ($groups as $group) {
b0ccd3fb 2806 if (delete_records('groups', 'id', $group->id)) {
3831de52 2807 if ($showfeedback) {
b0ccd3fb 2808 notify($strdeleted .' groups');
3831de52 2809 }
2810 } else {
2811 $result = false;
2812 }
2813 }
2814 }
2815 }
2816
2817 if ($removeevents) {
b0ccd3fb 2818 if (delete_records('event', 'courseid', $course->id)) {
3831de52 2819 if ($showfeedback) {
b0ccd3fb 2820 notify($strdeleted .' event');
3831de52 2821 }
2822 } else {
2823 $result = false;
2824 }
2825 }
2826
2827 if ($removelogs) {
b0ccd3fb 2828 if (delete_records('log', 'course', $course->id)) {
3831de52 2829 if ($showfeedback) {
b0ccd3fb 2830 notify($strdeleted .' log');
3831de52 2831 }
2832 } else {
2833 $result = false;
2834 }
2835 }
2836
2837 return $result;
2838
2839}
2840
2841
f9903ed0 2842
f374fb10 2843/// GROUPS /////////////////////////////////////////////////////////
d8ba183c 2844
f374fb10 2845
2846/**
2847* Returns a boolean: is the user a member of the given group?
d8ba183c 2848*
dcd338ff 2849* @param type description
7cf1c7bd 2850 * @todo Finish documenting this function
f374fb10 2851*/
2852function ismember($groupid, $userid=0) {
2853 global $USER;
2854
8a2c9076 2855 if (!$groupid) { // No point doing further checks
2856 return false;
2857 }
2858
f374fb10 2859 if (!$userid) {
0d67c514 2860 if (empty($USER->groupmember)) {
2861 return false;
2862 }
2863 foreach ($USER->groupmember as $courseid => $mgroupid) {
2864 if ($mgroupid == $groupid) {
2865 return true;
2866 }
2867 }
2868 return false;
f374fb10 2869 }
2870
b0ccd3fb 2871 return record_exists('groups_members', 'groupid', $groupid, 'userid', $userid);
f374fb10 2872}
2873
4ed533df 2874/**
2875 * Add a user to a group, return true upon success or if user already a group member
2876 *
2877 * @param groupid The group id
2878 * @param userid The user id
2879 * @todo Finish documenting this function
2880 */
2881function add_user_to_group ($groupid, $userid) {
2882 if (ismember($groupid, $userid)) return true;
2883 $record->groupid = $groupid;
2884 $record->userid = $userid;
d2a9f7cc 2885 $record->timeadded = time();
4ed533df 2886 return (insert_record('groups_members', $record) !== false);
2887}
2888
2889
0d67c514 2890/**
c6d15803 2891 * Returns the group ID of the current user in the given course
2892 *
2893 * @uses $USER
2894 * @param int $courseid The course being examined - relates to id field in 'course' table.
7cf1c7bd 2895 * @todo Finish documenting this function
c6d15803 2896 */
0d67c514 2897function mygroupid($courseid) {
2898 global $USER;
2899
2900 if (empty($USER->groupmember[$courseid])) {
2901 return 0;
2902 } else {
2903 return $USER->groupmember[$courseid];
2904 }
2905}
2906
f374fb10 2907/**
c6d15803 2908 * For a given course, and possibly course module, determine
2909 * what the current default groupmode is:
2910 * NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
2911 *
89dcb99d 2912 * @param course $course A {@link $COURSE} object
2913 * @param array? $cm A course module object
c6d15803 2914 * @return int A group mode (NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS)
2915 */
f374fb10 2916function groupmode($course, $cm=null) {
2917
2918 if ($cm and !$course->groupmodeforce) {
2919 return $cm->groupmode;
2920 }
2921 return $course->groupmode;
2922}
2923
2924
2925/**
c6d15803 2926 * Sets the current group in the session variable
2927 *
2928 * @uses $SESSION
2929 * @param int $courseid The course being examined - relates to id field in 'course' table.
2930 * @param int $groupid The group being examined.
2931 * @return int Current group id which was set by this function
7cf1c7bd 2932 * @todo Finish documenting this function
c6d15803 2933 */
f374fb10 2934function set_current_group($courseid, $groupid) {
2935 global $SESSION;
2936
2937 return $SESSION->currentgroup[$courseid] = $groupid;
2938}
2939
2940
2941/**
c6d15803 2942 * Gets the current group for the current user as an id or an object
2943 *
2944 * @uses $CFG
2945 * @uses $SESSION
2946 * @param int $courseid The course being examined - relates to id field in 'course' table.
9f1f6daf 2947 * @param boolean $full If true, the return value is a full record object. If false, just the id of the record.
7cf1c7bd 2948 * @todo Finish documenting this function
c6d15803 2949 */
f374fb10 2950function get_current_group($courseid, $full=false) {
2951 global $SESSION, $USER;
2952
ce04df6b 2953 if (!isset($SESSION->currentgroup[$courseid])) {
f374fb10 2954 if (empty($USER->groupmember[$courseid])) {
8a2c9076 2955 return 0;
f374fb10 2956 } else {
2957 $SESSION->currentgroup[$courseid] = $USER->groupmember[$courseid];
2958 }
2959 }
2960
2961 if ($full) {
0da33e07 2962 return get_record('groups', 'id', $SESSION->currentgroup[$courseid]);
f374fb10 2963 } else {
2964 return $SESSION->currentgroup[$courseid];
2965 }
2966}
2967
0d67c514 2968/**
c6d15803 2969 * A combination function to make it easier for modules
2970 * to set up groups.
2971 *
2972 * It will use a given "groupid" parameter and try to use
2973 * that to reset the current group for the user.
2974 *
2975 * @uses VISIBLEGROUPS
89dcb99d 2976 * @param course $course A {@link $COURSE} object
c6d15803 2977 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
2978 * @param int $groupid Will try to use this optional parameter to
2979 * reset the current group for the user
89dcb99d 2980 * @return int|false Returns the current group id or false if error.
7cf1c7bd 2981 * @todo Finish documenting this function
c6d15803 2982 */
eb6147a8 2983function get_and_set_current_group($course, $groupmode, $groupid=-1) {
0d67c514 2984
2985 if (!$groupmode) { // Groups don't even apply
d8ba183c 2986 return false;
0d67c514 2987 }
2988
2989 $currentgroupid = get_current_group($course->id);
2990
eb6147a8 2991 if ($groupid < 0) { // No change was specified
2992 return $currentgroupid;
2993 }
2994
2995 if ($groupid) { // Try to change the current group to this groupid
0d67c514 2996 if ($group = get_record('groups', 'id', $groupid, 'courseid', $course->id)) { // Exists
2997 if (isteacheredit($course->id)) { // Sets current default group
2998 $currentgroupid = set_current_group($course->id, $group->id);
2999
3000 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
3001 $currentgroupid = $group->id;
3002 }
3003 }
eb6147a8 3004 } else { // When groupid = 0 it means show ALL groups
3005 if (isteacheredit($course->id)) { // Sets current default group
3006 $currentgroupid = set_current_group($course->id, 0);
3007
3008 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
3009 $currentgroupid = 0;
3010 }
0d67c514 3011 }
3012
3013 return $currentgroupid;
3014}
3015
3016
c3cbfe7f 3017/**
c6d15803 3018 * A big combination function to make it easier for modules
3019 * to set up groups.
3020 *
3021 * Terminates if the current user shouldn't be looking at this group
3022 * Otherwise returns the current group if there is one
3023 * Otherwise returns false if groups aren't relevant
3024 *
3025 * @uses SEPARATEGROUPS
3026 * @uses VISIBLEGROUPS
89dcb99d 3027 * @param course $course A {@link $COURSE} object
c6d15803 3028 * @param int $groupmode Either NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
3029 * @param string $urlroot ?
7cf1c7bd 3030 * @todo Finish documenting this function
c6d15803 3031 */
c3cbfe7f 3032function setup_and_print_groups($course, $groupmode, $urlroot) {
3033
eb6147a8 3034 if (isset($_GET['group'])) {
3035 $changegroup = $_GET['group']; /// 0 or higher
3036 } else {
3037 $changegroup = -1; /// This means no group change was specified
3038 }
3039
3040 $currentgroup = get_and_set_current_group($course, $groupmode, $changegroup);
c3cbfe7f 3041
eb6147a8 3042 if ($currentgroup === false) {
c3cbfe7f 3043 return false;
3044 }
3045
4b6d8dd5 3046 if ($groupmode == SEPARATEGROUPS and !isteacheredit($course->id) and !$currentgroup) {
3047 print_heading(get_string('notingroup'));
c3cbfe7f 3048 print_footer($course);
3049 exit;
3050 }
3051
3052 if ($groupmode == VISIBLEGROUPS or ($groupmode and isteacheredit($course->id))) {
b0ccd3fb 3053 if ($groups = get_records_menu('groups', 'courseid', $course->id, 'name ASC', 'id,name')) {
eb6147a8 3054 echo '<div align="center">';
c3cbfe7f 3055 print_group_menu($groups, $groupmode, $currentgroup, $urlroot);
eb6147a8 3056 echo '</div>';
c3cbfe7f 3057 }
3058 }
3059
3060 return $currentgroup;
3061}
0d67c514 3062
bb64b51a 3063function generate_email_processing_address($modid,$modargs) {
3064 global $CFG;
303d0af1 3065
3066 if (empty($CFG->siteidentifier)) { // Unique site identification code
3067 set_config('siteidentifier', random_string(32));
bb64b51a 3068 }
d2a9f7cc 3069
bb64b51a 3070 $header = $CFG->mailprefix . substr(base64_encode(pack('C',$modid)),0,2).$modargs;
3071 return $header . substr(md5($header.$CFG->sitesecret),0,16).'@'.$CFG->maildomain;
3072}
3073
f374fb10 3074
bb64b51a 3075function moodle_process_email($modargs,$body) {
3076 // the first char should be an unencoded letter. We'll take this as an action
3077 switch ($modargs{0}) {
3078 case 'B': { // bounce
3079 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
3080 if ($user = get_record_select("user","id=$userid","id,email")) {
3081 // check the half md5 of their email
3082 $md5check = substr(md5($user->email),0,16);
3083 if ($md5check = substr($modargs, -16)) {
3084 set_bounce_count($user);
3085 }
3086 // else maybe they've already changed it?
3087 }
3088 }
3089 break;
3090 // maybe more later?
3091 }
3092}
f374fb10 3093
f9903ed0 3094/// CORRESPONDENCE ////////////////////////////////////////////////
3095
7cf1c7bd 3096/**
3097 * Send an email to a specified user
3098 *
7cf1c7bd 3099 * @uses $CFG
3100 * @uses $_SERVER
c6d15803 3101 * @uses SITEID
89dcb99d 3102 * @param user $user A {@link $USER} object
3103 * @param user $from A {@link $USER} object
7cf1c7bd 3104 * @param string $subject plain text subject line of the email
3105 * @param string $messagetext plain text version of the message
3106 * @param string $messagehtml complete html version of the message (optional)
3107 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
3108 * @param string $attachname the name of the file (extension indicates MIME)
361855e6 3109 * @param boolean $usetrueaddress determines whether $from email address should
c6d15803 3110 * be sent out. Will be overruled by user profile setting for maildisplay
361855e6 3111 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
c6d15803 3112 * was blocked by user and "false" if there was another sort of error.
7cf1c7bd 3113 */
bb64b51a 3114function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $repyto='', $replytoname='') {
f9903ed0 3115
f9f4d999 3116 global $CFG, $FULLME;
f9903ed0 3117
0cc6fa6a 3118 global $course; // This is a bit of an ugly hack to be gotten rid of later
3119 if (!empty($course->lang)) { // Course language is defined
3120 $CFG->courselang = $course->lang;
3121 }
32e2b302 3122 if (!empty($course->theme)) { // Course language is defined
3123 $CFG->coursetheme = $course->theme;
3124 }
0cc6fa6a 3125
b0ccd3fb 3126 include_once($CFG->libdir .'/phpmailer/class.phpmailer.php');
f9903ed0 3127
cadb96f2 3128 if (empty($user)) {
3129 return false;
3130 }
3131
3132 if (!empty($user->emailstop)) {
579dcca4 3133 return 'emailstop';
f9903ed0 3134 }
d2a9f7cc 3135
bb64b51a 3136 if (over_bounce_threshold($user)) {
3137 error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
3138 return false;
3139 }
d8ba183c 3140
f9903ed0 3141 $mail = new phpmailer;
3142
b0ccd3fb 3143 $mail->Version = 'Moodle '. $CFG->version; // mailer version
3144 $mail->PluginDir = $CFG->libdir .'/phpmailer/'; // plugin directory (eg smtp plugin)
562bbe90 3145
98c4eae3 3146
b0ccd3fb 3147 if (current_language() != 'en') {
3148 $mail->CharSet = get_string('thischarset');
98c4eae3 3149 }
3150
b0ccd3fb 3151 if ($CFG->smtphosts == 'qmail') {
62740736 3152 $mail->IsQmail(); // use Qmail system
3153
3154 } else if (empty($CFG->smtphosts)) {
3155 $mail->IsMail(); // use PHP mail() = sendmail
3156
3157 } else {
1e411ffc 3158 $mail->IsSMTP(); // use SMTP directly
57ef3480 3159 if ($CFG->debug > 7) {
b0ccd3fb 3160 echo '<pre>' . "\n";
57ef3480 3161 $mail->SMTPDebug = true;
3162 }
b0ccd3fb 3163 $mail->Host = $CFG->smtphosts; // specify main and backup servers
9f58537a 3164
3165 if ($CFG->smtpuser) { // Use SMTP authentication
3166 $mail->SMTPAuth = true;
3167 $mail->Username = $CFG->smtpuser;
3168 $mail->Password = $CFG->smtppass;
3169 }
7f86ce17 3170 }
f9903ed0 3171
2b97bd71 3172 $adminuser = get_admin();
3173
bb64b51a 3174 // make up an email address for handling bounces
3175 if (!empty($CFG->handlebounces)) {
3176 $modargs = 'B'.base64_encode(pack('V',$user->id)).substr(md5($user->email),0,16);
3177 $mail->Sender = generate_email_processing_address(0,$modargs);
3178 }
3179 else {
3180 $mail->Sender = $adminuser->email;
d2a9f7cc 3181 }
2b97bd71 3182
a402bdcb 3183 if (is_string($from)) { // So we can pass whatever we want if there is need
3184 $mail->From = $CFG->noreplyaddress;
0d8a590a 3185 $mail->FromName = $from;
a402bdcb 3186 } else if ($usetrueaddress and $from->maildisplay) {
b0ccd3fb 3187 $mail->From = $from->email;
6e506bf9 3188 $mail->FromName = fullname($from);
3189 } else {
b0ccd3fb 3190 $mail->From = $CFG->noreplyaddress;
0d8a590a 3191 $mail->FromName = fullname($from);
bb64b51a 3192 if (empty($replyto)) {
3193 $mail->AddReplyTo($CFG->noreplyaddress,get_string('noreplyname'));
3194 }
6e506bf9 3195 }
d2a9f7cc 3196
bb64b51a 3197 if (!empty($replyto)) {
3198 $mail->AddReplyTo($replyto,$replytoname);
3199 }
3200
136dabd8 3201 $mail->Subject = stripslashes($subject);
f9903ed0 3202
b0ccd3fb 3203 $mail->AddAddress($user->email, fullname($user) );
f9903ed0 3204
58d24720 3205 $mail->WordWrap = 79; // set word wrap
f9903ed0 3206
857b798b 3207 if (!empty($from->customheaders)) { // Add custom headers
3208 if (is_array($from->customheaders)) {
3209 foreach ($from->customheaders as $customheader) {
3210 $mail->AddCustomHeader($customheader);
3211 }
3212 } else {
3213 $mail->AddCustomHeader($from->customheaders);
3214 }
b68dca19 3215 }
8f0cd6ef 3216
433c8b2e 3217 if (!empty($from->priority)) {
3218 $mail->Priority = $from->priority;
3219 }
3220
756e1823 3221 if ($messagehtml && $user->mailformat == 1) { // Don't ever send HTML to users who don't want it
136dabd8 3222 $mail->IsHTML(true);
b0ccd3fb 3223 $mail->Encoding = 'quoted-printable'; // Encoding to use
136dabd8 3224 $mail->Body = $messagehtml;
78681899 3225 $mail->AltBody = "\n$messagetext\n";
136dabd8 3226 } else {
3227 $mail->IsHTML(false);
78681899 3228 $mail->Body = "\n$messagetext\n";
f9903ed0 3229 }
3230
136dabd8 3231 if ($attachment && $attachname) {
3232 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
b0ccd3fb 3233 $mail->AddAddress($adminuser->email, fullname($adminuser) );
3234 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
136dabd8 3235 } else {
f1e0649c 3236 require_once($CFG->libdir.'/filelib.php');
b0ccd3fb 3237 $mimetype = mimeinfo('type', $attachname);
3238 $mail->AddAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
136dabd8 3239 }
f9903ed0 3240 }
3241
136dabd8 3242 if ($mail->Send()) {
bb64b51a 3243 set_send_count($user);
136dabd8 3244 return true;
3245 } else {
b0ccd3fb 3246 mtrace('ERROR: '. $mail->ErrorInfo);
f9f4d999 3247 add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo);
f9903ed0 3248 return false;
3249 }
f9903ed0 3250}
3251
7cf1c7bd 3252/**
3253 * Resets specified user's password and send the new password to the user via email.