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