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