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