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