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