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