Updated the HEAD build version to 20080403
[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
94c82430 1234 $strtimezone = NULL;
1235 if (!is_numeric($timezone)) {
1236 $strtimezone = $timezone;
1237 }
1238
494b9296 1239 $timezone = get_user_timezone_offset($timezone);
a36166d3 1240
e34d817e 1241 if (abs($timezone) > 13) { // Server time
ed1f69b0 1242 return getdate($time);
d2a9f7cc 1243 }
1244
e34d817e 1245 // There is no gmgetdate so we use gmdate instead
94c82430 1246 $time += dst_offset_on($time, $strtimezone);
e34d817e 1247 $time += intval((float)$timezone * HOURSECS);
3bba1e6e 1248
1249 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
02f0527d 1250
9f1f6daf 1251 list(
1252 $getdate['seconds'],
1253 $getdate['minutes'],
1254 $getdate['hours'],
1255 $getdate['mday'],
1256 $getdate['mon'],
1257 $getdate['year'],
1258 $getdate['wday'],
1259 $getdate['yday'],
1260 $getdate['weekday'],
1261 $getdate['month']
3bba1e6e 1262 ) = explode('_', $datestring);
9f1f6daf 1263
d2d6171f 1264 return $getdate;
d552ead0 1265}
1266
7cf1c7bd 1267/**
1268 * Given a GMT timestamp (seconds since epoch), offsets it by
1269 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1270 *
2f87145b 1271 * @uses HOURSECS
c6d15803 1272 * @param int $date Timestamp in GMT
e34d817e 1273 * @param float $timezone
c6d15803 1274 * @return int
7cf1c7bd 1275 */
d552ead0 1276function usertime($date, $timezone=99) {
a36166d3 1277
494b9296 1278 $timezone = get_user_timezone_offset($timezone);
2665e47a 1279
0431bd7c 1280 if (abs($timezone) > 13) {
d552ead0 1281 return $date;
1282 }
7a5672c9 1283 return $date - (int)($timezone * HOURSECS);
d552ead0 1284}
1285
8c3dba73 1286/**
1287 * Given a time, return the GMT timestamp of the most recent midnight
1288 * for the current user.
1289 *
e34d817e 1290 * @param int $date Timestamp in GMT
1291 * @param float $timezone ?
c6d15803 1292 * @return ?
8c3dba73 1293 */
edf7fe8c 1294function usergetmidnight($date, $timezone=99) {
edf7fe8c 1295
494b9296 1296 $timezone = get_user_timezone_offset($timezone);
edf7fe8c 1297 $userdate = usergetdate($date, $timezone);
4606d9bb 1298
02f0527d 1299 // Time of midnight of this user's day, in GMT
1300 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
edf7fe8c 1301
1302}
1303
7cf1c7bd 1304/**
1305 * Returns a string that prints the user's timezone
1306 *
1307 * @param float $timezone The user's timezone
1308 * @return string
1309 */
d552ead0 1310function usertimezone($timezone=99) {
d552ead0 1311
0c244315 1312 $tz = get_user_timezone($timezone);
f30fe8d0 1313
0c244315 1314 if (!is_float($tz)) {
1315 return $tz;
d552ead0 1316 }
0c244315 1317
1318 if(abs($tz) > 13) { // Server time
1319 return get_string('serverlocaltime');
1320 }
1321
1322 if($tz == intval($tz)) {
1323 // Don't show .0 for whole hours
1324 $tz = intval($tz);
1325 }
1326
1327 if($tz == 0) {
61b420ac 1328 return 'UTC';
d552ead0 1329 }
0c244315 1330 else if($tz > 0) {
61b420ac 1331 return 'UTC+'.$tz;
0c244315 1332 }
1333 else {
61b420ac 1334 return 'UTC'.$tz;
d552ead0 1335 }
e1ecf0a0 1336
f9903ed0 1337}
1338
7cf1c7bd 1339/**
1340 * Returns a float which represents the user's timezone difference from GMT in hours
1341 * Checks various settings and picks the most dominant of those which have a value
1342 *
7cf1c7bd 1343 * @uses $CFG
1344 * @uses $USER
b2b68362 1345 * @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 1346 * @return int
7cf1c7bd 1347 */
494b9296 1348function get_user_timezone_offset($tz = 99) {
f30fe8d0 1349
43b59916 1350 global $USER, $CFG;
1351
e8904995 1352 $tz = get_user_timezone($tz);
c9e55a25 1353
7b9e355e 1354 if (is_float($tz)) {
1355 return $tz;
1356 } else {
e8904995 1357 $tzrecord = get_timezone_record($tz);
7b9e355e 1358 if (empty($tzrecord)) {
e8904995 1359 return 99.0;
1360 }
4f2dbde9 1361 return (float)$tzrecord->gmtoff / HOURMINS;
e8904995 1362 }
1363}
1364
61460dd6 1365/**
1366 * Returns an int which represents the systems's timezone difference from GMT in seconds
1367 * @param mixed $tz timezone
1368 * @return int if found, false is timezone 99 or error
1369 */
1370function get_timezone_offset($tz) {
1371 global $CFG;
1372
1373 if ($tz == 99) {
1374 return false;
1375 }
1376
1377 if (is_numeric($tz)) {
1378 return intval($tz * 60*60);
1379 }
1380
1381 if (!$tzrecord = get_timezone_record($tz)) {
1382 return false;
1383 }
1384 return intval($tzrecord->gmtoff * 60);
1385}
1386
bbd3f2c4 1387/**
b2b68362 1388 * Returns a float or a string which denotes the user's timezone
1389 * 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)
1390 * means that for this timezone there are also DST rules to be taken into account
1391 * Checks various settings and picks the most dominant of those which have a value
bbd3f2c4 1392 *
1393 * @uses $USER
1394 * @uses $CFG
b2b68362 1395 * @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
1396 * @return mixed
bbd3f2c4 1397 */
e8904995 1398function get_user_timezone($tz = 99) {
1399 global $USER, $CFG;
43b59916 1400
f30fe8d0 1401 $timezones = array(
e8904995 1402 $tz,
1403 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
43b59916 1404 isset($USER->timezone) ? $USER->timezone : 99,
1405 isset($CFG->timezone) ? $CFG->timezone : 99,
f30fe8d0 1406 );
43b59916 1407
e8904995 1408 $tz = 99;
43b59916 1409
e8904995 1410 while(($tz == '' || $tz == 99) && $next = each($timezones)) {
1411 $tz = $next['value'];
43b59916 1412 }
e8904995 1413
1414 return is_numeric($tz) ? (float) $tz : $tz;
43b59916 1415}
1416
bbd3f2c4 1417/**
1418 * ?
1419 *
1420 * @uses $CFG
1421 * @uses $db
1422 * @param string $timezonename ?
1423 * @return object
1424 */
43b59916 1425function get_timezone_record($timezonename) {
1426 global $CFG, $db;
1427 static $cache = NULL;
1428
8edffd15 1429 if ($cache === NULL) {
43b59916 1430 $cache = array();
1431 }
1432
8edffd15 1433 if (isset($cache[$timezonename])) {
43b59916 1434 return $cache[$timezonename];
f30fe8d0 1435 }
1436
952d8dc8 1437 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix.'timezone
1438 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
f30fe8d0 1439}
f9903ed0 1440
bbd3f2c4 1441/**
1442 * ?
1443 *
1444 * @uses $CFG
1445 * @uses $USER
1446 * @param ? $fromyear ?
1447 * @param ? $to_year ?
1448 * @return bool
1449 */
94c82430 1450function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2280ecf5 1451 global $CFG, $SESSION;
85cafb3e 1452
94c82430 1453 if ($strtimezone == NULL) {
1454 $usertz = get_user_timezone();
1455 } else {
1456 $usertz = $strtimezone;
1457 }
7cb29a3d 1458
989585e9 1459 if (is_float($usertz)) {
1460 // Trivial timezone, no DST
1461 return false;
1462 }
1463
2280ecf5 1464 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
989585e9 1465 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2280ecf5 1466 unset($SESSION->dst_offsets);
1467 unset($SESSION->dst_range);
830a2bbd 1468 }
1469
2280ecf5 1470 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
830a2bbd 1471 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1472 // This will be the return path most of the time, pretty light computationally
1473 return true;
85cafb3e 1474 }
1475
830a2bbd 1476 // Reaching here means we either need to extend our table or create it from scratch
989585e9 1477
1478 // Remember which TZ we calculated these changes for
2280ecf5 1479 $SESSION->dst_offsettz = $usertz;
989585e9 1480
2280ecf5 1481 if(empty($SESSION->dst_offsets)) {
830a2bbd 1482 // If we 're creating from scratch, put the two guard elements in there
2280ecf5 1483 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
830a2bbd 1484 }
2280ecf5 1485 if(empty($SESSION->dst_range)) {
830a2bbd 1486 // If creating from scratch
1487 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1488 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1489
1490 // Fill in the array with the extra years we need to process
1491 $yearstoprocess = array();
1492 for($i = $from; $i <= $to; ++$i) {
1493 $yearstoprocess[] = $i;
1494 }
1495
1496 // Take note of which years we have processed for future calls
2280ecf5 1497 $SESSION->dst_range = array($from, $to);
830a2bbd 1498 }
1499 else {
1500 // If needing to extend the table, do the same
1501 $yearstoprocess = array();
1502
2280ecf5 1503 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1504 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
830a2bbd 1505
2280ecf5 1506 if($from < $SESSION->dst_range[0]) {
830a2bbd 1507 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1508 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
830a2bbd 1509 $yearstoprocess[] = $i;
1510 }
2280ecf5 1511 $SESSION->dst_range[0] = $from;
830a2bbd 1512 }
2280ecf5 1513 if($to > $SESSION->dst_range[1]) {
830a2bbd 1514 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1515 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
830a2bbd 1516 $yearstoprocess[] = $i;
1517 }
2280ecf5 1518 $SESSION->dst_range[1] = $to;
830a2bbd 1519 }
1520 }
1521
1522 if(empty($yearstoprocess)) {
1523 // This means that there was a call requesting a SMALLER range than we have already calculated
1524 return true;
1525 }
1526
1527 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1528 // Also, the array is sorted in descending timestamp order!
1529
1530 // Get DB data
6a5dc27c 1531
1532 static $presets_cache = array();
1533 if (!isset($presets_cache[$usertz])) {
1534 $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');
1535 }
1536 if(empty($presets_cache[$usertz])) {
e789650d 1537 return false;
1538 }
57f1191c 1539
830a2bbd 1540 // Remove ending guard (first element of the array)
2280ecf5 1541 reset($SESSION->dst_offsets);
1542 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
830a2bbd 1543
1544 // Add all required change timestamps
1545 foreach($yearstoprocess as $y) {
1546 // Find the record which is in effect for the year $y
6a5dc27c 1547 foreach($presets_cache[$usertz] as $year => $preset) {
830a2bbd 1548 if($year <= $y) {
1549 break;
c9e72798 1550 }
830a2bbd 1551 }
1552
1553 $changes = dst_changes_for_year($y, $preset);
1554
1555 if($changes === NULL) {
1556 continue;
1557 }
1558 if($changes['dst'] != 0) {
2280ecf5 1559 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
830a2bbd 1560 }
1561 if($changes['std'] != 0) {
2280ecf5 1562 $SESSION->dst_offsets[$changes['std']] = 0;
c9e72798 1563 }
85cafb3e 1564 }
42d36497 1565
830a2bbd 1566 // Put in a guard element at the top
2280ecf5 1567 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1568 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
830a2bbd 1569
1570 // Sort again
2280ecf5 1571 krsort($SESSION->dst_offsets);
830a2bbd 1572
e789650d 1573 return true;
1574}
42d36497 1575
e789650d 1576function dst_changes_for_year($year, $timezone) {
7cb29a3d 1577
e789650d 1578 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1579 return NULL;
42d36497 1580 }
7cb29a3d 1581
e789650d 1582 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1583 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1584
1585 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1586 list($std_hour, $std_min) = explode(':', $timezone->std_time);
d2a9f7cc 1587
6dc8dddc 1588 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1589 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
830a2bbd 1590
1591 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1592 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1593 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1594
1595 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1596 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
42d36497 1597
e789650d 1598 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
42d36497 1599}
1600
02f0527d 1601// $time must NOT be compensated at all, it has to be a pure timestamp
94c82430 1602function dst_offset_on($time, $strtimezone = NULL) {
2280ecf5 1603 global $SESSION;
02f0527d 1604
94c82430 1605 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
c9e72798 1606 return 0;
85cafb3e 1607 }
1608
2280ecf5 1609 reset($SESSION->dst_offsets);
1610 while(list($from, $offset) = each($SESSION->dst_offsets)) {
59556d48 1611 if($from <= $time) {
c9e72798 1612 break;
1613 }
1614 }
1615
830a2bbd 1616 // This is the normal return path
1617 if($offset !== NULL) {
1618 return $offset;
02f0527d 1619 }
02f0527d 1620
830a2bbd 1621 // Reaching this point means we haven't calculated far enough, do it now:
1622 // Calculate extra DST changes if needed and recurse. The recursion always
1623 // moves toward the stopping condition, so will always end.
1624
1625 if($from == 0) {
2280ecf5 1626 // We need a year smaller than $SESSION->dst_range[0]
1627 if($SESSION->dst_range[0] == 1971) {
830a2bbd 1628 return 0;
1629 }
94c82430 1630 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
1631 return dst_offset_on($time, $strtimezone);
830a2bbd 1632 }
1633 else {
2280ecf5 1634 // We need a year larger than $SESSION->dst_range[1]
1635 if($SESSION->dst_range[1] == 2035) {
830a2bbd 1636 return 0;
1637 }
94c82430 1638 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
1639 return dst_offset_on($time, $strtimezone);
830a2bbd 1640 }
85cafb3e 1641}
02f0527d 1642
28902d99 1643function find_day_in_month($startday, $weekday, $month, $year) {
8dc3f6cf 1644
1645 $daysinmonth = days_in_month($month, $year);
1646
42d36497 1647 if($weekday == -1) {
28902d99 1648 // Don't care about weekday, so return:
1649 // abs($startday) if $startday != -1
1650 // $daysinmonth otherwise
1651 return ($startday == -1) ? $daysinmonth : abs($startday);
8dc3f6cf 1652 }
1653
1654 // From now on we 're looking for a specific weekday
8dc3f6cf 1655
28902d99 1656 // Give "end of month" its actual value, since we know it
1657 if($startday == -1) {
1658 $startday = -1 * $daysinmonth;
1659 }
1660
1661 // Starting from day $startday, the sign is the direction
8dc3f6cf 1662
28902d99 1663 if($startday < 1) {
8dc3f6cf 1664
28902d99 1665 $startday = abs($startday);
8dc3f6cf 1666 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1667
1668 // This is the last such weekday of the month
1669 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
1670 if($lastinmonth > $daysinmonth) {
1671 $lastinmonth -= 7;
42d36497 1672 }
8dc3f6cf 1673
28902d99 1674 // Find the first such weekday <= $startday
1675 while($lastinmonth > $startday) {
8dc3f6cf 1676 $lastinmonth -= 7;
42d36497 1677 }
8dc3f6cf 1678
1679 return $lastinmonth;
e1ecf0a0 1680
42d36497 1681 }
1682 else {
42d36497 1683
28902d99 1684 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
42d36497 1685
8dc3f6cf 1686 $diff = $weekday - $indexweekday;
1687 if($diff < 0) {
1688 $diff += 7;
42d36497 1689 }
42d36497 1690
28902d99 1691 // This is the first such weekday of the month equal to or after $startday
1692 $firstfromindex = $startday + $diff;
42d36497 1693
8dc3f6cf 1694 return $firstfromindex;
1695
1696 }
42d36497 1697}
1698
bbd3f2c4 1699/**
1700 * Calculate the number of days in a given month
1701 *
1702 * @param int $month The month whose day count is sought
1703 * @param int $year The year of the month whose day count is sought
1704 * @return int
1705 */
42d36497 1706function days_in_month($month, $year) {
1707 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1708}
1709
bbd3f2c4 1710/**
1711 * Calculate the position in the week of a specific calendar day
1712 *
1713 * @param int $day The day of the date whose position in the week is sought
1714 * @param int $month The month of the date whose position in the week is sought
1715 * @param int $year The year of the date whose position in the week is sought
1716 * @return int
1717 */
8dc3f6cf 1718function dayofweek($day, $month, $year) {
1719 // I wonder if this is any different from
1720 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1721 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1722}
1723
9fa49e22 1724/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 1725
bbd3f2c4 1726/**
1727 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1728 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1729 * sesskey string if $USER exists, or boolean false if not.
1730 *
1731 * @uses $USER
1732 * @return string
1733 */
04280e85 1734function sesskey() {
1a33f699 1735 global $USER;
1736
1737 if(!isset($USER)) {
1738 return false;
1739 }
1740
1741 if (empty($USER->sesskey)) {
1742 $USER->sesskey = random_string(10);
1743 }
1744
1745 return $USER->sesskey;
1746}
1747
0302c52f 1748
c4d0753b 1749/**
1750 * For security purposes, this function will check that the currently
1751 * given sesskey (passed as a parameter to the script or this function)
1752 * matches that of the current user.
1753 *
1754 * @param string $sesskey optionally provided sesskey
1755 * @return bool
1756 */
1757function confirm_sesskey($sesskey=NULL) {
1758 global $USER;
0302c52f 1759
c4d0753b 1760 if (!empty($USER->ignoresesskey) || !empty($CFG->ignoresesskey)) {
1761 return true;
0302c52f 1762 }
1763
c4d0753b 1764 if (empty($sesskey)) {
1765 $sesskey = required_param('sesskey', PARAM_RAW); // Check script parameters
0302c52f 1766 }
1767
c4d0753b 1768 if (!isset($USER->sesskey)) {
1769 return false;
1770 }
0302c52f 1771
c4d0753b 1772 return ($USER->sesskey === $sesskey);
0302c52f 1773}
c4d0753b 1774
dcf6d93c 1775/**
9152fc99 1776 * Setup all global $CFG course variables, set locale and also themes
1777 * This function can be used on pages that do not require login instead of require_login()
1778 *
dcf6d93c 1779 * @param mixed $courseorid id of the course or course object
1780 */
1781function course_setup($courseorid=0) {
1306c5ea 1782 global $COURSE, $CFG, $SITE;
dcf6d93c 1783
1784/// Redefine global $COURSE if needed
1785 if (empty($courseorid)) {
1786 // no change in global $COURSE - for backwards compatibiltiy
5e623a33 1787 // if require_rogin() used after require_login($courseid);
dcf6d93c 1788 } else if (is_object($courseorid)) {
1789 $COURSE = clone($courseorid);
1790 } else {
1791 global $course; // used here only to prevent repeated fetching from DB - may be removed later
a6a251c7 1792 if ($courseorid == SITEID) {
9152fc99 1793 $COURSE = clone($SITE);
1794 } else if (!empty($course->id) and $course->id == $courseorid) {
dcf6d93c 1795 $COURSE = clone($course);
1796 } else {
1797 if (!$COURSE = get_record('course', 'id', $courseorid)) {
1798 error('Invalid course ID');
1799 }
1800 }
1801 }
1802
9152fc99 1803/// set locale and themes
dcf6d93c 1804 moodle_setlocale();
dcf6d93c 1805 theme_setup();
1806
dcf6d93c 1807}
c4d0753b 1808
7cf1c7bd 1809/**
ec81373f 1810 * This function checks that the current user is logged in and has the
1811 * required privileges
1812 *
7cf1c7bd 1813 * This function checks that the current user is logged in, and optionally
ec81373f 1814 * whether they are allowed to be in a particular course and view a particular
1815 * course module.
1816 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 1817 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 1818 * case they are automatically logged in as guests.
1819 * If $courseid is given and the user is not enrolled in that course then the
1820 * user is redirected to the course enrolment page.
1821 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1822 * in the course then the user is redirected to the course home page.
7cf1c7bd 1823 *
7cf1c7bd 1824 * @uses $CFG
c6d15803 1825 * @uses $SESSION
7cf1c7bd 1826 * @uses $USER
1827 * @uses $FULLME
c6d15803 1828 * @uses SITEID
f07fa644 1829 * @uses $COURSE
33ebaf7c 1830 * @param mixed $courseorid id of the course or course object
bbd3f2c4 1831 * @param bool $autologinguest
1832 * @param object $cm course module object
7cf1c7bd 1833 */
33ebaf7c 1834function require_login($courseorid=0, $autologinguest=true, $cm=null) {
f9903ed0 1835
083c3743 1836 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
d8ba183c 1837
083c3743 1838/// setup global $COURSE, themes, language and locale
dcf6d93c 1839 course_setup($courseorid);
be933850 1840
1845f8b8 1841/// If the user is not even logged in yet then make sure they are
083c3743 1842 if (!isloggedin()) {
1843 //NOTE: $USER->site check was obsoleted by session test cookie,
1844 // $USER->confirmed test is in login/index.php
f9903ed0 1845 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1846 if (!empty($_SERVER['HTTP_REFERER'])) {
1847 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
9f44d972 1848 }
ad56b737 1849 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
8e8d0524 1850 $loginguest = '?loginguest=true';
1851 } else {
1852 $loginguest = '';
a2ebe6a5 1853 }
2c040c29 1854 if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
b0ccd3fb 1855 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
8a33e371 1856 } else {
2c3432e6 1857 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
083c3743 1858 redirect($wwwroot .'/login/index.php');
8a33e371 1859 }
20fde7b1 1860 exit;
f9903ed0 1861 }
808a3baa 1862
f6f66b03 1863/// loginas as redirection if needed
1864 if ($COURSE->id != SITEID and !empty($USER->realuser)) {
1865 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
1866 if ($USER->loginascontext->instanceid != $COURSE->id) {
3887fe4a 1867 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
5e623a33 1868 }
f6f66b03 1869 }
1870 }
1871
1872
5602f7cf 1873/// check whether the user should be changing password (but only if it is REALLY them)
346c3e2f 1874 if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser)) {
21e2dcd9 1875 $userauth = get_auth_plugin($USER->auth);
03d820c7 1876 if ($userauth->can_change_password()) {
20fde7b1 1877 $SESSION->wantsurl = $FULLME;
80274abf 1878 if ($changeurl = $userauth->change_password_url()) {
9696bd89 1879 //use plugin custom url
80274abf 1880 redirect($changeurl);
1437f0a5 1881 } else {
9696bd89 1882 //use moodle internal method
1883 if (empty($CFG->loginhttps)) {
1884 redirect($CFG->wwwroot .'/login/change_password.php');
1885 } else {
1886 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1887 redirect($wwwroot .'/login/change_password.php');
1888 }
1437f0a5 1889 }
d35757eb 1890 } else {
a8ee7194 1891 print_error('nopasswordchangeforced', 'auth');
d35757eb 1892 }
1893 }
083c3743 1894
1845f8b8 1895/// Check that the user account is properly set up
808a3baa 1896 if (user_not_fully_set_up($USER)) {
20fde7b1 1897 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1898 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 1899 }
d8ba183c 1900
1845f8b8 1901/// Make sure current IP matches the one for this session (if required)
361855e6 1902 if (!empty($CFG->tracksessionip)) {
366dfa60 1903 if ($USER->sessionIP != md5(getremoteaddr())) {
a8ee7194 1904 print_error('sessionipnomatch', 'error');
366dfa60 1905 }
1906 }
6d8f47d6 1907
1845f8b8 1908/// Make sure the USER has a sesskey set up. Used for checking script parameters.
04280e85 1909 sesskey();
366dfa60 1910
027a1604 1911 // Check that the user has agreed to a site policy if there is one
1912 if (!empty($CFG->sitepolicy)) {
1913 if (!$USER->policyagreed) {
957b5198 1914 $SESSION->wantsurl = $FULLME;
027a1604 1915 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 1916 }
1695b680 1917 }
1918
21e2dcd9 1919 // Fetch the system context, we are going to use it a lot.
1920 $sysctx = get_context_instance(CONTEXT_SYSTEM);
1921
1845f8b8 1922/// If the site is currently under maintenance, then print a message
21e2dcd9 1923 if (!has_capability('moodle/site:config', $sysctx)) {
eeefd0b0 1924 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
1695b680 1925 print_maintenance_message();
20fde7b1 1926 exit;
1695b680 1927 }
027a1604 1928 }
1929
f8e3d5f0 1930/// groupmembersonly access control
1931 if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
1932 if (isguestuser() or !groups_has_membership($cm)) {
a8ee7194 1933 print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
f8e3d5f0 1934 }
1935 }
1845f8b8 1936
21e2dcd9 1937 // Fetch the course context, and prefetch its child contexts
1938 if (!isset($COURSE->context)) {
1939 if ( ! $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id) ) {
1940 print_error('nocontext');
1941 }
1942 }
33ebaf7c 1943 if ($COURSE->id == SITEID) {
21e2dcd9 1944 /// Eliminate hidden site activities straight away
1945 if (!empty($cm) && !$cm->visible
1946 && !has_capability('moodle/course:viewhiddenactivities', $COURSE->context)) {
33ebaf7c 1947 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
e3512050 1948 }
33ebaf7c 1949 return;
881a77bf 1950
5e623a33 1951 } else {
1845f8b8 1952
21e2dcd9 1953 /// Check if the user can be in a particular course
1954 if (empty($USER->access['rsw'][$COURSE->context->path])) {
1cf2e21b 1955 //
a8ee7194 1956 // MDL-13900 - If the course or the parent category are hidden
1957 // and the user hasn't the 'course:viewhiddencourses' capability, prevent access
1cf2e21b 1958 //
a8ee7194 1959 if ( !($COURSE->visible && course_parent_visible($COURSE)) &&
1960 !has_capability('moodle/course:viewhiddencourses', $COURSE->context)) {
1cf2e21b 1961 print_header_simple();
1962 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
1963 }
a8ee7194 1964 }
1965
f71346e2 1966 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1967
21e2dcd9 1968 if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) {
33ebaf7c 1969 if ($COURSE->guest == 1) {
eef879ec 1970 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
21e2dcd9 1971 $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access);
f71346e2 1972 }
1973 }
1974
1845f8b8 1975 /// If the user is a guest then treat them according to the course policy about guests
1976
21e2dcd9 1977 if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) {
5f431c1b 1978 if (has_capability('moodle/site:doanything', $sysctx)) {
1979 // administrators must be able to access any course - even if somebody gives them guest access
b03f7215 1980 return;
5f431c1b 1981 }
1982
33ebaf7c 1983 switch ($COURSE->guest) { /// Check course policy about guest access
1845f8b8 1984
21e2dcd9 1985 case 1: /// Guests always allowed
1986 if (!has_capability('moodle/course:view', $COURSE->context)) { // Prohibited by capability
1845f8b8 1987 print_header_simple();
6ba65fa0 1988 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
1845f8b8 1989 }
1990 if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
5e623a33 1991 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
1845f8b8 1992 get_string('activityiscurrentlyhidden'));
1993 }
1994
1995 return; // User is allowed to see this course
1996
1997 break;
1998
5e623a33 1999 case 2: /// Guests allowed with key
33ebaf7c 2000 if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
b1f318a6 2001 return true;
2002 }
2003 // otherwise drop through to logic below (--> enrol.php)
1845f8b8 2004 break;
bbbf2d40 2005
1845f8b8 2006 default: /// Guests not allowed
0be6f678 2007 $strloggedinasguest = get_string('loggedinasguest');
2008 print_header_simple('', '',
2009 build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc'))));
21e2dcd9 2010 if (empty($USER->access['rsw'][$COURSE->context->path])) { // Normal guest
6ba65fa0 2011 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
21596567 2012 } else {
6ba65fa0 2013 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
33ebaf7c 2014 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
2015 print_footer($COURSE);
21596567 2016 exit;
2017 }
1845f8b8 2018 break;
2019 }
2020
2021 /// For non-guests, check if they have course view access
2022
21e2dcd9 2023 } else if (has_capability('moodle/course:view', $COURSE->context)) {
1845f8b8 2024 if (!empty($USER->realuser)) { // Make sure the REAL person can also access this course
21e2dcd9 2025 if (!has_capability('moodle/course:view', $COURSE->context, $USER->realuser)) {
1845f8b8 2026 print_header_simple();
b0ccd3fb 2027 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
cb909d74 2028 }
3ce2f1e0 2029 }
1845f8b8 2030
2031 /// Make sure they can read this activity too, if specified
2032
21e2dcd9 2033 if (!empty($cm) and !$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $COURSE->context)) {
ec81373f 2034 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
2035 }
1845f8b8 2036 return; // User is allowed to see this course
2037
da5c172a 2038 }
f9903ed0 2039
9ca3b4f3 2040
1845f8b8 2041 /// Currently not enrolled in the course, so see if they want to enrol
da5c172a 2042 $SESSION->wantsurl = $FULLME;
33ebaf7c 2043 redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
da5c172a 2044 die;
2045 }
f9903ed0 2046}
2047
c4d0753b 2048
2049
2050/**
2051 * This function just makes sure a user is logged out.
2052 *
2053 * @uses $CFG
2054 * @uses $USER
2055 */
2056function require_logout() {
2057
2d4beaff 2058 global $USER, $CFG, $SESSION;
c4d0753b 2059
111e2360 2060 if (isloggedin()) {
c4d0753b 2061 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2062
533f7910 2063 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2064 foreach($authsequence as $authname) {
2065 $authplugin = get_auth_plugin($authname);
2066 $authplugin->prelogout_hook();
81693ac7 2067 }
c4d0753b 2068 }
2069
2070 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
2071 // This method is just to try to avoid silly warnings from PHP 4.3.0
2072 session_unregister("USER");
2073 session_unregister("SESSION");
2074 }
2075
f8bd7030 2076 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
2077 $file = $line = null;
2078 if (headers_sent($file, $line)) {
2079 error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__);
2080 error_log('Headers were already sent in file: '.$file.' on line '.$line);
2081 } else {
8cadac9d 2082 if (check_php_version('5.2.0')) {
748923a0 2083 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
2084 } else {
2085 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure);
2086 }
f8bd7030 2087 }
2088
c4d0753b 2089 unset($_SESSION['USER']);
2090 unset($_SESSION['SESSION']);
2091
2092 unset($SESSION);
2093 unset($USER);
2094
2095}
2096
7cf1c7bd 2097/**
2098 * This is a weaker version of {@link require_login()} which only requires login
2099 * when called from within a course rather than the site page, unless
2100 * the forcelogin option is turned on.
2101 *
2102 * @uses $CFG
33ebaf7c 2103 * @param mixed $courseorid The course object or id in question
bbd3f2c4 2104 * @param bool $autologinguest Allow autologin guests if that is wanted
4febb58f 2105 * @param object $cm Course activity module if known
7cf1c7bd 2106 */
33ebaf7c 2107function require_course_login($courseorid, $autologinguest=true, $cm=null) {
f950af3c 2108 global $CFG;
1596edff 2109 if (!empty($CFG->forcelogin)) {
33ebaf7c 2110 // login required for both SITE and courses
2111 require_login($courseorid, $autologinguest, $cm);
63c9ee99 2112
2113 } else if (!empty($cm) and !$cm->visible) {
2114 // always login for hidden activities
2115 require_login($courseorid, $autologinguest, $cm);
2116
39de90ac 2117 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2118 or (!is_object($courseorid) and $courseorid == SITEID)) {
33ebaf7c 2119 //login for SITE not required
63c9ee99 2120 return;
2121
33ebaf7c 2122 } else {
2123 // course login always required
2124 require_login($courseorid, $autologinguest, $cm);
f950af3c 2125 }
2126}
2127
61c6071f 2128/**
2129 * Require key login. Function terminates with error if key not found or incorrect.
2130 * @param string $script unique script identifier
2131 * @param int $instance optional instance id
2132 */
2133function require_user_key_login($script, $instance=null) {
e2fa911b 2134 global $nomoodlecookie, $USER, $SESSION, $CFG;
61c6071f 2135
2136 if (empty($nomoodlecookie)) {
2137 error('Incorrect use of require_key_login() - session cookies must be disabled!');
2138 }
2139
2140/// extra safety
2141 @session_write_close();
2142
2143 $keyvalue = required_param('key', PARAM_ALPHANUM);
2144
2145 if (!$key = get_record('user_private_key', 'script', $script, 'value', $keyvalue, 'instance', $instance)) {
2146 error('Incorrect key');
2147 }
2148
2149 if (!empty($key->validuntil) and $key->validuntil < time()) {
2150 error('Expired key');
2151 }
2152
e436033f 2153 if ($key->iprestriction) {
2154 $remoteaddr = getremoteaddr();
2155 if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2156 error('Client IP address mismatch');
2157 }
61c6071f 2158 }
2159
2160 if (!$user = get_record('user', 'id', $key->userid)) {
2161 error('Incorrect user record');
2162 }
2163
2164/// emulate normal session
2165 $SESSION = new object();
2166 $USER = $user;
2167
e2fa911b 2168/// note we are not using normal login
2169 if (!defined('USER_KEY_LOGIN')) {
2170 define('USER_KEY_LOGIN', true);
2171 }
2172
2173 load_all_capabilities();
2174
61c6071f 2175/// return isntance id - it might be empty
2176 return $key->instance;
2177}
2178
2179/**
2180 * Creates a new private user access key.
2181 * @param string $script unique target identifier
2182 * @param int $userid
2183 * @param instance $int optional instance id
2184 * @param string $iprestriction optional ip restricted access
2185 * @param timestamp $validuntil key valid only until given data
2186 * @return string access key value
2187 */
2188function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2189 $key = new object();
2190 $key->script = $script;
2191 $key->userid = $userid;
2192 $key->instance = $instance;
2193 $key->iprestriction = $iprestriction;
2194 $key->validuntil = $validuntil;
2195 $key->timecreated = time();
2196
2197 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
2198 while (record_exists('user_private_key', 'value', $key->value)) {
2199 // must be unique
2200 $key->value = md5($userid.'_'.time().random_string(40));
2201 }
2202
2203 if (!insert_record('user_private_key', $key)) {
2204 error('Can not insert new key');
2205 }
2206
2207 return $key->value;
2208}
2209
7cf1c7bd 2210/**
2211 * Modify the user table by setting the currently logged in user's
2212 * last login to now.
2213 *
2214 * @uses $USER
bbd3f2c4 2215 * @return bool
7cf1c7bd 2216 */
1d881d92 2217function update_user_login_times() {
2218 global $USER;
2219
53467aa6 2220 $user = new object();
1d881d92 2221 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2a2f5f11 2222 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1d881d92 2223
2224 $user->id = $USER->id;
2225
b0ccd3fb 2226 return update_record('user', $user);
1d881d92 2227}
2228
7cf1c7bd 2229/**
2230 * Determines if a user has completed setting up their account.
2231 *
89dcb99d 2232 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
bbd3f2c4 2233 * @return bool
7cf1c7bd 2234 */
808a3baa 2235function user_not_fully_set_up($user) {
bb64b51a 2236 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
2237}
2238
2239function over_bounce_threshold($user) {
d2a9f7cc 2240
bb64b51a 2241 global $CFG;
d2a9f7cc 2242
bb64b51a 2243 if (empty($CFG->handlebounces)) {
2244 return false;
2245 }
2246 // set sensible defaults
2247 if (empty($CFG->minbounces)) {
2248 $CFG->minbounces = 10;
2249 }
2250 if (empty($CFG->bounceratio)) {
2251 $CFG->bounceratio = .20;
2252 }
2253 $bouncecount = 0;
2254 $sendcount = 0;
2255 if ($bounce = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
2256 $bouncecount = $bounce->value;
2257 }
2258 if ($send = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
2259 $sendcount = $send->value;
2260 }
2261 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2262}
2263
d2a9f7cc 2264/**
bb64b51a 2265 * @param $user - object containing an id
2266 * @param $reset - will reset the count to 0
2267 */
2268function set_send_count($user,$reset=false) {
d2a9f7cc 2269 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
bb64b51a 2270 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2271 update_record('user_preferences',$pref);
2272 }
2273 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2274 // make a new one
2275 $pref->name = 'email_send_count';
2276 $pref->value = 1;
2277 $pref->userid = $user->id;
06ba0b04 2278 insert_record('user_preferences',$pref, false);
bb64b51a 2279 }
2280}
2281
d2a9f7cc 2282/**
bb64b51a 2283* @param $user - object containing an id
2284 * @param $reset - will reset the count to 0
2285 */
2286function set_bounce_count($user,$reset=false) {
d2a9f7cc 2287 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
bb64b51a 2288 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2289 update_record('user_preferences',$pref);
2290 }
2291 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2292 // make a new one
2293 $pref->name = 'email_bounce_count';
2294 $pref->value = 1;
2295 $pref->userid = $user->id;
06ba0b04 2296 insert_record('user_preferences',$pref, false);
bb64b51a 2297 }
808a3baa 2298}
f9903ed0 2299
7cf1c7bd 2300/**
2301 * Keeps track of login attempts
2302 *
2303 * @uses $SESSION
2304 */
f9903ed0 2305function update_login_count() {
9fa49e22 2306
f9903ed0 2307 global $SESSION;
2308
2309 $max_logins = 10;
2310
2311 if (empty($SESSION->logincount)) {
2312 $SESSION->logincount = 1;
2313 } else {
2314 $SESSION->logincount++;
2315 }
2316
2317 if ($SESSION->logincount > $max_logins) {
9fa49e22 2318 unset($SESSION->wantsurl);
a8ee7194 2319 print_error('errortoomanylogins');
d578afc8 2320 }
2321}
2322
7cf1c7bd 2323/**
2324 * Resets login attempts
2325 *
2326 * @uses $SESSION
2327 */
9fa49e22 2328function reset_login_count() {
9fa49e22 2329 global $SESSION;
d578afc8 2330
9fa49e22 2331 $SESSION->logincount = 0;
d578afc8 2332}
2333
b61efafb 2334function sync_metacourses() {
2335
2336 global $CFG;
2337
1aad4310 2338 if (!$courses = get_records('course', 'metacourse', 1)) {
b61efafb 2339 return;
2340 }
d2a9f7cc 2341
b61efafb 2342 foreach ($courses as $course) {
1aad4310 2343 sync_metacourse($course);
b61efafb 2344 }
2345}
2346
b61efafb 2347/**
2348 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
5e623a33 2349 *
123545bc 2350 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
d2a9f7cc 2351 */
1aad4310 2352function sync_metacourse($course) {
755c8d58 2353 global $CFG;
b61efafb 2354
123545bc 2355 // Check the course is valid.
1aad4310 2356 if (!is_object($course)) {
2357 if (!$course = get_record('course', 'id', $course)) {
2358 return false; // invalid course id
b61efafb 2359 }
b61efafb 2360 }
5e623a33 2361
123545bc 2362 // Check that we actually have a metacourse.
1aad4310 2363 if (empty($course->metacourse)) {
123545bc 2364 return false;
755c8d58 2365 }
87671466 2366
b3170072 2367 // Get a list of roles that should not be synced.
4db9bff7 2368 if (!empty($CFG->nonmetacoursesyncroleids)) {
b3170072 2369 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
5e623a33 2370 } else {
b3170072 2371 $roleexclusions = '';
2372 }
2373
123545bc 2374 // Get the context of the metacourse.
1aad4310 2375 $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
e1ecf0a0 2376
123545bc 2377 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
b79da3ac 2378 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
1aad4310 2379 $managers = array_keys($users);
2380 } else {
2381 $managers = array();
b61efafb 2382 }
2383
123545bc 2384 // Get assignments of a user to a role that exist in a child course, but
2385 // not in the meta coure. That is, get a list of the assignments that need to be made.
2386 if (!$assignments = get_records_sql("
2387 SELECT
2388 ra.id, ra.roleid, ra.userid
2389 FROM
2390 {$CFG->prefix}role_assignments ra,
2391 {$CFG->prefix}context con,
2392 {$CFG->prefix}course_meta cm
2393 WHERE
2394 ra.contextid = con.id AND
2395 con.contextlevel = " . CONTEXT_COURSE . " AND
2396 con.instanceid = cm.child_course AND
2397 cm.parent_course = {$course->id} AND
b3170072 2398 $roleexclusions
123545bc 2399 NOT EXISTS (
2400 SELECT 1 FROM
2401 {$CFG->prefix}role_assignments ra2
2402 WHERE
2403 ra2.userid = ra.userid AND
2404 ra2.roleid = ra.roleid AND
2405 ra2.contextid = {$context->id}
2406 )
2407 ")) {
2408 $assignments = array();
2409 }
2410
2411 // Get assignments of a user to a role that exist in the meta course, but
2412 // not in any child courses. That is, get a list of the unassignments that need to be made.
2413 if (!$unassignments = get_records_sql("
2414 SELECT
2415 ra.id, ra.roleid, ra.userid
2416 FROM
2417 {$CFG->prefix}role_assignments ra
2418 WHERE
2419 ra.contextid = {$context->id} AND
b3170072 2420 $roleexclusions
123545bc 2421 NOT EXISTS (
2422 SELECT 1 FROM
2423 {$CFG->prefix}role_assignments ra2,
2424 {$CFG->prefix}context con2,
2425 {$CFG->prefix}course_meta cm
2426 WHERE
2427 ra2.userid = ra.userid AND
2428 ra2.roleid = ra.roleid AND
2429 ra2.contextid = con2.id AND
2430 con2.contextlevel = " . CONTEXT_COURSE . " AND
2431 con2.instanceid = cm.child_course AND
2432 cm.parent_course = {$course->id}
2433 )
2434 ")) {
2435 $unassignments = array();
2436 }
2437
2438 $success = true;
2439
2440 // Make the unassignments, if they are not managers.
2441 foreach ($unassignments as $unassignment) {
2442 if (!in_array($unassignment->userid, $managers)) {
2443 $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
1aad4310 2444 }
755c8d58 2445 }
e1ecf0a0 2446
123545bc 2447 // Make the assignments.
2448 foreach ($assignments as $assignment) {
2449 $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id) && $success;
b61efafb 2450 }
755c8d58 2451
123545bc 2452 return $success;
5e623a33 2453
1aad4310 2454// TODO: finish timeend and timestart
2455// maybe we could rely on cron job to do the cleaning from time to time
b61efafb 2456}
2457
d2a9f7cc 2458/**
b61efafb 2459 * Adds a record to the metacourse table and calls sync_metacoures
2460 */
2461function add_to_metacourse ($metacourseid, $courseid) {
d2a9f7cc 2462
b61efafb 2463 if (!$metacourse = get_record("course","id",$metacourseid)) {
2464 return false;
2465 }
d2a9f7cc 2466
b61efafb 2467 if (!$course = get_record("course","id",$courseid)) {
2468 return false;
2469 }
2470
5f37b628 2471 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
53467aa6 2472 $rec = new object();
b61efafb 2473 $rec->parent_course = $metacourseid;
2474 $rec->child_course = $courseid;
5f37b628 2475 if (!insert_record('course_meta',$rec)) {
b61efafb 2476 return false;
2477 }
2478 return sync_metacourse($metacourseid);
2479 }
2480 return true;
d2a9f7cc 2481
b61efafb 2482}
2483
d2a9f7cc 2484/**
b61efafb 2485 * Removes the record from the metacourse table and calls sync_metacourse
2486 */
2487function remove_from_metacourse($metacourseid, $courseid) {
2488
5f37b628 2489 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
b61efafb 2490 return sync_metacourse($metacourseid);
2491 }
2492 return false;
2493}
2494
2495
7c12949d 2496/**
2497 * Determines if a user is currently logged in
2498 *
2499 * @uses $USER
bbd3f2c4 2500 * @return bool
7c12949d 2501 */
2502function isloggedin() {
2503 global $USER;
2504
2505 return (!empty($USER->id));
2506}
2507
2a919fd7 2508/**
2509 * Determines if a user is logged in as real guest user with username 'guest'.
2510 * This function is similar to original isguest() in 1.6 and earlier.
2511 * Current isguest() is deprecated - do not use it anymore.
2512 *
2513 * @param $user mixed user object or id, $USER if not specified
2514 * @return bool true if user is the real guest user, false if not logged in or other user
2515 */
2516function isguestuser($user=NULL) {
2517 global $USER;
2518 if ($user === NULL) {
2519 $user = $USER;
2520 } else if (is_numeric($user)) {
2521 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2522 }
2523
2524 if (empty($user->id)) {
2525 return false; // not logged in, can not be guest
2526 }
2527
2528 return ($user->username == 'guest');
2529}
7c12949d 2530
7cf1c7bd 2531/**
e6260a45 2532 * Determines if the currently logged in user is in editing mode.
2533 * Note: originally this function had $userid parameter - it was not usable anyway
7cf1c7bd 2534 *
0df35335 2535 * @uses $USER, $PAGE
bbd3f2c4 2536 * @return bool
7cf1c7bd 2537 */
0df35335 2538function isediting() {
2539 global $USER, $PAGE;
e6260a45 2540
2541 if (empty($USER->editing)) {
9c9f7d77 2542 return false;
0df35335 2543 } elseif (is_object($PAGE) && method_exists($PAGE,'user_allowed_editing')) {
2544 return $PAGE->user_allowed_editing();
9c9f7d77 2545 }
0df35335 2546 return true;//false;
2c309dc2 2547}
2548
7cf1c7bd 2549/**
2550 * Determines if the logged in user is currently moving an activity
2551 *
2552 * @uses $USER
c6d15803 2553 * @param int $courseid The id of the course being tested
bbd3f2c4 2554 * @return bool
7cf1c7bd 2555 */
7977cffd 2556function ismoving($courseid) {
7977cffd 2557 global $USER;
2558
2559 if (!empty($USER->activitycopy)) {
2560 return ($USER->activitycopycourse == $courseid);
2561 }
2562 return false;
2563}
2564
7cf1c7bd 2565/**
2566 * Given an object containing firstname and lastname
2567 * values, this function returns a string with the
2568 * full name of the person.
2569 * The result may depend on system settings
2570 * or language. 'override' will force both names
361855e6 2571 * to be used even if system settings specify one.
68fbd8e1 2572 *
7cf1c7bd 2573 * @uses $CFG
2574 * @uses $SESSION
68fbd8e1 2575 * @param object $user A {@link $USER} object to get full name of
2576 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
7cf1c7bd 2577 */
e2cd5065 2578function fullname($user, $override=false) {
b5cbb64d 2579
f374fb10 2580 global $CFG, $SESSION;
2581
6527c077 2582 if (!isset($user->firstname) and !isset($user->lastname)) {
2583 return '';
2584 }
2585
4c202228 2586 if (!$override) {
2587 if (!empty($CFG->forcefirstname)) {
2588 $user->firstname = $CFG->forcefirstname;
2589 }
2590 if (!empty($CFG->forcelastname)) {
2591 $user->lastname = $CFG->forcelastname;
2592 }
2593 }
2594
f374fb10 2595 if (!empty($SESSION->fullnamedisplay)) {
2596 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
2597 }
e2cd5065 2598
b5cbb64d 2599 if ($CFG->fullnamedisplay == 'firstname lastname') {
b0ccd3fb 2600 return $user->firstname .' '. $user->lastname;
b5cbb64d 2601
2602 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 2603 return $user->lastname .' '. $user->firstname;
e2cd5065 2604
b5cbb64d 2605 } else if ($CFG->fullnamedisplay == 'firstname') {
2606 if ($override) {
2607 return get_string('fullnamedisplay', '', $user);
2608 } else {
2609 return $user->firstname;
2610 }
2611 }
e2cd5065 2612
b5cbb64d 2613 return get_string('fullnamedisplay', '', $user);
e2cd5065 2614}
2615
7cf1c7bd 2616/**
2617 * Sets a moodle cookie with an encrypted string
2618 *
2619 * @uses $CFG
2f87145b 2620 * @uses DAYSECS
2621 * @uses HOURSECS
7cf1c7bd 2622 * @param string $thing The string to encrypt and place in a cookie
2623 */
f9903ed0 2624function set_moodle_cookie($thing) {
7185e073 2625 global $CFG;
482b6e6e 2626
7cbe6afe 2627 if ($thing == 'guest') { // Ignore guest account
2628 return;
2629 }
2630
482b6e6e 2631 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
f9903ed0 2632
2633 $days = 60;
7a5672c9 2634 $seconds = DAYSECS*$days;
f9903ed0 2635
4ea8df21 2636 // no need to set secure or http cookie only here - it is not secret
1504e261 2637 setCookie($cookiename, '', time() - HOURSECS, $CFG->sessioncookiepath);
2638 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, $CFG->sessioncookiepath);
f9903ed0 2639}
2640
7cf1c7bd 2641/**
2642 * Gets a moodle cookie with an encrypted string
2643 *
2644 * @uses $CFG
2645 * @return string
2646 */
f9903ed0 2647function get_moodle_cookie() {
7185e073 2648 global $CFG;
2649
482b6e6e 2650 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
7185e073 2651
1079c8a8 2652 if (empty($_COOKIE[$cookiename])) {
b0ccd3fb 2653 return '';
1079c8a8 2654 } else {
7cbe6afe 2655 $thing = rc4decrypt($_COOKIE[$cookiename]);
2656 return ($thing == 'guest') ? '': $thing; // Ignore guest account
1079c8a8 2657 }
f9903ed0 2658}
2659
7cf1c7bd 2660/**
03d820c7 2661 * Returns whether a given authentication plugin exists.
7cf1c7bd 2662 *
2663 * @uses $CFG
03d820c7 2664 * @param string $auth Form of authentication to check for. Defaults to the
2665 * global setting in {@link $CFG}.
2666 * @return boolean Whether the plugin is available.
7cf1c7bd 2667 */
16793340 2668function exists_auth_plugin($auth) {
03d820c7 2669 global $CFG;
5e623a33 2670
03d820c7 2671 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2672 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2673 }
2674 return false;
2675}
ba7166c3 2676
03d820c7 2677/**
2678 * Checks if a given plugin is in the list of enabled authentication plugins.
5e623a33 2679 *
03d820c7 2680 * @param string $auth Authentication plugin.
2681 * @return boolean Whether the plugin is enabled.
2682 */
16793340 2683function is_enabled_auth($auth) {
16793340 2684 if (empty($auth)) {
2685 return false;
03d820c7 2686 }
16793340 2687
c7b10b5f 2688 $enabled = get_enabled_auth_plugins();
2689
2690 return in_array($auth, $enabled);
03d820c7 2691}
2692
2693/**
2694 * Returns an authentication plugin instance.
2695 *
2696 * @uses $CFG
9696bd89 2697 * @param string $auth name of authentication plugin
03d820c7 2698 * @return object An instance of the required authentication plugin.
2699 */
9696bd89 2700function get_auth_plugin($auth) {
03d820c7 2701 global $CFG;
5e623a33 2702
03d820c7 2703 // check the plugin exists first
2704 if (! exists_auth_plugin($auth)) {
2705 error("Authentication plugin '$auth' not found.");
2706 }
5e623a33 2707
03d820c7 2708 // return auth plugin instance
2709 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2710 $class = "auth_plugin_$auth";
2711 return new $class;
2712}
2713
c7b10b5f 2714/**
2715 * Returns array of active auth plugins.
2716 *
2717 * @param bool $fix fix $CFG->auth if needed
2718 * @return array
2719 */
2720function get_enabled_auth_plugins($fix=false) {
2721 global $CFG;
2722
2723 $default = array('manual', 'nologin');
2724
2725 if (empty($CFG->auth)) {
2726 $auths = array();
2727 } else {
2728 $auths = explode(',', $CFG->auth);
2729 }
2730
2731 if ($fix) {
2732 $auths = array_unique($auths);
2733 foreach($auths as $k=>$authname) {
2734 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
2735 unset($auths[$k]);
2736 }
2737 }
2738 $newconfig = implode(',', $auths);
2739 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
2740 set_config('auth', $newconfig);
2741 }
2742 }
2743
2744 return (array_merge($default, $auths));
2745}
2746
03d820c7 2747/**
2748 * Returns true if an internal authentication method is being used.
2749 * if method not specified then, global default is assumed
2750 *
2751 * @uses $CFG
2752 * @param string $auth Form of authentication required
2753 * @return bool
03d820c7 2754 */
16793340 2755function is_internal_auth($auth) {
03d820c7 2756 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2757 return $authplugin->is_internal();
a3f1f815 2758}
2759
8c3dba73 2760/**
2761 * Returns an array of user fields
2762 *
c6d15803 2763 * @uses $CFG
2764 * @uses $db
2765 * @return array User field/column names
8c3dba73 2766 */
a3f1f815 2767function get_user_fieldnames() {
a3f1f815 2768
2769 global $CFG, $db;
2770
2771 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
2772 unset($fieldarray['ID']);
2773
2774 return $fieldarray;
ba7166c3 2775}
f9903ed0 2776
08103c93
ML
2777/**
2778 * Creates the default "guest" user. Used both from
2779 * admin/index.php and login/index.php
2780 * @return mixed user object created or boolean false if the creation has failed
2781 */
2782function create_guest_record() {
2783
2784 global $CFG;
2785
c824d478 2786 $guest = new stdClass();
08103c93
ML
2787 $guest->auth = 'manual';
2788 $guest->username = 'guest';
2789 $guest->password = hash_internal_user_password('guest');
2790 $guest->firstname = addslashes(get_string('guestuser'));
2791 $guest->lastname = ' ';
2792 $guest->email = 'root@localhost';
2793 $guest->description = addslashes(get_string('guestuserinfo'));
2794 $guest->mnethostid = $CFG->mnet_localhost_id;
2795 $guest->confirmed = 1;
2796 $guest->lang = $CFG->lang;
2797 $guest->timemodified= time();
2798
2799 if (! $guest->id = insert_record("user", $guest)) {
2800 return false;
2801 }
2802
2803 return $guest;
2804}
2805
7cf1c7bd 2806/**
2807 * Creates a bare-bones user record
2808 *
2809 * @uses $CFG
7cf1c7bd 2810 * @param string $username New user's username to add to record
2811 * @param string $password New user's password to add to record
2812 * @param string $auth Form of authentication required
68fbd8e1 2813 * @return object A {@link $USER} object
7cf1c7bd 2814 * @todo Outline auth types and provide code example
2815 */
f76cfc7a 2816function create_user_record($username, $password, $auth='manual') {
366dfa60 2817 global $CFG;
71f9abf9 2818
1e22bc9c 2819 //just in case check text case
2820 $username = trim(moodle_strtolower($username));
71f9abf9 2821
03d820c7 2822 $authplugin = get_auth_plugin($auth);
2823
6bc1e5d5 2824 if ($newinfo = $authplugin->get_userinfo($username)) {
2825 $newinfo = truncate_userinfo($newinfo);
2826 foreach ($newinfo as $key => $value){
2827 $newuser->$key = addslashes($value);
e858f9da 2828 }
2829 }
f9903ed0 2830
85a1d4c9 2831 if (!empty($newuser->email)) {
2832 if (email_is_not_allowed($newuser->email)) {
2833 unset($newuser->email);
2834 }
2835 }
2836
f76cfc7a 2837 $newuser->auth = $auth;
faebaf0f 2838 $newuser->username = $username;
5e623a33 2839
e51917eb 2840 // fix for MDL-8480
2841 // user CFG lang for user if $newuser->lang is empty
2842 // or $user->lang is not an installed language
2843 $sitelangs = array_keys(get_list_of_languages());
2844 if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
2845 $newuser -> lang = $CFG->lang;
5e623a33 2846 }
faebaf0f 2847 $newuser->confirmed = 1;
d96466d2 2848 $newuser->lastip = getremoteaddr();
faebaf0f 2849 $newuser->timemodified = time();
03d820c7 2850 $newuser->mnethostid = $CFG->mnet_localhost_id;
f9903ed0 2851
b0ccd3fb 2852 if (insert_record('user', $newuser)) {
16793340 2853 $user = get_complete_user_data('username', $newuser->username);
da5bcc9f 2854 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
16793340 2855 set_user_preference('auth_forcepasswordchange', 1, $user->id);
2856 }
2857 update_internal_user_password($user, $password);
2858 return $user;
faebaf0f 2859 }
2860 return false;
2861}
2862
7cf1c7bd 2863/**
2864 * Will update a local user record from an external source
2865 *
2866 * @uses $CFG
2867 * @param string $username New user's username to add to record
89dcb99d 2868 * @return user A {@link $USER} object
7cf1c7bd 2869 */
03d820c7 2870function update_user_record($username, $authplugin) {
6bc1e5d5 2871 $username = trim(moodle_strtolower($username)); /// just in case check text case
2872
2873 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2874 $userauth = get_auth_plugin($oldinfo->auth);
2875
2876 if ($newinfo = $userauth->get_userinfo($username)) {
2877 $newinfo = truncate_userinfo($newinfo);
2878 foreach ($newinfo as $key => $value){
2879 $confkey = 'field_updatelocal_' . $key;
2880 if (!empty($userauth->config->$confkey) and $userauth->config->$confkey === 'onlogin') {
2881 $value = addslashes(stripslashes($value)); // Just in case
2882 set_field('user', $key, $value, 'username', $username)
2883 or error_log("Error updating $key for $username");
d35757eb 2884 }
2885 }
2886 }
6bc1e5d5 2887
7c12949d 2888 return get_complete_user_data('username', $username);
d35757eb 2889}
0609562b 2890
b36a8fc4 2891function truncate_userinfo($info) {
2892/// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2893/// which may have large fields
2894
2895 // define the limits
2896 $limit = array(
2897 'username' => 100,
1c66bf59 2898 'idnumber' => 64,
8bcd295c 2899 'firstname' => 100,
2900 'lastname' => 100,
b36a8fc4 2901 'email' => 100,
2902 'icq' => 15,
2903 'phone1' => 20,
2904 'phone2' => 20,
2905 'institution' => 40,
2906 'department' => 30,
2907 'address' => 70,
2908 'city' => 20,
2909 'country' => 2,
2910 'url' => 255,
2911 );
361855e6 2912
b36a8fc4 2913 // apply where needed
2914 foreach (array_keys($info) as $key) {
2915 if (!empty($limit[$key])) {
adfc03f9 2916 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
361855e6 2917 }
b36a8fc4 2918 }
361855e6 2919
b36a8fc4 2920 return $info;
90afcf32 2921}
2922
2923/**
2924 * Marks user deleted in internal user database and notifies the auth plugin.
2925 * Also unenrols user from all roles and does other cleanup.
2926 * @param object $user Userobject before delete (without system magic quotes)
2927 * @return boolean success
2928 */
2929function delete_user($user) {
2930 global $CFG;
2931 require_once($CFG->libdir.'/grouplib.php');
ece966f0 2932 require_once($CFG->libdir.'/gradelib.php');
90afcf32 2933
2934 begin_sql();
2935
2936 // delete all grades - backup is kept in grade_grades_history table
2937 if ($grades = grade_grade::fetch_all(array('userid'=>$user->id))) {
2938 foreach ($grades as $grade) {
2939 $grade->delete('userdelete');
2940 }
2941 }
2942
2943 // remove from all groups
2944 delete_records('groups_members', 'userid', $user->id);
2945
2946 // unenrol from all roles in all contexts
2947 role_unassign(0, $user->id); // this might be slow but it is really needed - modules might do some extra cleanup!
2948
2949 // now do a final accesslib cleanup - removes all role assingments in user context and context itself
2950 delete_context(CONTEXT_USER, $user->id);
2951
6d11d0ee 2952 // workaround for bulk deletes of users with the same email address
2953 $delname = addslashes("$user->email.".time());
2954 while (record_exists('user', 'username', $delname)) { // no need to use mnethostid here
2955 $delname++;
2956 }
2957
90afcf32 2958 // mark internal user record as "deleted"
2959 $updateuser = new object();
2960 $updateuser->id = $user->id;
2961 $updateuser->deleted = 1;
6d11d0ee 2962 $updateuser->username = $delname; // Remember it just in case
90afcf32 2963 $updateuser->email = ''; // Clear this field to free it up
2964 $updateuser->idnumber = ''; // Clear this field to free it up
2965 $updateuser->timemodified = time();
2966
2967 if (update_record('user', $updateuser)) {
2968 commit_sql();
2969 // notify auth plugin - do not block the delete even when plugin fails
2970 $authplugin = get_auth_plugin($user->auth);
2971 $authplugin->user_delete($user);
2972 return true;
2973
2974 } else {
2975 rollback_sql();
2976 return false;
2977 }
b36a8fc4 2978}
2979
7cf1c7bd 2980/**
2981 * Retrieve the guest user object
2982 *
2983 * @uses $CFG
89dcb99d 2984 * @return user A {@link $USER} object
7cf1c7bd 2985 */
0609562b 2986function guest_user() {
2987 global $CFG;
2988
b59c7ec0 2989 if ($newuser = get_record('user', 'username', 'guest', 'mnethostid', $CFG->mnet_localhost_id)) {
0609562b 2990 $newuser->confirmed = 1;
0609562b 2991 $newuser->lang = $CFG->lang;
d96466d2 2992 $newuser->lastip = getremoteaddr();
0609562b 2993 }
2994
2995 return $newuser;
2996}
2997
7cf1c7bd 2998/**
2999 * Given a username and password, this function looks them
3000 * up using the currently selected authentication mechanism,
3001 * and if the authentication is successful, it returns a
3002 * valid $user object from the 'user' table.
361855e6 3003 *
7cf1c7bd 3004 * Uses auth_ functions from the currently active auth module
3005 *
a238e822 3006 * After authenticate_user_login() returns success, you will need to
3007 * log that the user has logged in, and call complete_user_login() to set
3008 * the session up.
3009 *
7cf1c7bd 3010 * @uses $CFG
f5fd4347 3011 * @param string $username User's username (with system magic quotes)
3012 * @param string $password User's password (with system magic quotes)
89dcb99d 3013 * @return user|flase A {@link $USER} object or false if error
7cf1c7bd 3014 */
faebaf0f 3015function authenticate_user_login($username, $password) {
faebaf0f 3016
3017 global $CFG;
3018
c7b10b5f 3019 $authsenabled = get_enabled_auth_plugins();
39a5a35d 3020
16793340 3021 if ($user = get_complete_user_data('username', $username)) {
3022 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
3023 if ($auth=='nologin' or !is_enabled_auth($auth)) {
3024 add_to_log(0, 'login', 'error', 'index.php', $username);
3025 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3026 return false;
27286aeb 3027 }
16793340 3028 if (!empty($user->deleted)) {
3029 add_to_log(0, 'login', 'error', 'index.php', $username);
3030 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3031 return false;
d35757eb 3032 }
16793340 3033 $auths = array($auth);
3034
71f9abf9 3035 } else {
16793340 3036 $auths = $authsenabled;
3037 $user = new object();
3038 $user->id = 0; // User does not exist
27286aeb 3039 }
8f0cd6ef 3040
03d820c7 3041 foreach ($auths as $auth) {
3042 $authplugin = get_auth_plugin($auth);
466558e3 3043
16793340 3044 // on auth fail fall through to the next plugin
03d820c7 3045 if (!$authplugin->user_login($username, $password)) {
03d820c7 3046 continue;
3047 }
faebaf0f 3048
03d820c7 3049 // successful authentication
d613daf0 3050 if ($user->id) { // User already exists in database
71f9abf9 3051 if (empty($user->auth)) { // For some reason auth isn't set yet
3052 set_field('user', 'auth', $auth, 'username', $username);
16793340 3053 $user->auth = $auth;
71f9abf9 3054 }
16793340 3055
3056 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3057
03d820c7 3058 if (!$authplugin->is_internal()) { // update user record from external DB
3059 $user = update_user_record($username, get_auth_plugin($user->auth));
d35757eb 3060 }
faebaf0f 3061 } else {
16793340 3062 // if user not found, create him
71f9abf9 3063 $user = create_user_record($username, $password, $auth);
faebaf0f 3064 }
01af6da6 3065
6bc1e5d5 3066 $authplugin->sync_roles($user);
3067
f5fd4347 3068 foreach ($authsenabled as $hau) {
3069 $hauth = get_auth_plugin($hau);
3070 $hauth->user_authenticated_hook($user, $username, $password);
3071 }
3072
3073 /// Log in to a second system if necessary
3074 /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
3075 if (!empty($CFG->sso)) {
3076 include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
3077 if (function_exists('sso_user_login')) {
3078 if (!sso_user_login($username, $password)) { // Perform the signon process
3079 notify('Second sign-on failed');
3080 }
3081 }
3082 }
01af6da6 3083
a668c808 3084 if ($user->id===0) {
3085 return false;
3086 }
e582b65e 3087 return $user;
5e623a33 3088 }
3089
03d820c7 3090 // failed if all the plugins have failed
3091 add_to_log(0, 'login', 'error', 'index.php', $username);
0d626493 3092 if (debugging('', DEBUG_ALL)) {
3093 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3094 }
03d820c7 3095 return false;
f9903ed0 3096}
3097
a238e822 3098/**
3099 * Call to complete the user login process after authenticate_user_login()
3100 * has succeeded. It will setup the $USER variable and other required bits
3101 * and pieces.
3102 *
3103 * NOTE:
3104 * - It will NOT log anything -- up to the caller to decide what to log.
3105 *
3106 *
3107 *
3108 * @uses $CFG, $USER
3109 * @param string $user obj
3110 * @return user|flase A {@link $USER} object or false if error
3111 */
3112function complete_user_login($user) {
3113 global $CFG, $USER;
3114
ff396fd5 3115 $USER = $user; // this is required because we need to access preferences here!
3116
3117 reload_user_preferences();
a238e822 3118
3119 update_user_login_times();
3120 if (empty($CFG->nolastloggedin)) {
3121 set_moodle_cookie($USER->username);
3122 } else {
3123 // do not store last logged in user in cookie
3124 // auth plugins can temporarily override this from loginpage_hook()
3125 // do not save $CFG->nolastloggedin in database!
3126 set_moodle_cookie('nobody');
3127 }
3128 set_login_session_preferences();
3129
8f9e1d2c 3130 // Call enrolment plugins
3131 check_enrolment_plugins($user);
3132
a238e822 3133 /// This is what lets the user do anything on the site :-)
3134 load_all_capabilities();
3135
3136 /// Select password change url
3137 $userauth = get_auth_plugin($USER->auth);
3138
3139 /// check whether the user should be changing password
3140 if (get_user_preferences('auth_forcepasswordchange', false)){
3141 if ($userauth->can_change_password()) {
3142 if ($changeurl = $userauth->change_password_url()) {
3143 redirect($changeurl);
3144 } else {
3145 redirect($CFG->httpswwwroot.'/login/change_password.php');
3146 }
3147 } else {
a8ee7194 3148 print_error('nopasswordchangeforced', 'auth');
a238e822 3149 }
3150 }
3151 return $USER;
3152}
3153
df193157 3154/**
4908ad3e 3155 * Compare password against hash stored in internal user table.
df193157 3156 * If necessary it also updates the stored hash to new format.
5e623a33 3157 *
df193157 3158 * @param object user
3159 * @param string plain text password
3160 * @return bool is password valid?
3161 */
3162function validate_internal_user_password(&$user, $password) {
3163 global $CFG;
3164
4908ad3e 3165 if (!isset($CFG->passwordsaltmain)) {
3166 $CFG->passwordsaltmain = '';
3167 }
3168
df193157 3169 $validated = false;
3170
a044c05d 3171 // get password original encoding in case it was not updated to unicode yet
fb773106 3172 $textlib = textlib_get_instance();
810944af 3173 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
df193157 3174
4908ad3e 3175 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
3176 or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
df193157 3177 $validated = true;
4908ad3e 3178 } else {
aaeaa4b0 3179 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
4908ad3e 3180 $alt = 'passwordsaltalt'.$i;
3181 if (!empty($CFG->$alt)) {
3182 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
3183 $validated = true;
3184 break;
3185 }
3186 }
3187 }
df193157 3188 }
3189
3190 if ($validated) {
4908ad3e 3191 // force update of password hash using latest main password salt and encoding if needed
df193157 3192 update_internal_user_password($user, $password);
3193 }
3194
3195 return $validated;
3196}
3197
3198/**
3199 * Calculate hashed value from password using current hash mechanism.
5e623a33 3200 *
df193157 3201 * @param string password
3202 * @return string password hash
3203 */
3204function hash_internal_user_password($password) {
4908ad3e 3205 global $CFG;
3206
3207 if (isset($CFG->passwordsaltmain)) {
3208 return md5($password.$CFG->passwordsaltmain);
3209 } else {
3210 return md5($password);
3211 }
df193157 3212}
3213
3214/**
3215 * Update pssword hash in user object.
5e623a33 3216 *
df193157 3217 * @param object user
3218 * @param string plain text password
3219 * @param bool store changes also in db, default true
3220 * @return true if hash changed
3221 */
16793340 3222function update_internal_user_password(&$user, $password) {
df193157 3223 global $CFG;
3224
03d820c7 3225 $authplugin = get_auth_plugin($user->auth);
16793340 3226 if (!empty($authplugin->config->preventpassindb)) {
df193157 3227 $hashedpassword = 'not cached';
3228 } else {
3229 $hashedpassword = hash_internal_user_password($password);
3230 }
3231
b7b50143 3232 return set_field('user', 'password', $hashedpassword, 'id', $user->id);
df193157 3233}
3234
7c12949d 3235/**
3236 * Get a complete user record, which includes all the info
5c98bf9e 3237 * in the user record
7c12949d 3238 * Intended for setting as $USER session variable
3239 *
3240 * @uses $CFG
3241 * @uses SITEID
e1ecf0a0 3242 * @param string $field The user field to be checked for a given value.
7c12949d 3243 * @param string $value The value to match for $field.
3244 * @return user A {@link $USER} object.
3245 */
b7b50143 3246function get_complete_user_data($field, $value, $mnethostid=null) {
7c12949d 3247
3248 global $CFG;
3249
3250 if (!$field || !$value) {
3251 return false;
3252 }
3253
b7b50143 3254/// Build the WHERE clause for an SQL query
3255
3256 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
3257
e5edab1b 3258 if (is_null($mnethostid)) {
3259 // if null, we restrict to local users
3260 // ** testing for local user can be done with
5e623a33 3261 // mnethostid = $CFG->mnet_localhost_id
e5edab1b 3262 // or with
5e623a33 3263 // auth != 'mnet'
e5edab1b 3264 // but the first one is FAST with our indexes
3265 $mnethostid = $CFG->mnet_localhost_id;
3266 }
3267 $mnethostid = (int)$mnethostid;
3268 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
b7b50143 3269
7c12949d 3270/// Get all the basic user data
3271
b7b50143 3272 if (! $user = get_record_select('user', $constraints)) {
7c12949d 3273 return false;
3274 }
3275
7c12949d 3276/// Get various settings and preferences
3277
3278 if ($displays = get_records('course_display', 'userid', $user->id)) {
3279 foreach ($displays as $display) {
3280 $user->display[$display->course] = $display->display;
3281 }
3282 }