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