MDL-18228 Fixed the language issue and removed the grader report preference
[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);
013376de 801 $DB->delete_records('config', array('name'=>$name));
5e623a33 802 } else {
013376de 803 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
b0270f84 804 }
013376de 805
806 return true;
b0270f84 807}
808
4b600aa0 809/**
810 * Remove all the config variables for a given plugin.
811 *
812 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
813 * @return boolean whether the operation succeeded.
814 */
815function unset_all_config_for_plugin($plugin) {
816 global $DB;
013376de 817 $DB->delete_records('config_plugins', array('plugin' => $plugin));
818 $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%'));
819 return true;
4b600aa0 820}
821
4413941f 822/**
823 * Use this funciton to get a list of users from a config setting of type admin_setting_users_with_capability.
b3d960e6 824 * @param string $value the value of the config setting.
4413941f 825 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
826 * @return array of user objects.
827 */
828function get_users_from_config($value, $capability) {
829 global $CFG;
830 if ($value == '$@ALL@$') {
831 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
832 } else {
833 list($where, $params) = $DB->get_in_or_equal(explode(',', $CFG->courserequestnotify));
834 $params[] = $CFG->mnet_localhost_id;
835 $users = $DB->get_records_select('user', 'username ' . $where . ' AND mnethostid = ?', $params);
836 }
837 return $users;
838}
839
bafd7e78 840/**
841 * Get volatile flags
842 *
843 * @param string $type
844 * @param int $changedsince
845 * @return records array
846 *
847 */
848function get_cache_flags($type, $changedsince=NULL) {
ae040d4b 849 global $DB;
bafd7e78 850
ae040d4b 851 $params = array('type'=>$type, 'expiry'=>time());
852 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
bafd7e78 853 if ($changedsince !== NULL) {
ae040d4b 854 $params['changedsince'] = $changedsince;
855 $sqlwhere .= " AND timemodified > :changedsince";
bafd7e78 856 }
857 $cf = array();
ae040d4b 858
859 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
bafd7e78 860 foreach ($flags as $flag) {
861 $cf[$flag->name] = $flag->value;
862 }
863 }
864 return $cf;
865}
866
a489cf72 867/**
868 * Get volatile flags
869 *
870 * @param string $type
871 * @param string $name
872 * @param int $changedsince
873 * @return records array
874 *
875 */
876function get_cache_flag($type, $name, $changedsince=NULL) {
ae040d4b 877 global $DB;
a489cf72 878
ae040d4b 879 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
a489cf72 880
ae040d4b 881 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
a489cf72 882 if ($changedsince !== NULL) {
ae040d4b 883 $params['changedsince'] = $changedsince;
884 $sqlwhere .= " AND timemodified > :changedsince";
a489cf72 885 }
ae040d4b 886
887 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
a489cf72 888}
bafd7e78 889
890/**
891 * Set a volatile flag
892 *
893 * @param string $type the "type" namespace for the key
894 * @param string $name the key to set
895 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
896 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
897 * @return bool
898 */
899function set_cache_flag($type, $name, $value, $expiry=NULL) {
ae040d4b 900 global $DB;
bafd7e78 901
902 $timemodified = time();
903 if ($expiry===NULL || $expiry < $timemodified) {
904 $expiry = $timemodified + 24 * 60 * 60;
905 } else {
906 $expiry = (int)$expiry;
907 }
908
909 if ($value === NULL) {
013376de 910 unset_cache_flag($type,$name);
911 return true;
bafd7e78 912 }
913
ae040d4b 914 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type))) { // this is a potentail problem in DEBUG_DEVELOPER
128f0984 915 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
916 return true; //no need to update; helps rcache too
917 }
ae040d4b 918 $f->value = $value;
bafd7e78 919 $f->expiry = $expiry;
920 $f->timemodified = $timemodified;
013376de 921 $DB->update_record('cache_flags', $f);
bafd7e78 922 } else {
128f0984 923 $f = new object();
bafd7e78 924 $f->flagtype = $type;
925 $f->name = $name;
ae040d4b 926 $f->value = $value;
bafd7e78 927 $f->expiry = $expiry;
928 $f->timemodified = $timemodified;
013376de 929 $DB->insert_record('cache_flags', $f);
bafd7e78 930 }
013376de 931 return true;
bafd7e78 932}
933
934/**
935 * Removes a single volatile flag
936 *
937 * @param string $type the "type" namespace for the key
938 * @param string $name the key to set
939 * @uses $CFG
940 * @return bool
941 */
942function unset_cache_flag($type, $name) {
ae040d4b 943 global $DB;
013376de 944 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
945 return true;
bafd7e78 946}
947
948/**
949 * Garbage-collect volatile flags
950 *
951 */
952function gc_cache_flags() {
ae040d4b 953 global $DB;
013376de 954 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
955 return true;
bafd7e78 956}
a4080313 957
2660377f 958/// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
959
7cf1c7bd 960/**
961 * Refresh current $USER session global variable with all their current preferences.
962 * @uses $USER
963 */
2660377f 964function check_user_preferences_loaded($time = null) {
ae040d4b 965 global $USER, $DB;
2660377f 966 static $timenow = null; // Static cache, so we only check up-to-dateness once per request.
967
2e3adc25 968 if (!empty($USER->preference) && isset($USER->preference['_lastloaded'])) {
2660377f 969 // Already loaded. Are we up to date?
970
971 if (is_null($timenow) || (!is_null($time) && $time != $timenow)) {
972 $timenow = time();
973 if (!get_cache_flag('userpreferenceschanged', $USER->id, $USER->preference['_lastloaded'])) {
974 // We are up-to-date.
975 return;
976 }
977 } else {
978 // Already checked for up-to-date-ness.
979 return;
980 }
981 }
70812e39 982
2660377f 983 // OK, so we have to reload. Reset preference
346c3e2f 984 $USER->preference = array();
070e2616 985
346c3e2f 986 if (!isloggedin() or isguestuser()) {
2660377f 987 // No permanent storage for not-logged-in user and guest
70812e39 988
ae040d4b 989 } else if ($preferences = $DB->get_records('user_preferences', array('userid'=>$USER->id))) {
70812e39 990 foreach ($preferences as $preference) {
991 $USER->preference[$preference->name] = $preference->value;
992 }
c6d15803 993 }
346c3e2f 994
2660377f 995 $USER->preference['_lastloaded'] = $timenow;
996}
997
998/**
999 * Called from set/delete_user_preferences, so that the prefs can be correctly reloaded.
1000 * @param integer $userid the user whose prefs were changed.
1001 */
1002function mark_user_preferences_changed($userid) {
1003 global $CFG, $USER;
1004 if ($userid == $USER->id) {
1005 check_user_preferences_loaded(time());
1006 }
1007 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
70812e39 1008}
1009
7cf1c7bd 1010/**
1011 * Sets a preference for the current user
1012 * Optionally, can set a preference for a different user object
1013 * @uses $USER
68fbd8e1 1014 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
1015
7cf1c7bd 1016 * @param string $name The key to set as preference for the specified user
1017 * @param string $value The value to set forthe $name key in the specified user's record
346c3e2f 1018 * @param int $otheruserid A moodle user ID
bbd3f2c4 1019 * @return bool
7cf1c7bd 1020 */
346c3e2f 1021function set_user_preference($name, $value, $otheruserid=NULL) {
ae040d4b 1022 global $USER, $DB;
70812e39 1023
1024 if (empty($name)) {
1025 return false;
1026 }
1027
346c3e2f 1028 $nostore = false;
346c3e2f 1029 if (empty($otheruserid)){
1030 if (!isloggedin() or isguestuser()) {
1031 $nostore = true;
1032 }
1033 $userid = $USER->id;
1034 } else {
1035 if (isguestuser($otheruserid)) {
1036 $nostore = true;
1037 }
1038 $userid = $otheruserid;
1039 }
1040
346c3e2f 1041 if ($nostore) {
114201c8 1042 // no permanent storage for not-logged-in user and guest
346c3e2f 1043
ae040d4b 1044 } else if ($preference = $DB->get_record('user_preferences', array('userid'=>$userid, 'name'=>$name))) {
a1244706 1045 if ($preference->value === $value) {
1046 return true;
1047 }
013376de 1048 $DB->set_field('user_preferences', 'value', (string)$value, array('id'=>$preference->id));
70812e39 1049
1050 } else {
346c3e2f 1051 $preference = new object();
a3f1f815 1052 $preference->userid = $userid;
ae040d4b 1053 $preference->name = $name;
1054 $preference->value = (string)$value;
013376de 1055 $DB->insert_record('user_preferences', $preference);
2660377f 1056 }
1057
013376de 1058 mark_user_preferences_changed($userid);
1059 // update value in USER session if needed
1060 if ($userid == $USER->id) {
1061 $USER->preference[$name] = (string)$value;
1062 $USER->preference['_lastloaded'] = time();
70812e39 1063 }
346c3e2f 1064
013376de 1065 return true;
2660377f 1066}
1067
1068/**
1069 * Sets a whole array of preferences for the current user
1070 * @param array $prefarray An array of key/value pairs to be set
1071 * @param int $otheruserid A moodle user ID
1072 * @return bool
1073 */
1074function set_user_preferences($prefarray, $otheruserid=NULL) {
1075
1076 if (!is_array($prefarray) or empty($prefarray)) {
1077 return false;
346c3e2f 1078 }
1079
2660377f 1080 foreach ($prefarray as $name => $value) {
013376de 1081 set_user_preference($name, $value, $otheruserid);
2660377f 1082 }
013376de 1083 return true;
70812e39 1084}
1085
6eb3e776 1086/**
1087 * Unsets a preference completely by deleting it from the database
1088 * Optionally, can set a preference for a different user id
1089 * @uses $USER
1090 * @param string $name The key to unset as preference for the specified user
346c3e2f 1091 * @param int $otheruserid A moodle user ID
6eb3e776 1092 */
346c3e2f 1093function unset_user_preference($name, $otheruserid=NULL) {
ae040d4b 1094 global $USER, $DB;
6eb3e776 1095
346c3e2f 1096 if (empty($otheruserid)){
1097 $userid = $USER->id;
2660377f 1098 check_user_preferences_loaded();
346c3e2f 1099 } else {
1100 $userid = $otheruserid;
1101 }
1102
49d005ee 1103 //Then from DB
013376de 1104 $DB->delete_records('user_preferences', array('userid'=>$userid, 'name'=>$name));
1105
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();
70812e39 1111 }
1112
013376de 1113 return true;
70812e39 1114}
1115
7cf1c7bd 1116/**
1117 * If no arguments are supplied this function will return
361855e6 1118 * all of the current user preferences as an array.
7cf1c7bd 1119 * If a name is specified then this function
1120 * attempts to return that particular preference value. If
1121 * none is found, then the optional value $default is returned,
1122 * otherwise NULL.
1123 * @param string $name Name of the key to use in finding a preference value
1124 * @param string $default Value to be returned if the $name key is not set in the user preferences
346c3e2f 1125 * @param int $otheruserid A moodle user ID
7cf1c7bd 1126 * @uses $USER
1127 * @return string
1128 */
346c3e2f 1129function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
ae040d4b 1130 global $USER, $DB;
70812e39 1131
46933753 1132 if (empty($otheruserid) || (!empty($USER->id) && ($USER->id == $otheruserid))){
2660377f 1133 check_user_preferences_loaded();
346c3e2f 1134
2660377f 1135 if (empty($name)) {
1136 return $USER->preference; // All values
1137 } else if (array_key_exists($name, $USER->preference)) {
1138 return $USER->preference[$name]; // The single value
1139 } else {
1140 return $default; // Default value (or NULL)
a3f1f815 1141 }
346c3e2f 1142
1143 } else {
2660377f 1144 if (empty($name)) {
1145 return $DB->get_records_menu('user_preferences', array('userid'=>$otheruserid), '', 'name,value'); // All values
46933753 1146 } else if ($value = $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>$name))) {
2660377f 1147 return $value; // The single value
1148 } else {
1149 return $default; // Default value (or NULL)
1150 }
70812e39 1151 }
70812e39 1152}
1153
bd1884fe 1154/**
1155 * You need to call this function if you wish to use the set_user_preference
1156 * method in javascript_static.php, to white-list the preference you want to update
1157 * from JavaScript, and to specify the type of cleaning you expect to be done on
1158 * values.
1159 *
1160 * @param string $name the name of the user_perference we should allow to be
1161 * updated by remote calls.
1162 * @param integer $paramtype one of the PARAM_{TYPE} constants, user to clean
1163 * submitted values before set_user_preference is called.
1164 */
1165function user_preference_allow_ajax_update($name, $paramtype) {
1166 global $USER;
f2eb5002 1167
1168 // Make sure that the required JavaScript libraries are loaded.
bd1884fe 1169 require_js(array('yui_yahoo', 'yui_connection'));
f2eb5002 1170
1171 // Record in the session that this user_preference is allowed to updated remotely.
bd1884fe 1172 $USER->ajax_updatable_user_prefs[$name] = $paramtype;
1173}
70812e39 1174
9fa49e22 1175/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 1176
7cf1c7bd 1177/**
c6d15803 1178 * Given date parts in user time produce a GMT timestamp.
7cf1c7bd 1179 *
68fbd8e1 1180 * @param int $year The year part to create timestamp of
1181 * @param int $month The month part to create timestamp of
1182 * @param int $day The day part to create timestamp of
1183 * @param int $hour The hour part to create timestamp of
1184 * @param int $minute The minute part to create timestamp of
1185 * @param int $second The second part to create timestamp of
1186 * @param float $timezone ?
1187 * @param bool $applydst ?
e34d817e 1188 * @return int timestamp
7cf1c7bd 1189 * @todo Finish documenting this function
1190 */
9f1f6daf 1191function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
39917a09 1192
33998d30 1193 $strtimezone = NULL;
1194 if (!is_numeric($timezone)) {
1195 $strtimezone = $timezone;
1196 }
1197
dddb014a 1198 $timezone = get_user_timezone_offset($timezone);
1199
94e34118 1200 if (abs($timezone) > 13) {
68fbd8e1 1201 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
03c17ddf 1202 } else {
68fbd8e1 1203 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
196f2619 1204 $time = usertime($time, $timezone);
28c66824 1205 if($applydst) {
33998d30 1206 $time -= dst_offset_on($time, $strtimezone);
28c66824 1207 }
9f1f6daf 1208 }
1209
196f2619 1210 return $time;
85cafb3e 1211
39917a09 1212}
1213
7cf1c7bd 1214/**
1215 * Given an amount of time in seconds, returns string
5602f7cf 1216 * formatted nicely as weeks, days, hours etc as needed
7cf1c7bd 1217 *
2f87145b 1218 * @uses MINSECS
1219 * @uses HOURSECS
1220 * @uses DAYSECS
5602f7cf 1221 * @uses YEARSECS
c6d15803 1222 * @param int $totalsecs ?
1223 * @param array $str ?
89dcb99d 1224 * @return string
7cf1c7bd 1225 */
1226 function format_time($totalsecs, $str=NULL) {
c7e3ac2a 1227
6b174680 1228 $totalsecs = abs($totalsecs);
c7e3ac2a 1229
8dbed6be 1230 if (!$str) { // Create the str structure the slow way
b0ccd3fb 1231 $str->day = get_string('day');
1232 $str->days = get_string('days');
1233 $str->hour = get_string('hour');
1234 $str->hours = get_string('hours');
1235 $str->min = get_string('min');
1236 $str->mins = get_string('mins');
1237 $str->sec = get_string('sec');
1238 $str->secs = get_string('secs');
5602f7cf 1239 $str->year = get_string('year');
1240 $str->years = get_string('years');
8dbed6be 1241 }
1242
5602f7cf 1243
1244 $years = floor($totalsecs/YEARSECS);
1245 $remainder = $totalsecs - ($years*YEARSECS);
5602f7cf 1246 $days = floor($remainder/DAYSECS);
7a5672c9 1247 $remainder = $totalsecs - ($days*DAYSECS);
1248 $hours = floor($remainder/HOURSECS);
1249 $remainder = $remainder - ($hours*HOURSECS);
1250 $mins = floor($remainder/MINSECS);
1251 $secs = $remainder - ($mins*MINSECS);
8dbed6be 1252
1253 $ss = ($secs == 1) ? $str->sec : $str->secs;
1254 $sm = ($mins == 1) ? $str->min : $str->mins;
1255 $sh = ($hours == 1) ? $str->hour : $str->hours;
1256 $sd = ($days == 1) ? $str->day : $str->days;
5602f7cf 1257 $sy = ($years == 1) ? $str->year : $str->years;
8dbed6be 1258
5602f7cf 1259 $oyears = '';
b0ccd3fb 1260 $odays = '';
1261 $ohours = '';
1262 $omins = '';
1263 $osecs = '';
9c9f7d77 1264
5602f7cf 1265 if ($years) $oyears = $years .' '. $sy;
b0ccd3fb 1266 if ($days) $odays = $days .' '. $sd;
1267 if ($hours) $ohours = $hours .' '. $sh;
1268 if ($mins) $omins = $mins .' '. $sm;
1269 if ($secs) $osecs = $secs .' '. $ss;
6b174680 1270
77ac808e 1271 if ($years) return trim($oyears .' '. $odays);
1272 if ($days) return trim($odays .' '. $ohours);
1273 if ($hours) return trim($ohours .' '. $omins);
1274 if ($mins) return trim($omins .' '. $osecs);
b0ccd3fb 1275 if ($secs) return $osecs;
1276 return get_string('now');
6b174680 1277}
f9903ed0 1278
7cf1c7bd 1279/**
1280 * Returns a formatted string that represents a date in user time
1281 * <b>WARNING: note that the format is for strftime(), not date().</b>
1282 * Because of a bug in most Windows time libraries, we can't use
1283 * the nicer %e, so we have to use %d which has leading zeroes.
1284 * A lot of the fuss in the function is just getting rid of these leading
1285 * zeroes as efficiently as possible.
361855e6 1286 *
8c3dba73 1287 * If parameter fixday = true (default), then take off leading
7cf1c7bd 1288 * zero from %d, else mantain it.
1289 *
0a0cf09a 1290 * @param int $date the timestamp in UTC, as obtained from the database.
1291 * @param string $format strftime format. You should probably get this using
1292 * get_string('strftime...', 'langconfig');
1293 * @param float $timezone by default, uses the user's time zone.
1294 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1295 * If false then the leading zero is mantained.
1296 * @return string the formatted date/time.
7cf1c7bd 1297 */
0a0cf09a 1298function userdate($date, $format = '', $timezone = 99, $fixday = true) {
7a302afc 1299
1ac7ee24 1300 global $CFG;
1301
33998d30 1302 $strtimezone = NULL;
1303 if (!is_numeric($timezone)) {
1304 $strtimezone = $timezone;
1305 }
1306
1306c5ea 1307 if (empty($format)) {
0a0cf09a 1308 $format = get_string('strftimedaydatetime', 'langconfig');
5fa51a39 1309 }
035cdbff 1310
c3a3c5b8 1311 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1312 $fixday = false;
1313 } else if ($fixday) {
1314 $formatnoday = str_replace('%d', 'DD', $format);
61ae5d36 1315 $fixday = ($formatnoday != $format);
1316 }
dcde9f02 1317
33998d30 1318 $date += dst_offset_on($date, $strtimezone);
85351042 1319
494b9296 1320 $timezone = get_user_timezone_offset($timezone);
102dc313 1321
1322 if (abs($timezone) > 13) { /// Server time
d2a9f7cc 1323 if ($fixday) {
102dc313 1324 $datestring = strftime($formatnoday, $date);
3e95343a 1325 $daystring = str_replace(array(' 0', ' '), '', strftime(' %d', $date));
102dc313 1326 $datestring = str_replace('DD', $daystring, $datestring);
1327 } else {
1328 $datestring = strftime($format, $date);
1329 }
88ec5b7c 1330 } else {
102dc313 1331 $date += (int)($timezone * 3600);
1332 if ($fixday) {
1333 $datestring = gmstrftime($formatnoday, $date);
9db3992a 1334 $daystring = str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date));
102dc313 1335 $datestring = str_replace('DD', $daystring, $datestring);
1336 } else {
1337 $datestring = gmstrftime($format, $date);
1338 }
88ec5b7c 1339 }
102dc313 1340
fb773106 1341/// If we are running under Windows convert from windows encoding to UTF-8
1342/// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
11f7b25d 1343
fb773106 1344 if ($CFG->ostype == 'WINDOWS') {
11f7b25d 1345 if ($localewincharset = get_string('localewincharset')) {
1346 $textlib = textlib_get_instance();
810944af 1347 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
11f7b25d 1348 }
1349 }
1350
035cdbff 1351 return $datestring;
873960de 1352}
1353
7cf1c7bd 1354/**
196f2619 1355 * Given a $time timestamp in GMT (seconds since epoch),
c6d15803 1356 * returns an array that represents the date in user time
7cf1c7bd 1357 *
2f87145b 1358 * @uses HOURSECS
196f2619 1359 * @param int $time Timestamp in GMT
68fbd8e1 1360 * @param float $timezone ?
c6d15803 1361 * @return array An array that represents the date in user time
7cf1c7bd 1362 * @todo Finish documenting this function
1363 */
196f2619 1364function usergetdate($time, $timezone=99) {
6b174680 1365
94c82430 1366 $strtimezone = NULL;
1367 if (!is_numeric($timezone)) {
1368 $strtimezone = $timezone;
1369 }
1370
494b9296 1371 $timezone = get_user_timezone_offset($timezone);
a36166d3 1372
e34d817e 1373 if (abs($timezone) > 13) { // Server time
ed1f69b0 1374 return getdate($time);
d2a9f7cc 1375 }
1376
e34d817e 1377 // There is no gmgetdate so we use gmdate instead
94c82430 1378 $time += dst_offset_on($time, $strtimezone);
e34d817e 1379 $time += intval((float)$timezone * HOURSECS);
3bba1e6e 1380
1381 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
02f0527d 1382
9f1f6daf 1383 list(
1384 $getdate['seconds'],
1385 $getdate['minutes'],
1386 $getdate['hours'],
1387 $getdate['mday'],
1388 $getdate['mon'],
1389 $getdate['year'],
1390 $getdate['wday'],
1391 $getdate['yday'],
1392 $getdate['weekday'],
1393 $getdate['month']
3bba1e6e 1394 ) = explode('_', $datestring);
9f1f6daf 1395
d2d6171f 1396 return $getdate;
d552ead0 1397}
1398
7cf1c7bd 1399/**
1400 * Given a GMT timestamp (seconds since epoch), offsets it by
1401 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1402 *
2f87145b 1403 * @uses HOURSECS
c6d15803 1404 * @param int $date Timestamp in GMT
e34d817e 1405 * @param float $timezone
c6d15803 1406 * @return int
7cf1c7bd 1407 */
d552ead0 1408function usertime($date, $timezone=99) {
a36166d3 1409
494b9296 1410 $timezone = get_user_timezone_offset($timezone);
2665e47a 1411
0431bd7c 1412 if (abs($timezone) > 13) {
d552ead0 1413 return $date;
1414 }
7a5672c9 1415 return $date - (int)($timezone * HOURSECS);
d552ead0 1416}
1417
8c3dba73 1418/**
1419 * Given a time, return the GMT timestamp of the most recent midnight
1420 * for the current user.
1421 *
e34d817e 1422 * @param int $date Timestamp in GMT
1423 * @param float $timezone ?
c6d15803 1424 * @return ?
8c3dba73 1425 */
edf7fe8c 1426function usergetmidnight($date, $timezone=99) {
edf7fe8c 1427
edf7fe8c 1428 $userdate = usergetdate($date, $timezone);
4606d9bb 1429
02f0527d 1430 // Time of midnight of this user's day, in GMT
1431 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
edf7fe8c 1432
1433}
1434
7cf1c7bd 1435/**
1436 * Returns a string that prints the user's timezone
1437 *
1438 * @param float $timezone The user's timezone
1439 * @return string
1440 */
d552ead0 1441function usertimezone($timezone=99) {
d552ead0 1442
0c244315 1443 $tz = get_user_timezone($timezone);
f30fe8d0 1444
0c244315 1445 if (!is_float($tz)) {
1446 return $tz;
d552ead0 1447 }
0c244315 1448
1449 if(abs($tz) > 13) { // Server time
1450 return get_string('serverlocaltime');
1451 }
1452
1453 if($tz == intval($tz)) {
1454 // Don't show .0 for whole hours
1455 $tz = intval($tz);
1456 }
1457
1458 if($tz == 0) {
61b420ac 1459 return 'UTC';
d552ead0 1460 }
0c244315 1461 else if($tz > 0) {
61b420ac 1462 return 'UTC+'.$tz;
0c244315 1463 }
1464 else {
61b420ac 1465 return 'UTC'.$tz;
d552ead0 1466 }
e1ecf0a0 1467
f9903ed0 1468}
1469
7cf1c7bd 1470/**
1471 * Returns a float which represents the user's timezone difference from GMT in hours
1472 * Checks various settings and picks the most dominant of those which have a value
1473 *
7cf1c7bd 1474 * @uses $CFG
1475 * @uses $USER
b2b68362 1476 * @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 1477 * @return int
7cf1c7bd 1478 */
494b9296 1479function get_user_timezone_offset($tz = 99) {
f30fe8d0 1480
43b59916 1481 global $USER, $CFG;
1482
e8904995 1483 $tz = get_user_timezone($tz);
c9e55a25 1484
7b9e355e 1485 if (is_float($tz)) {
1486 return $tz;
1487 } else {
e8904995 1488 $tzrecord = get_timezone_record($tz);
7b9e355e 1489 if (empty($tzrecord)) {
e8904995 1490 return 99.0;
1491 }
4f2dbde9 1492 return (float)$tzrecord->gmtoff / HOURMINS;
e8904995 1493 }
1494}
1495
61460dd6 1496/**
1497 * Returns an int which represents the systems's timezone difference from GMT in seconds
1498 * @param mixed $tz timezone
1499 * @return int if found, false is timezone 99 or error
1500 */
1501function get_timezone_offset($tz) {
1502 global $CFG;
1503
1504 if ($tz == 99) {
1505 return false;
1506 }
1507
1508 if (is_numeric($tz)) {
1509 return intval($tz * 60*60);
1510 }
1511
1512 if (!$tzrecord = get_timezone_record($tz)) {
1513 return false;
1514 }
1515 return intval($tzrecord->gmtoff * 60);
1516}
1517
bbd3f2c4 1518/**
b2b68362 1519 * Returns a float or a string which denotes the user's timezone
1520 * 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)
1521 * means that for this timezone there are also DST rules to be taken into account
1522 * Checks various settings and picks the most dominant of those which have a value
bbd3f2c4 1523 *
1524 * @uses $USER
1525 * @uses $CFG
b2b68362 1526 * @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
1527 * @return mixed
bbd3f2c4 1528 */
e8904995 1529function get_user_timezone($tz = 99) {
1530 global $USER, $CFG;
43b59916 1531
f30fe8d0 1532 $timezones = array(
e8904995 1533 $tz,
1534 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
43b59916 1535 isset($USER->timezone) ? $USER->timezone : 99,
1536 isset($CFG->timezone) ? $CFG->timezone : 99,
f30fe8d0 1537 );
43b59916 1538
e8904995 1539 $tz = 99;
43b59916 1540
33998d30 1541 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
e8904995 1542 $tz = $next['value'];
43b59916 1543 }
e8904995 1544
1545 return is_numeric($tz) ? (float) $tz : $tz;
43b59916 1546}
1547
bbd3f2c4 1548/**
f33e1ed4 1549 * Returns cached timezone record for given $timezonename
bbd3f2c4 1550 *
f33e1ed4 1551 * @param string $timezonename
1552 * @return mixed timezonerecord object or false
bbd3f2c4 1553 */
43b59916 1554function get_timezone_record($timezonename) {
f33e1ed4 1555 global $CFG, $DB;
43b59916 1556 static $cache = NULL;
1557
8edffd15 1558 if ($cache === NULL) {
43b59916 1559 $cache = array();
1560 }
1561
8edffd15 1562 if (isset($cache[$timezonename])) {
43b59916 1563 return $cache[$timezonename];
f30fe8d0 1564 }
1565
f33e1ed4 1566 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
ae040d4b 1567 WHERE name = ? ORDER BY year DESC', array($timezonename), true);
f30fe8d0 1568}
f9903ed0 1569
bbd3f2c4 1570/**
1571 * ?
1572 *
1573 * @uses $CFG
1574 * @uses $USER
1575 * @param ? $fromyear ?
1576 * @param ? $to_year ?
1577 * @return bool
1578 */
94c82430 1579function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
ae040d4b 1580 global $CFG, $SESSION, $DB;
85cafb3e 1581
33998d30 1582 $usertz = get_user_timezone($strtimezone);
7cb29a3d 1583
989585e9 1584 if (is_float($usertz)) {
1585 // Trivial timezone, no DST
1586 return false;
1587 }
1588
2280ecf5 1589 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
989585e9 1590 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2280ecf5 1591 unset($SESSION->dst_offsets);
1592 unset($SESSION->dst_range);
830a2bbd 1593 }
1594
2280ecf5 1595 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
830a2bbd 1596 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1597 // This will be the return path most of the time, pretty light computationally
1598 return true;
85cafb3e 1599 }
1600
830a2bbd 1601 // Reaching here means we either need to extend our table or create it from scratch
989585e9 1602
1603 // Remember which TZ we calculated these changes for
2280ecf5 1604 $SESSION->dst_offsettz = $usertz;
989585e9 1605
2280ecf5 1606 if(empty($SESSION->dst_offsets)) {
830a2bbd 1607 // If we 're creating from scratch, put the two guard elements in there
2280ecf5 1608 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
830a2bbd 1609 }
2280ecf5 1610 if(empty($SESSION->dst_range)) {
830a2bbd 1611 // If creating from scratch
1612 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1613 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1614
1615 // Fill in the array with the extra years we need to process
1616 $yearstoprocess = array();
1617 for($i = $from; $i <= $to; ++$i) {
1618 $yearstoprocess[] = $i;
1619 }
1620
1621 // Take note of which years we have processed for future calls
2280ecf5 1622 $SESSION->dst_range = array($from, $to);
830a2bbd 1623 }
1624 else {
1625 // If needing to extend the table, do the same
1626 $yearstoprocess = array();
1627
2280ecf5 1628 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1629 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
830a2bbd 1630
2280ecf5 1631 if($from < $SESSION->dst_range[0]) {
830a2bbd 1632 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1633 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
830a2bbd 1634 $yearstoprocess[] = $i;
1635 }
2280ecf5 1636 $SESSION->dst_range[0] = $from;
830a2bbd 1637 }
2280ecf5 1638 if($to > $SESSION->dst_range[1]) {
830a2bbd 1639 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1640 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
830a2bbd 1641 $yearstoprocess[] = $i;
1642 }
2280ecf5 1643 $SESSION->dst_range[1] = $to;
830a2bbd 1644 }
1645 }
1646
1647 if(empty($yearstoprocess)) {
1648 // This means that there was a call requesting a SMALLER range than we have already calculated
1649 return true;
1650 }
1651
1652 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1653 // Also, the array is sorted in descending timestamp order!
1654
1655 // Get DB data
6a5dc27c 1656
1657 static $presets_cache = array();
1658 if (!isset($presets_cache[$usertz])) {
ae040d4b 1659 $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 1660 }
1661 if(empty($presets_cache[$usertz])) {
e789650d 1662 return false;
1663 }
57f1191c 1664
830a2bbd 1665 // Remove ending guard (first element of the array)
2280ecf5 1666 reset($SESSION->dst_offsets);
1667 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
830a2bbd 1668
1669 // Add all required change timestamps
1670 foreach($yearstoprocess as $y) {
1671 // Find the record which is in effect for the year $y
6a5dc27c 1672 foreach($presets_cache[$usertz] as $year => $preset) {
830a2bbd 1673 if($year <= $y) {
1674 break;
c9e72798 1675 }
830a2bbd 1676 }
1677
1678 $changes = dst_changes_for_year($y, $preset);
1679
1680 if($changes === NULL) {
1681 continue;
1682 }
1683 if($changes['dst'] != 0) {
2280ecf5 1684 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
830a2bbd 1685 }
1686 if($changes['std'] != 0) {
2280ecf5 1687 $SESSION->dst_offsets[$changes['std']] = 0;
c9e72798 1688 }
85cafb3e 1689 }
42d36497 1690
830a2bbd 1691 // Put in a guard element at the top
2280ecf5 1692 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1693 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
830a2bbd 1694
1695 // Sort again
2280ecf5 1696 krsort($SESSION->dst_offsets);
830a2bbd 1697
e789650d 1698 return true;
1699}
42d36497 1700
e789650d 1701function dst_changes_for_year($year, $timezone) {
7cb29a3d 1702
e789650d 1703 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1704 return NULL;
42d36497 1705 }
7cb29a3d 1706
e789650d 1707 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1708 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1709
1710 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1711 list($std_hour, $std_min) = explode(':', $timezone->std_time);
d2a9f7cc 1712
6dc8dddc 1713 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1714 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
830a2bbd 1715
1716 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1717 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1718 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1719
1720 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1721 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
42d36497 1722
e789650d 1723 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
42d36497 1724}
1725
02f0527d 1726// $time must NOT be compensated at all, it has to be a pure timestamp
94c82430 1727function dst_offset_on($time, $strtimezone = NULL) {
2280ecf5 1728 global $SESSION;
02f0527d 1729
94c82430 1730 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
c9e72798 1731 return 0;
85cafb3e 1732 }
1733
2280ecf5 1734 reset($SESSION->dst_offsets);
1735 while(list($from, $offset) = each($SESSION->dst_offsets)) {
59556d48 1736 if($from <= $time) {
c9e72798 1737 break;
1738 }
1739 }
1740
830a2bbd 1741 // This is the normal return path
1742 if($offset !== NULL) {
1743 return $offset;
02f0527d 1744 }
02f0527d 1745
830a2bbd 1746 // Reaching this point means we haven't calculated far enough, do it now:
1747 // Calculate extra DST changes if needed and recurse. The recursion always
1748 // moves toward the stopping condition, so will always end.
1749
1750 if($from == 0) {
2280ecf5 1751 // We need a year smaller than $SESSION->dst_range[0]
1752 if($SESSION->dst_range[0] == 1971) {
830a2bbd 1753 return 0;
1754 }
94c82430 1755 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
1756 return dst_offset_on($time, $strtimezone);
830a2bbd 1757 }
1758 else {
2280ecf5 1759 // We need a year larger than $SESSION->dst_range[1]
1760 if($SESSION->dst_range[1] == 2035) {
830a2bbd 1761 return 0;
1762 }
94c82430 1763 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
1764 return dst_offset_on($time, $strtimezone);
830a2bbd 1765 }
85cafb3e 1766}
02f0527d 1767
28902d99 1768function find_day_in_month($startday, $weekday, $month, $year) {
8dc3f6cf 1769
1770 $daysinmonth = days_in_month($month, $year);
1771
42d36497 1772 if($weekday == -1) {
28902d99 1773 // Don't care about weekday, so return:
1774 // abs($startday) if $startday != -1
1775 // $daysinmonth otherwise
1776 return ($startday == -1) ? $daysinmonth : abs($startday);
8dc3f6cf 1777 }
1778
1779 // From now on we 're looking for a specific weekday
8dc3f6cf 1780
28902d99 1781 // Give "end of month" its actual value, since we know it
1782 if($startday == -1) {
1783 $startday = -1 * $daysinmonth;
1784 }
1785
1786 // Starting from day $startday, the sign is the direction
8dc3f6cf 1787
28902d99 1788 if($startday < 1) {
8dc3f6cf 1789
28902d99 1790 $startday = abs($startday);
8dc3f6cf 1791 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1792
1793 // This is the last such weekday of the month
1794 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
1795 if($lastinmonth > $daysinmonth) {
1796 $lastinmonth -= 7;
42d36497 1797 }
8dc3f6cf 1798
28902d99 1799 // Find the first such weekday <= $startday
1800 while($lastinmonth > $startday) {
8dc3f6cf 1801 $lastinmonth -= 7;
42d36497 1802 }
8dc3f6cf 1803
1804 return $lastinmonth;
e1ecf0a0 1805
42d36497 1806 }
1807 else {
42d36497 1808
28902d99 1809 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
42d36497 1810
8dc3f6cf 1811 $diff = $weekday - $indexweekday;
1812 if($diff < 0) {
1813 $diff += 7;
42d36497 1814 }
42d36497 1815
28902d99 1816 // This is the first such weekday of the month equal to or after $startday
1817 $firstfromindex = $startday + $diff;
42d36497 1818
8dc3f6cf 1819 return $firstfromindex;
1820
1821 }
42d36497 1822}
1823
bbd3f2c4 1824/**
1825 * Calculate the number of days in a given month
1826 *
1827 * @param int $month The month whose day count is sought
1828 * @param int $year The year of the month whose day count is sought
1829 * @return int
1830 */
42d36497 1831function days_in_month($month, $year) {
1832 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1833}
1834
bbd3f2c4 1835/**
1836 * Calculate the position in the week of a specific calendar day
1837 *
1838 * @param int $day The day of the date whose position in the week is sought
1839 * @param int $month The month of the date whose position in the week is sought
1840 * @param int $year The year of the date whose position in the week is sought
1841 * @return int
1842 */
8dc3f6cf 1843function dayofweek($day, $month, $year) {
1844 // I wonder if this is any different from
1845 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1846 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1847}
1848
9fa49e22 1849/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 1850
dcf6d93c 1851/**
9152fc99 1852 * Setup all global $CFG course variables, set locale and also themes
1853 * This function can be used on pages that do not require login instead of require_login()
1854 *
dcf6d93c 1855 * @param mixed $courseorid id of the course or course object
1856 */
1857function course_setup($courseorid=0) {
ae040d4b 1858 global $COURSE, $SITE, $DB;
dcf6d93c 1859
1860/// Redefine global $COURSE if needed
1861 if (empty($courseorid)) {
1862 // no change in global $COURSE - for backwards compatibiltiy
5e623a33 1863 // if require_rogin() used after require_login($courseid);
dcf6d93c 1864 } else if (is_object($courseorid)) {
1865 $COURSE = clone($courseorid);
1866 } else {
a6a251c7 1867 if ($courseorid == SITEID) {
9152fc99 1868 $COURSE = clone($SITE);
dcf6d93c 1869 } else {
ae040d4b 1870 if (!$COURSE = $DB->get_record('course', array('id'=>$courseorid))) {
2f137aa1 1871 print_error('invalidcourseid');
dcf6d93c 1872 }
1873 }
1874 }
1875
9152fc99 1876/// set locale and themes
dcf6d93c 1877 moodle_setlocale();
dcf6d93c 1878 theme_setup();
1879
dcf6d93c 1880}
c4d0753b 1881
93f66983 1882/**
1883 * Returns full login url.
1884 *
1885 * @param bool $loginguest add login guest param
1886 * @return string login url
1887 */
1888function get_login_url($loginguest=false) {
1889 global $CFG;
1890
1891 if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
1892 $loginguest = $loginguest ? '?loginguest=true' : '';
1893 $url = "$CFG->wwwroot/login/index.php$loginguest";
1894
1895 } else {
1896 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1897 $url = "$wwwroot/login/index.php";
1898 }
1899
1900 return $url;
1901}
1902
7cf1c7bd 1903/**
ec81373f 1904 * This function checks that the current user is logged in and has the
1905 * required privileges
1906 *
7cf1c7bd 1907 * This function checks that the current user is logged in, and optionally
ec81373f 1908 * whether they are allowed to be in a particular course and view a particular
1909 * course module.
1910 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 1911 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 1912 * case they are automatically logged in as guests.
1913 * If $courseid is given and the user is not enrolled in that course then the
1914 * user is redirected to the course enrolment page.
1915 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1916 * in the course then the user is redirected to the course home page.
7cf1c7bd 1917 *
7cf1c7bd 1918 * @uses $CFG
c6d15803 1919 * @uses $SESSION
7cf1c7bd 1920 * @uses $USER
1921 * @uses $FULLME
c6d15803 1922 * @uses SITEID
f07fa644 1923 * @uses $COURSE
33ebaf7c 1924 * @param mixed $courseorid id of the course or course object
bbd3f2c4 1925 * @param bool $autologinguest
1926 * @param object $cm course module object
f4013c10 1927 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
1928 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
1929 * in order to keep redirects working properly. MDL-14495
7cf1c7bd 1930 */
f4013c10 1931function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsurltome=true) {
083c3743 1932 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
d8ba183c 1933
083c3743 1934/// setup global $COURSE, themes, language and locale
dcf6d93c 1935 course_setup($courseorid);
be933850 1936
1845f8b8 1937/// If the user is not even logged in yet then make sure they are
083c3743 1938 if (!isloggedin()) {
1939 //NOTE: $USER->site check was obsoleted by session test cookie,
1940 // $USER->confirmed test is in login/index.php
f4013c10 1941 if ($setwantsurltome) {
1942 $SESSION->wantsurl = $FULLME;
1943 }
b0ccd3fb 1944 if (!empty($_SERVER['HTTP_REFERER'])) {
1945 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
9f44d972 1946 }
ad56b737 1947 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
93f66983 1948 $loginguest = true;
8a33e371 1949 } else {
93f66983 1950 $loginguest = false;
8a33e371 1951 }
93f66983 1952 redirect(get_login_url($loginguest));
1953 exit; // never reached
f9903ed0 1954 }
808a3baa 1955
f6f66b03 1956/// loginas as redirection if needed
b7b64ff2 1957 if ($COURSE->id != SITEID and session_is_loggedinas()) {
f6f66b03 1958 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
1959 if ($USER->loginascontext->instanceid != $COURSE->id) {
3887fe4a 1960 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
5e623a33 1961 }
f6f66b03 1962 }
1963 }
1964
5602f7cf 1965/// check whether the user should be changing password (but only if it is REALLY them)
b7b64ff2 1966 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
21e2dcd9 1967 $userauth = get_auth_plugin($USER->auth);
03d820c7 1968 if ($userauth->can_change_password()) {
20fde7b1 1969 $SESSION->wantsurl = $FULLME;
80274abf 1970 if ($changeurl = $userauth->change_password_url()) {
9696bd89 1971 //use plugin custom url
80274abf 1972 redirect($changeurl);
1437f0a5 1973 } else {
9696bd89 1974 //use moodle internal method
1975 if (empty($CFG->loginhttps)) {
1976 redirect($CFG->wwwroot .'/login/change_password.php');
1977 } else {
1978 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1979 redirect($wwwroot .'/login/change_password.php');
1980 }
1437f0a5 1981 }
d35757eb 1982 } else {
a8ee7194 1983 print_error('nopasswordchangeforced', 'auth');
d35757eb 1984 }
1985 }
083c3743 1986
1845f8b8 1987/// Check that the user account is properly set up
808a3baa 1988 if (user_not_fully_set_up($USER)) {
20fde7b1 1989 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1990 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 1991 }
d8ba183c 1992
1845f8b8 1993/// Make sure the USER has a sesskey set up. Used for checking script parameters.
04280e85 1994 sesskey();
366dfa60 1995
027a1604 1996 // Check that the user has agreed to a site policy if there is one
1997 if (!empty($CFG->sitepolicy)) {
1998 if (!$USER->policyagreed) {
957b5198 1999 $SESSION->wantsurl = $FULLME;
027a1604 2000 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 2001 }
1695b680 2002 }
2003
21e2dcd9 2004 // Fetch the system context, we are going to use it a lot.
2005 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2006
1845f8b8 2007/// If the site is currently under maintenance, then print a message
21e2dcd9 2008 if (!has_capability('moodle/site:config', $sysctx)) {
eeefd0b0 2009 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
1695b680 2010 print_maintenance_message();
20fde7b1 2011 exit;
1695b680 2012 }
027a1604 2013 }
2014
f8e3d5f0 2015/// groupmembersonly access control
2016 if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2017 if (isguestuser() or !groups_has_membership($cm)) {
a8ee7194 2018 print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
f8e3d5f0 2019 }
2020 }
1845f8b8 2021
21e2dcd9 2022 // Fetch the course context, and prefetch its child contexts
2023 if (!isset($COURSE->context)) {
2024 if ( ! $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id) ) {
ae040d4b 2025 print_error('nocontext');
21e2dcd9 2026 }
2027 }
82bd6a5e 2028
2029 // Conditional activity access control
2030 if(!empty($CFG->enableavailability) and $cm) {
2031 // We cache conditional access in session
2032 if(!isset($SESSION->conditionaccessok)) {
013376de 2033 $SESSION->conditionaccessok = array();
82bd6a5e 2034 }
2035 // If you have been allowed into the module once then you are allowed
2036 // in for rest of session, no need to do conditional checks
013376de 2037 if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) {
82bd6a5e 2038 // Get condition info (does a query for the availability table)
b3d960e6 2039 require_once($CFG->libdir.'/conditionlib.php');
013376de 2040 $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
82bd6a5e 2041 // Check condition for user (this will do a query if the availability
2042 // information depends on grade or completion information)
013376de 2043 if ($ci->is_available($junk) ||
82bd6a5e 2044 has_capability('moodle/course:viewhiddenactivities', $COURSE->context)) {
013376de 2045 $SESSION->conditionaccessok[$cm->id] = true;
82bd6a5e 2046 } else {
2047 print_error('activityiscurrentlyhidden');
2048 }
2049 }
2050 }
2051
33ebaf7c 2052 if ($COURSE->id == SITEID) {
21e2dcd9 2053 /// Eliminate hidden site activities straight away
ae040d4b 2054 if (!empty($cm) && !$cm->visible
21e2dcd9 2055 && !has_capability('moodle/course:viewhiddenactivities', $COURSE->context)) {
33ebaf7c 2056 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
e3512050 2057 }
341b5ed2 2058 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
33ebaf7c 2059 return;
881a77bf 2060
5e623a33 2061 } else {
1845f8b8 2062
21e2dcd9 2063 /// Check if the user can be in a particular course
2064 if (empty($USER->access['rsw'][$COURSE->context->path])) {
1cf2e21b 2065 //
a8ee7194 2066 // MDL-13900 - If the course or the parent category are hidden
2067 // and the user hasn't the 'course:viewhiddencourses' capability, prevent access
1cf2e21b 2068 //
a8ee7194 2069 if ( !($COURSE->visible && course_parent_visible($COURSE)) &&
2070 !has_capability('moodle/course:viewhiddencourses', $COURSE->context)) {
1cf2e21b 2071 print_header_simple();
2072 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2073 }
a8ee7194 2074 }
2075
f71346e2 2076 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
2077
21e2dcd9 2078 if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) {
33ebaf7c 2079 if ($COURSE->guest == 1) {
eef879ec 2080 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
21e2dcd9 2081 $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access);
f71346e2 2082 }
2083 }
2084
1845f8b8 2085 /// If the user is a guest then treat them according to the course policy about guests
2086
21e2dcd9 2087 if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) {
5f431c1b 2088 if (has_capability('moodle/site:doanything', $sysctx)) {
2089 // administrators must be able to access any course - even if somebody gives them guest access
341b5ed2 2090 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
b03f7215 2091 return;
5f431c1b 2092 }
2093
33ebaf7c 2094 switch ($COURSE->guest) { /// Check course policy about guest access
1845f8b8 2095
ae040d4b 2096 case 1: /// Guests always allowed
21e2dcd9 2097 if (!has_capability('moodle/course:view', $COURSE->context)) { // Prohibited by capability
1845f8b8 2098 print_header_simple();
93f66983 2099 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url());
1845f8b8 2100 }
2101 if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
5e623a33 2102 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
1845f8b8 2103 get_string('activityiscurrentlyhidden'));
2104 }
2105
341b5ed2 2106 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
1845f8b8 2107 return; // User is allowed to see this course
2108
2109 break;
2110
5e623a33 2111 case 2: /// Guests allowed with key
33ebaf7c 2112 if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
341b5ed2 2113 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
b1f318a6 2114 return true;
2115 }
2116 // otherwise drop through to logic below (--> enrol.php)
1845f8b8 2117 break;
bbbf2d40 2118
1845f8b8 2119 default: /// Guests not allowed
0be6f678 2120 $strloggedinasguest = get_string('loggedinasguest');
2121 print_header_simple('', '',
2122 build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc'))));
21e2dcd9 2123 if (empty($USER->access['rsw'][$COURSE->context->path])) { // Normal guest
93f66983 2124 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url());
21596567 2125 } else {
6ba65fa0 2126 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
33ebaf7c 2127 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
2128 print_footer($COURSE);
21596567 2129 exit;
2130 }
1845f8b8 2131 break;
2132 }
2133
2134 /// For non-guests, check if they have course view access
2135
21e2dcd9 2136 } else if (has_capability('moodle/course:view', $COURSE->context)) {
b7b64ff2 2137 if (session_is_loggedinas()) { // Make sure the REAL person can also access this course
2138 $realuser = session_get_realuser();
6132768e 2139 if (!has_capability('moodle/course:view', $COURSE->context, $realuser->id)) {
1845f8b8 2140 print_header_simple();
b0ccd3fb 2141 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
cb909d74 2142 }
3ce2f1e0 2143 }
1845f8b8 2144
2145 /// Make sure they can read this activity too, if specified
2146
ae040d4b 2147 if (!empty($cm) and !$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $COURSE->context)) {
ec81373f 2148 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
2149 }
341b5ed2 2150 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
1845f8b8 2151 return; // User is allowed to see this course
2152
da5c172a 2153 }
f9903ed0 2154
9ca3b4f3 2155
1845f8b8 2156 /// Currently not enrolled in the course, so see if they want to enrol
da5c172a 2157 $SESSION->wantsurl = $FULLME;
33ebaf7c 2158 redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
da5c172a 2159 die;
2160 }
f9903ed0 2161}
2162
c4d0753b 2163
2164
2165/**
2166 * This function just makes sure a user is logged out.
2167 *
2168 * @uses $CFG
2169 * @uses $USER
2170 */
2171function require_logout() {
dd9e22f8 2172 global $USER;
c4d0753b 2173
111e2360 2174 if (isloggedin()) {
c4d0753b 2175 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2176
533f7910 2177 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2178 foreach($authsequence as $authname) {
2179 $authplugin = get_auth_plugin($authname);
2180 $authplugin->prelogout_hook();
81693ac7 2181 }
c4d0753b 2182 }
2183
56949c17 2184 session_get_instance()->terminate_current();
c4d0753b 2185}
2186
7cf1c7bd 2187/**
2188 * This is a weaker version of {@link require_login()} which only requires login
2189 * when called from within a course rather than the site page, unless
2190 * the forcelogin option is turned on.
2191 *
2192 * @uses $CFG
33ebaf7c 2193 * @param mixed $courseorid The course object or id in question
bbd3f2c4 2194 * @param bool $autologinguest Allow autologin guests if that is wanted
4febb58f 2195 * @param object $cm Course activity module if known
f4013c10 2196 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2197 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2198 * in order to keep redirects working properly. MDL-14495
7cf1c7bd 2199 */
f4013c10 2200function require_course_login($courseorid, $autologinguest=true, $cm=null, $setwantsurltome=true) {
f950af3c 2201 global $CFG;
1596edff 2202 if (!empty($CFG->forcelogin)) {
33ebaf7c 2203 // login required for both SITE and courses
f4013c10 2204 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
63c9ee99 2205
2206 } else if (!empty($cm) and !$cm->visible) {
2207 // always login for hidden activities
f4013c10 2208 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
63c9ee99 2209
39de90ac 2210 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2211 or (!is_object($courseorid) and $courseorid == SITEID)) {
33ebaf7c 2212 //login for SITE not required
341b5ed2 2213 user_accesstime_log(SITEID);
63c9ee99 2214 return;
2215
33ebaf7c 2216 } else {
2217 // course login always required
f4013c10 2218 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
f950af3c 2219 }
2220}
2221
61c6071f 2222/**
2223 * Require key login. Function terminates with error if key not found or incorrect.
2224 * @param string $script unique script identifier
2225 * @param int $instance optional instance id
2226 */
2227function require_user_key_login($script, $instance=null) {
82dd4f42 2228 global $USER, $SESSION, $CFG, $DB;
61c6071f 2229
82dd4f42 2230 if (!NO_MOODLE_COOKIES) {
2f137aa1 2231 print_error('sessioncookiesdisable');
61c6071f 2232 }
2233
2234/// extra safety
2235 @session_write_close();
2236
2237 $keyvalue = required_param('key', PARAM_ALPHANUM);
2238
ae040d4b 2239 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2f137aa1 2240 print_error('invalidkey');
61c6071f 2241 }
2242
2243 if (!empty($key->validuntil) and $key->validuntil < time()) {
2f137aa1 2244 print_error('expiredkey');
61c6071f 2245 }
2246
e436033f 2247 if ($key->iprestriction) {
2248 $remoteaddr = getremoteaddr();
2249 if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2f137aa1 2250 print_error('ipmismatch');
e436033f 2251 }
61c6071f 2252 }
2253
ae040d4b 2254 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2f137aa1 2255 print_error('invaliduserid');
61c6071f 2256 }
2257
2258/// emulate normal session
27df7ae8 2259 session_set_user($user);
61c6071f 2260
e2fa911b 2261/// note we are not using normal login
2262 if (!defined('USER_KEY_LOGIN')) {
2263 define('USER_KEY_LOGIN', true);
2264 }
2265
61c6071f 2266/// return isntance id - it might be empty
2267 return $key->instance;
2268}
2269
2270/**
2271 * Creates a new private user access key.
2272 * @param string $script unique target identifier
2273 * @param int $userid
2274 * @param instance $int optional instance id
2275 * @param string $iprestriction optional ip restricted access
2276 * @param timestamp $validuntil key valid only until given data
2277 * @return string access key value
2278 */
2279function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
ae040d4b 2280 global $DB;
2281
61c6071f 2282 $key = new object();
2283 $key->script = $script;
2284 $key->userid = $userid;
2285 $key->instance = $instance;
2286 $key->iprestriction = $iprestriction;
2287 $key->validuntil = $validuntil;
2288 $key->timecreated = time();
2289
2290 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
ae040d4b 2291 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
61c6071f 2292 // must be unique
2293 $key->value = md5($userid.'_'.time().random_string(40));
2294 }
2295
ae040d4b 2296 if (!$DB->insert_record('user_private_key', $key)) {
2f137aa1 2297 print_error('cannotinsertkey');
61c6071f 2298 }
2299
2300 return $key->value;
2301}
2302
7cf1c7bd 2303/**
2304 * Modify the user table by setting the currently logged in user's
2305 * last login to now.
2306 *
2307 * @uses $USER
bbd3f2c4 2308 * @return bool
7cf1c7bd 2309 */
1d881d92 2310function update_user_login_times() {
ae040d4b 2311 global $USER, $DB;
1d881d92 2312
53467aa6 2313 $user = new object();
1d881d92 2314 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2a2f5f11 2315 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1d881d92 2316
2317 $user->id = $USER->id;
2318
013376de 2319 $DB->update_record('user', $user);
2320 return true;
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;
013376de 2559 $DB->insert_record('course_meta', $rec);
b61efafb 2560 return sync_metacourse($metacourseid);
2561 }
2562 return true;
d2a9f7cc 2563
b61efafb 2564}
2565
d2a9f7cc 2566/**
b61efafb 2567 * Removes the record from the metacourse table and calls sync_metacourse
2568 */
2569function remove_from_metacourse($metacourseid, $courseid) {
ae040d4b 2570 global $DB;
b61efafb 2571
ae040d4b 2572 if ($DB->delete_records('course_meta', array('parent_course'=>$metacourseid, 'child_course'=>$courseid))) {
b61efafb 2573 return sync_metacourse($metacourseid);
2574 }
2575 return false;
2576}
2577
2578
7c12949d 2579/**
2580 * Determines if a user is currently logged in
2581 *
2582 * @uses $USER
bbd3f2c4 2583 * @return bool
7c12949d 2584 */
2585function isloggedin() {
2586 global $USER;
2587
2588 return (!empty($USER->id));
2589}
2590
2a919fd7 2591/**
2592 * Determines if a user is logged in as real guest user with username 'guest'.
2593 * This function is similar to original isguest() in 1.6 and earlier.
2594 * Current isguest() is deprecated - do not use it anymore.
2595 *
2596 * @param $user mixed user object or id, $USER if not specified
2597 * @return bool true if user is the real guest user, false if not logged in or other user
2598 */
2599function isguestuser($user=NULL) {
ae040d4b 2600 global $USER, $DB;
2601
2a919fd7 2602 if ($user === NULL) {
2603 $user = $USER;
2604 } else if (is_numeric($user)) {
ae040d4b 2605 $user = $DB->get_record('user', array('id'=>$user), 'id, username');
2a919fd7 2606 }
2607
2608 if (empty($user->id)) {
2609 return false; // not logged in, can not be guest
2610 }
2611
2612 return ($user->username == 'guest');
2613}
7c12949d 2614
7cf1c7bd 2615/**
e6260a45 2616 * Determines if the currently logged in user is in editing mode.
2617 * Note: originally this function had $userid parameter - it was not usable anyway
7cf1c7bd 2618 *
0df35335 2619 * @uses $USER, $PAGE
bbd3f2c4 2620 * @return bool
7cf1c7bd 2621 */
0df35335 2622function isediting() {
2623 global $USER, $PAGE;
e6260a45 2624
2625 if (empty($USER->editing)) {
9c9f7d77 2626 return false;
0df35335 2627 } elseif (is_object($PAGE) && method_exists($PAGE,'user_allowed_editing')) {
2628 return $PAGE->user_allowed_editing();
9c9f7d77 2629 }
0df35335 2630 return true;//false;
2c309dc2 2631}
2632
7cf1c7bd 2633/**
2634 * Determines if the logged in user is currently moving an activity
2635 *
2636 * @uses $USER
c6d15803 2637 * @param int $courseid The id of the course being tested
bbd3f2c4 2638 * @return bool
7cf1c7bd 2639 */
7977cffd 2640function ismoving($courseid) {
7977cffd 2641 global $USER;
2642
2643 if (!empty($USER->activitycopy)) {
2644 return ($USER->activitycopycourse == $courseid);
2645 }
2646 return false;
2647}
2648
7cf1c7bd 2649/**
2650 * Given an object containing firstname and lastname
2651 * values, this function returns a string with the
2652 * full name of the person.
2653 * The result may depend on system settings
2654 * or language. 'override' will force both names
361855e6 2655 * to be used even if system settings specify one.
68fbd8e1 2656 *
7cf1c7bd 2657 * @uses $CFG
2658 * @uses $SESSION
68fbd8e1 2659 * @param object $user A {@link $USER} object to get full name of
2660 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
7cf1c7bd 2661 */
e2cd5065 2662function fullname($user, $override=false) {
f374fb10 2663 global $CFG, $SESSION;
2664
6527c077 2665 if (!isset($user->firstname) and !isset($user->lastname)) {
2666 return '';
2667 }
2668
4c202228 2669 if (!$override) {
2670 if (!empty($CFG->forcefirstname)) {
2671 $user->firstname = $CFG->forcefirstname;
2672 }
2673 if (!empty($CFG->forcelastname)) {
2674 $user->lastname = $CFG->forcelastname;
2675 }
2676 }
2677
f374fb10 2678 if (!empty($SESSION->fullnamedisplay)) {
2679 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
2680 }
e2cd5065 2681
775f811a 2682 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
b0ccd3fb 2683 return $user->firstname .' '. $user->lastname;
b5cbb64d 2684
2685 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 2686 return $user->lastname .' '. $user->firstname;
e2cd5065 2687
b5cbb64d 2688 } else if ($CFG->fullnamedisplay == 'firstname') {
2689 if ($override) {
2690 return get_string('fullnamedisplay', '', $user);
2691 } else {
2692 return $user->firstname;
2693 }
2694 }
e2cd5065 2695
b5cbb64d 2696 return get_string('fullnamedisplay', '', $user);
e2cd5065 2697}
2698
7cf1c7bd 2699/**
03d820c7 2700 * Returns whether a given authentication plugin exists.
7cf1c7bd 2701 *
2702 * @uses $CFG
03d820c7 2703 * @param string $auth Form of authentication to check for. Defaults to the
2704 * global setting in {@link $CFG}.
2705 * @return boolean Whether the plugin is available.
7cf1c7bd 2706 */
16793340 2707function exists_auth_plugin($auth) {
03d820c7 2708 global $CFG;
5e623a33 2709
03d820c7 2710 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2711 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2712 }
2713 return false;
2714}
ba7166c3 2715
03d820c7 2716/**
2717 * Checks if a given plugin is in the list of enabled authentication plugins.
5e623a33 2718 *
03d820c7 2719 * @param string $auth Authentication plugin.
2720 * @return boolean Whether the plugin is enabled.
2721 */
16793340 2722function is_enabled_auth($auth) {
16793340 2723 if (empty($auth)) {
2724 return false;
03d820c7 2725 }
16793340 2726
c7b10b5f 2727 $enabled = get_enabled_auth_plugins();
2728
2729 return in_array($auth, $enabled);
03d820c7 2730}
2731
2732/**
2733 * Returns an authentication plugin instance.
2734 *
2735 * @uses $CFG
9696bd89 2736 * @param string $auth name of authentication plugin
03d820c7 2737 * @return object An instance of the required authentication plugin.
2738 */
9696bd89 2739function get_auth_plugin($auth) {
03d820c7 2740 global $CFG;
5e623a33 2741
03d820c7 2742 // check the plugin exists first
2743 if (! exists_auth_plugin($auth)) {
2f137aa1 2744 print_error('authpluginnotfound', 'debug', '', $auth);
03d820c7 2745 }
5e623a33 2746
03d820c7 2747 // return auth plugin instance
2748 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2749 $class = "auth_plugin_$auth";
2750 return new $class;
2751}
2752
c7b10b5f 2753/**
2754 * Returns array of active auth plugins.
2755 *
2756 * @param bool $fix fix $CFG->auth if needed
2757 * @return array
2758 */
2759function get_enabled_auth_plugins($fix=false) {
2760 global $CFG;
2761
2762 $default = array('manual', 'nologin');
2763
2764 if (empty($CFG->auth)) {
2765 $auths = array();
2766 } else {
2767 $auths = explode(',', $CFG->auth);
2768 }
2769
2770 if ($fix) {
2771 $auths = array_unique($auths);
2772 foreach($auths as $k=>$authname) {
2773 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
2774 unset($auths[$k]);
2775 }
2776 }
2777 $newconfig = implode(',', $auths);
2778 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
2779 set_config('auth', $newconfig);
2780 }
2781 }
2782
2783 return (array_merge($default, $auths));
2784}
2785
03d820c7 2786/**
2787 * Returns true if an internal authentication method is being used.
2788 * if method not specified then, global default is assumed
2789 *
2790 * @uses $CFG
2791 * @param string $auth Form of authentication required
2792 * @return bool
03d820c7 2793 */
16793340 2794function is_internal_auth($auth) {
03d820c7 2795 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2796 return $authplugin->is_internal();
a3f1f815 2797}
2798
8c3dba73 2799/**
2800 * Returns an array of user fields
2801 *
c6d15803 2802 * @return array User field/column names
8c3dba73 2803 */
a3f1f815 2804function get_user_fieldnames() {
f33e1ed4 2805 global $DB;
a3f1f815 2806
f33e1ed4 2807 $fieldarray = $DB->get_columns('user');
2808 unset($fieldarray['id']);
2809 $fieldarray = array_keys($fieldarray);
a3f1f815 2810
2811 return $fieldarray;
ba7166c3 2812}
f9903ed0 2813
7cf1c7bd 2814/**
2815 * Creates a bare-bones user record
2816 *
2817 * @uses $CFG
7cf1c7bd 2818 * @param string $username New user's username to add to record
2819 * @param string $password New user's password to add to record
2820 * @param string $auth Form of authentication required
68fbd8e1 2821 * @return object A {@link $USER} object
7cf1c7bd 2822 * @todo Outline auth types and provide code example
2823 */
f76cfc7a 2824function create_user_record($username, $password, $auth='manual') {
ae040d4b 2825 global $CFG, $DB;
71f9abf9 2826
1e22bc9c 2827 //just in case check text case
2828 $username = trim(moodle_strtolower($username));
71f9abf9 2829
03d820c7 2830 $authplugin = get_auth_plugin($auth);
2831
ae040d4b 2832 $newuser = new object();
2833
6bc1e5d5 2834 if ($newinfo = $authplugin->get_userinfo($username)) {
2835 $newinfo = truncate_userinfo($newinfo);
2836 foreach ($newinfo as $key => $value){
ae040d4b 2837 $newuser->$key = $value;
e858f9da 2838 }
2839 }
f9903ed0 2840
85a1d4c9 2841 if (!empty($newuser->email)) {
2842 if (email_is_not_allowed($newuser->email)) {
2843 unset($newuser->email);
2844 }
2845 }
2846
27134b7d 2847 if (!isset($newuser->city)) {
2848 $newuser->city = '';
2849 }
2850
f76cfc7a 2851 $newuser->auth = $auth;
faebaf0f 2852 $newuser->username = $username;
5e623a33 2853
e51917eb 2854 // fix for MDL-8480
2855 // user CFG lang for user if $newuser->lang is empty
2856 // or $user->lang is not an installed language
2857 $sitelangs = array_keys(get_list_of_languages());
2858 if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
9c6972d6 2859 $newuser->lang = $CFG->lang;
5e623a33 2860 }
faebaf0f 2861 $newuser->confirmed = 1;
d96466d2 2862 $newuser->lastip = getremoteaddr();
faebaf0f 2863 $newuser->timemodified = time();
03d820c7 2864 $newuser->mnethostid = $CFG->mnet_localhost_id;
f9903ed0 2865
9c6972d6 2866 $DB->insert_record('user', $newuser);
2867 $user = get_complete_user_data('username', $newuser->username);
2868 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
2869 set_user_preference('auth_forcepasswordchange', 1, $user->id);
faebaf0f 2870 }
9c6972d6 2871 update_internal_user_password($user, $password);
2872 return $user;
faebaf0f 2873}
2874
7cf1c7bd 2875/**
2876 * Will update a local user record from an external source
2877 *
2878 * @uses $CFG
2879 * @param string $username New user's username to add to record
89dcb99d 2880 * @return user A {@link $USER} object
7cf1c7bd 2881 */
03d820c7 2882function update_user_record($username, $authplugin) {
ae040d4b 2883 global $DB;
2884
6bc1e5d5 2885 $username = trim(moodle_strtolower($username)); /// just in case check text case
2886
ae040d4b 2887 $oldinfo = $DB->get_record('user', array('username'=>$username), 'username, auth');
6bc1e5d5 2888 $userauth = get_auth_plugin($oldinfo->auth);
2889
2890 if ($newinfo = $userauth->get_userinfo($username)) {
2891 $newinfo = truncate_userinfo($newinfo);
2892 foreach ($newinfo as $key => $value){
5261baf1 2893 if ($key === 'username') {
2894 // 'username' is not a mapped updateable/lockable field, so skip it.
2895 continue;
2896 }
6ceb0cd0 2897 $confval = $userauth->config->{'field_updatelocal_' . $key};
2898 $lockval = $userauth->config->{'field_lock_' . $key};
2899 if (empty($confval) || empty($lockval)) {
2900 continue;
2901 }
2902 if ($confval === 'onlogin') {
6ceb0cd0 2903 // MDL-4207 Don't overwrite modified user profile values with
2904 // empty LDAP values when 'unlocked if empty' is set. The purpose
2905 // of the setting 'unlocked if empty' is to allow the user to fill
2906 // in a value for the selected field _if LDAP is giving
2907 // nothing_ for this field. Thus it makes sense to let this value
2908 // stand in until LDAP is giving a value for this field.
2909 if (!(empty($value) && $lockval === 'unlockedifempty')) {
8f0632f0 2910 $DB->set_field('user', $key, $value, array('username'=>$username));
6ceb0cd0 2911 }
d35757eb 2912 }
2913 }
2914 }
6bc1e5d5 2915
7c12949d 2916 return get_complete_user_data('username', $username);
d35757eb 2917}
0609562b 2918
be544ec3 2919/**
38fb8190 2920 * will truncate userinfo as it comes from auth_get_userinfo (from external auth)
be544ec3 2921 * which may have large fields
2922 */
b36a8fc4 2923function truncate_userinfo($info) {
b36a8fc4 2924 // define the limits
2925 $limit = array(
2926 'username' => 100,
8b9cfac4 2927 'idnumber' => 255,
8bcd295c 2928 'firstname' => 100,
2929 'lastname' => 100,
b36a8fc4 2930 'email' => 100,
2931 'icq' => 15,
2932 'phone1' => 20,
2933 'phone2' => 20,
2934 'institution' => 40,
2935 'department' => 30,
2936 'address' => 70,
2937 'city' => 20,
2938 'country' => 2,
2939 'url' => 255,
2940 );
361855e6 2941
b36a8fc4 2942 // apply where needed
2943 foreach (array_keys($info) as $key) {
2944 if (!empty($limit[$key])) {
adfc03f9 2945 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
361855e6 2946 }
b36a8fc4 2947 }
361855e6 2948
b36a8fc4 2949 return $info;
90afcf32 2950}
2951
2952/**
2953 * Marks user deleted in internal user database and notifies the auth plugin.
2954 * Also unenrols user from all roles and does other cleanup.
2955 * @param object $user Userobject before delete (without system magic quotes)
2956 * @return boolean success
2957 */
2958function delete_user($user) {
ae040d4b 2959 global $CFG, $DB;
90afcf32 2960 require_once($CFG->libdir.'/grouplib.php');
ece966f0 2961 require_once($CFG->libdir.'/gradelib.php');
90afcf32 2962
9c6972d6 2963 // TODO: decide if this transaction is really needed
ae040d4b 2964 $DB->begin_sql();
90afcf32 2965
9c6972d6 2966 try {
2967 // delete all grades - backup is kept in grade_grades_history table
2968 if ($grades = grade_grade::fetch_all(array('userid'=>$user->id))) {
2969 foreach ($grades as $grade) {
2970 $grade->delete('userdelete');
2971 }
90afcf32 2972 }
90afcf32 2973
9c6972d6 2974 // remove from all groups
2975 $DB->delete_records('groups_members', array('userid'=>$user->id));
90afcf32 2976
9c6972d6 2977 // unenrol from all roles in all contexts
2978 role_unassign(0, $user->id); // this might be slow but it is really needed - modules might do some extra cleanup!
90afcf32 2979
9c6972d6 2980 // now do a final accesslib cleanup - removes all role assingments in user context and context itself
2981 delete_context(CONTEXT_USER, $user->id);
90afcf32 2982
9c6972d6 2983 require_once($CFG->dirroot.'/tag/lib.php');
2984 tag_set('user', $user->id, array());
13b31d6f 2985
9c6972d6 2986 // workaround for bulk deletes of users with the same email address
2987 $delname = "$user->email.".time();
2988 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
2989 $delname++;
2990 }
2991
2992 // mark internal user record as "deleted"
2993 $updateuser = new object();
2994 $updateuser->id = $user->id;
2995 $updateuser->deleted = 1;
2996 $updateuser->username = $delname; // Remember it just in case
2997 $updateuser->email = ''; // Clear this field to free it up
2998 $updateuser->idnumber = ''; // Clear this field to free it up
2999 $updateuser->timemodified = time();
6d11d0ee 3000
9c6972d6 3001 $DB->update_record('user', $updateuser);
90afcf32 3002
ae040d4b 3003 $DB->commit_sql();
9c6972d6 3004
90afcf32 3005 // notify auth plugin - do not block the delete even when plugin fails
3006 $authplugin = get_auth_plugin($user->auth);
3007 $authplugin->user_delete($user);
2942a5cd 3008
3009 events_trigger('user_deleted', $user);
90afcf32 3010
9c6972d6 3011 } catch (Exception $e) {
ae040d4b 3012 $DB->rollback_sql();
9c6972d6 3013 throw $e;
90afcf32 3014 }
9c6972d6 3015
3016 return true;
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: