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