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