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