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