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