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