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