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