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