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