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