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