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