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