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