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