moodle_page: MDL-12212 deprecate page_import_types and clean up file
[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
dcf6d93c 1867/**
9152fc99 1868 * Setup all global $CFG course variables, set locale and also themes
1869 * This function can be used on pages that do not require login instead of require_login()
1870 *
dcf6d93c 1871 * @param mixed $courseorid id of the course or course object
1872 */
1873function course_setup($courseorid=0) {
ae040d4b 1874 global $COURSE, $SITE, $DB;
dcf6d93c 1875
1876/// Redefine global $COURSE if needed
1877 if (empty($courseorid)) {
1878 // no change in global $COURSE - for backwards compatibiltiy
5e623a33 1879 // if require_rogin() used after require_login($courseid);
dcf6d93c 1880 } else if (is_object($courseorid)) {
1881 $COURSE = clone($courseorid);
1882 } else {
a6a251c7 1883 if ($courseorid == SITEID) {
9152fc99 1884 $COURSE = clone($SITE);
dcf6d93c 1885 } else {
ae040d4b 1886 if (!$COURSE = $DB->get_record('course', array('id'=>$courseorid))) {
2f137aa1 1887 print_error('invalidcourseid');
dcf6d93c 1888 }
1889 }
1890 }
1891
9152fc99 1892/// set locale and themes
dcf6d93c 1893 moodle_setlocale();
dcf6d93c 1894 theme_setup();
1895
dcf6d93c 1896}
c4d0753b 1897
93f66983 1898/**
1899 * Returns full login url.
1900 *
1901 * @param bool $loginguest add login guest param
1902 * @return string login url
1903 */
1904function get_login_url($loginguest=false) {
1905 global $CFG;
1906
1907 if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
1908 $loginguest = $loginguest ? '?loginguest=true' : '';
1909 $url = "$CFG->wwwroot/login/index.php$loginguest";
1910
1911 } else {
1912 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1913 $url = "$wwwroot/login/index.php";
1914 }
1915
1916 return $url;
1917}
1918
7cf1c7bd 1919/**
ec81373f 1920 * This function checks that the current user is logged in and has the
1921 * required privileges
1922 *
7cf1c7bd 1923 * This function checks that the current user is logged in, and optionally
ec81373f 1924 * whether they are allowed to be in a particular course and view a particular
1925 * course module.
1926 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 1927 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 1928 * case they are automatically logged in as guests.
1929 * If $courseid is given and the user is not enrolled in that course then the
1930 * user is redirected to the course enrolment page.
1931 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1932 * in the course then the user is redirected to the course home page.
7cf1c7bd 1933 *
7cf1c7bd 1934 * @uses $CFG
c6d15803 1935 * @uses $SESSION
7cf1c7bd 1936 * @uses $USER
1937 * @uses $FULLME
c6d15803 1938 * @uses SITEID
f07fa644 1939 * @uses $COURSE
33ebaf7c 1940 * @param mixed $courseorid id of the course or course object
bbd3f2c4 1941 * @param bool $autologinguest
1942 * @param object $cm course module object
f4013c10 1943 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
1944 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
1945 * in order to keep redirects working properly. MDL-14495
7cf1c7bd 1946 */
f4013c10 1947function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsurltome=true) {
083c3743 1948 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
d8ba183c 1949
083c3743 1950/// setup global $COURSE, themes, language and locale
dcf6d93c 1951 course_setup($courseorid);
be933850 1952
1845f8b8 1953/// If the user is not even logged in yet then make sure they are
083c3743 1954 if (!isloggedin()) {
1955 //NOTE: $USER->site check was obsoleted by session test cookie,
1956 // $USER->confirmed test is in login/index.php
f4013c10 1957 if ($setwantsurltome) {
1958 $SESSION->wantsurl = $FULLME;
1959 }
b0ccd3fb 1960 if (!empty($_SERVER['HTTP_REFERER'])) {
1961 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
9f44d972 1962 }
ad56b737 1963 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
93f66983 1964 $loginguest = true;
8a33e371 1965 } else {
93f66983 1966 $loginguest = false;
8a33e371 1967 }
93f66983 1968 redirect(get_login_url($loginguest));
1969 exit; // never reached
f9903ed0 1970 }
808a3baa 1971
f6f66b03 1972/// loginas as redirection if needed
b7b64ff2 1973 if ($COURSE->id != SITEID and session_is_loggedinas()) {
f6f66b03 1974 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
1975 if ($USER->loginascontext->instanceid != $COURSE->id) {
3887fe4a 1976 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
5e623a33 1977 }
f6f66b03 1978 }
1979 }
1980
5602f7cf 1981/// check whether the user should be changing password (but only if it is REALLY them)
b7b64ff2 1982 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
21e2dcd9 1983 $userauth = get_auth_plugin($USER->auth);
03d820c7 1984 if ($userauth->can_change_password()) {
20fde7b1 1985 $SESSION->wantsurl = $FULLME;
80274abf 1986 if ($changeurl = $userauth->change_password_url()) {
9696bd89 1987 //use plugin custom url
80274abf 1988 redirect($changeurl);
1437f0a5 1989 } else {
9696bd89 1990 //use moodle internal method
1991 if (empty($CFG->loginhttps)) {
1992 redirect($CFG->wwwroot .'/login/change_password.php');
1993 } else {
1994 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1995 redirect($wwwroot .'/login/change_password.php');
1996 }
1437f0a5 1997 }
d35757eb 1998 } else {
a8ee7194 1999 print_error('nopasswordchangeforced', 'auth');
d35757eb 2000 }
2001 }
083c3743 2002
1845f8b8 2003/// Check that the user account is properly set up
808a3baa 2004 if (user_not_fully_set_up($USER)) {
20fde7b1 2005 $SESSION->wantsurl = $FULLME;
b0ccd3fb 2006 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 2007 }
d8ba183c 2008
1845f8b8 2009/// Make sure the USER has a sesskey set up. Used for checking script parameters.
04280e85 2010 sesskey();
366dfa60 2011
027a1604 2012 // Check that the user has agreed to a site policy if there is one
2013 if (!empty($CFG->sitepolicy)) {
2014 if (!$USER->policyagreed) {
957b5198 2015 $SESSION->wantsurl = $FULLME;
027a1604 2016 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 2017 }
1695b680 2018 }
2019
21e2dcd9 2020 // Fetch the system context, we are going to use it a lot.
2021 $sysctx = get_context_instance(CONTEXT_SYSTEM);
2022
1845f8b8 2023/// If the site is currently under maintenance, then print a message
21e2dcd9 2024 if (!has_capability('moodle/site:config', $sysctx)) {
eeefd0b0 2025 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
1695b680 2026 print_maintenance_message();
20fde7b1 2027 exit;
1695b680 2028 }
027a1604 2029 }
2030
f8e3d5f0 2031/// groupmembersonly access control
2032 if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2033 if (isguestuser() or !groups_has_membership($cm)) {
a8ee7194 2034 print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
f8e3d5f0 2035 }
2036 }
1845f8b8 2037
21e2dcd9 2038 // Fetch the course context, and prefetch its child contexts
2039 if (!isset($COURSE->context)) {
2040 if ( ! $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id) ) {
ae040d4b 2041 print_error('nocontext');
21e2dcd9 2042 }
2043 }
48f9c073 2044 if (!empty($cm) && !isset($cm->context)) {
2045 if ( ! $cm->context = get_context_instance(CONTEXT_MODULE, $cm->id) ) {
2046 print_error('nocontext');
2047 }
2048 }
82bd6a5e 2049
2050 // Conditional activity access control
2051 if(!empty($CFG->enableavailability) and $cm) {
2052 // We cache conditional access in session
2053 if(!isset($SESSION->conditionaccessok)) {
013376de 2054 $SESSION->conditionaccessok = array();
82bd6a5e 2055 }
2056 // If you have been allowed into the module once then you are allowed
2057 // in for rest of session, no need to do conditional checks
013376de 2058 if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) {
82bd6a5e 2059 // Get condition info (does a query for the availability table)
b3d960e6 2060 require_once($CFG->libdir.'/conditionlib.php');
013376de 2061 $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE);
82bd6a5e 2062 // Check condition for user (this will do a query if the availability
2063 // information depends on grade or completion information)
013376de 2064 if ($ci->is_available($junk) ||
48f9c073 2065 has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
013376de 2066 $SESSION->conditionaccessok[$cm->id] = true;
82bd6a5e 2067 } else {
2068 print_error('activityiscurrentlyhidden');
2069 }
2070 }
2071 }
2072
33ebaf7c 2073 if ($COURSE->id == SITEID) {
21e2dcd9 2074 /// Eliminate hidden site activities straight away
ae040d4b 2075 if (!empty($cm) && !$cm->visible
48f9c073 2076 && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
33ebaf7c 2077 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
e3512050 2078 }
341b5ed2 2079 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
33ebaf7c 2080 return;
881a77bf 2081
5e623a33 2082 } else {
1845f8b8 2083
21e2dcd9 2084 /// Check if the user can be in a particular course
2085 if (empty($USER->access['rsw'][$COURSE->context->path])) {
1cf2e21b 2086 //
a8ee7194 2087 // MDL-13900 - If the course or the parent category are hidden
2088 // and the user hasn't the 'course:viewhiddencourses' capability, prevent access
1cf2e21b 2089 //
a8ee7194 2090 if ( !($COURSE->visible && course_parent_visible($COURSE)) &&
2091 !has_capability('moodle/course:viewhiddencourses', $COURSE->context)) {
1cf2e21b 2092 print_header_simple();
2093 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2094 }
a8ee7194 2095 }
2096
f71346e2 2097 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
2098
21e2dcd9 2099 if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) {
33ebaf7c 2100 if ($COURSE->guest == 1) {
eef879ec 2101 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
21e2dcd9 2102 $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access);
f71346e2 2103 }
2104 }
2105
1845f8b8 2106 /// If the user is a guest then treat them according to the course policy about guests
2107
21e2dcd9 2108 if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) {
5f431c1b 2109 if (has_capability('moodle/site:doanything', $sysctx)) {
2110 // administrators must be able to access any course - even if somebody gives them guest access
341b5ed2 2111 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
b03f7215 2112 return;
5f431c1b 2113 }
2114
33ebaf7c 2115 switch ($COURSE->guest) { /// Check course policy about guest access
1845f8b8 2116
ae040d4b 2117 case 1: /// Guests always allowed
21e2dcd9 2118 if (!has_capability('moodle/course:view', $COURSE->context)) { // Prohibited by capability
1845f8b8 2119 print_header_simple();
93f66983 2120 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url());
1845f8b8 2121 }
2122 if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
5e623a33 2123 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
1845f8b8 2124 get_string('activityiscurrentlyhidden'));
2125 }
2126
341b5ed2 2127 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
1845f8b8 2128 return; // User is allowed to see this course
2129
2130 break;
2131
5e623a33 2132 case 2: /// Guests allowed with key
33ebaf7c 2133 if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
341b5ed2 2134 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
b1f318a6 2135 return true;
2136 }
2137 // otherwise drop through to logic below (--> enrol.php)
1845f8b8 2138 break;
bbbf2d40 2139
1845f8b8 2140 default: /// Guests not allowed
0be6f678 2141 $strloggedinasguest = get_string('loggedinasguest');
2142 print_header_simple('', '',
2143 build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc'))));
21e2dcd9 2144 if (empty($USER->access['rsw'][$COURSE->context->path])) { // Normal guest
93f66983 2145 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url());
21596567 2146 } else {
6ba65fa0 2147 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
33ebaf7c 2148 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
2149 print_footer($COURSE);
21596567 2150 exit;
2151 }
1845f8b8 2152 break;
2153 }
2154
2155 /// For non-guests, check if they have course view access
2156
21e2dcd9 2157 } else if (has_capability('moodle/course:view', $COURSE->context)) {
b7b64ff2 2158 if (session_is_loggedinas()) { // Make sure the REAL person can also access this course
2159 $realuser = session_get_realuser();
6132768e 2160 if (!has_capability('moodle/course:view', $COURSE->context, $realuser->id)) {
1845f8b8 2161 print_header_simple();
b0ccd3fb 2162 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
cb909d74 2163 }
3ce2f1e0 2164 }
1845f8b8 2165
2166 /// Make sure they can read this activity too, if specified
2167
2bf69a85 2168 if (!empty($cm) && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
ec81373f 2169 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
2170 }
341b5ed2 2171 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
1845f8b8 2172 return; // User is allowed to see this course
2173
da5c172a 2174 }
f9903ed0 2175
9ca3b4f3 2176
1845f8b8 2177 /// Currently not enrolled in the course, so see if they want to enrol
da5c172a 2178 $SESSION->wantsurl = $FULLME;
33ebaf7c 2179 redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
da5c172a 2180 die;
2181 }
f9903ed0 2182}
2183
c4d0753b 2184
2185
2186/**
2187 * This function just makes sure a user is logged out.
2188 *
2189 * @uses $CFG
2190 * @uses $USER
2191 */
2192function require_logout() {
dd9e22f8 2193 global $USER;
c4d0753b 2194
111e2360 2195 if (isloggedin()) {
c4d0753b 2196 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2197
533f7910 2198 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2199 foreach($authsequence as $authname) {
2200 $authplugin = get_auth_plugin($authname);
2201 $authplugin->prelogout_hook();
81693ac7 2202 }
c4d0753b 2203 }
2204
56949c17 2205 session_get_instance()->terminate_current();
c4d0753b 2206}
2207
7cf1c7bd 2208/**
2209 * This is a weaker version of {@link require_login()} which only requires login
2210 * when called from within a course rather than the site page, unless
2211 * the forcelogin option is turned on.
2212 *
2213 * @uses $CFG
33ebaf7c 2214 * @param mixed $courseorid The course object or id in question
bbd3f2c4 2215 * @param bool $autologinguest Allow autologin guests if that is wanted
4febb58f 2216 * @param object $cm Course activity module if known
f4013c10 2217 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2218 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2219 * in order to keep redirects working properly. MDL-14495
7cf1c7bd 2220 */
f4013c10 2221function require_course_login($courseorid, $autologinguest=true, $cm=null, $setwantsurltome=true) {
f950af3c 2222 global $CFG;
1596edff 2223 if (!empty($CFG->forcelogin)) {
33ebaf7c 2224 // login required for both SITE and courses
f4013c10 2225 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
63c9ee99 2226
2227 } else if (!empty($cm) and !$cm->visible) {
2228 // always login for hidden activities
f4013c10 2229 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
63c9ee99 2230
39de90ac 2231 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2232 or (!is_object($courseorid) and $courseorid == SITEID)) {
33ebaf7c 2233 //login for SITE not required
341b5ed2 2234 user_accesstime_log(SITEID);
63c9ee99 2235 return;
2236
33ebaf7c 2237 } else {
2238 // course login always required
f4013c10 2239 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
f950af3c 2240 }
2241}
2242
61c6071f 2243/**
2244 * Require key login. Function terminates with error if key not found or incorrect.
2245 * @param string $script unique script identifier
2246 * @param int $instance optional instance id
2247 */
2248function require_user_key_login($script, $instance=null) {
82dd4f42 2249 global $USER, $SESSION, $CFG, $DB;
61c6071f 2250
82dd4f42 2251 if (!NO_MOODLE_COOKIES) {
2f137aa1 2252 print_error('sessioncookiesdisable');
61c6071f 2253 }
2254
2255/// extra safety
2256 @session_write_close();
2257
2258 $keyvalue = required_param('key', PARAM_ALPHANUM);
2259
ae040d4b 2260 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2f137aa1 2261 print_error('invalidkey');
61c6071f 2262 }
2263
2264 if (!empty($key->validuntil) and $key->validuntil < time()) {
2f137aa1 2265 print_error('expiredkey');
61c6071f 2266 }
2267
e436033f 2268 if ($key->iprestriction) {
2269 $remoteaddr = getremoteaddr();
2270 if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2f137aa1 2271 print_error('ipmismatch');
e436033f 2272 }
61c6071f 2273 }
2274
ae040d4b 2275 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2f137aa1 2276 print_error('invaliduserid');
61c6071f 2277 }
2278
2279/// emulate normal session
27df7ae8 2280 session_set_user($user);
61c6071f 2281
e2fa911b 2282/// note we are not using normal login
2283 if (!defined('USER_KEY_LOGIN')) {
2284 define('USER_KEY_LOGIN', true);
2285 }
2286
61c6071f 2287/// return isntance id - it might be empty
2288 return $key->instance;
2289}
2290
2291/**
2292 * Creates a new private user access key.
2293 * @param string $script unique target identifier
2294 * @param int $userid
2295 * @param instance $int optional instance id
2296 * @param string $iprestriction optional ip restricted access
2297 * @param timestamp $validuntil key valid only until given data
2298 * @return string access key value
2299 */
2300function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
ae040d4b 2301 global $DB;
2302
61c6071f 2303 $key = new object();
2304 $key->script = $script;
2305 $key->userid = $userid;
2306 $key->instance = $instance;
2307 $key->iprestriction = $iprestriction;
2308 $key->validuntil = $validuntil;
2309 $key->timecreated = time();
2310
2311 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
ae040d4b 2312 while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
61c6071f 2313 // must be unique
2314 $key->value = md5($userid.'_'.time().random_string(40));
2315 }
2316
ae040d4b 2317 if (!$DB->insert_record('user_private_key', $key)) {
2f137aa1 2318 print_error('cannotinsertkey');
61c6071f 2319 }
2320
2321 return $key->value;
2322}
2323
7cf1c7bd 2324/**
2325 * Modify the user table by setting the currently logged in user's
2326 * last login to now.
2327 *
2328 * @uses $USER
bbd3f2c4 2329 * @return bool
7cf1c7bd 2330 */
1d881d92 2331function update_user_login_times() {
ae040d4b 2332 global $USER, $DB;
1d881d92 2333
53467aa6 2334 $user = new object();
1d881d92 2335 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2a2f5f11 2336 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1d881d92 2337
2338 $user->id = $USER->id;
2339
013376de 2340 $DB->update_record('user', $user);
2341 return true;
1d881d92 2342}
2343
7cf1c7bd 2344/**
2345 * Determines if a user has completed setting up their account.
2346 *
89dcb99d 2347 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
bbd3f2c4 2348 * @return bool
7cf1c7bd 2349 */
808a3baa 2350function user_not_fully_set_up($user) {
bb64b51a 2351 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
2352}
2353
2354function over_bounce_threshold($user) {
ae040d4b 2355 global $CFG, $DB;
d2a9f7cc 2356
bb64b51a 2357 if (empty($CFG->handlebounces)) {
2358 return false;
2359 }
e0ec2d45 2360
2361 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2362 return false;
2363 }
2364
bb64b51a 2365 // set sensible defaults
2366 if (empty($CFG->minbounces)) {
2367 $CFG->minbounces = 10;
2368 }
2369 if (empty($CFG->bounceratio)) {
2370 $CFG->bounceratio = .20;
2371 }
2372 $bouncecount = 0;
2373 $sendcount = 0;
ae040d4b 2374 if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
bb64b51a 2375 $bouncecount = $bounce->value;
2376 }
ae040d4b 2377 if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
bb64b51a 2378 $sendcount = $send->value;
2379 }
2380 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2381}
2382
d2a9f7cc 2383/**
bb64b51a 2384 * @param $user - object containing an id
2385 * @param $reset - will reset the count to 0
2386 */
2387function set_send_count($user,$reset=false) {
ae040d4b 2388 global $DB;
2389
e0ec2d45 2390 if (empty($user->id)) { /// No real (DB) user, nothing to do here.
2391 return;
2392 }
2393
ae040d4b 2394 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
bb64b51a 2395 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
ae040d4b 2396 $DB->update_record('user_preferences', $pref);
bb64b51a 2397 }
2398 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2399 // make a new one
ae040d4b 2400 $pref = new object();
2401 $pref->name = 'email_send_count';
2402 $pref->value = 1;
bb64b51a 2403 $pref->userid = $user->id;
ae040d4b 2404 $DB->insert_record('user_preferences', $pref, false);
bb64b51a 2405 }
2406}
2407
d2a9f7cc 2408/**
bb64b51a 2409* @param $user - object containing an id
2410 * @param $reset - will reset the count to 0
2411 */
2412function set_bounce_count($user,$reset=false) {
ae040d4b 2413 global $DB;
2414
2415 if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
bb64b51a 2416 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
ae040d4b 2417 $DB->update_record('user_preferences', $pref);
bb64b51a 2418 }
2419 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2420 // make a new one
ae040d4b 2421 $pref = new object();
2422 $pref->name = 'email_bounce_count';
2423 $pref->value = 1;
bb64b51a 2424 $pref->userid = $user->id;
ae040d4b 2425 $DB->insert_record('user_preferences', $pref, false);
bb64b51a 2426 }
808a3baa 2427}
f9903ed0 2428
7cf1c7bd 2429/**
2430 * Keeps track of login attempts
2431 *
2432 * @uses $SESSION
2433 */
f9903ed0 2434function update_login_count() {
2435 global $SESSION;
2436
2437 $max_logins = 10;
2438
2439 if (empty($SESSION->logincount)) {
2440 $SESSION->logincount = 1;
2441 } else {
2442 $SESSION->logincount++;
2443 }
2444
2445 if ($SESSION->logincount > $max_logins) {
9fa49e22 2446 unset($SESSION->wantsurl);
a8ee7194 2447 print_error('errortoomanylogins');
d578afc8 2448 }
2449}
2450
7cf1c7bd 2451/**
2452 * Resets login attempts
2453 *
2454 * @uses $SESSION
2455 */
9fa49e22 2456function reset_login_count() {
9fa49e22 2457 global $SESSION;
d578afc8 2458
9fa49e22 2459 $SESSION->logincount = 0;
d578afc8 2460}
2461
b61efafb 2462function sync_metacourses() {
ae040d4b 2463 global $DB;
b61efafb 2464
ae040d4b 2465 if (!$courses = $DB->get_records('course', array('metacourse'=>1))) {
b61efafb 2466 return;
2467 }
d2a9f7cc 2468
b61efafb 2469 foreach ($courses as $course) {
1aad4310 2470 sync_metacourse($course);
b61efafb 2471 }
2472}
2473
b61efafb 2474/**
2475 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
5e623a33 2476 *
123545bc 2477 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
d2a9f7cc 2478 */
1aad4310 2479function sync_metacourse($course) {
ae040d4b 2480 global $CFG, $DB;
b61efafb 2481
123545bc 2482 // Check the course is valid.
1aad4310 2483 if (!is_object($course)) {
ae040d4b 2484 if (!$course = $DB->get_record('course', array('id'=>$course))) {
1aad4310 2485 return false; // invalid course id
b61efafb 2486 }
b61efafb 2487 }
5e623a33 2488
123545bc 2489 // Check that we actually have a metacourse.
1aad4310 2490 if (empty($course->metacourse)) {
123545bc 2491 return false;
755c8d58 2492 }
87671466 2493
b3170072 2494 // Get a list of roles that should not be synced.
4db9bff7 2495 if (!empty($CFG->nonmetacoursesyncroleids)) {
b3170072 2496 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
5e623a33 2497 } else {
b3170072 2498 $roleexclusions = '';
2499 }
2500
123545bc 2501 // Get the context of the metacourse.
1aad4310 2502 $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
e1ecf0a0 2503
123545bc 2504 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
b79da3ac 2505 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
1aad4310 2506 $managers = array_keys($users);
2507 } else {
2508 $managers = array();
b61efafb 2509 }
2510
123545bc 2511 // Get assignments of a user to a role that exist in a child course, but
2512 // not in the meta coure. That is, get a list of the assignments that need to be made.
ae040d4b 2513 if (!$assignments = $DB->get_records_sql("
2514 SELECT ra.id, ra.roleid, ra.userid
2515 FROM {role_assignments} ra, {context} con, {course_meta} cm
2516 WHERE ra.contextid = con.id AND
2517 con.contextlevel = ".CONTEXT_COURSE." AND
2518 con.instanceid = cm.child_course AND
2519 cm.parent_course = ? AND
2520 $roleexclusions
2521 NOT EXISTS (
2522 SELECT 1
2523 FROM {role_assignments} ra2
2524 WHERE ra2.userid = ra.userid AND
2525 ra2.roleid = ra.roleid AND
2526 ra2.contextid = ?
2527 )", array($course->id, $context->id))) {
123545bc 2528 $assignments = array();
2529 }
2530
2531 // Get assignments of a user to a role that exist in the meta course, but
2532 // not in any child courses. That is, get a list of the unassignments that need to be made.
ae040d4b 2533 if (!$unassignments = $DB->get_records_sql("
2534 SELECT ra.id, ra.roleid, ra.userid
2535 FROM {role_assignments} ra
2536 WHERE ra.contextid = ? AND
2537 $roleexclusions
2538 NOT EXISTS (
2539 SELECT 1
2540 FROM {role_assignments} ra2, {context} con2, {course_meta} cm
2541 WHERE ra2.userid = ra.userid AND
2542 ra2.roleid = ra.roleid AND
2543 ra2.contextid = con2.id AND
2544 con2.contextlevel = " . CONTEXT_COURSE . " AND
2545 con2.instanceid = cm.child_course AND
2546 cm.parent_course = ?
2547 )", array($context->id, $course->id))) {
123545bc 2548 $unassignments = array();
2549 }
2550
2551 $success = true;
2552
2553 // Make the unassignments, if they are not managers.
2554 foreach ($unassignments as $unassignment) {
2555 if (!in_array($unassignment->userid, $managers)) {
2556 $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
1aad4310 2557 }
755c8d58 2558 }
e1ecf0a0 2559
123545bc 2560 // Make the assignments.
2561 foreach ($assignments as $assignment) {
2562 $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id) && $success;
b61efafb 2563 }
755c8d58 2564
123545bc 2565 return $success;
5e623a33 2566
1aad4310 2567// TODO: finish timeend and timestart
2568// maybe we could rely on cron job to do the cleaning from time to time
b61efafb 2569}
2570
d2a9f7cc 2571/**
b61efafb 2572 * Adds a record to the metacourse table and calls sync_metacoures
2573 */
2574function add_to_metacourse ($metacourseid, $courseid) {
ae040d4b 2575 global $DB;
d2a9f7cc 2576
ae040d4b 2577 if (!$metacourse = $DB->get_record("course", array("id"=>$metacourseid))) {
b61efafb 2578 return false;
2579 }
d2a9f7cc 2580
ae040d4b 2581 if (!$course = $DB->get_record("course", array("id"=>$courseid))) {
b61efafb 2582 return false;
2583 }
2584
ae040d4b 2585 if (!$record = $DB->get_record("course_meta", array("parent_course"=>$metacourseid, "child_course"=>$courseid))) {
53467aa6 2586 $rec = new object();
b61efafb 2587 $rec->parent_course = $metacourseid;
ae040d4b 2588 $rec->child_course = $courseid;
013376de 2589 $DB->insert_record('course_meta', $rec);
b61efafb 2590 return sync_metacourse($metacourseid);
2591 }
2592 return true;
d2a9f7cc 2593
b61efafb 2594}
2595
d2a9f7cc 2596/**
b61efafb 2597 * Removes the record from the metacourse table and calls sync_metacourse
2598 */
2599function remove_from_metacourse($metacourseid, $courseid) {
ae040d4b 2600 global $DB;
b61efafb 2601
ae040d4b 2602 if ($DB->delete_records('course_meta', array('parent_course'=>$metacourseid, 'child_course'=>$courseid))) {
b61efafb 2603 return sync_metacourse($metacourseid);
2604 }
2605 return false;
2606}
2607
2608
7c12949d 2609/**
2610 * Determines if a user is currently logged in
2611 *
2612 * @uses $USER
bbd3f2c4 2613 * @return bool
7c12949d 2614 */
2615function isloggedin() {
2616 global $USER;
2617
2618 return (!empty($USER->id));
2619}
2620
2a919fd7 2621/**
2622 * Determines if a user is logged in as real guest user with username 'guest'.
2623 * This function is similar to original isguest() in 1.6 and earlier.
2624 * Current isguest() is deprecated - do not use it anymore.
2625 *
2626 * @param $user mixed user object or id, $USER if not specified
2627 * @return bool true if user is the real guest user, false if not logged in or other user
2628 */
2629function isguestuser($user=NULL) {
ae040d4b 2630 global $USER, $DB;
2631
2a919fd7 2632 if ($user === NULL) {
2633 $user = $USER;
2634 } else if (is_numeric($user)) {
ae040d4b 2635 $user = $DB->get_record('user', array('id'=>$user), 'id, username');
2a919fd7 2636 }
2637
2638 if (empty($user->id)) {
2639 return false; // not logged in, can not be guest
2640 }
2641
2642 return ($user->username == 'guest');
2643}
7c12949d 2644
7cf1c7bd 2645/**
e6260a45 2646 * Determines if the currently logged in user is in editing mode.
2647 * Note: originally this function had $userid parameter - it was not usable anyway
7cf1c7bd 2648 *
0df35335 2649 * @uses $USER, $PAGE
bbd3f2c4 2650 * @return bool
7cf1c7bd 2651 */
0df35335 2652function isediting() {
2653 global $USER, $PAGE;
e6260a45 2654
2655 if (empty($USER->editing)) {
9c9f7d77 2656 return false;
0df35335 2657 } elseif (is_object($PAGE) && method_exists($PAGE,'user_allowed_editing')) {
2658 return $PAGE->user_allowed_editing();
9c9f7d77 2659 }
0df35335 2660 return true;//false;
2c309dc2 2661}
2662
7cf1c7bd 2663/**
2664 * Determines if the logged in user is currently moving an activity
2665 *
2666 * @uses $USER
c6d15803 2667 * @param int $courseid The id of the course being tested
bbd3f2c4 2668 * @return bool
7cf1c7bd 2669 */
7977cffd 2670function ismoving($courseid) {
7977cffd 2671 global $USER;
2672
2673 if (!empty($USER->activitycopy)) {
2674 return ($USER->activitycopycourse == $courseid);
2675 }
2676 return false;
2677}
2678
7cf1c7bd 2679/**
2680 * Given an object containing firstname and lastname
2681 * values, this function returns a string with the
2682 * full name of the person.
2683 * The result may depend on system settings
2684 * or language. 'override' will force both names
361855e6 2685 * to be used even if system settings specify one.
68fbd8e1 2686 *
7cf1c7bd 2687 * @uses $CFG
2688 * @uses $SESSION
68fbd8e1 2689 * @param object $user A {@link $USER} object to get full name of
2690 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
7cf1c7bd 2691 */
e2cd5065 2692function fullname($user, $override=false) {
f374fb10 2693 global $CFG, $SESSION;
2694
6527c077 2695 if (!isset($user->firstname) and !isset($user->lastname)) {
2696 return '';
2697 }
2698
4c202228 2699 if (!$override) {
2700 if (!empty($CFG->forcefirstname)) {
2701 $user->firstname = $CFG->forcefirstname;
2702 }
2703 if (!empty($CFG->forcelastname)) {
2704 $user->lastname = $CFG->forcelastname;
2705 }
2706 }
2707
f374fb10 2708 if (!empty($SESSION->fullnamedisplay)) {
2709 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
2710 }
e2cd5065 2711
775f811a 2712 if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
b0ccd3fb 2713 return $user->firstname .' '. $user->lastname;
b5cbb64d 2714
2715 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 2716 return $user->lastname .' '. $user->firstname;
e2cd5065 2717
b5cbb64d 2718 } else if ($CFG->fullnamedisplay == 'firstname') {
2719 if ($override) {
2720 return get_string('fullnamedisplay', '', $user);
2721 } else {
2722 return $user->firstname;
2723 }
2724 }
e2cd5065 2725
b5cbb64d 2726 return get_string('fullnamedisplay', '', $user);
e2cd5065 2727}
2728
7cf1c7bd 2729/**
03d820c7 2730 * Returns whether a given authentication plugin exists.
7cf1c7bd 2731 *
2732 * @uses $CFG
03d820c7 2733 * @param string $auth Form of authentication to check for. Defaults to the
2734 * global setting in {@link $CFG}.
2735 * @return boolean Whether the plugin is available.
7cf1c7bd 2736 */
16793340 2737function exists_auth_plugin($auth) {
03d820c7 2738 global $CFG;
5e623a33 2739
03d820c7 2740 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2741 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2742 }
2743 return false;
2744}
ba7166c3 2745
03d820c7 2746/**
2747 * Checks if a given plugin is in the list of enabled authentication plugins.
5e623a33 2748 *
03d820c7 2749 * @param string $auth Authentication plugin.
2750 * @return boolean Whether the plugin is enabled.
2751 */
16793340 2752function is_enabled_auth($auth) {
16793340 2753 if (empty($auth)) {
2754 return false;
03d820c7 2755 }
16793340 2756
c7b10b5f 2757 $enabled = get_enabled_auth_plugins();
2758
2759 return in_array($auth, $enabled);
03d820c7 2760}
2761
2762/**
2763 * Returns an authentication plugin instance.
2764 *
2765 * @uses $CFG
9696bd89 2766 * @param string $auth name of authentication plugin
03d820c7 2767 * @return object An instance of the required authentication plugin.
2768 */
9696bd89 2769function get_auth_plugin($auth) {
03d820c7 2770 global $CFG;
5e623a33 2771
03d820c7 2772 // check the plugin exists first
2773 if (! exists_auth_plugin($auth)) {
2f137aa1 2774 print_error('authpluginnotfound', 'debug', '', $auth);
03d820c7 2775 }
5e623a33 2776
03d820c7 2777 // return auth plugin instance
2778 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2779 $class = "auth_plugin_$auth";
2780 return new $class;
2781}
2782
c7b10b5f 2783/**
2784 * Returns array of active auth plugins.
2785 *
2786 * @param bool $fix fix $CFG->auth if needed
2787 * @return array
2788 */
2789function get_enabled_auth_plugins($fix=false) {
2790 global $CFG;
2791
2792 $default = array('manual', 'nologin');
2793
2794 if (empty($CFG->auth)) {
2795 $auths = array();
2796 } else {
2797 $auths = explode(',', $CFG->auth);
2798 }
2799
2800 if ($fix) {
2801 $auths = array_unique($auths);
2802 foreach($auths as $k=>$authname) {
2803 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
2804 unset($auths[$k]);
2805 }
2806 }
2807 $newconfig = implode(',', $auths);
2808 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
2809 set_config('auth', $newconfig);
2810 }
2811 }
2812
2813 return (array_merge($default, $auths));
2814}
2815
03d820c7 2816/**
2817 * Returns true if an internal authentication method is being used.
2818 * if method not specified then, global default is assumed
2819 *
2820 * @uses $CFG
2821 * @param string $auth Form of authentication required
2822 * @return bool
03d820c7 2823 */
16793340 2824function is_internal_auth($auth) {
03d820c7 2825 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2826 return $authplugin->is_internal();
a3f1f815 2827}
2828
8c3dba73 2829/**
2830 * Returns an array of user fields
2831 *
c6d15803 2832 * @return array User field/column names
8c3dba73 2833 */
a3f1f815 2834function get_user_fieldnames() {
f33e1ed4 2835 global $DB;
a3f1f815 2836
f33e1ed4 2837 $fieldarray = $DB->get_columns('user');
2838 unset($fieldarray['id']);
2839 $fieldarray = array_keys($fieldarray);
a3f1f815 2840
2841 return $fieldarray;
ba7166c3 2842}
f9903ed0 2843
7cf1c7bd 2844/**
2845 * Creates a bare-bones user record
2846 *
2847 * @uses $CFG
7cf1c7bd 2848 * @param string $username New user's username to add to record
2849 * @param string $password New user's password to add to record
2850 * @param string $auth Form of authentication required
68fbd8e1 2851 * @return object A {@link $USER} object
7cf1c7bd 2852 * @todo Outline auth types and provide code example
2853 */
f76cfc7a 2854function create_user_record($username, $password, $auth='manual') {
ae040d4b 2855 global $CFG, $DB;
71f9abf9 2856
1e22bc9c 2857 //just in case check text case
2858 $username = trim(moodle_strtolower($username));
71f9abf9 2859
03d820c7 2860 $authplugin = get_auth_plugin($auth);
2861
ae040d4b 2862 $newuser = new object();
2863
6bc1e5d5 2864 if ($newinfo = $authplugin->get_userinfo($username)) {
2865 $newinfo = truncate_userinfo($newinfo);
2866 foreach ($newinfo as $key => $value){
ae040d4b 2867 $newuser->$key = $value;
e858f9da 2868 }
2869 }
f9903ed0 2870
85a1d4c9 2871 if (!empty($newuser->email)) {
2872 if (email_is_not_allowed($newuser->email)) {
2873 unset($newuser->email);
2874 }
2875 }
2876
27134b7d 2877 if (!isset($newuser->city)) {
2878 $newuser->city = '';
2879 }
2880
f76cfc7a 2881 $newuser->auth = $auth;
faebaf0f 2882 $newuser->username = $username;
5e623a33 2883
e51917eb 2884 // fix for MDL-8480
2885 // user CFG lang for user if $newuser->lang is empty
2886 // or $user->lang is not an installed language
2887 $sitelangs = array_keys(get_list_of_languages());
2888 if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
9c6972d6 2889 $newuser->lang = $CFG->lang;
5e623a33 2890 }
faebaf0f 2891 $newuser->confirmed = 1;
d96466d2 2892 $newuser->lastip = getremoteaddr();
faebaf0f 2893 $newuser->timemodified = time();
03d820c7 2894 $newuser->mnethostid = $CFG->mnet_localhost_id;
f9903ed0 2895
9c6972d6 2896 $DB->insert_record('user', $newuser);
2897 $user = get_complete_user_data('username', $newuser->username);
2898 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
2899 set_user_preference('auth_forcepasswordchange', 1, $user->id);
faebaf0f 2900 }
9c6972d6 2901 update_internal_user_password($user, $password);
2902 return $user;
faebaf0f 2903}
2904
7cf1c7bd 2905/**
2906 * Will update a local user record from an external source
2907 *
2908 * @uses $CFG
2909 * @param string $username New user's username to add to record
89dcb99d 2910 * @return user A {@link $USER} object
7cf1c7bd 2911 */
03d820c7 2912function update_user_record($username, $authplugin) {
ae040d4b 2913 global $DB;
2914
6bc1e5d5 2915 $username = trim(moodle_strtolower($username)); /// just in case check text case
2916
ae040d4b 2917 $oldinfo = $DB->get_record('user', array('username'=>$username), 'username, auth');
6bc1e5d5 2918 $userauth = get_auth_plugin($oldinfo->auth);
2919
2920 if ($newinfo = $userauth->get_userinfo($username)) {
2921 $newinfo = truncate_userinfo($newinfo);
2922 foreach ($newinfo as $key => $value){
5261baf1 2923 if ($key === 'username') {
2924 // 'username' is not a mapped updateable/lockable field, so skip it.
2925 continue;
2926 }
6ceb0cd0 2927 $confval = $userauth->config->{'field_updatelocal_' . $key};
2928 $lockval = $userauth->config->{'field_lock_' . $key};
2929 if (empty($confval) || empty($lockval)) {
2930 continue;
2931 }
2932 if ($confval === 'onlogin') {
6ceb0cd0 2933 // MDL-4207 Don't overwrite modified user profile values with
2934 // empty LDAP values when 'unlocked if empty' is set. The purpose
2935 // of the setting 'unlocked if empty' is to allow the user to fill
2936 // in a value for the selected field _if LDAP is giving
2937 // nothing_ for this field. Thus it makes sense to let this value
2938 // stand in until LDAP is giving a value for this field.
2939 if (!(empty($value) && $lockval === 'unlockedifempty')) {
8f0632f0 2940 $DB->set_field('user', $key, $value, array('username'=>$username));
6ceb0cd0 2941 }
d35757eb 2942 }
2943 }
2944 }
6bc1e5d5 2945
7c12949d 2946 return get_complete_user_data('username', $username);
d35757eb 2947}
0609562b 2948
be544ec3 2949/**
38fb8190 2950 * will truncate userinfo as it comes from auth_get_userinfo (from external auth)
be544ec3 2951 * which may have large fields
2952 */
b36a8fc4 2953function truncate_userinfo($info) {
b36a8fc4 2954 // define the limits
2955 $limit = array(
2956 'username' => 100,
8b9cfac4 2957 'idnumber' => 255,
8bcd295c 2958 'firstname' => 100,
2959 'lastname' => 100,
b36a8fc4 2960 'email' => 100,
2961 'icq' => 15,
2962 'phone1' => 20,
2963 'phone2' => 20,
2964 'institution' => 40,
2965 'department' => 30,
2966 'address' => 70,
2967 'city' => 20,
2968 'country' => 2,
2969 'url' => 255,
2970 );
361855e6 2971
b36a8fc4 2972 // apply where needed
2973 foreach (array_keys($info) as $key) {
2974 if (!empty($limit[$key])) {
adfc03f9 2975 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
361855e6 2976 }
b36a8fc4 2977 }
361855e6 2978
b36a8fc4 2979 return $info;
90afcf32 2980}
2981
2982/**
2983 * Marks user deleted in internal user database and notifies the auth plugin.
2984 * Also unenrols user from all roles and does other cleanup.
2985 * @param object $user Userobject before delete (without system magic quotes)
2986 * @return boolean success
2987 */
2988function delete_user($user) {
ae040d4b 2989 global $CFG, $DB;
90afcf32 2990 require_once($CFG->libdir.'/grouplib.php');
ece966f0 2991 require_once($CFG->libdir.'/gradelib.php');
6bdf4c99 2992 require_once($CFG->dirroot.'/message/lib.php');
90afcf32 2993
9c6972d6 2994 // TODO: decide if this transaction is really needed
ae040d4b 2995 $DB->begin_sql();
90afcf32 2996
9c6972d6 2997 try {
2998 // delete all grades - backup is kept in grade_grades_history table
2999 if ($grades = grade_grade::fetch_all(array('userid'=>$user->id))) {
3000 foreach ($grades as $grade) {
3001 $grade->delete('userdelete');
3002 }
90afcf32 3003 }
90afcf32 3004
6bdf4c99 3005 //move unread messages from this user to read
3006 message_move_userfrom_unread2read($user->id);
3007
9c6972d6 3008 // remove from all groups
3009 $DB->delete_records('groups_members', array('userid'=>$user->id));
90afcf32 3010
9c6972d6 3011 // unenrol from all roles in all contexts
3012 role_unassign(0, $user->id); // this might be slow but it is really needed - modules might do some extra cleanup!
90afcf32 3013
9c6972d6 3014 // now do a final accesslib cleanup - removes all role assingments in user context and context itself
3015 delete_context(CONTEXT_USER, $user->id);
90afcf32 3016
9c6972d6 3017 require_once($CFG->dirroot.'/tag/lib.php');
3018 tag_set('user', $user->id, array());
13b31d6f 3019
9c6972d6 3020 // workaround for bulk deletes of users with the same email address
3021 $delname = "$user->email.".time();
3022 while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
3023 $delname++;
3024 }
3025
3026 // mark internal user record as "deleted"
3027 $updateuser = new object();
3028 $updateuser->id = $user->id;
3029 $updateuser->deleted = 1;
3030 $updateuser->username = $delname; // Remember it just in case
3031 $updateuser->email = ''; // Clear this field to free it up
3032 $updateuser->idnumber = ''; // Clear this field to free it up
3033 $updateuser->timemodified = time();
6d11d0ee 3034
9c6972d6 3035 $DB->update_record('user', $updateuser);
90afcf32 3036
ae040d4b 3037 $DB->commit_sql();
9c6972d6 3038
90afcf32 3039 // notify auth plugin - do not block the delete even when plugin fails
3040 $authplugin = get_auth_plugin($user->auth);
3041 $authplugin->user_delete($user);
2942a5cd 3042
3043 events_trigger('user_deleted', $user);
90afcf32 3044
9c6972d6 3045 } catch (Exception $e) {
ae040d4b 3046 $DB->rollback_sql();
9c6972d6 3047 throw $e;
90afcf32 3048 }
9c6972d6 3049
3050 return true;
b36a8fc4 3051}
3052
7cf1c7bd 3053/**
3054 * Retrieve the guest user object
3055 *
3056 * @uses $CFG
89dcb99d 3057 * @return user A {@link $USER} object
7cf1c7bd 3058 */
0609562b 3059function guest_user() {
ae040d4b 3060 global $CFG, $DB;
0609562b 3061
ae040d4b 3062 if ($newuser = $DB->get_record('user', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
0609562b 3063 $newuser->confirmed = 1;
0609562b 3064 $newuser->lang = $CFG->lang;
d96466d2 3065 $newuser->lastip = getremoteaddr();
0609562b 3066 }
3067
3068 return $newuser;
3069}
3070
7cf1c7bd 3071/**
3072 * Given a username and password, this function looks them
3073 * up using the currently selected authentication mechanism,
3074 * and if the authentication is successful, it returns a
3075 * valid $user object from the 'user' table.
361855e6 3076 *
7cf1c7bd 3077 * Uses auth_ functions from the currently active auth module
3078 *
a238e822 3079 * After authenticate_user_login() returns success, you will need to
3080 * log that the user has logged in, and call complete_user_login() to set
3081 * the session up.
3082 *
7cf1c7bd 3083 * @uses $CFG
576c063b 3084 * @param string $username User's username
3085 * @param string $password User's password
89dcb99d 3086 * @return user|flase A {@link $USER} object or false if error
7cf1c7bd 3087 */
faebaf0f 3088function authenticate_user_login($username, $password) {
ae040d4b 3089 global $CFG, $DB;
faebaf0f 3090
c7b10b5f 3091 $authsenabled = get_enabled_auth_plugins();
39a5a35d 3092
16793340 3093 if ($user = get_complete_user_data('username', $username)) {
3094 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
3095 if ($auth=='nologin' or !is_enabled_auth($auth)) {
3096 add_to_log(0, 'login', 'error', 'index.php', $username);
a91b910e 3097 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
16793340 3098 return false;
27286aeb 3099 }
16793340 3100 if (!empty($user->deleted)) {
3101 add_to_log(0, 'login', 'error', 'index.php', $username);
a91b910e 3102 error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
16793340 3103 return false;
d35757eb 3104 }
16793340 3105 $auths = array($auth);
3106
71f9abf9 3107 } else {
16793340 3108 $auths = $authsenabled;
3109 $user = new object();
3110 $user->id = 0; // User does not exist
27286aeb 3111 }
8f0cd6ef 3112
03d820c7 3113 foreach ($auths as $auth) {
3114 $authplugin = get_auth_plugin($auth);
466558e3 3115
16793340 3116 // on auth fail fall through to the next plugin
03d820c7 3117 if (!$authplugin->user_login($username, $password)) {
03d820c7 3118 continue;
3119 }
faebaf0f 3120
03d820c7 3121 // successful authentication
d613daf0 3122 if ($user->id) { // User already exists in database
71f9abf9 3123 if (empty($user->auth)) { // For some reason auth isn't set yet
ae040d4b 3124 $DB->set_field('user', 'auth', $auth, array('username'=>$username));
16793340 3125 $user->auth = $auth;
71f9abf9 3126 }
1263a0ff 3127 if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
3128 $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
3129 $user->firstaccess = $user->timemodified;
3130 }
16793340 3131
3132 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3133
03d820c7 3134 if (!$authplugin->is_internal()) { // update user record from external DB
3135 $user = update_user_record($username, get_auth_plugin($user->auth));
d35757eb 3136 }
faebaf0f 3137 } else {
16793340 3138 // if user not found, create him
71f9abf9 3139 $user = create_user_record($username, $password, $auth);
faebaf0f 3140 }
01af6da6 3141