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