MDL-11719 increased size of idnumber in user table - needed for some enrolment plugin...
[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/**
157 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
158 */
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 */
3d535996 262//To prevent problems with multibytes strings, this should not exceed the
263//length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
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 {
5a2a5331 309 print_error('A required parameter ('.$parname.') was missing');
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:
3d535996 573 //as long as magic_quotes_gpc is used, a backslash will be a
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
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 '';
596 }
597
a083b93c 598 default: // throw error, switched parameters in optional_param or another serious problem
5a2a5331 599 print_error("Unknown parameter type: $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 *
7cf1c7bd 616 * @param string $name the key to set
9cdb766d 617 * @param string $value the value to set (without magic quotes)
a4080313 618 * @param string $plugin (optional) the plugin scope
7cf1c7bd 619 * @uses $CFG
620 * @return bool
621 */
a4080313 622function set_config($name, $value, $plugin=NULL) {
9fa49e22 623/// No need for get_config because they are usually always available in $CFG
70812e39 624
42282810 625 global $CFG;
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
a4080313 637 if (get_field('config', 'name', 'name', $name)) {
6fd511eb 638 if ($value===null) {
6fd511eb 639 return delete_records('config', 'name', $name);
640 } else {
641 return set_field('config', 'value', addslashes($value), 'name', $name);
642 }
a4080313 643 } else {
6fd511eb 644 if ($value===null) {
645 return true;
646 }
9cdb766d 647 $config = new object();
a4080313 648 $config->name = $name;
9cdb766d 649 $config->value = addslashes($value);
a4080313 650 return insert_record('config', $config);
651 }
652 } else { // plugin scope
653 if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
6fd511eb 654 if ($value===null) {
655 return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
656 } else {
657 return set_field('config_plugins', 'value', addslashes($value), 'id', $id);
658 }
a4080313 659 } else {
6fd511eb 660 if ($value===null) {
661 return true;
662 }
9cdb766d 663 $config = new object();
664 $config->plugin = addslashes($plugin);
a4080313 665 $config->name = $name;
f855cdad 666 $config->value = addslashes($value);
a4080313 667 return insert_record('config_plugins', $config);
668 }
669 }
670}
671
672/**
e1ecf0a0 673 * Get configuration values from the global config table
a4080313 674 * or the config_plugins table.
675 *
676 * If called with no parameters it will do the right thing
677 * generating $CFG safely from the database without overwriting
e1ecf0a0 678 * existing values.
a4080313 679 *
9220fba5 680 * If called with 2 parameters it will return a $string single
681 * value or false of the value is not found.
682 *
e1ecf0a0 683 * @param string $plugin
684 * @param string $name
a4080313 685 * @uses $CFG
686 * @return hash-like object or single value
687 *
688 */
689function get_config($plugin=NULL, $name=NULL) {
7cf1c7bd 690
a4080313 691 global $CFG;
dfc9ba9b 692
a4080313 693 if (!empty($name)) { // the user is asking for a specific value
694 if (!empty($plugin)) {
9220fba5 695 return get_field('config_plugins', 'value', 'plugin' , $plugin, 'name', $name);
a4080313 696 } else {
9220fba5 697 return get_field('config', 'value', 'name', $name);
a4080313 698 }
699 }
700
701 // the user is after a recordset
702 if (!empty($plugin)) {
703 if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
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
715 if ($configs = get_records('config')) {
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) {
743
744 global $CFG;
745
746 unset($CFG->$name);
747
748 if (empty($plugin)) {
749 return delete_records('config', 'name', $name);
5e623a33 750 } else {
b0270f84 751 return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
752 }
753}
754
bafd7e78 755/**
756 * Get volatile flags
757 *
758 * @param string $type
759 * @param int $changedsince
760 * @return records array
761 *
762 */
763function get_cache_flags($type, $changedsince=NULL) {
764
765 $type = addslashes($type);
766
767 $sqlwhere = 'flagtype=\'' . $type . '\' AND expiry >= ' . time();
768 if ($changedsince !== NULL) {
769 $changedsince = (int)$changedsince;
770 $sqlwhere .= ' AND timemodified > ' . $changedsince;
771 }
772 $cf = array();
773 if ($flags=get_records_select('cache_flags', $sqlwhere, '', 'name,value')) {
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) {
791
792 $type = addslashes($type);
793 $name = addslashes($name);
794
795 $sqlwhere = 'flagtype=\'' . $type . '\' AND name=\'' . $name . '\' AND expiry >= ' . time();
796 if ($changedsince !== NULL) {
797 $changedsince = (int)$changedsince;
798 $sqlwhere .= ' AND timemodified > ' . $changedsince;
799 }
800 return get_field_select('cache_flags', 'value', $sqlwhere);
801}
bafd7e78 802
803/**
804 * Set a volatile flag
805 *
806 * @param string $type the "type" namespace for the key
807 * @param string $name the key to set
808 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
809 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
810 * @return bool
811 */
812function set_cache_flag($type, $name, $value, $expiry=NULL) {
813
814
815 $timemodified = time();
816 if ($expiry===NULL || $expiry < $timemodified) {
817 $expiry = $timemodified + 24 * 60 * 60;
818 } else {
819 $expiry = (int)$expiry;
820 }
821
822 if ($value === NULL) {
823 return unset_cache_flag($type,$name);
824 }
825
826 $type = addslashes($type);
827 $name = addslashes($name);
128f0984 828 if ($f = get_record('cache_flags', 'name', $name, 'flagtype', $type)) { // this is a potentail problem in DEBUG_DEVELOPER
829 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
830 return true; //no need to update; helps rcache too
831 }
832 $f->value = addslashes($value);
bafd7e78 833 $f->expiry = $expiry;
834 $f->timemodified = $timemodified;
835 return update_record('cache_flags', $f);
836 } else {
128f0984 837 $f = new object();
bafd7e78 838 $f->flagtype = $type;
839 $f->name = $name;
128f0984 840 $f->value = addslashes($value);
bafd7e78 841 $f->expiry = $expiry;
842 $f->timemodified = $timemodified;
128f0984 843 return (bool)insert_record('cache_flags', $f);
bafd7e78 844 }
845}
846
847/**
848 * Removes a single volatile flag
849 *
850 * @param string $type the "type" namespace for the key
851 * @param string $name the key to set
852 * @uses $CFG
853 * @return bool
854 */
855function unset_cache_flag($type, $name) {
856
857 return delete_records('cache_flags',
858 'name', addslashes($name),
859 'flagtype', addslashes($type));
860}
861
862/**
863 * Garbage-collect volatile flags
864 *
865 */
866function gc_cache_flags() {
867 return delete_records_select('cache_flags', 'expiry < ' . time());
868}
a4080313 869
7cf1c7bd 870/**
871 * Refresh current $USER session global variable with all their current preferences.
872 * @uses $USER
873 */
70812e39 874function reload_user_preferences() {
70812e39 875
876 global $USER;
877
346c3e2f 878 //reset preference
879 $USER->preference = array();
070e2616 880
346c3e2f 881 if (!isloggedin() or isguestuser()) {
114201c8 882 // no permanent storage for not-logged-in user and guest
70812e39 883
346c3e2f 884 } else if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
70812e39 885 foreach ($preferences as $preference) {
886 $USER->preference[$preference->name] = $preference->value;
887 }
c6d15803 888 }
346c3e2f 889
890 return true;
70812e39 891}
892
7cf1c7bd 893/**
894 * Sets a preference for the current user
895 * Optionally, can set a preference for a different user object
896 * @uses $USER
68fbd8e1 897 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
898
7cf1c7bd 899 * @param string $name The key to set as preference for the specified user
900 * @param string $value The value to set forthe $name key in the specified user's record
346c3e2f 901 * @param int $otheruserid A moodle user ID
bbd3f2c4 902 * @return bool
7cf1c7bd 903 */
346c3e2f 904function set_user_preference($name, $value, $otheruserid=NULL) {
70812e39 905
906 global $USER;
907
346c3e2f 908 if (!isset($USER->preference)) {
909 reload_user_preferences();
d35757eb 910 }
911
70812e39 912 if (empty($name)) {
913 return false;
914 }
915
346c3e2f 916 $nostore = false;
917
918 if (empty($otheruserid)){
919 if (!isloggedin() or isguestuser()) {
920 $nostore = true;
921 }
922 $userid = $USER->id;
923 } else {
924 if (isguestuser($otheruserid)) {
925 $nostore = true;
926 }
927 $userid = $otheruserid;
928 }
929
930 $return = true;
931 if ($nostore) {
114201c8 932 // no permanent storage for not-logged-in user and guest
346c3e2f 933
934 } else if ($preference = get_record('user_preferences', 'userid', $userid, 'name', addslashes($name))) {
a1244706 935 if ($preference->value === $value) {
936 return true;
937 }
346c3e2f 938 if (!set_field('user_preferences', 'value', addslashes((string)$value), 'id', $preference->id)) {
939 $return = false;
066af654 940 }
70812e39 941
942 } else {
346c3e2f 943 $preference = new object();
a3f1f815 944 $preference->userid = $userid;
346c3e2f 945 $preference->name = addslashes($name);
946 $preference->value = addslashes((string)$value);
947 if (!insert_record('user_preferences', $preference)) {
948 $return = false;
70812e39 949 }
950 }
346c3e2f 951
952 // update value in USER session if needed
953 if ($userid == $USER->id) {
954 $USER->preference[$name] = (string)$value;
955 }
956
957 return $return;
70812e39 958}
959
6eb3e776 960/**
961 * Unsets a preference completely by deleting it from the database
962 * Optionally, can set a preference for a different user id
963 * @uses $USER
964 * @param string $name The key to unset as preference for the specified user
346c3e2f 965 * @param int $otheruserid A moodle user ID
6eb3e776 966 */
346c3e2f 967function unset_user_preference($name, $otheruserid=NULL) {
6eb3e776 968
969 global $USER;
970
346c3e2f 971 if (!isset($USER->preference)) {
972 reload_user_preferences();
6eb3e776 973 }
974
346c3e2f 975 if (empty($otheruserid)){
976 $userid = $USER->id;
977 } else {
978 $userid = $otheruserid;
979 }
980
981 //Delete the preference from $USER if needed
982 if ($userid == $USER->id) {
49d005ee 983 unset($USER->preference[$name]);
984 }
e1ecf0a0 985
49d005ee 986 //Then from DB
346c3e2f 987 return delete_records('user_preferences', 'userid', $userid, 'name', addslashes($name));
6eb3e776 988}
989
990
7cf1c7bd 991/**
992 * Sets a whole array of preferences for the current user
993 * @param array $prefarray An array of key/value pairs to be set
346c3e2f 994 * @param int $otheruserid A moodle user ID
bbd3f2c4 995 * @return bool
7cf1c7bd 996 */
346c3e2f 997function set_user_preferences($prefarray, $otheruserid=NULL) {
70812e39 998
999 if (!is_array($prefarray) or empty($prefarray)) {
1000 return false;
1001 }
1002
1003 $return = true;
1004 foreach ($prefarray as $name => $value) {
346c3e2f 1005 // The order is important; test for return is done first
1006 $return = (set_user_preference($name, $value, $otheruserid) && $return);
70812e39 1007 }
1008 return $return;
1009}
1010
7cf1c7bd 1011/**
1012 * If no arguments are supplied this function will return
361855e6 1013 * all of the current user preferences as an array.
7cf1c7bd 1014 * If a name is specified then this function
1015 * attempts to return that particular preference value. If
1016 * none is found, then the optional value $default is returned,
1017 * otherwise NULL.
1018 * @param string $name Name of the key to use in finding a preference value
1019 * @param string $default Value to be returned if the $name key is not set in the user preferences
346c3e2f 1020 * @param int $otheruserid A moodle user ID
7cf1c7bd 1021 * @uses $USER
1022 * @return string
1023 */
346c3e2f 1024function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
70812e39 1025 global $USER;
1026
346c3e2f 1027 if (!isset($USER->preference)) {
1028 reload_user_preferences();
1029 }
a3f1f815 1030
346c3e2f 1031 if (empty($otheruserid)){
1032 $userid = $USER->id;
a3f1f815 1033 } else {
346c3e2f 1034 $userid = $otheruserid;
1035 }
a3f1f815 1036
346c3e2f 1037 if ($userid == $USER->id) {
1038 $preference = $USER->preference;
1039
1040 } else {
1041 $preference = array();
1042 if ($prefdata = get_records('user_preferences', 'userid', $userid)) {
1043 foreach ($prefdata as $pref) {
1044 $preference[$pref->name] = $pref->value;
1045 }
a3f1f815 1046 }
346c3e2f 1047 }
1048
1049 if (empty($name)) {
1050 return $preference; // All values
1051
1052 } else if (array_key_exists($name, $preference)) {
1053 return $preference[$name]; // The single value
1054
1055 } else {
1056 return $default; // Default value (or NULL)
70812e39 1057 }
70812e39 1058}
1059
1060
9fa49e22 1061/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 1062
7cf1c7bd 1063/**
c6d15803 1064 * Given date parts in user time produce a GMT timestamp.
7cf1c7bd 1065 *
68fbd8e1 1066 * @param int $year The year part to create timestamp of
1067 * @param int $month The month part to create timestamp of
1068 * @param int $day The day part to create timestamp of
1069 * @param int $hour The hour part to create timestamp of
1070 * @param int $minute The minute part to create timestamp of
1071 * @param int $second The second part to create timestamp of
1072 * @param float $timezone ?
1073 * @param bool $applydst ?
e34d817e 1074 * @return int timestamp
7cf1c7bd 1075 * @todo Finish documenting this function
1076 */
9f1f6daf 1077function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
39917a09 1078
33998d30 1079 $strtimezone = NULL;
1080 if (!is_numeric($timezone)) {
1081 $strtimezone = $timezone;
1082 }
1083
dddb014a 1084 $timezone = get_user_timezone_offset($timezone);
1085
94e34118 1086 if (abs($timezone) > 13) {
68fbd8e1 1087 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
03c17ddf 1088 } else {
68fbd8e1 1089 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
196f2619 1090 $time = usertime($time, $timezone);
28c66824 1091 if($applydst) {
33998d30 1092 $time -= dst_offset_on($time, $strtimezone);
28c66824 1093 }
9f1f6daf 1094 }
1095
196f2619 1096 return $time;
85cafb3e 1097
39917a09 1098}
1099
7cf1c7bd 1100/**
1101 * Given an amount of time in seconds, returns string
5602f7cf 1102 * formatted nicely as weeks, days, hours etc as needed
7cf1c7bd 1103 *
2f87145b 1104 * @uses MINSECS
1105 * @uses HOURSECS
1106 * @uses DAYSECS
5602f7cf 1107 * @uses YEARSECS
c6d15803 1108 * @param int $totalsecs ?
1109 * @param array $str ?
89dcb99d 1110 * @return string
7cf1c7bd 1111 */
1112 function format_time($totalsecs, $str=NULL) {
c7e3ac2a 1113
6b174680 1114 $totalsecs = abs($totalsecs);
c7e3ac2a 1115
8dbed6be 1116 if (!$str) { // Create the str structure the slow way
b0ccd3fb 1117 $str->day = get_string('day');
1118 $str->days = get_string('days');
1119 $str->hour = get_string('hour');
1120 $str->hours = get_string('hours');
1121 $str->min = get_string('min');
1122 $str->mins = get_string('mins');
1123 $str->sec = get_string('sec');
1124 $str->secs = get_string('secs');
5602f7cf 1125 $str->year = get_string('year');
1126 $str->years = get_string('years');
8dbed6be 1127 }
1128
5602f7cf 1129
1130 $years = floor($totalsecs/YEARSECS);
1131 $remainder = $totalsecs - ($years*YEARSECS);
5602f7cf 1132 $days = floor($remainder/DAYSECS);
7a5672c9 1133 $remainder = $totalsecs - ($days*DAYSECS);
1134 $hours = floor($remainder/HOURSECS);
1135 $remainder = $remainder - ($hours*HOURSECS);
1136 $mins = floor($remainder/MINSECS);
1137 $secs = $remainder - ($mins*MINSECS);
8dbed6be 1138
1139 $ss = ($secs == 1) ? $str->sec : $str->secs;
1140 $sm = ($mins == 1) ? $str->min : $str->mins;
1141 $sh = ($hours == 1) ? $str->hour : $str->hours;
1142 $sd = ($days == 1) ? $str->day : $str->days;
5602f7cf 1143 $sy = ($years == 1) ? $str->year : $str->years;
8dbed6be 1144
5602f7cf 1145 $oyears = '';
b0ccd3fb 1146 $odays = '';
1147 $ohours = '';
1148 $omins = '';
1149 $osecs = '';
9c9f7d77 1150
5602f7cf 1151 if ($years) $oyears = $years .' '. $sy;
b0ccd3fb 1152 if ($days) $odays = $days .' '. $sd;
1153 if ($hours) $ohours = $hours .' '. $sh;
1154 if ($mins) $omins = $mins .' '. $sm;
1155 if ($secs) $osecs = $secs .' '. $ss;
6b174680 1156
77ac808e 1157 if ($years) return trim($oyears .' '. $odays);
1158 if ($days) return trim($odays .' '. $ohours);
1159 if ($hours) return trim($ohours .' '. $omins);
1160 if ($mins) return trim($omins .' '. $osecs);
b0ccd3fb 1161 if ($secs) return $osecs;
1162 return get_string('now');
6b174680 1163}
f9903ed0 1164
7cf1c7bd 1165/**
1166 * Returns a formatted string that represents a date in user time
1167 * <b>WARNING: note that the format is for strftime(), not date().</b>
1168 * Because of a bug in most Windows time libraries, we can't use
1169 * the nicer %e, so we have to use %d which has leading zeroes.
1170 * A lot of the fuss in the function is just getting rid of these leading
1171 * zeroes as efficiently as possible.
361855e6 1172 *
8c3dba73 1173 * If parameter fixday = true (default), then take off leading
7cf1c7bd 1174 * zero from %d, else mantain it.
1175 *
2f87145b 1176 * @uses HOURSECS
e34d817e 1177 * @param int $date timestamp in GMT
1178 * @param string $format strftime format
d2a9f7cc 1179 * @param float $timezone
bbd3f2c4 1180 * @param bool $fixday If true (default) then the leading
c6d15803 1181 * zero from %d is removed. If false then the leading zero is mantained.
1182 * @return string
7cf1c7bd 1183 */
b0ccd3fb 1184function userdate($date, $format='', $timezone=99, $fixday = true) {
7a302afc 1185
1ac7ee24 1186 global $CFG;
1187
33998d30 1188 $strtimezone = NULL;
1189 if (!is_numeric($timezone)) {
1190 $strtimezone = $timezone;
1191 }
1192
1306c5ea 1193 if (empty($format)) {
1194 $format = get_string('strftimedaydatetime');
5fa51a39 1195 }
035cdbff 1196
c3a3c5b8 1197 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1198 $fixday = false;
1199 } else if ($fixday) {
1200 $formatnoday = str_replace('%d', 'DD', $format);
61ae5d36 1201 $fixday = ($formatnoday != $format);
1202 }
dcde9f02 1203
33998d30 1204 $date += dst_offset_on($date, $strtimezone);
85351042 1205
494b9296 1206 $timezone = get_user_timezone_offset($timezone);
102dc313 1207
1208 if (abs($timezone) > 13) { /// Server time
d2a9f7cc 1209 if ($fixday) {
102dc313 1210 $datestring = strftime($formatnoday, $date);
1211 $daystring = str_replace(' 0', '', strftime(' %d', $date));
1212 $datestring = str_replace('DD', $daystring, $datestring);
1213 } else {
1214 $datestring = strftime($format, $date);
1215 }
88ec5b7c 1216 } else {
102dc313 1217 $date += (int)($timezone * 3600);
1218 if ($fixday) {
1219 $datestring = gmstrftime($formatnoday, $date);
1220 $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
1221 $datestring = str_replace('DD', $daystring, $datestring);
1222 } else {
1223 $datestring = gmstrftime($format, $date);
1224 }
88ec5b7c 1225 }
102dc313 1226
fb773106 1227/// If we are running under Windows convert from windows encoding to UTF-8
1228/// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
11f7b25d 1229
fb773106 1230 if ($CFG->ostype == 'WINDOWS') {
11f7b25d 1231 if ($localewincharset = get_string('localewincharset')) {
1232 $textlib = textlib_get_instance();
810944af 1233 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
11f7b25d 1234 }
1235 }
1236
035cdbff 1237 return $datestring;
873960de 1238}
1239
7cf1c7bd 1240/**
196f2619 1241 * Given a $time timestamp in GMT (seconds since epoch),
c6d15803 1242 * returns an array that represents the date in user time
7cf1c7bd 1243 *
2f87145b 1244 * @uses HOURSECS
196f2619 1245 * @param int $time Timestamp in GMT
68fbd8e1 1246 * @param float $timezone ?
c6d15803 1247 * @return array An array that represents the date in user time
7cf1c7bd 1248 * @todo Finish documenting this function
1249 */
196f2619 1250function usergetdate($time, $timezone=99) {
6b174680 1251
94c82430 1252 $strtimezone = NULL;
1253 if (!is_numeric($timezone)) {
1254 $strtimezone = $timezone;
1255 }
1256
494b9296 1257 $timezone = get_user_timezone_offset($timezone);
a36166d3 1258
e34d817e 1259 if (abs($timezone) > 13) { // Server time
ed1f69b0 1260 return getdate($time);
d2a9f7cc 1261 }
1262
e34d817e 1263 // There is no gmgetdate so we use gmdate instead
94c82430 1264 $time += dst_offset_on($time, $strtimezone);
e34d817e 1265 $time += intval((float)$timezone * HOURSECS);
3bba1e6e 1266
1267 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
02f0527d 1268
9f1f6daf 1269 list(
1270 $getdate['seconds'],
1271 $getdate['minutes'],
1272 $getdate['hours'],
1273 $getdate['mday'],
1274 $getdate['mon'],
1275 $getdate['year'],
1276 $getdate['wday'],
1277 $getdate['yday'],
1278 $getdate['weekday'],
1279 $getdate['month']
3bba1e6e 1280 ) = explode('_', $datestring);
9f1f6daf 1281
d2d6171f 1282 return $getdate;
d552ead0 1283}
1284
7cf1c7bd 1285/**
1286 * Given a GMT timestamp (seconds since epoch), offsets it by
1287 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1288 *
2f87145b 1289 * @uses HOURSECS
c6d15803 1290 * @param int $date Timestamp in GMT
e34d817e 1291 * @param float $timezone
c6d15803 1292 * @return int
7cf1c7bd 1293 */
d552ead0 1294function usertime($date, $timezone=99) {
a36166d3 1295
494b9296 1296 $timezone = get_user_timezone_offset($timezone);
2665e47a 1297
0431bd7c 1298 if (abs($timezone) > 13) {
d552ead0 1299 return $date;
1300 }
7a5672c9 1301 return $date - (int)($timezone * HOURSECS);
d552ead0 1302}
1303
8c3dba73 1304/**
1305 * Given a time, return the GMT timestamp of the most recent midnight
1306 * for the current user.
1307 *
e34d817e 1308 * @param int $date Timestamp in GMT
1309 * @param float $timezone ?
c6d15803 1310 * @return ?
8c3dba73 1311 */
edf7fe8c 1312function usergetmidnight($date, $timezone=99) {
edf7fe8c 1313
edf7fe8c 1314 $userdate = usergetdate($date, $timezone);
4606d9bb 1315
02f0527d 1316 // Time of midnight of this user's day, in GMT
1317 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
edf7fe8c 1318
1319}
1320
7cf1c7bd 1321/**
1322 * Returns a string that prints the user's timezone
1323 *
1324 * @param float $timezone The user's timezone
1325 * @return string
1326 */
d552ead0 1327function usertimezone($timezone=99) {
d552ead0 1328
0c244315 1329 $tz = get_user_timezone($timezone);
f30fe8d0 1330
0c244315 1331 if (!is_float($tz)) {
1332 return $tz;
d552ead0 1333 }
0c244315 1334
1335 if(abs($tz) > 13) { // Server time
1336 return get_string('serverlocaltime');
1337 }
1338
1339 if($tz == intval($tz)) {
1340 // Don't show .0 for whole hours
1341 $tz = intval($tz);
1342 }
1343
1344 if($tz == 0) {
61b420ac 1345 return 'UTC';
d552ead0 1346 }
0c244315 1347 else if($tz > 0) {
61b420ac 1348 return 'UTC+'.$tz;
0c244315 1349 }
1350 else {
61b420ac 1351 return 'UTC'.$tz;
d552ead0 1352 }
e1ecf0a0 1353
f9903ed0 1354}
1355
7cf1c7bd 1356/**
1357 * Returns a float which represents the user's timezone difference from GMT in hours
1358 * Checks various settings and picks the most dominant of those which have a value
1359 *
7cf1c7bd 1360 * @uses $CFG
1361 * @uses $USER
b2b68362 1362 * @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 1363 * @return int
7cf1c7bd 1364 */
494b9296 1365function get_user_timezone_offset($tz = 99) {
f30fe8d0 1366
43b59916 1367 global $USER, $CFG;
1368
e8904995 1369 $tz = get_user_timezone($tz);
c9e55a25 1370
7b9e355e 1371 if (is_float($tz)) {
1372 return $tz;
1373 } else {
e8904995 1374 $tzrecord = get_timezone_record($tz);
7b9e355e 1375 if (empty($tzrecord)) {
e8904995 1376 return 99.0;
1377 }
4f2dbde9 1378 return (float)$tzrecord->gmtoff / HOURMINS;
e8904995 1379 }
1380}
1381
61460dd6 1382/**
1383 * Returns an int which represents the systems's timezone difference from GMT in seconds
1384 * @param mixed $tz timezone
1385 * @return int if found, false is timezone 99 or error
1386 */
1387function get_timezone_offset($tz) {
1388 global $CFG;
1389
1390 if ($tz == 99) {
1391 return false;
1392 }
1393
1394 if (is_numeric($tz)) {
1395 return intval($tz * 60*60);
1396 }
1397
1398 if (!$tzrecord = get_timezone_record($tz)) {
1399 return false;
1400 }
1401 return intval($tzrecord->gmtoff * 60);
1402}
1403
bbd3f2c4 1404/**
b2b68362 1405 * Returns a float or a string which denotes the user's timezone
1406 * 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)
1407 * means that for this timezone there are also DST rules to be taken into account
1408 * Checks various settings and picks the most dominant of those which have a value
bbd3f2c4 1409 *
1410 * @uses $USER
1411 * @uses $CFG
b2b68362 1412 * @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
1413 * @return mixed
bbd3f2c4 1414 */
e8904995 1415function get_user_timezone($tz = 99) {
1416 global $USER, $CFG;
43b59916 1417
f30fe8d0 1418 $timezones = array(
e8904995 1419 $tz,
1420 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
43b59916 1421 isset($USER->timezone) ? $USER->timezone : 99,
1422 isset($CFG->timezone) ? $CFG->timezone : 99,
f30fe8d0 1423 );
43b59916 1424
e8904995 1425 $tz = 99;
43b59916 1426
33998d30 1427 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
e8904995 1428 $tz = $next['value'];
43b59916 1429 }
e8904995 1430
1431 return is_numeric($tz) ? (float) $tz : $tz;
43b59916 1432}
1433
bbd3f2c4 1434/**
1435 * ?
1436 *
1437 * @uses $CFG
1438 * @uses $db
1439 * @param string $timezonename ?
1440 * @return object
1441 */
43b59916 1442function get_timezone_record($timezonename) {
1443 global $CFG, $db;
1444 static $cache = NULL;
1445
8edffd15 1446 if ($cache === NULL) {
43b59916 1447 $cache = array();
1448 }
1449
8edffd15 1450 if (isset($cache[$timezonename])) {
43b59916 1451 return $cache[$timezonename];
f30fe8d0 1452 }
1453
952d8dc8 1454 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix.'timezone
1455 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
f30fe8d0 1456}
f9903ed0 1457
bbd3f2c4 1458/**
1459 * ?
1460 *
1461 * @uses $CFG
1462 * @uses $USER
1463 * @param ? $fromyear ?
1464 * @param ? $to_year ?
1465 * @return bool
1466 */
94c82430 1467function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
2280ecf5 1468 global $CFG, $SESSION;
85cafb3e 1469
33998d30 1470 $usertz = get_user_timezone($strtimezone);
7cb29a3d 1471
989585e9 1472 if (is_float($usertz)) {
1473 // Trivial timezone, no DST
1474 return false;
1475 }
1476
2280ecf5 1477 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
989585e9 1478 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2280ecf5 1479 unset($SESSION->dst_offsets);
1480 unset($SESSION->dst_range);
830a2bbd 1481 }
1482
2280ecf5 1483 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
830a2bbd 1484 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1485 // This will be the return path most of the time, pretty light computationally
1486 return true;
85cafb3e 1487 }
1488
830a2bbd 1489 // Reaching here means we either need to extend our table or create it from scratch
989585e9 1490
1491 // Remember which TZ we calculated these changes for
2280ecf5 1492 $SESSION->dst_offsettz = $usertz;
989585e9 1493
2280ecf5 1494 if(empty($SESSION->dst_offsets)) {
830a2bbd 1495 // If we 're creating from scratch, put the two guard elements in there
2280ecf5 1496 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
830a2bbd 1497 }
2280ecf5 1498 if(empty($SESSION->dst_range)) {
830a2bbd 1499 // If creating from scratch
1500 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1501 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1502
1503 // Fill in the array with the extra years we need to process
1504 $yearstoprocess = array();
1505 for($i = $from; $i <= $to; ++$i) {
1506 $yearstoprocess[] = $i;
1507 }
1508
1509 // Take note of which years we have processed for future calls
2280ecf5 1510 $SESSION->dst_range = array($from, $to);
830a2bbd 1511 }
1512 else {
1513 // If needing to extend the table, do the same
1514 $yearstoprocess = array();
1515
2280ecf5 1516 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1517 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
830a2bbd 1518
2280ecf5 1519 if($from < $SESSION->dst_range[0]) {
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 = $from; $i < $SESSION->dst_range[0]; ++$i) {
830a2bbd 1522 $yearstoprocess[] = $i;
1523 }
2280ecf5 1524 $SESSION->dst_range[0] = $from;
830a2bbd 1525 }
2280ecf5 1526 if($to > $SESSION->dst_range[1]) {
830a2bbd 1527 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1528 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
830a2bbd 1529 $yearstoprocess[] = $i;
1530 }
2280ecf5 1531 $SESSION->dst_range[1] = $to;
830a2bbd 1532 }
1533 }
1534
1535 if(empty($yearstoprocess)) {
1536 // This means that there was a call requesting a SMALLER range than we have already calculated
1537 return true;
1538 }
1539
1540 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1541 // Also, the array is sorted in descending timestamp order!
1542
1543 // Get DB data
6a5dc27c 1544
1545 static $presets_cache = array();
1546 if (!isset($presets_cache[$usertz])) {
1547 $presets_cache[$usertz] = get_records('timezone', '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');
1548 }
1549 if(empty($presets_cache[$usertz])) {
e789650d 1550 return false;
1551 }
57f1191c 1552
830a2bbd 1553 // Remove ending guard (first element of the array)
2280ecf5 1554 reset($SESSION->dst_offsets);
1555 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
830a2bbd 1556
1557 // Add all required change timestamps
1558 foreach($yearstoprocess as $y) {
1559 // Find the record which is in effect for the year $y
6a5dc27c 1560 foreach($presets_cache[$usertz] as $year => $preset) {
830a2bbd 1561 if($year <= $y) {
1562 break;
c9e72798 1563 }
830a2bbd 1564 }
1565
1566 $changes = dst_changes_for_year($y, $preset);
1567
1568 if($changes === NULL) {
1569 continue;
1570 }
1571 if($changes['dst'] != 0) {
2280ecf5 1572 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
830a2bbd 1573 }
1574 if($changes['std'] != 0) {
2280ecf5 1575 $SESSION->dst_offsets[$changes['std']] = 0;
c9e72798 1576 }
85cafb3e 1577 }
42d36497 1578
830a2bbd 1579 // Put in a guard element at the top
2280ecf5 1580 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1581 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
830a2bbd 1582
1583 // Sort again
2280ecf5 1584 krsort($SESSION->dst_offsets);
830a2bbd 1585
e789650d 1586 return true;
1587}
42d36497 1588
e789650d 1589function dst_changes_for_year($year, $timezone) {
7cb29a3d 1590
e789650d 1591 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1592 return NULL;
42d36497 1593 }
7cb29a3d 1594
e789650d 1595 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1596 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1597
1598 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1599 list($std_hour, $std_min) = explode(':', $timezone->std_time);
d2a9f7cc 1600
6dc8dddc 1601 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1602 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
830a2bbd 1603
1604 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1605 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1606 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1607
1608 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1609 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
42d36497 1610
e789650d 1611 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
42d36497 1612}
1613
02f0527d 1614// $time must NOT be compensated at all, it has to be a pure timestamp
94c82430 1615function dst_offset_on($time, $strtimezone = NULL) {
2280ecf5 1616 global $SESSION;
02f0527d 1617
94c82430 1618 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
c9e72798 1619 return 0;
85cafb3e 1620 }
1621
2280ecf5 1622 reset($SESSION->dst_offsets);
1623 while(list($from, $offset) = each($SESSION->dst_offsets)) {
59556d48 1624 if($from <= $time) {
c9e72798 1625 break;
1626 }
1627 }
1628
830a2bbd 1629 // This is the normal return path
1630 if($offset !== NULL) {
1631 return $offset;
02f0527d 1632 }
02f0527d 1633
830a2bbd 1634 // Reaching this point means we haven't calculated far enough, do it now:
1635 // Calculate extra DST changes if needed and recurse. The recursion always
1636 // moves toward the stopping condition, so will always end.
1637
1638 if($from == 0) {
2280ecf5 1639 // We need a year smaller than $SESSION->dst_range[0]
1640 if($SESSION->dst_range[0] == 1971) {
830a2bbd 1641 return 0;
1642 }
94c82430 1643 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
1644 return dst_offset_on($time, $strtimezone);
830a2bbd 1645 }
1646 else {
2280ecf5 1647 // We need a year larger than $SESSION->dst_range[1]
1648 if($SESSION->dst_range[1] == 2035) {
830a2bbd 1649 return 0;
1650 }
94c82430 1651 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
1652 return dst_offset_on($time, $strtimezone);
830a2bbd 1653 }
85cafb3e 1654}
02f0527d 1655
28902d99 1656function find_day_in_month($startday, $weekday, $month, $year) {
8dc3f6cf 1657
1658 $daysinmonth = days_in_month($month, $year);
1659
42d36497 1660 if($weekday == -1) {
28902d99 1661 // Don't care about weekday, so return:
1662 // abs($startday) if $startday != -1
1663 // $daysinmonth otherwise
1664 return ($startday == -1) ? $daysinmonth : abs($startday);
8dc3f6cf 1665 }
1666
1667 // From now on we 're looking for a specific weekday
8dc3f6cf 1668
28902d99 1669 // Give "end of month" its actual value, since we know it
1670 if($startday == -1) {
1671 $startday = -1 * $daysinmonth;
1672 }
1673
1674 // Starting from day $startday, the sign is the direction
8dc3f6cf 1675
28902d99 1676 if($startday < 1) {
8dc3f6cf 1677
28902d99 1678 $startday = abs($startday);
8dc3f6cf 1679 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1680
1681 // This is the last such weekday of the month
1682 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
1683 if($lastinmonth > $daysinmonth) {
1684 $lastinmonth -= 7;
42d36497 1685 }
8dc3f6cf 1686
28902d99 1687 // Find the first such weekday <= $startday
1688 while($lastinmonth > $startday) {
8dc3f6cf 1689 $lastinmonth -= 7;
42d36497 1690 }
8dc3f6cf 1691
1692 return $lastinmonth;
e1ecf0a0 1693
42d36497 1694 }
1695 else {
42d36497 1696
28902d99 1697 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
42d36497 1698
8dc3f6cf 1699 $diff = $weekday - $indexweekday;
1700 if($diff < 0) {
1701 $diff += 7;
42d36497 1702 }
42d36497 1703
28902d99 1704 // This is the first such weekday of the month equal to or after $startday
1705 $firstfromindex = $startday + $diff;
42d36497 1706
8dc3f6cf 1707 return $firstfromindex;
1708
1709 }
42d36497 1710}
1711
bbd3f2c4 1712/**
1713 * Calculate the number of days in a given month
1714 *
1715 * @param int $month The month whose day count is sought
1716 * @param int $year The year of the month whose day count is sought
1717 * @return int
1718 */
42d36497 1719function days_in_month($month, $year) {
1720 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1721}
1722
bbd3f2c4 1723/**
1724 * Calculate the position in the week of a specific calendar day
1725 *
1726 * @param int $day The day of the date whose position in the week is sought
1727 * @param int $month The month of the date whose position in the week is sought
1728 * @param int $year The year of the date whose position in the week is sought
1729 * @return int
1730 */
8dc3f6cf 1731function dayofweek($day, $month, $year) {
1732 // I wonder if this is any different from
1733 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1734 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1735}
1736
9fa49e22 1737/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 1738
bbd3f2c4 1739/**
1740 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1741 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1742 * sesskey string if $USER exists, or boolean false if not.
1743 *
1744 * @uses $USER
1745 * @return string
1746 */
04280e85 1747function sesskey() {
1a33f699 1748 global $USER;
1749
1750 if(!isset($USER)) {
1751 return false;
1752 }
1753
1754 if (empty($USER->sesskey)) {
1755 $USER->sesskey = random_string(10);
1756 }
1757
1758 return $USER->sesskey;
1759}
1760
0302c52f 1761
c4d0753b 1762/**
1763 * For security purposes, this function will check that the currently
1764 * given sesskey (passed as a parameter to the script or this function)
1765 * matches that of the current user.
1766 *
1767 * @param string $sesskey optionally provided sesskey
1768 * @return bool
1769 */
1770function confirm_sesskey($sesskey=NULL) {
1771 global $USER;
0302c52f 1772
c4d0753b 1773 if (!empty($USER->ignoresesskey) || !empty($CFG->ignoresesskey)) {
1774 return true;
0302c52f 1775 }
1776
c4d0753b 1777 if (empty($sesskey)) {
1778 $sesskey = required_param('sesskey', PARAM_RAW); // Check script parameters
0302c52f 1779 }
1780
c4d0753b 1781 if (!isset($USER->sesskey)) {
1782 return false;
1783 }
0302c52f 1784
c4d0753b 1785 return ($USER->sesskey === $sesskey);
0302c52f 1786}
c4d0753b 1787
dcf6d93c 1788/**
9152fc99 1789 * Setup all global $CFG course variables, set locale and also themes
1790 * This function can be used on pages that do not require login instead of require_login()
1791 *
dcf6d93c 1792 * @param mixed $courseorid id of the course or course object
1793 */
1794function course_setup($courseorid=0) {
1306c5ea 1795 global $COURSE, $CFG, $SITE;
dcf6d93c 1796
1797/// Redefine global $COURSE if needed
1798 if (empty($courseorid)) {
1799 // no change in global $COURSE - for backwards compatibiltiy
5e623a33 1800 // if require_rogin() used after require_login($courseid);
dcf6d93c 1801 } else if (is_object($courseorid)) {
1802 $COURSE = clone($courseorid);
1803 } else {
1804 global $course; // used here only to prevent repeated fetching from DB - may be removed later
a6a251c7 1805 if ($courseorid == SITEID) {
9152fc99 1806 $COURSE = clone($SITE);
1807 } else if (!empty($course->id) and $course->id == $courseorid) {
dcf6d93c 1808 $COURSE = clone($course);
1809 } else {
1810 if (!$COURSE = get_record('course', 'id', $courseorid)) {
5a2a5331 1811 print_error('Invalid course ID');
dcf6d93c 1812 }
1813 }
1814 }
1815
9152fc99 1816/// set locale and themes
dcf6d93c 1817 moodle_setlocale();
dcf6d93c 1818 theme_setup();
1819
dcf6d93c 1820}
c4d0753b 1821
7cf1c7bd 1822/**
ec81373f 1823 * This function checks that the current user is logged in and has the
1824 * required privileges
1825 *
7cf1c7bd 1826 * This function checks that the current user is logged in, and optionally
ec81373f 1827 * whether they are allowed to be in a particular course and view a particular
1828 * course module.
1829 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 1830 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 1831 * case they are automatically logged in as guests.
1832 * If $courseid is given and the user is not enrolled in that course then the
1833 * user is redirected to the course enrolment page.
1834 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1835 * in the course then the user is redirected to the course home page.
7cf1c7bd 1836 *
7cf1c7bd 1837 * @uses $CFG
c6d15803 1838 * @uses $SESSION
7cf1c7bd 1839 * @uses $USER
1840 * @uses $FULLME
c6d15803 1841 * @uses SITEID
f07fa644 1842 * @uses $COURSE
33ebaf7c 1843 * @param mixed $courseorid id of the course or course object
bbd3f2c4 1844 * @param bool $autologinguest
1845 * @param object $cm course module object
f4013c10 1846 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
1847 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
1848 * in order to keep redirects working properly. MDL-14495
7cf1c7bd 1849 */
f4013c10 1850function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsurltome=true) {
f9903ed0 1851
083c3743 1852 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
d8ba183c 1853
083c3743 1854/// setup global $COURSE, themes, language and locale
dcf6d93c 1855 course_setup($courseorid);
be933850 1856
1845f8b8 1857/// If the user is not even logged in yet then make sure they are
083c3743 1858 if (!isloggedin()) {
1859 //NOTE: $USER->site check was obsoleted by session test cookie,
1860 // $USER->confirmed test is in login/index.php
f4013c10 1861 if ($setwantsurltome) {
1862 $SESSION->wantsurl = $FULLME;
1863 }
b0ccd3fb 1864 if (!empty($_SERVER['HTTP_REFERER'])) {
1865 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
9f44d972 1866 }
ad56b737 1867 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
8e8d0524 1868 $loginguest = '?loginguest=true';
1869 } else {
1870 $loginguest = '';
a2ebe6a5 1871 }
2c040c29 1872 if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
b0ccd3fb 1873 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
8a33e371 1874 } else {
2c3432e6 1875 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
083c3743 1876 redirect($wwwroot .'/login/index.php');
8a33e371 1877 }
20fde7b1 1878 exit;
f9903ed0 1879 }
808a3baa 1880
f6f66b03 1881/// loginas as redirection if needed
1882 if ($COURSE->id != SITEID and !empty($USER->realuser)) {
1883 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
1884 if ($USER->loginascontext->instanceid != $COURSE->id) {
3887fe4a 1885 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
5e623a33 1886 }
f6f66b03 1887 }
1888 }
1889
5602f7cf 1890/// check whether the user should be changing password (but only if it is REALLY them)
346c3e2f 1891 if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser)) {
21e2dcd9 1892 $userauth = get_auth_plugin($USER->auth);
03d820c7 1893 if ($userauth->can_change_password()) {
20fde7b1 1894 $SESSION->wantsurl = $FULLME;
80274abf 1895 if ($changeurl = $userauth->change_password_url()) {
9696bd89 1896 //use plugin custom url
80274abf 1897 redirect($changeurl);
1437f0a5 1898 } else {
9696bd89 1899 //use moodle internal method
1900 if (empty($CFG->loginhttps)) {
1901 redirect($CFG->wwwroot .'/login/change_password.php');
1902 } else {
1903 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1904 redirect($wwwroot .'/login/change_password.php');
1905 }
1437f0a5 1906 }
d35757eb 1907 } else {
a8ee7194 1908 print_error('nopasswordchangeforced', 'auth');
d35757eb 1909 }
1910 }
083c3743 1911
1845f8b8 1912/// Check that the user account is properly set up
808a3baa 1913 if (user_not_fully_set_up($USER)) {
20fde7b1 1914 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1915 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 1916 }
d8ba183c 1917
1845f8b8 1918/// Make sure current IP matches the one for this session (if required)
361855e6 1919 if (!empty($CFG->tracksessionip)) {
366dfa60 1920 if ($USER->sessionIP != md5(getremoteaddr())) {
a8ee7194 1921 print_error('sessionipnomatch', 'error');
366dfa60 1922 }
1923 }
6d8f47d6 1924
1845f8b8 1925/// Make sure the USER has a sesskey set up. Used for checking script parameters.
04280e85 1926 sesskey();
366dfa60 1927
027a1604 1928 // Check that the user has agreed to a site policy if there is one
1929 if (!empty($CFG->sitepolicy)) {
1930 if (!$USER->policyagreed) {
957b5198 1931 $SESSION->wantsurl = $FULLME;
027a1604 1932 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 1933 }
1695b680 1934 }
1935
21e2dcd9 1936 // Fetch the system context, we are going to use it a lot.
1937 $sysctx = get_context_instance(CONTEXT_SYSTEM);
1938
1845f8b8 1939/// If the site is currently under maintenance, then print a message
21e2dcd9 1940 if (!has_capability('moodle/site:config', $sysctx)) {
eeefd0b0 1941 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
1695b680 1942 print_maintenance_message();
20fde7b1 1943 exit;
1695b680 1944 }
027a1604 1945 }
1946
f8e3d5f0 1947/// groupmembersonly access control
1948 if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
1949 if (isguestuser() or !groups_has_membership($cm)) {
a8ee7194 1950 print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
f8e3d5f0 1951 }
1952 }
1845f8b8 1953
21e2dcd9 1954 // Fetch the course context, and prefetch its child contexts
1955 if (!isset($COURSE->context)) {
1956 if ( ! $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id) ) {
1957 print_error('nocontext');
1958 }
1959 }
33ebaf7c 1960 if ($COURSE->id == SITEID) {
21e2dcd9 1961 /// Eliminate hidden site activities straight away
1962 if (!empty($cm) && !$cm->visible
1963 && !has_capability('moodle/course:viewhiddenactivities', $COURSE->context)) {
33ebaf7c 1964 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
e3512050 1965 }
341b5ed2 1966 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
33ebaf7c 1967 return;
881a77bf 1968
5e623a33 1969 } else {
1845f8b8 1970
21e2dcd9 1971 /// Check if the user can be in a particular course
1972 if (empty($USER->access['rsw'][$COURSE->context->path])) {
1cf2e21b 1973 //
a8ee7194 1974 // MDL-13900 - If the course or the parent category are hidden
1975 // and the user hasn't the 'course:viewhiddencourses' capability, prevent access
1cf2e21b 1976 //
a8ee7194 1977 if ( !($COURSE->visible && course_parent_visible($COURSE)) &&
1978 !has_capability('moodle/course:viewhiddencourses', $COURSE->context)) {
1cf2e21b 1979 print_header_simple();
1980 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
1981 }
a8ee7194 1982 }
1983
f71346e2 1984 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1985
21e2dcd9 1986 if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) {
33ebaf7c 1987 if ($COURSE->guest == 1) {
eef879ec 1988 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
21e2dcd9 1989 $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access);
f71346e2 1990 }
1991 }
1992
1845f8b8 1993 /// If the user is a guest then treat them according to the course policy about guests
1994
21e2dcd9 1995 if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) {
5f431c1b 1996 if (has_capability('moodle/site:doanything', $sysctx)) {
1997 // administrators must be able to access any course - even if somebody gives them guest access
341b5ed2 1998 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
b03f7215 1999 return;
5f431c1b 2000 }
2001
33ebaf7c 2002 switch ($COURSE->guest) { /// Check course policy about guest access
1845f8b8 2003
21e2dcd9 2004 case 1: /// Guests always allowed
2005 if (!has_capability('moodle/course:view', $COURSE->context)) { // Prohibited by capability
1845f8b8 2006 print_header_simple();
6ba65fa0 2007 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
1845f8b8 2008 }
2009 if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
5e623a33 2010 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
1845f8b8 2011 get_string('activityiscurrentlyhidden'));
2012 }
2013
341b5ed2 2014 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
1845f8b8 2015 return; // User is allowed to see this course
2016
2017 break;
2018
5e623a33 2019 case 2: /// Guests allowed with key
33ebaf7c 2020 if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
341b5ed2 2021 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
b1f318a6 2022 return true;
2023 }
2024 // otherwise drop through to logic below (--> enrol.php)
1845f8b8 2025 break;
bbbf2d40 2026
1845f8b8 2027 default: /// Guests not allowed
0be6f678 2028 $strloggedinasguest = get_string('loggedinasguest');
2029 print_header_simple('', '',
2030 build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc'))));
21e2dcd9 2031 if (empty($USER->access['rsw'][$COURSE->context->path])) { // Normal guest
6ba65fa0 2032 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
21596567 2033 } else {
6ba65fa0 2034 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
33ebaf7c 2035 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
2036 print_footer($COURSE);
21596567 2037 exit;
2038 }
1845f8b8 2039 break;
2040 }
2041
2042 /// For non-guests, check if they have course view access
2043
21e2dcd9 2044 } else if (has_capability('moodle/course:view', $COURSE->context)) {
1845f8b8 2045 if (!empty($USER->realuser)) { // Make sure the REAL person can also access this course
21e2dcd9 2046 if (!has_capability('moodle/course:view', $COURSE->context, $USER->realuser)) {
1845f8b8 2047 print_header_simple();
b0ccd3fb 2048 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
cb909d74 2049 }
3ce2f1e0 2050 }
1845f8b8 2051
2052 /// Make sure they can read this activity too, if specified
2053
21e2dcd9 2054 if (!empty($cm) and !$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $COURSE->context)) {
ec81373f 2055 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
2056 }
341b5ed2 2057 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
1845f8b8 2058 return; // User is allowed to see this course
2059
da5c172a 2060 }
f9903ed0 2061
9ca3b4f3 2062
1845f8b8 2063 /// Currently not enrolled in the course, so see if they want to enrol
da5c172a 2064 $SESSION->wantsurl = $FULLME;
33ebaf7c 2065 redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
da5c172a 2066 die;
2067 }
f9903ed0 2068}
2069
c4d0753b 2070
2071
2072/**
2073 * This function just makes sure a user is logged out.
2074 *
2075 * @uses $CFG
2076 * @uses $USER
2077 */
2078function require_logout() {
2079
2d4beaff 2080 global $USER, $CFG, $SESSION;
c4d0753b 2081
111e2360 2082 if (isloggedin()) {
c4d0753b 2083 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2084
533f7910 2085 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2086 foreach($authsequence as $authname) {
2087 $authplugin = get_auth_plugin($authname);
2088 $authplugin->prelogout_hook();
81693ac7 2089 }
c4d0753b 2090 }
2091
f8bd7030 2092 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
2093 $file = $line = null;
2094 if (headers_sent($file, $line)) {
2095 error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__);
2096 error_log('Headers were already sent in file: '.$file.' on line '.$line);
2097 } else {
2881200b 2098 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
f8bd7030 2099 }
2100
c4d0753b 2101 unset($_SESSION['USER']);
2102 unset($_SESSION['SESSION']);
2103
2104 unset($SESSION);
2105 unset($USER);
2106
2107}
2108
7cf1c7bd 2109/**
2110 * This is a weaker version of {@link require_login()} which only requires login
2111 * when called from within a course rather than the site page, unless
2112 * the forcelogin option is turned on.
2113 *
2114 * @uses $CFG
33ebaf7c 2115 * @param mixed $courseorid The course object or id in question
bbd3f2c4 2116 * @param bool $autologinguest Allow autologin guests if that is wanted
4febb58f 2117 * @param object $cm Course activity module if known
f4013c10 2118 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2119 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2120 * in order to keep redirects working properly. MDL-14495
7cf1c7bd 2121 */
f4013c10 2122function require_course_login($courseorid, $autologinguest=true, $cm=null, $setwantsurltome=true) {
f950af3c 2123 global $CFG;
1596edff 2124 if (!empty($CFG->forcelogin)) {
33ebaf7c 2125 // login required for both SITE and courses
f4013c10 2126 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
63c9ee99 2127
2128 } else if (!empty($cm) and !$cm->visible) {
2129 // always login for hidden activities
f4013c10 2130 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
63c9ee99 2131
39de90ac 2132 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2133 or (!is_object($courseorid) and $courseorid == SITEID)) {
33ebaf7c 2134 //login for SITE not required
341b5ed2 2135 user_accesstime_log(SITEID);
63c9ee99 2136 return;
2137
33ebaf7c 2138 } else {
2139 // course login always required
f4013c10 2140 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
f950af3c 2141 }
2142}
2143
61c6071f 2144/**
2145 * Require key login. Function terminates with error if key not found or incorrect.
2146 * @param string $script unique script identifier
2147 * @param int $instance optional instance id
2148 */
2149function require_user_key_login($script, $instance=null) {
e2fa911b 2150 global $nomoodlecookie, $USER, $SESSION, $CFG;
61c6071f 2151
2152 if (empty($nomoodlecookie)) {
5a2a5331 2153 print_error('Incorrect use of require_key_login() - session cookies must be disabled!');
61c6071f 2154 }
2155
2156/// extra safety
2157 @session_write_close();
2158
2159 $keyvalue = required_param('key', PARAM_ALPHANUM);
2160
2161 if (!$key = get_record('user_private_key', 'script', $script, 'value', $keyvalue, 'instance', $instance)) {
5a2a5331 2162 print_error('Incorrect key');
61c6071f 2163 }
2164
2165 if (!empty($key->validuntil) and $key->validuntil < time()) {
5a2a5331 2166 print_error('Expired key');
61c6071f 2167 }
2168
e436033f 2169 if ($key->iprestriction) {
2170 $remoteaddr = getremoteaddr();
2171 if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction)) {
5a2a5331 2172 print_error('Client IP address mismatch');
e436033f 2173 }
61c6071f 2174 }
2175
2176 if (!$user = get_record('user', 'id', $key->userid)) {
5a2a5331 2177 print_error('Incorrect user record');
61c6071f 2178 }
2179
2180/// emulate normal session
2181 $SESSION = new object();
2182 $USER = $user;
2183
e2fa911b 2184/// note we are not using normal login
2185 if (!defined('USER_KEY_LOGIN')) {
2186 define('USER_KEY_LOGIN', true);
2187 }
2188
2189 load_all_capabilities();
2190
61c6071f 2191/// return isntance id - it might be empty
2192 return $key->instance;
2193}
2194
2195/**
2196 * Creates a new private user access key.
2197 * @param string $script unique target identifier
2198 * @param int $userid
2199 * @param instance $int optional instance id
2200 * @param string $iprestriction optional ip restricted access
2201 * @param timestamp $validuntil key valid only until given data
2202 * @return string access key value
2203 */
2204function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2205 $key = new object();
2206 $key->script = $script;
2207 $key->userid = $userid;
2208 $key->instance = $instance;
2209 $key->iprestriction = $iprestriction;
2210 $key->validuntil = $validuntil;
2211 $key->timecreated = time();
2212
2213 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
2214 while (record_exists('user_private_key', 'value', $key->value)) {
2215 // must be unique
2216 $key->value = md5($userid.'_'.time().random_string(40));
2217 }
2218
2219 if (!insert_record('user_private_key', $key)) {
5a2a5331 2220 print_error('Can not insert new key');
61c6071f 2221 }
2222
2223 return $key->value;
2224}
2225
7cf1c7bd 2226/**
2227 * Modify the user table by setting the currently logged in user's
2228 * last login to now.
2229 *
2230 * @uses $USER
bbd3f2c4 2231 * @return bool
7cf1c7bd 2232 */
1d881d92 2233function update_user_login_times() {
2234 global $USER;
2235
53467aa6 2236 $user = new object();
1d881d92 2237 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2a2f5f11 2238 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1d881d92 2239
2240 $user->id = $USER->id;
2241
b0ccd3fb 2242 return update_record('user', $user);
1d881d92 2243}
2244
7cf1c7bd 2245/**
2246 * Determines if a user has completed setting up their account.
2247 *
89dcb99d 2248 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
bbd3f2c4 2249 * @return bool
7cf1c7bd 2250 */
808a3baa 2251function user_not_fully_set_up($user) {
bb64b51a 2252 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
2253}
2254
2255function over_bounce_threshold($user) {
d2a9f7cc 2256
bb64b51a 2257 global $CFG;
d2a9f7cc 2258
bb64b51a 2259 if (empty($CFG->handlebounces)) {
2260 return false;
2261 }
2262 // set sensible defaults
2263 if (empty($CFG->minbounces)) {
2264 $CFG->minbounces = 10;
2265 }
2266 if (empty($CFG->bounceratio)) {
2267 $CFG->bounceratio = .20;
2268 }
2269 $bouncecount = 0;
2270 $sendcount = 0;
2271 if ($bounce = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
2272 $bouncecount = $bounce->value;
2273 }
2274 if ($send = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
2275 $sendcount = $send->value;
2276 }
2277 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2278}
2279
d2a9f7cc 2280/**
bb64b51a 2281 * @param $user - object containing an id
2282 * @param $reset - will reset the count to 0
2283 */
2284function set_send_count($user,$reset=false) {
d2a9f7cc 2285 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
bb64b51a 2286 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2287 update_record('user_preferences',$pref);
2288 }
2289 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2290 // make a new one
2291 $pref->name = 'email_send_count';
2292 $pref->value = 1;
2293 $pref->userid = $user->id;
06ba0b04 2294 insert_record('user_preferences',$pref, false);
bb64b51a 2295 }
2296}
2297
d2a9f7cc 2298/**
bb64b51a 2299* @param $user - object containing an id
2300 * @param $reset - will reset the count to 0
2301 */
2302function set_bounce_count($user,$reset=false) {
d2a9f7cc 2303 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
bb64b51a 2304 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2305 update_record('user_preferences',$pref);
2306 }
2307 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2308 // make a new one
2309 $pref->name = 'email_bounce_count';
2310 $pref->value = 1;
2311 $pref->userid = $user->id;
06ba0b04 2312 insert_record('user_preferences',$pref, false);
bb64b51a 2313 }
808a3baa 2314}
f9903ed0 2315
7cf1c7bd 2316/**
2317 * Keeps track of login attempts
2318 *
2319 * @uses $SESSION
2320 */
f9903ed0 2321function update_login_count() {
9fa49e22 2322
f9903ed0 2323 global $SESSION;
2324
2325 $max_logins = 10;
2326
2327 if (empty($SESSION->logincount)) {
2328 $SESSION->logincount = 1;
2329 } else {
2330 $SESSION->logincount++;
2331 }
2332
2333 if ($SESSION->logincount > $max_logins) {
9fa49e22 2334 unset($SESSION->wantsurl);
a8ee7194 2335 print_error('errortoomanylogins');
d578afc8 2336 }
2337}
2338
7cf1c7bd 2339/**
2340 * Resets login attempts
2341 *
2342 * @uses $SESSION
2343 */
9fa49e22 2344function reset_login_count() {
9fa49e22 2345 global $SESSION;
d578afc8 2346
9fa49e22 2347 $SESSION->logincount = 0;
d578afc8 2348}
2349
b61efafb 2350function sync_metacourses() {
2351
2352 global $CFG;
2353
1aad4310 2354 if (!$courses = get_records('course', 'metacourse', 1)) {
b61efafb 2355 return;
2356 }
d2a9f7cc 2357
b61efafb 2358 foreach ($courses as $course) {
1aad4310 2359 sync_metacourse($course);
b61efafb 2360 }
2361}
2362
b61efafb 2363/**
2364 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
5e623a33 2365 *
123545bc 2366 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
d2a9f7cc 2367 */
1aad4310 2368function sync_metacourse($course) {
755c8d58 2369 global $CFG;
b61efafb 2370
123545bc 2371 // Check the course is valid.
1aad4310 2372 if (!is_object($course)) {
2373 if (!$course = get_record('course', 'id', $course)) {
2374 return false; // invalid course id
b61efafb 2375 }
b61efafb 2376 }
5e623a33 2377
123545bc 2378 // Check that we actually have a metacourse.
1aad4310 2379 if (empty($course->metacourse)) {
123545bc 2380 return false;
755c8d58 2381 }
87671466 2382
b3170072 2383 // Get a list of roles that should not be synced.
4db9bff7 2384 if (!empty($CFG->nonmetacoursesyncroleids)) {
b3170072 2385 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
5e623a33 2386 } else {
b3170072 2387 $roleexclusions = '';
2388 }
2389
123545bc 2390 // Get the context of the metacourse.
1aad4310 2391 $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
e1ecf0a0 2392
123545bc 2393 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
b79da3ac 2394 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
1aad4310 2395 $managers = array_keys($users);
2396 } else {
2397 $managers = array();
b61efafb 2398 }
2399
123545bc 2400 // Get assignments of a user to a role that exist in a child course, but
2401 // not in the meta coure. That is, get a list of the assignments that need to be made.
2402 if (!$assignments = get_records_sql("
2403 SELECT
2404 ra.id, ra.roleid, ra.userid
2405 FROM
2406 {$CFG->prefix}role_assignments ra,
2407 {$CFG->prefix}context con,
2408 {$CFG->prefix}course_meta cm
2409 WHERE
2410 ra.contextid = con.id AND
2411 con.contextlevel = " . CONTEXT_COURSE . " AND
2412 con.instanceid = cm.child_course AND
2413 cm.parent_course = {$course->id} AND
b3170072 2414 $roleexclusions
123545bc 2415 NOT EXISTS (
2416 SELECT 1 FROM
2417 {$CFG->prefix}role_assignments ra2
2418 WHERE
2419 ra2.userid = ra.userid AND
2420 ra2.roleid = ra.roleid AND
2421 ra2.contextid = {$context->id}
2422 )
2423 ")) {
2424 $assignments = array();
2425 }
2426
2427 // Get assignments of a user to a role that exist in the meta course, but
2428 // not in any child courses. That is, get a list of the unassignments that need to be made.
2429 if (!$unassignments = get_records_sql("
2430 SELECT
2431 ra.id, ra.roleid, ra.userid
2432 FROM
2433 {$CFG->prefix}role_assignments ra
2434 WHERE
2435 ra.contextid = {$context->id} AND
b3170072 2436 $roleexclusions
123545bc 2437 NOT EXISTS (
2438 SELECT 1 FROM
2439 {$CFG->prefix}role_assignments ra2,
2440 {$CFG->prefix}context con2,
2441 {$CFG->prefix}course_meta cm
2442 WHERE
2443 ra2.userid = ra.userid AND
2444 ra2.roleid = ra.roleid AND
2445 ra2.contextid = con2.id AND
2446 con2.contextlevel = " . CONTEXT_COURSE . " AND
2447 con2.instanceid = cm.child_course AND
2448 cm.parent_course = {$course->id}
2449 )
2450 ")) {
2451 $unassignments = array();
2452 }
2453
2454 $success = true;
2455
2456 // Make the unassignments, if they are not managers.
2457 foreach ($unassignments as $unassignment) {
2458 if (!in_array($unassignment->userid, $managers)) {
2459 $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
1aad4310 2460 }
755c8d58 2461 }
e1ecf0a0 2462
123545bc 2463 // Make the assignments.
2464 foreach ($assignments as $assignment) {
2465 $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id) && $success;
b61efafb 2466 }
755c8d58 2467
123545bc 2468 return $success;
5e623a33 2469
1aad4310 2470// TODO: finish timeend and timestart
2471// maybe we could rely on cron job to do the cleaning from time to time
b61efafb 2472}
2473
d2a9f7cc 2474/**
b61efafb 2475 * Adds a record to the metacourse table and calls sync_metacoures
2476 */
2477function add_to_metacourse ($metacourseid, $courseid) {
d2a9f7cc 2478
b61efafb 2479 if (!$metacourse = get_record("course","id",$metacourseid)) {
2480 return false;
2481 }
d2a9f7cc 2482
b61efafb 2483 if (!$course = get_record("course","id",$courseid)) {
2484 return false;
2485 }
2486
5f37b628 2487 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
53467aa6 2488 $rec = new object();
b61efafb 2489 $rec->parent_course = $metacourseid;
2490 $rec->child_course = $courseid;
5f37b628 2491 if (!insert_record('course_meta',$rec)) {
b61efafb 2492 return false;
2493 }
2494 return sync_metacourse($metacourseid);
2495 }
2496 return true;
d2a9f7cc 2497
b61efafb 2498}
2499
d2a9f7cc 2500/**
b61efafb 2501 * Removes the record from the metacourse table and calls sync_metacourse
2502 */
2503function remove_from_metacourse($metacourseid, $courseid) {
2504
5f37b628 2505 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
b61efafb 2506 return sync_metacourse($metacourseid);
2507 }
2508 return false;
2509}
2510
2511
7c12949d 2512/**
2513 * Determines if a user is currently logged in
2514 *
2515 * @uses $USER
bbd3f2c4 2516 * @return bool
7c12949d 2517 */
2518function isloggedin() {
2519 global $USER;
2520
2521 return (!empty($USER->id));
2522}
2523
2a919fd7 2524/**
2525 * Determines if a user is logged in as real guest user with username 'guest'.
2526 * This function is similar to original isguest() in 1.6 and earlier.
2527 * Current isguest() is deprecated - do not use it anymore.
2528 *
2529 * @param $user mixed user object or id, $USER if not specified
2530 * @return bool true if user is the real guest user, false if not logged in or other user
2531 */
2532function isguestuser($user=NULL) {
2533 global $USER;
2534 if ($user === NULL) {
2535 $user = $USER;
2536 } else if (is_numeric($user)) {
2537 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2538 }
2539
2540 if (empty($user->id)) {
2541 return false; // not logged in, can not be guest
2542 }
2543
2544 return ($user->username == 'guest');
2545}
7c12949d 2546
7cf1c7bd 2547/**
e6260a45 2548 * Determines if the currently logged in user is in editing mode.
2549 * Note: originally this function had $userid parameter - it was not usable anyway
7cf1c7bd 2550 *
0df35335 2551 * @uses $USER, $PAGE
bbd3f2c4 2552 * @return bool
7cf1c7bd 2553 */
0df35335 2554function isediting() {
2555 global $USER, $PAGE;
e6260a45 2556
2557 if (empty($USER->editing)) {
9c9f7d77 2558 return false;
0df35335 2559 } elseif (is_object($PAGE) && method_exists($PAGE,'user_allowed_editing')) {
2560 return $PAGE->user_allowed_editing();
9c9f7d77 2561 }
0df35335 2562 return true;//false;
2c309dc2 2563}
2564
7cf1c7bd 2565/**
2566 * Determines if the logged in user is currently moving an activity
2567 *
2568 * @uses $USER
c6d15803 2569 * @param int $courseid The id of the course being tested
bbd3f2c4 2570 * @return bool
7cf1c7bd 2571 */
7977cffd 2572function ismoving($courseid) {
7977cffd 2573 global $USER;
2574
2575 if (!empty($USER->activitycopy)) {
2576 return ($USER->activitycopycourse == $courseid);
2577 }
2578 return false;
2579}
2580
7cf1c7bd 2581/**
2582 * Given an object containing firstname and lastname
2583 * values, this function returns a string with the
2584 * full name of the person.
2585 * The result may depend on system settings
2586 * or language. 'override' will force both names
361855e6 2587 * to be used even if system settings specify one.
68fbd8e1 2588 *
7cf1c7bd 2589 * @uses $CFG
2590 * @uses $SESSION
68fbd8e1 2591 * @param object $user A {@link $USER} object to get full name of
2592 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
7cf1c7bd 2593 */
e2cd5065 2594function fullname($user, $override=false) {
b5cbb64d 2595
f374fb10 2596 global $CFG, $SESSION;
2597
6527c077 2598 if (!isset($user->firstname) and !isset($user->lastname)) {
2599 return '';
2600 }
2601
4c202228 2602 if (!$override) {
2603 if (!empty($CFG->forcefirstname)) {
2604 $user->firstname = $CFG->forcefirstname;
2605 }
2606 if (!empty($CFG->forcelastname)) {
2607 $user->lastname = $CFG->forcelastname;
2608 }
2609 }
2610
f374fb10 2611 if (!empty($SESSION->fullnamedisplay)) {
2612 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
2613 }
e2cd5065 2614
b5cbb64d 2615 if ($CFG->fullnamedisplay == 'firstname lastname') {
b0ccd3fb 2616 return $user->firstname .' '. $user->lastname;
b5cbb64d 2617
2618 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 2619 return $user->lastname .' '. $user->firstname;
e2cd5065 2620
b5cbb64d 2621 } else if ($CFG->fullnamedisplay == 'firstname') {
2622 if ($override) {
2623 return get_string('fullnamedisplay', '', $user);
2624 } else {
2625 return $user->firstname;
2626 }
2627 }
e2cd5065 2628
b5cbb64d 2629 return get_string('fullnamedisplay', '', $user);
e2cd5065 2630}
2631
7cf1c7bd 2632/**
2633 * Sets a moodle cookie with an encrypted string
2634 *
2635 * @uses $CFG
2f87145b 2636 * @uses DAYSECS
2637 * @uses HOURSECS
7cf1c7bd 2638 * @param string $thing The string to encrypt and place in a cookie
2639 */
f9903ed0 2640function set_moodle_cookie($thing) {
7185e073 2641 global $CFG;
482b6e6e 2642
7cbe6afe 2643 if ($thing == 'guest') { // Ignore guest account
2644 return;
2645 }
2646
482b6e6e 2647 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
f9903ed0 2648
2649 $days = 60;
7a5672c9 2650 $seconds = DAYSECS*$days;
f9903ed0 2651
4ea8df21 2652 // no need to set secure or http cookie only here - it is not secret
1504e261 2653 setCookie($cookiename, '', time() - HOURSECS, $CFG->sessioncookiepath);
2654 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, $CFG->sessioncookiepath);
f9903ed0 2655}
2656
7cf1c7bd 2657/**
2658 * Gets a moodle cookie with an encrypted string
2659 *
2660 * @uses $CFG
2661 * @return string
2662 */
f9903ed0 2663function get_moodle_cookie() {
7185e073 2664 global $CFG;
2665
482b6e6e 2666 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
7185e073 2667
1079c8a8 2668 if (empty($_COOKIE[$cookiename])) {
b0ccd3fb 2669 return '';
1079c8a8 2670 } else {
7cbe6afe 2671 $thing = rc4decrypt($_COOKIE[$cookiename]);
2672 return ($thing == 'guest') ? '': $thing; // Ignore guest account
1079c8a8 2673 }
f9903ed0 2674}
2675
7cf1c7bd 2676/**
03d820c7 2677 * Returns whether a given authentication plugin exists.
7cf1c7bd 2678 *
2679 * @uses $CFG
03d820c7 2680 * @param string $auth Form of authentication to check for. Defaults to the
2681 * global setting in {@link $CFG}.
2682 * @return boolean Whether the plugin is available.
7cf1c7bd 2683 */
16793340 2684function exists_auth_plugin($auth) {
03d820c7 2685 global $CFG;
5e623a33 2686
03d820c7 2687 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2688 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2689 }
2690 return false;
2691}
ba7166c3 2692
03d820c7 2693/**
2694 * Checks if a given plugin is in the list of enabled authentication plugins.
5e623a33 2695 *
03d820c7 2696 * @param string $auth Authentication plugin.
2697 * @return boolean Whether the plugin is enabled.
2698 */
16793340 2699function is_enabled_auth($auth) {
16793340 2700 if (empty($auth)) {
2701 return false;
03d820c7 2702 }
16793340 2703
c7b10b5f 2704 $enabled = get_enabled_auth_plugins();
2705
2706 return in_array($auth, $enabled);
03d820c7 2707}
2708
2709/**
2710 * Returns an authentication plugin instance.
2711 *
2712 * @uses $CFG
9696bd89 2713 * @param string $auth name of authentication plugin
03d820c7 2714 * @return object An instance of the required authentication plugin.
2715 */
9696bd89 2716function get_auth_plugin($auth) {
03d820c7 2717 global $CFG;
5e623a33 2718
03d820c7 2719 // check the plugin exists first
2720 if (! exists_auth_plugin($auth)) {
5a2a5331 2721 print_error("Authentication plugin '$auth' not found.");
03d820c7 2722 }
5e623a33 2723
03d820c7 2724 // return auth plugin instance
2725 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2726 $class = "auth_plugin_$auth";
2727 return new $class;
2728}
2729
c7b10b5f 2730/**
2731 * Returns array of active auth plugins.
2732 *
2733 * @param bool $fix fix $CFG->auth if needed
2734 * @return array
2735 */
2736function get_enabled_auth_plugins($fix=false) {
2737 global $CFG;
2738
2739 $default = array('manual', 'nologin');
2740
2741 if (empty($CFG->auth)) {
2742 $auths = array();
2743 } else {
2744 $auths = explode(',', $CFG->auth);
2745 }
2746
2747 if ($fix) {
2748 $auths = array_unique($auths);
2749 foreach($auths as $k=>$authname) {
2750 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
2751 unset($auths[$k]);
2752 }
2753 }
2754 $newconfig = implode(',', $auths);
2755 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
2756 set_config('auth', $newconfig);
2757 }
2758 }
2759
2760 return (array_merge($default, $auths));
2761}
2762
03d820c7 2763/**
2764 * Returns true if an internal authentication method is being used.
2765 * if method not specified then, global default is assumed
2766 *
2767 * @uses $CFG
2768 * @param string $auth Form of authentication required
2769 * @return bool
03d820c7 2770 */
16793340 2771function is_internal_auth($auth) {
03d820c7 2772 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2773 return $authplugin->is_internal();
a3f1f815 2774}
2775
8c3dba73 2776/**
2777 * Returns an array of user fields
2778 *
c6d15803 2779 * @uses $CFG
2780 * @uses $db
2781 * @return array User field/column names
8c3dba73 2782 */
a3f1f815 2783function get_user_fieldnames() {
a3f1f815 2784
2785 global $CFG, $db;
2786
2787 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
2788 unset($fieldarray['ID']);
2789
2790 return $fieldarray;
ba7166c3 2791}
f9903ed0 2792
08103c93
ML
2793/**
2794 * Creates the default "guest" user. Used both from
2795 * admin/index.php and login/index.php
2796 * @return mixed user object created or boolean false if the creation has failed
2797 */
2798function create_guest_record() {
2799
2800 global $CFG;
2801
c824d478 2802 $guest = new stdClass();
08103c93
ML
2803 $guest->auth = 'manual';
2804 $guest->username = 'guest';
2805 $guest->password = hash_internal_user_password('guest');
2806 $guest->firstname = addslashes(get_string('guestuser'));
2807 $guest->lastname = ' ';
2808 $guest->email = 'root@localhost';
2809 $guest->description = addslashes(get_string('guestuserinfo'));
2810 $guest->mnethostid = $CFG->mnet_localhost_id;
2811 $guest->confirmed = 1;
2812 $guest->lang = $CFG->lang;
2813 $guest->timemodified= time();
2814
2815 if (! $guest->id = insert_record("user", $guest)) {
2816 return false;
2817 }
2818
2819 return $guest;
2820}
2821
7cf1c7bd 2822/**
2823 * Creates a bare-bones user record
2824 *
2825 * @uses $CFG
7cf1c7bd 2826 * @param string $username New user's username to add to record
2827 * @param string $password New user's password to add to record
2828 * @param string $auth Form of authentication required
68fbd8e1 2829 * @return object A {@link $USER} object
7cf1c7bd 2830 * @todo Outline auth types and provide code example
2831 */
f76cfc7a 2832function create_user_record($username, $password, $auth='manual') {
366dfa60 2833 global $CFG;
71f9abf9 2834
1e22bc9c 2835 //just in case check text case
2836 $username = trim(moodle_strtolower($username));
71f9abf9 2837
03d820c7 2838 $authplugin = get_auth_plugin($auth);
2839
6bc1e5d5 2840 if ($newinfo = $authplugin->get_userinfo($username)) {
2841 $newinfo = truncate_userinfo($newinfo);
2842 foreach ($newinfo as $key => $value){
2843 $newuser->$key = addslashes($value);
e858f9da 2844 }
2845 }
f9903ed0 2846
85a1d4c9 2847 if (!empty($newuser->email)) {
2848 if (email_is_not_allowed($newuser->email)) {
2849 unset($newuser->email);
2850 }
2851 }
2852
f76cfc7a 2853 $newuser->auth = $auth;
faebaf0f 2854 $newuser->username = $username;
5e623a33 2855
e51917eb 2856 // fix for MDL-8480
2857 // user CFG lang for user if $newuser->lang is empty
2858 // or $user->lang is not an installed language
2859 $sitelangs = array_keys(get_list_of_languages());
2860 if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
2861 $newuser -> lang = $CFG->lang;
5e623a33 2862 }
faebaf0f 2863 $newuser->confirmed = 1;
d96466d2 2864 $newuser->lastip = getremoteaddr();
faebaf0f 2865 $newuser->timemodified = time();
03d820c7 2866 $newuser->mnethostid = $CFG->mnet_localhost_id;
f9903ed0 2867
b0ccd3fb 2868 if (insert_record('user', $newuser)) {
16793340 2869 $user = get_complete_user_data('username', $newuser->username);
da5bcc9f 2870 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
16793340 2871 set_user_preference('auth_forcepasswordchange', 1, $user->id);
2872 }
2873 update_internal_user_password($user, $password);
2874 return $user;
faebaf0f 2875 }
2876 return false;
2877}
2878
7cf1c7bd 2879/**
2880 * Will update a local user record from an external source
2881 *
2882 * @uses $CFG
2883 * @param string $username New user's username to add to record
89dcb99d 2884 * @return user A {@link $USER} object
7cf1c7bd 2885 */
03d820c7 2886function update_user_record($username, $authplugin) {
6bc1e5d5 2887 $username = trim(moodle_strtolower($username)); /// just in case check text case
2888
2889 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2890 $userauth = get_auth_plugin($oldinfo->auth);
2891
2892 if ($newinfo = $userauth->get_userinfo($username)) {
2893 $newinfo = truncate_userinfo($newinfo);
2894 foreach ($newinfo as $key => $value){
2895 $confkey = 'field_updatelocal_' . $key;
2896 if (!empty($userauth->config->$confkey) and $userauth->config->$confkey === 'onlogin') {
2897 $value = addslashes(stripslashes($value)); // Just in case
2898 set_field('user', $key, $value, 'username', $username)
2899 or error_log("Error updating $key for $username");
d35757eb 2900 }
2901 }
2902 }
6bc1e5d5 2903
7c12949d 2904 return get_complete_user_data('username', $username);
d35757eb 2905}
0609562b 2906
b36a8fc4 2907function truncate_userinfo($info) {
2908/// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2909/// which may have large fields
2910
2911 // define the limits
2912 $limit = array(
2913 'username' => 100,
8b9cfac4 2914 'idnumber' => 255,
8bcd295c 2915 'firstname' => 100,
2916 'lastname' => 100,
b36a8fc4 2917 'email' => 100,
2918 'icq' => 15,
2919 'phone1' => 20,
2920 'phone2' => 20,
2921 'institution' => 40,
2922 'department' => 30,
2923 'address' => 70,
2924 'city' => 20,
2925 'country' => 2,
2926 'url' => 255,
2927 );
361855e6 2928
b36a8fc4 2929 // apply where needed
2930 foreach (array_keys($info) as $key) {
2931 if (!empty($limit[$key])) {
adfc03f9 2932 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
361855e6 2933 }
b36a8fc4 2934 }
361855e6 2935
b36a8fc4 2936 return $info;
90afcf32 2937}
2938
2939/**
2940 * Marks user deleted in internal user database and notifies the auth plugin.
2941 * Also unenrols user from all roles and does other cleanup.
2942 * @param object $user Userobject before delete (without system magic quotes)
2943 * @return boolean success
2944 */
2945function delete_user($user) {
2946 global $CFG;
2947 require_once($CFG->libdir.'/grouplib.php');
ece966f0 2948 require_once($CFG->libdir.'/gradelib.php');
90afcf32 2949
2950 begin_sql();
2951
2952 // delete all grades - backup is kept in grade_grades_history table
2953 if ($grades = grade_grade::fetch_all(array('userid'=>$user->id))) {
2954 foreach ($grades as $grade) {
2955 $grade->delete('userdelete');
2956 }
2957 }
2958
2959 // remove from all groups
2960 delete_records('groups_members', 'userid', $user->id);
2961
2962 // unenrol from all roles in all contexts
2963 role_unassign(0, $user->id); // this might be slow but it is really needed - modules might do some extra cleanup!
2964
2965 // now do a final accesslib cleanup - removes all role assingments in user context and context itself
2966 delete_context(CONTEXT_USER, $user->id);
2967
13b31d6f 2968 require_once($CFG->dirroot.'/tag/lib.php');
2969 tag_set('user', $user->id, array());
2970
6d11d0ee 2971 // workaround for bulk deletes of users with the same email address
2972 $delname = addslashes("$user->email.".time());
2973 while (record_exists('user', 'username', $delname)) { // no need to use mnethostid here
2974 $delname++;
2975 }
2976
90afcf32 2977 // mark internal user record as "deleted"
2978 $updateuser = new object();
2979 $updateuser->id = $user->id;
2980 $updateuser->deleted = 1;
6d11d0ee 2981 $updateuser->username = $delname; // Remember it just in case
90afcf32 2982 $updateuser->email = ''; // Clear this field to free it up
2983 $updateuser->idnumber = ''; // Clear this field to free it up
2984 $updateuser->timemodified = time();
2985
2986 if (update_record('user', $updateuser)) {
2987 commit_sql();
2988 // notify auth plugin - do not block the delete even when plugin fails
2989 $authplugin = get_auth_plugin($user->auth);
2990 $authplugin->user_delete($user);
2991 return true;
2992
2993 } else {
2994 rollback_sql();
2995 return false;
2996 }
b36a8fc4 2997}
2998
7cf1c7bd 2999/**
3000 * Retrieve the guest user object
3001 *
3002 * @uses $CFG
89dcb99d 3003 * @return user A {@link $USER} object
7cf1c7bd 3004 */
0609562b 3005function guest_user() {
3006 global $CFG;
3007
b59c7ec0 3008 if ($newuser = get_record('user', 'username', 'guest', 'mnethostid', $CFG->mnet_localhost_id)) {
0609562b 3009 $newuser->confirmed = 1;
0609562b 3010 $newuser->lang = $CFG->lang;
d96466d2 3011 $newuser->lastip = getremoteaddr();
0609562b 3012 }
3013
3014 return $newuser;
3015}
3016
7cf1c7bd 3017/**
3018 * Given a username and password, this function looks them
3019 * up using the currently selected authentication mechanism,
3020 * and if the authentication is successful, it returns a
3021 * valid $user object from the 'user' table.
361855e6 3022 *
7cf1c7bd 3023 * Uses auth_ functions from the currently active auth module
3024 *
a238e822 3025 * After authenticate_user_login() returns success, you will need to
3026 * log that the user has logged in, and call complete_user_login() to set
3027 * the session up.
3028 *
7cf1c7bd 3029 * @uses $CFG
f5fd4347 3030 * @param string $username User's username (with system magic quotes)
3031 * @param string $password User's password (with system magic quotes)
89dcb99d 3032 * @return user|flase A {@link $USER} object or false if error
7cf1c7bd 3033 */
faebaf0f 3034function authenticate_user_login($username, $password) {
faebaf0f 3035
3036 global $CFG;
3037
c7b10b5f 3038 $authsenabled = get_enabled_auth_plugins();
39a5a35d 3039
16793340 3040 if ($user = get_complete_user_data('username', $username)) {
3041 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
3042 if ($auth=='nologin' or !is_enabled_auth($auth)) {
3043 add_to_log(0, 'login', 'error', 'index.php', $username);
3044 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3045 return false;
27286aeb 3046 }
16793340 3047 if (!empty($user->deleted)) {
3048 add_to_log(0, 'login', 'error', 'index.php', $username);
3049 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3050 return false;
d35757eb 3051 }
16793340 3052 $auths = array($auth);
3053
71f9abf9 3054 } else {
16793340 3055 $auths = $authsenabled;
3056 $user = new object();
3057 $user->id = 0; // User does not exist
27286aeb 3058 }
8f0cd6ef 3059
03d820c7 3060 foreach ($auths as $auth) {
3061 $authplugin = get_auth_plugin($auth);
466558e3 3062
16793340 3063 // on auth fail fall through to the next plugin
03d820c7 3064 if (!$authplugin->user_login($username, $password)) {
03d820c7 3065 continue;
3066 }
faebaf0f 3067
03d820c7 3068 // successful authentication
d613daf0 3069 if ($user->id) { // User already exists in database
71f9abf9 3070 if (empty($user->auth)) { // For some reason auth isn't set yet
3071 set_field('user', 'auth', $auth, 'username', $username);
16793340 3072 $user->auth = $auth;
71f9abf9 3073 }
16793340 3074
3075 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3076
03d820c7 3077 if (!$authplugin->is_internal()) { // update user record from external DB
3078 $user = update_user_record($username, get_auth_plugin($user->auth));
d35757eb 3079 }
faebaf0f 3080 } else {
16793340 3081 // if user not found, create him
71f9abf9 3082 $user = create_user_record($username, $password, $auth);
faebaf0f 3083 }
01af6da6 3084
6bc1e5d5 3085 $authplugin->sync_roles($user);
3086
f5fd4347 3087 foreach ($authsenabled as $hau) {
3088 $hauth = get_auth_plugin($hau);
3089 $hauth->user_authenticated_hook($user, $username, $password);
3090 }
3091
3092 /// Log in to a second system if necessary
3093 /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
3094 if (!empty($CFG->sso)) {
3095 include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
3096 if (function_exists('sso_user_login')) {
3097 if (!sso_user_login($username, $password)) { // Perform the signon process
3098 notify('Second sign-on failed');
3099 }
3100 }
3101 }
01af6da6 3102
a668c808 3103 if ($user->id===0) {
3104 return false;
3105 }
e582b65e 3106 return $user;
5e623a33 3107 }
3108
03d820c7 3109 // failed if all the plugins have failed
3110 add_to_log(0, 'login', 'error', 'index.php', $username);
0d626493 3111 if (debugging('', DEBUG_ALL)) {
3112 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3113 }
03d820c7 3114 return false;
f9903ed0 3115}
3116
a238e822 3117/**
3118 * Call to complete the user login process after authenticate_user_login()
3119 * has succeeded. It will setup the $USER variable and other required bits
3120 * and pieces.
3121 *
3122 * NOTE:
3123 * - It will NOT log anything -- up to the caller to decide what to log.
3124 *
3125 *
3126 *
3127 * @uses $CFG, $USER
3128 * @param string $user obj
3129 * @return user|flase A {@link $USER} object or false if error
3130 */
3131function complete_user_login($user) {
3132 global $CFG, $USER;
3133
ff396fd5 3134 $USER = $user; // this is required because we need to access preferences here!
3135
3136 reload_user_preferences();
a238e822 3137
3138 update_user_login_times();
3139 if (empty($CFG->nolastloggedin)) {
3140 set_moodle_cookie($USER->username);
3141 } else {
3142 // do not store last logged in user in cookie
3143 // auth plugins can temporarily override this from loginpage_hook()
3144 // do not save $CFG->nolastloggedin in database!
3145 set_moodle_cookie('nobody');
3146 }
3147 set_login_session_preferences();
3148
8f9e1d2c 3149 // Call enrolment plugins
3150 check_enrolment_plugins($user);
3151
a238e822 3152 /// This is what lets the user do anything on the site :-)
3153 load_all_capabilities();
3154
3155 /// Select password change url
3156 $userauth = get_auth_plugin($USER->auth);
3157
3158 /// check whether the user should be changing password
3159 if (get_user_preferences('auth_forcepasswordchange', false)){
3160 if ($userauth->can_change_password()) {
3161 if ($changeurl = $userauth->change_password_url()) {
3162 redirect($changeurl);
3163 } else {
3164 redirect($CFG->httpswwwroot.'/login/change_password.php');
3165 }
3166 } else {
a8ee7194 3167 print_error('nopasswordchangeforced', 'auth');
a238e822 3168 }
3169 }
3170 return $USER;
3171}
3172
df193157 3173/**
4908ad3e 3174 * Compare password against hash stored in internal user table.
df193157 3175 * If necessary it also updates the stored hash to new format.
5e623a33 3176 *
df193157 3177 * @param object user
3178 * @param string plain text password
3179 * @return bool is password valid?
3180 */
3181function validate_internal_user_password(&$user, $password) {
3182 global $CFG;
3183
4908ad3e 3184 if (!isset($CFG->passwordsaltmain)) {
3185 $CFG->passwordsaltmain = '';
3186 }
3187
df193157 3188 $validated = false;
3189
a044c05d 3190 // get password original encoding in case it was not updated to unicode yet
fb773106 3191 $textlib = textlib_get_instance();
810944af 3192 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
df193157 3193
4908ad3e 3194 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
3195 or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
df193157 3196 $validated = true;
4908ad3e 3197 } else {
aaeaa4b0 3198 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
4908ad3e 3199 $alt = 'passwordsaltalt'.$i;
3200 if (!empty($CFG->$alt)) {
3201 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
3202 $validated = true;
3203 break;
3204 }
3205 }
3206 }
df193157 3207 }
3208
3209 if ($validated) {
4908ad3e 3210 // force update of password hash using latest main password salt and encoding if needed
df193157 3211 update_internal_user_password($user, $password);
3212 }
3213
3214 return $validated;
3215}
3216
3217/**
3218 * Calculate hashed value from password using current hash mechanism.
5e623a33 3219 *
df193157 3220 * @param string password
3221 * @return string password hash
3222 */
3223function hash_internal_user_password($password) {
4908ad3e 3224 global $CFG;
3225
3226 if (isset($CFG->passwordsaltmain)) {
3227 return md5($password.$CFG->passwordsaltmain);
3228 } else {
3229 return md5($password);
3230 }
df193157 3231}
3232
3233/**
3234 * Update pssword hash in user object.
5e623a33 3235 *
df193157 3236 * @param object user
3237 * @param string plain text password
3238 * @param bool store changes also in db, default true
3239 * @return true if hash changed
3240 */
16793340 3241function update_internal_user_password(&$user, $password) {
df193157 3242 global $CFG;
3243
03d820c7 3244 $authplugin = get_auth_plugin($user->auth);
16793340 3245 if (!empty($authplugin->config->preventpassindb)) {
df193157 3246 $hashedpassword = 'not cached';
3247 } else {
3248 $hashedpassword = hash_internal_user_password($password);
3249 }
3250
b7b50143 3251 return set_field('user', 'password', $hashedpassword, 'id', $user->id);
df193157 3252}
3253
7c12949d 3254/**
3255 * Get a complete user record, which includes all the info
5c98bf9e 3256 * in the user record
7c12949d 3257 * Intended for setting as $USER session variable
3258 *
3259 * @uses $CFG
3260 * @uses SITEID
e1ecf0a0 3261 * @param string $field The user field to be checked for a given value.
7c12949d 3262 * @param string $value The value to match for $field.
3263 * @return user A {@link $USER} object.