MDL-32988 Lib: Course delete does availability/completion in wrong order
[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 }
51b7297b
PS
1130 // lower error reporting because glibc throws bogus notices
1131 $olderror = error_reporting();
1132 if ($olderror & E_NOTICE) {
1133 error_reporting($olderror ^ E_NOTICE);
1134 }
1135 $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
1136 if ($olderror & E_NOTICE) {
1137 error_reporting($olderror);
1138 }
1139 return $result;
78fcdb5f
PS
1140
1141 } else if (is_array($value)) {
1142 foreach ($value as $k=>$v) {
1143 $value[$k] = fix_utf8($v);
1144 }
1145 return $value;
1146
1147 } else if (is_object($value)) {
1148 $value = clone($value); // do not modify original
1149 foreach ($value as $k=>$v) {
1150 $value->$k = fix_utf8($v);
1151 }
1152 return $value;
1153
1154 } else {
1155 // this is some other type, no utf-8 here
1156 return $value;
1157 }
1158}
1159
6e73ae10 1160/**
1161 * Return true if given value is integer or string with integer value
0d0a8bf6 1162 *
1163 * @param mixed $value String or Int
1164 * @return bool true if number, false if not
6e73ae10 1165 */
1166function is_number($value) {
1167 if (is_int($value)) {
1168 return true;
1169 } else if (is_string($value)) {
1170 return ((string)(int)$value) === $value;
1171 } else {
1172 return false;
1173 }
1174}
7a530277 1175
aa282b10 1176/**
1177 * Returns host part from url
1178 * @param string $url full url
1179 * @return string host, null if not found
1180 */
1181function get_host_from_url($url) {
1182 preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1183 if ($matches) {
1184 return $matches[1];
1185 }
1186 return null;
1187}
1188
94a6d656 1189/**
0d0a8bf6 1190 * Tests whether anything was returned by text editor
1191 *
94a6d656 1192 * This function is useful for testing whether something you got back from
1193 * the HTML editor actually contains anything. Sometimes the HTML editor
1194 * appear to be empty, but actually you get back a <br> tag or something.
1195 *
1196 * @param string $string a string containing HTML.
1197 * @return boolean does the string contain any actual content - that is text,
efb8c375 1198 * images, objects, etc.
94a6d656 1199 */
1200function html_is_blank($string) {
1201 return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1202}
1203
7cf1c7bd 1204/**
1205 * Set a key in global configuration
1206 *
89dcb99d 1207 * Set a key/value pair in both this session's {@link $CFG} global variable
7cf1c7bd 1208 * and in the 'config' database table for future sessions.
e1ecf0a0 1209 *
1210 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1211 * In that case it doesn't affect $CFG.
7cf1c7bd 1212 *
6fd511eb 1213 * A NULL value will delete the entry.
1214 *
0d0a8bf6 1215 * @global object
1216 * @global object
7cf1c7bd 1217 * @param string $name the key to set
9cdb766d 1218 * @param string $value the value to set (without magic quotes)
0d0a8bf6 1219 * @param string $plugin (optional) the plugin scope, default NULL
5e2f308b 1220 * @return bool true or exception
7cf1c7bd 1221 */
a4080313 1222function set_config($name, $value, $plugin=NULL) {
ae040d4b 1223 global $CFG, $DB;
42282810 1224
a4080313 1225 if (empty($plugin)) {
220a90c5 1226 if (!array_key_exists($name, $CFG->config_php_settings)) {
1227 // So it's defined for this invocation at least
1228 if (is_null($value)) {
1229 unset($CFG->$name);
1230 } else {
9c305ba1 1231 $CFG->$name = (string)$value; // settings from db are always strings
220a90c5 1232 }
1233 }
e1ecf0a0 1234
ae040d4b 1235 if ($DB->get_field('config', 'name', array('name'=>$name))) {
5e2f308b 1236 if ($value === null) {
1237 $DB->delete_records('config', array('name'=>$name));
6fd511eb 1238 } else {
5e2f308b 1239 $DB->set_field('config', 'value', $value, array('name'=>$name));
6fd511eb 1240 }
a4080313 1241 } else {
5e2f308b 1242 if ($value !== null) {
365a5941 1243 $config = new stdClass();
5e2f308b 1244 $config->name = $name;
1245 $config->value = $value;
1246 $DB->insert_record('config', $config, false);
6fd511eb 1247 }
a4080313 1248 }
ae040d4b 1249
a4080313 1250 } else { // plugin scope
ae040d4b 1251 if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
6fd511eb 1252 if ($value===null) {
5e2f308b 1253 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
6fd511eb 1254 } else {
5e2f308b 1255 $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
6fd511eb 1256 }
a4080313 1257 } else {
5e2f308b 1258 if ($value !== null) {
365a5941 1259 $config = new stdClass();
5e2f308b 1260 $config->plugin = $plugin;
1261 $config->name = $name;
1262 $config->value = $value;
1263 $DB->insert_record('config_plugins', $config, false);
6fd511eb 1264 }
a4080313 1265 }
1266 }
5e2f308b 1267
1268 return true;
a4080313 1269}
1270
1271/**
e1ecf0a0 1272 * Get configuration values from the global config table
a4080313 1273 * or the config_plugins table.
1274 *
13daf6a2 1275 * If called with one parameter, it will load all the config
12bb0c3e 1276 * variables for one plugin, and return them as an object.
13daf6a2 1277 *
12bb0c3e
PS
1278 * If called with 2 parameters it will return a string single
1279 * value or false if the value is not found.
9220fba5 1280 *
12bb0c3e 1281 * @param string $plugin full component name
0d0a8bf6 1282 * @param string $name default NULL
07ab0c80 1283 * @return mixed hash-like object or single value, return false no config found
a4080313 1284 */
12bb0c3e 1285function get_config($plugin, $name = NULL) {
ae040d4b 1286 global $CFG, $DB;
dfc9ba9b 1287
12bb0c3e
PS
1288 // normalise component name
1289 if ($plugin === 'moodle' or $plugin === 'core') {
1290 $plugin = NULL;
1291 }
1292
a4080313 1293 if (!empty($name)) { // the user is asking for a specific value
1294 if (!empty($plugin)) {
12bb0c3e
PS
1295 if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
1296 // setting forced in config file
1297 return $CFG->forced_plugin_settings[$plugin][$name];
1298 } else {
1299 return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
1300 }
a4080313 1301 } else {
12bb0c3e
PS
1302 if (array_key_exists($name, $CFG->config_php_settings)) {
1303 // setting force in config file
1304 return $CFG->config_php_settings[$name];
1305 } else {
1306 return $DB->get_field('config', 'value', array('name'=>$name));
1307 }
a4080313 1308 }
1309 }
1310
1311 // the user is after a recordset
12bb0c3e 1312 if ($plugin) {
13daf6a2 1313 $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
12bb0c3e
PS
1314 if (isset($CFG->forced_plugin_settings[$plugin])) {
1315 foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
1316 if (is_null($v) or is_array($v) or is_object($v)) {
1317 // we do not want any extra mess here, just real settings that could be saved in db
1318 unset($localcfg[$n]);
1319 } else {
1320 //convert to string as if it went through the DB
1321 $localcfg[$n] = (string)$v;
a4080313 1322 }
1323 }
a4080313 1324 }
bfb82da3
TH
1325 if ($localcfg) {
1326 return (object)$localcfg;
1327 } else {
268b6709 1328 return new stdClass();
bfb82da3 1329 }
e1ecf0a0 1330
12bb0c3e
PS
1331 } else {
1332 // this part is not really used any more, but anyway...
1333 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
1334 foreach($CFG->config_php_settings as $n=>$v) {
1335 if (is_null($v) or is_array($v) or is_object($v)) {
1336 // we do not want any extra mess here, just real settings that could be saved in db
1337 unset($localcfg[$n]);
1338 } else {
1339 //convert to string as if it went through the DB
1340 $localcfg[$n] = (string)$v;
1341 }
1342 }
1343 return (object)$localcfg;
39917a09 1344 }
39917a09 1345}
1346
b0270f84 1347/**
1348 * Removes a key from global configuration
1349 *
1350 * @param string $name the key to set
1351 * @param string $plugin (optional) the plugin scope
0d0a8bf6 1352 * @global object
4b600aa0 1353 * @return boolean whether the operation succeeded.
b0270f84 1354 */
1355function unset_config($name, $plugin=NULL) {
ae040d4b 1356 global $CFG, $DB;
b0270f84 1357
b0270f84 1358 if (empty($plugin)) {
4b600aa0 1359 unset($CFG->$name);
013376de 1360 $DB->delete_records('config', array('name'=>$name));
5e623a33 1361 } else {
013376de 1362 $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
b0270f84 1363 }
013376de 1364
1365 return true;
b0270f84 1366}
1367
4b600aa0 1368/**
1369 * Remove all the config variables for a given plugin.
1370 *
1371 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1372 * @return boolean whether the operation succeeded.
1373 */
1374function unset_all_config_for_plugin($plugin) {
1375 global $DB;
013376de 1376 $DB->delete_records('config_plugins', array('plugin' => $plugin));
a4193166
PS
1377 $like = $DB->sql_like('name', '?', true, true, false, '|');
1378 $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1379 $DB->delete_records_select('config', $like, $params);
013376de 1380 return true;
4b600aa0 1381}
1382
4413941f 1383/**
efb8c375 1384 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
adf176d7
PS
1385 *
1386 * All users are verified if they still have the necessary capability.
1387 *
b3d960e6 1388 * @param string $value the value of the config setting.
4413941f 1389 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
efb8c375 1390 * @param bool $include admins, include administrators
4413941f 1391 * @return array of user objects.
1392 */
adf176d7
PS
1393function get_users_from_config($value, $capability, $includeadmins = true) {
1394 global $CFG, $DB;
1395
1396 if (empty($value) or $value === '$@NONE@$') {
1397 return array();
4413941f 1398 }
adf176d7
PS
1399
1400 // we have to make sure that users still have the necessary capability,
1401 // it should be faster to fetch them all first and then test if they are present
6b8ad965 1402 // instead of validating them one-by-one
adf176d7
PS
1403 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
1404 if ($includeadmins) {
1405 $admins = get_admins();
1406 foreach ($admins as $admin) {
1407 $users[$admin->id] = $admin;
1408 }
1409 }
1410
1411 if ($value === '$@ALL@$') {
1412 return $users;
1413 }
1414
1415 $result = array(); // result in correct order
1416 $allowed = explode(',', $value);
1417 foreach ($allowed as $uid) {
1418 if (isset($users[$uid])) {
1419 $user = $users[$uid];
1420 $result[$user->id] = $user;
1421 }
1422 }
1423
1424 return $result;
4413941f 1425}
1426
f87eab7e
PS
1427
1428/**
1429 * Invalidates browser caches and cached data in temp
1430 * @return void
1431 */
1432function purge_all_caches() {
1433 global $CFG;
1434
f87eab7e
PS
1435 reset_text_filters_cache();
1436 js_reset_all_caches();
1437 theme_reset_all_caches();
1438 get_string_manager()->reset_caches();
bc5c10f6 1439 textlib::reset_caches();
f87eab7e 1440
dc2c9bd7 1441 // purge all other caches: rss, simplepie, etc.
365bec4c 1442 remove_dir($CFG->cachedir.'', true);
f87eab7e 1443
c426ef3a 1444 // make sure cache dir is writable, throws exception if not
5a87c912 1445 make_cache_directory('');
f87eab7e 1446
b216a820
PS
1447 // hack: this script may get called after the purifier was initialised,
1448 // but we do not want to verify repeatedly this exists in each call
5a87c912 1449 make_cache_directory('htmlpurifier');
f87eab7e
PS
1450}
1451
bafd7e78 1452/**
1453 * Get volatile flags
1454 *
1455 * @param string $type
0d0a8bf6 1456 * @param int $changedsince default null
bafd7e78 1457 * @return records array
bafd7e78 1458 */
1459function get_cache_flags($type, $changedsince=NULL) {
ae040d4b 1460 global $DB;
bafd7e78 1461
ae040d4b 1462 $params = array('type'=>$type, 'expiry'=>time());
1463 $sqlwhere = "flagtype = :type AND expiry >= :expiry";
bafd7e78 1464 if ($changedsince !== NULL) {
ae040d4b 1465 $params['changedsince'] = $changedsince;
1466 $sqlwhere .= " AND timemodified > :changedsince";
bafd7e78 1467 }
1468 $cf = array();
ae040d4b 1469
1470 if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
bafd7e78 1471 foreach ($flags as $flag) {
1472 $cf[$flag->name] = $flag->value;
1473 }
1474 }
1475 return $cf;
1476}
1477
a489cf72 1478/**
1479 * Get volatile flags
1480 *
1481 * @param string $type
1482 * @param string $name
0d0a8bf6 1483 * @param int $changedsince default null
a489cf72 1484 * @return records array
a489cf72 1485 */
1486function get_cache_flag($type, $name, $changedsince=NULL) {
ae040d4b 1487 global $DB;
a489cf72 1488
ae040d4b 1489 $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
a489cf72 1490
ae040d4b 1491 $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
a489cf72 1492 if ($changedsince !== NULL) {
ae040d4b 1493 $params['changedsince'] = $changedsince;
1494 $sqlwhere .= " AND timemodified > :changedsince";
a489cf72 1495 }
ae040d4b 1496
1497 return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
a489cf72 1498}
bafd7e78 1499
1500/**
1501 * Set a volatile flag
1502 *
1503 * @param string $type the "type" namespace for the key
1504 * @param string $name the key to set
1505 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
1506 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
0d0a8bf6 1507 * @return bool Always returns true
bafd7e78 1508 */
1509function set_cache_flag($type, $name, $value, $expiry=NULL) {
ae040d4b 1510 global $DB;
bafd7e78 1511
1512 $timemodified = time();
1513 if ($expiry===NULL || $expiry < $timemodified) {
1514 $expiry = $timemodified + 24 * 60 * 60;
1515 } else {
1516 $expiry = (int)$expiry;
1517 }
1518
1519 if ($value === NULL) {
013376de 1520 unset_cache_flag($type,$name);
1521 return true;
bafd7e78 1522 }
1523
39461de3 1524 if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
128f0984 1525 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1526 return true; //no need to update; helps rcache too
1527 }
ae040d4b 1528 $f->value = $value;
bafd7e78 1529 $f->expiry = $expiry;
1530 $f->timemodified = $timemodified;
013376de 1531 $DB->update_record('cache_flags', $f);
bafd7e78 1532 } else {
365a5941 1533 $f = new stdClass();
bafd7e78 1534 $f->flagtype = $type;
1535 $f->name = $name;
ae040d4b 1536 $f->value = $value;
bafd7e78 1537 $f->expiry = $expiry;
1538 $f->timemodified = $timemodified;
013376de 1539 $DB->insert_record('cache_flags', $f);
bafd7e78 1540 }
013376de 1541 return true;
bafd7e78 1542}
1543
1544/**
1545 * Removes a single volatile flag
1546 *
0d0a8bf6 1547 * @global object
bafd7e78 1548 * @param string $type the "type" namespace for the key
1549 * @param string $name the key to set
bafd7e78 1550 * @return bool
1551 */
1552function unset_cache_flag($type, $name) {
ae040d4b 1553 global $DB;
013376de 1554 $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
1555 return true;
bafd7e78 1556}
1557
1558/**
1559 * Garbage-collect volatile flags
1560 *
0d0a8bf6 1561 * @return bool Always returns true
bafd7e78 1562 */
1563function gc_cache_flags() {
ae040d4b 1564 global $DB;
013376de 1565 $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1566 return true;
bafd7e78 1567}
a4080313 1568
4d6b40a0 1569// USER PREFERENCE API
2660377f 1570
7cf1c7bd 1571/**
39461de3
PS
1572 * Refresh user preference cache. This is used most often for $USER
1573 * object that is stored in session, but it also helps with performance in cron script.
0d0a8bf6 1574 *
39461de3
PS
1575 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1576 *
4d6b40a0
GGC
1577 * @package core
1578 * @category preference
1579 * @access public
1580 * @param stdClass $user User object. Preferences are preloaded into 'preference' property
1581 * @param int $cachelifetime Cache life time on the current page (in seconds)
1582 * @throws coding_exception
1583 * @return null
7cf1c7bd 1584 */
39461de3
PS
1585function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1586 global $DB;
1587 static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
2660377f 1588
39461de3
PS
1589 if (!isset($user->id)) {
1590 throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1591 }
2660377f 1592
39461de3
PS
1593 if (empty($user->id) or isguestuser($user->id)) {
1594 // No permanent storage for not-logged-in users and guest
1595 if (!isset($user->preference)) {
1596 $user->preference = array();
2660377f 1597 }
39461de3 1598 return;
2660377f 1599 }
70812e39 1600
39461de3 1601 $timenow = time();
070e2616 1602
39461de3
PS
1603 if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1604 // Already loaded at least once on this page. Are we up to date?
1605 if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1606 // no need to reload - we are on the same page and we loaded prefs just a moment ago
1607 return;
70812e39 1608
39461de3
PS
1609 } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1610 // no change since the lastcheck on this page
1611 $user->preference['_lastloaded'] = $timenow;
1612 return;
70812e39 1613 }
c6d15803 1614 }
346c3e2f 1615
39461de3
PS
1616 // OK, so we have to reload all preferences
1617 $loadedusers[$user->id] = true;
1618 $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
1619 $user->preference['_lastloaded'] = $timenow;
2660377f 1620}
1621
1622/**
4d6b40a0 1623 * Called from set/unset_user_preferences, so that the prefs can
39461de3
PS
1624 * be correctly reloaded in different sessions.
1625 *
1626 * NOTE: internal function, do not call from other code.
0d0a8bf6 1627 *
4d6b40a0
GGC
1628 * @package core
1629 * @access private
1630 * @param integer $userid the user whose prefs were changed.
2660377f 1631 */
1632function mark_user_preferences_changed($userid) {
39461de3
PS
1633 global $CFG;
1634
1635 if (empty($userid) or isguestuser($userid)) {
1636 // no cache flags for guest and not-logged-in users
1637 return;
2660377f 1638 }
39461de3 1639
2660377f 1640 set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
70812e39 1641}
1642
7cf1c7bd 1643/**
39461de3 1644 * Sets a preference for the specified user.
0d0a8bf6 1645 *
4d6b40a0 1646 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
0d0a8bf6 1647 *
4d6b40a0
GGC
1648 * @package core
1649 * @category preference
1650 * @access public
1651 * @param string $name The key to set as preference for the specified user
1652 * @param string $value The value to set for the $name key in the specified user's
1653 * record, null means delete current value.
1654 * @param stdClass|int|null $user A moodle user object or id, null means current user
1655 * @throws coding_exception
1656 * @return bool Always true or exception
7cf1c7bd 1657 */
39461de3 1658function set_user_preference($name, $value, $user = null) {
ae040d4b 1659 global $USER, $DB;
70812e39 1660
39461de3
PS
1661 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1662 throw new coding_exception('Invalid preference name in set_user_preference() call');
70812e39 1663 }
1664
39461de3
PS
1665 if (is_null($value)) {
1666 // null means delete current
1667 return unset_user_preference($name, $user);
1668 } else if (is_object($value)) {
1669 throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1670 } else if (is_array($value)) {
1671 throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1672 }
1673 $value = (string)$value;
8e54ce97
AD
1674 if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
1675 throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1676 }
39461de3
PS
1677
1678 if (is_null($user)) {
1679 $user = $USER;
1680 } else if (isset($user->id)) {
1681 // $user is valid object
1682 } else if (is_numeric($user)) {
1683 $user = (object)array('id'=>(int)$user);
346c3e2f 1684 } else {
39461de3 1685 throw new coding_exception('Invalid $user parameter in set_user_preference() call');
346c3e2f 1686 }
1687
39461de3
PS
1688 check_user_preferences_loaded($user);
1689
1690 if (empty($user->id) or isguestuser($user->id)) {
1691 // no permanent storage for not-logged-in users and guest
1692 $user->preference[$name] = $value;
1693 return true;
1694 }
346c3e2f 1695
39461de3
PS
1696 if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
1697 if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1698 // preference already set to this value
a1244706 1699 return true;
1700 }
39461de3 1701 $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
70812e39 1702
1703 } else {
365a5941 1704 $preference = new stdClass();
39461de3 1705 $preference->userid = $user->id;
ae040d4b 1706 $preference->name = $name;
39461de3 1707 $preference->value = $value;
013376de 1708 $DB->insert_record('user_preferences', $preference);
2660377f 1709 }
1710
39461de3
PS
1711 // update value in cache
1712 $user->preference[$name] = $value;
1713
1714 // set reload flag for other sessions
1715 mark_user_preferences_changed($user->id);
346c3e2f 1716
013376de 1717 return true;
2660377f 1718}
1719
1720/**
1721 * Sets a whole array of preferences for the current user
0d0a8bf6 1722 *
4d6b40a0 1723 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
39461de3 1724 *
4d6b40a0
GGC
1725 * @package core
1726 * @category preference
1727 * @access public
1728 * @param array $prefarray An array of key/value pairs to be set
1729 * @param stdClass|int|null $user A moodle user object or id, null means current user
1730 * @return bool Always true or exception
2660377f 1731 */
39461de3 1732function set_user_preferences(array $prefarray, $user = null) {
2660377f 1733 foreach ($prefarray as $name => $value) {
39461de3 1734 set_user_preference($name, $value, $user);
2660377f 1735 }
013376de 1736 return true;
70812e39 1737}
1738
6eb3e776 1739/**
1740 * Unsets a preference completely by deleting it from the database
0d0a8bf6 1741 *
4d6b40a0 1742 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
0d0a8bf6 1743 *
4d6b40a0
GGC
1744 * @package core
1745 * @category preference
1746 * @access public
1747 * @param string $name The key to unset as preference for the specified user
1748 * @param stdClass|int|null $user A moodle user object or id, null means current user
1749 * @throws coding_exception
1750 * @return bool Always true or exception
6eb3e776 1751 */
39461de3 1752function unset_user_preference($name, $user = null) {
ae040d4b 1753 global $USER, $DB;
6eb3e776 1754
39461de3
PS
1755 if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1756 throw new coding_exception('Invalid preference name in unset_user_preference() call');
1757 }
1758
1759 if (is_null($user)) {
1760 $user = $USER;
1761 } else if (isset($user->id)) {
1762 // $user is valid object
1763 } else if (is_numeric($user)) {
1764 $user = (object)array('id'=>(int)$user);
346c3e2f 1765 } else {
39461de3 1766 throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
346c3e2f 1767 }
1768
39461de3 1769 check_user_preferences_loaded($user);
013376de 1770
39461de3
PS
1771 if (empty($user->id) or isguestuser($user->id)) {
1772 // no permanent storage for not-logged-in user and guest
1773 unset($user->preference[$name]);
1774 return true;
70812e39 1775 }
1776
39461de3
PS
1777 // delete from DB
1778 $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
1779
1780 // delete the preference from cache
1781 unset($user->preference[$name]);
1782
1783 // set reload flag for other sessions
1784 mark_user_preferences_changed($user->id);
1785
013376de 1786 return true;
70812e39 1787}
1788
7cf1c7bd 1789/**
0d0a8bf6 1790 * Used to fetch user preference(s)
1791 *
7cf1c7bd 1792 * If no arguments are supplied this function will return
361855e6 1793 * all of the current user preferences as an array.
0d0a8bf6 1794 *
7cf1c7bd 1795 * If a name is specified then this function
1796 * attempts to return that particular preference value. If
1797 * none is found, then the optional value $default is returned,
1798 * otherwise NULL.
0d0a8bf6 1799 *
4d6b40a0 1800 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
39461de3 1801 *
4d6b40a0
GGC
1802 * @package core
1803 * @category preference
1804 * @access public
1805 * @param string $name Name of the key to use in finding a preference value
1806 * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
1807 * @param stdClass|int|null $user A moodle user object or id, null means current user
1808 * @throws coding_exception
1809 * @return string|mixed|null A string containing the value of a single preference. An
1810 * array with all of the preferences or null
7cf1c7bd 1811 */
39461de3
PS
1812function get_user_preferences($name = null, $default = null, $user = null) {
1813 global $USER;
70812e39 1814
39461de3
PS
1815 if (is_null($name)) {
1816 // all prefs
1817 } else if (is_numeric($name) or $name === '_lastloaded') {
1818 throw new coding_exception('Invalid preference name in get_user_preferences() call');
1819 }
346c3e2f 1820
39461de3
PS
1821 if (is_null($user)) {
1822 $user = $USER;
1823 } else if (isset($user->id)) {
1824 // $user is valid object
1825 } else if (is_numeric($user)) {
1826 $user = (object)array('id'=>(int)$user);
1827 } else {
1828 throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1829 }
1830
1831 check_user_preferences_loaded($user);
346c3e2f 1832
39461de3
PS
1833 if (empty($name)) {
1834 return $user->preference; // All values
1835 } else if (isset($user->preference[$name])) {
1836 return $user->preference[$name]; // The single string value
346c3e2f 1837 } else {
39461de3 1838 return $default; // Default value (null if not specified)
70812e39 1839 }
70812e39 1840}
1841
9fa49e22 1842/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 1843
7cf1c7bd 1844/**
c6d15803 1845 * Given date parts in user time produce a GMT timestamp.
7cf1c7bd 1846 *
9df12115
RT
1847 * @package core
1848 * @category time
68fbd8e1 1849 * @param int $year The year part to create timestamp of
1850 * @param int $month The month part to create timestamp of
1851 * @param int $day The day part to create timestamp of
1852 * @param int $hour The hour part to create timestamp of
1853 * @param int $minute The minute part to create timestamp of
1854 * @param int $second The second part to create timestamp of
9df12115
RT
1855 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
1856 * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
6a0bf5c4
RT
1857 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1858 * applied only if timezone is 99 or string.
9df12115 1859 * @return int GMT timestamp
7cf1c7bd 1860 */
9f1f6daf 1861function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
39917a09 1862
6a0bf5c4
RT
1863 //save input timezone, required for dst offset check.
1864 $passedtimezone = $timezone;
33998d30 1865
dddb014a 1866 $timezone = get_user_timezone_offset($timezone);
1867
6a0bf5c4 1868 if (abs($timezone) > 13) { //server time
68fbd8e1 1869 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
03c17ddf 1870 } else {
68fbd8e1 1871 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
196f2619 1872 $time = usertime($time, $timezone);
6a0bf5c4
RT
1873
1874 //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
1875 if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
1876 $time -= dst_offset_on($time, $passedtimezone);
28c66824 1877 }
9f1f6daf 1878 }
1879
196f2619 1880 return $time;
85cafb3e 1881
39917a09 1882}
1883
7cf1c7bd 1884/**
0d0a8bf6 1885 * Format a date/time (seconds) as weeks, days, hours etc as needed
1886 *
7cf1c7bd 1887 * Given an amount of time in seconds, returns string
5602f7cf 1888 * formatted nicely as weeks, days, hours etc as needed
7cf1c7bd 1889 *
9df12115
RT
1890 * @package core
1891 * @category time
2f87145b 1892 * @uses MINSECS
1893 * @uses HOURSECS
1894 * @uses DAYSECS
5602f7cf 1895 * @uses YEARSECS
0d0a8bf6 1896 * @param int $totalsecs Time in seconds
1897 * @param object $str Should be a time object
1898 * @return string A nicely formatted date/time string
7cf1c7bd 1899 */
1900 function format_time($totalsecs, $str=NULL) {
c7e3ac2a 1901
6b174680 1902 $totalsecs = abs($totalsecs);
c7e3ac2a 1903
8dbed6be 1904 if (!$str) { // Create the str structure the slow way
b85b25eb 1905 $str = new stdClass();
b0ccd3fb 1906 $str->day = get_string('day');
1907 $str->days = get_string('days');
1908 $str->hour = get_string('hour');
1909 $str->hours = get_string('hours');
1910 $str->min = get_string('min');
1911 $str->mins = get_string('mins');
1912 $str->sec = get_string('sec');
1913 $str->secs = get_string('secs');
5602f7cf 1914 $str->year = get_string('year');
1915 $str->years = get_string('years');
8dbed6be 1916 }
1917
5602f7cf 1918
1919 $years = floor($totalsecs/YEARSECS);
1920 $remainder = $totalsecs - ($years*YEARSECS);
5602f7cf 1921 $days = floor($remainder/DAYSECS);
7a5672c9 1922 $remainder = $totalsecs - ($days*DAYSECS);
1923 $hours = floor($remainder/HOURSECS);
1924 $remainder = $remainder - ($hours*HOURSECS);
1925 $mins = floor($remainder/MINSECS);
1926 $secs = $remainder - ($mins*MINSECS);
8dbed6be 1927
1928 $ss = ($secs == 1) ? $str->sec : $str->secs;
1929 $sm = ($mins == 1) ? $str->min : $str->mins;
1930 $sh = ($hours == 1) ? $str->hour : $str->hours;
1931 $sd = ($days == 1) ? $str->day : $str->days;
5602f7cf 1932 $sy = ($years == 1) ? $str->year : $str->years;
8dbed6be 1933
5602f7cf 1934 $oyears = '';
b0ccd3fb 1935 $odays = '';
1936 $ohours = '';
1937 $omins = '';
1938 $osecs = '';
9c9f7d77 1939
5602f7cf 1940 if ($years) $oyears = $years .' '. $sy;
b0ccd3fb 1941 if ($days) $odays = $days .' '. $sd;
1942 if ($hours) $ohours = $hours .' '. $sh;
1943 if ($mins) $omins = $mins .' '. $sm;
1944 if ($secs) $osecs = $secs .' '. $ss;
6b174680 1945
77ac808e 1946 if ($years) return trim($oyears .' '. $odays);
1947 if ($days) return trim($odays .' '. $ohours);
1948 if ($hours) return trim($ohours .' '. $omins);
1949 if ($mins) return trim($omins .' '. $osecs);
b0ccd3fb 1950 if ($secs) return $osecs;
1951 return get_string('now');
6b174680 1952}
f9903ed0 1953
7cf1c7bd 1954/**
0d0a8bf6 1955 * Returns a formatted string that represents a date in user time
1956 *
7cf1c7bd 1957 * Returns a formatted string that represents a date in user time
1958 * <b>WARNING: note that the format is for strftime(), not date().</b>
1959 * Because of a bug in most Windows time libraries, we can't use
1960 * the nicer %e, so we have to use %d which has leading zeroes.
1961 * A lot of the fuss in the function is just getting rid of these leading
1962 * zeroes as efficiently as possible.
361855e6 1963 *
8c3dba73 1964 * If parameter fixday = true (default), then take off leading
efb8c375 1965 * zero from %d, else maintain it.
7cf1c7bd 1966 *
9df12115
RT
1967 * @package core
1968 * @category time
0a0cf09a 1969 * @param int $date the timestamp in UTC, as obtained from the database.
1970 * @param string $format strftime format. You should probably get this using
9df12115
RT
1971 * get_string('strftime...', 'langconfig');
1972 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
1973 * not 99 then daylight saving will not be added.
1974 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
0a0cf09a 1975 * @param bool $fixday If true (default) then the leading zero from %d is removed.
9df12115 1976 * If false then the leading zero is maintained.
d9498b38 1977 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
0a0cf09a 1978 * @return string the formatted date/time.
7cf1c7bd 1979 */
d9498b38 1980function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
7a302afc 1981
1ac7ee24 1982 global $CFG;
1983
1306c5ea 1984 if (empty($format)) {
0a0cf09a 1985 $format = get_string('strftimedaydatetime', 'langconfig');
5fa51a39 1986 }
035cdbff 1987
c3a3c5b8 1988 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1989 $fixday = false;
1990 } else if ($fixday) {
1991 $formatnoday = str_replace('%d', 'DD', $format);
61ae5d36 1992 $fixday = ($formatnoday != $format);
d9498b38 1993 $format = $formatnoday;
1994 }
1995
1996 // Note: This logic about fixing 12-hour time to remove unnecessary leading
1997 // zero is required because on Windows, PHP strftime function does not
1998 // support the correct 'hour without leading zero' parameter (%l).
1999 if (!empty($CFG->nofixhour)) {
2000 // Config.php can force %I not to be fixed.
2001 $fixhour = false;
2002 } else if ($fixhour) {
2003 $formatnohour = str_replace('%I', 'HH', $format);
2004 $fixhour = ($formatnohour != $format);
2005 $format = $formatnohour;
61ae5d36 2006 }
dcde9f02 2007
6a0bf5c4
RT
2008 //add daylight saving offset for string timezones only, as we can't get dst for
2009 //float values. if timezone is 99 (user default timezone), then try update dst.
2010 if ((99 == $timezone) || !is_numeric($timezone)) {
2011 $date += dst_offset_on($date, $timezone);
2012 }
85351042 2013
494b9296 2014 $timezone = get_user_timezone_offset($timezone);
102dc313 2015
2016 if (abs($timezone) > 13) { /// Server time
d9498b38 2017 $datestring = strftime($format, $date);
d2a9f7cc 2018 if ($fixday) {
35f7287f 2019 $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
102dc313 2020 $datestring = str_replace('DD', $daystring, $datestring);
d9498b38 2021 }
2022 if ($fixhour) {
2023 $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
2024 $datestring = str_replace('HH', $hourstring, $datestring);
102dc313 2025 }
88ec5b7c 2026 } else {
102dc313 2027 $date += (int)($timezone * 3600);
d9498b38 2028 $datestring = gmstrftime($format, $date);
102dc313 2029 if ($fixday) {
35f7287f 2030 $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
102dc313 2031 $datestring = str_replace('DD', $daystring, $datestring);
d9498b38 2032 }
2033 if ($fixhour) {
2034 $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
2035 $datestring = str_replace('HH', $hourstring, $datestring);
102dc313 2036 }
88ec5b7c 2037 }
102dc313 2038
fb773106 2039/// If we are running under Windows convert from windows encoding to UTF-8
2040/// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
11f7b25d 2041
fb773106 2042 if ($CFG->ostype == 'WINDOWS') {
bf69b06d 2043 if ($localewincharset = get_string('localewincharset', 'langconfig')) {
f8311def 2044 $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
11f7b25d 2045 }
487de67c 2046 }
11f7b25d 2047
035cdbff 2048 return $datestring;
873960de 2049}
2050
7cf1c7bd 2051/**
196f2619 2052 * Given a $time timestamp in GMT (seconds since epoch),
c6d15803 2053 * returns an array that represents the date in user time
7cf1c7bd 2054 *
9df12115
RT
2055 * @package core
2056 * @category time
2f87145b 2057 * @uses HOURSECS
196f2619 2058 * @param int $time Timestamp in GMT
9df12115
RT
2059 * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
2060 * dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
c6d15803 2061 * @return array An array that represents the date in user time
7cf1c7bd 2062 */
196f2619 2063function usergetdate($time, $timezone=99) {
6b174680 2064
6a0bf5c4
RT
2065 //save input timezone, required for dst offset check.
2066 $passedtimezone = $timezone;
94c82430 2067
494b9296 2068 $timezone = get_user_timezone_offset($timezone);
a36166d3 2069
e34d817e 2070 if (abs($timezone) > 13) { // Server time
ed1f69b0 2071 return getdate($time);
d2a9f7cc 2072 }
2073
6a0bf5c4
RT
2074 //add daylight saving offset for string timezones only, as we can't get dst for
2075 //float values. if timezone is 99 (user default timezone), then try update dst.
2076 if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
2077 $time += dst_offset_on($time, $passedtimezone);
2078 }
2079
e34d817e 2080 $time += intval((float)$timezone * HOURSECS);
3bba1e6e 2081
24d38a6e 2082 $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
02f0527d 2083
24d38a6e 2084 //be careful to ensure the returned array matches that produced by getdate() above
9f1f6daf 2085 list(
24d38a6e
AD
2086 $getdate['month'],
2087 $getdate['weekday'],
2088 $getdate['yday'],
9f1f6daf 2089 $getdate['year'],
24d38a6e 2090 $getdate['mon'],
9f1f6daf 2091 $getdate['wday'],
24d38a6e
AD
2092 $getdate['mday'],
2093 $getdate['hours'],
2094 $getdate['minutes'],
2095 $getdate['seconds']
3bba1e6e 2096 ) = explode('_', $datestring);
9f1f6daf 2097
4a9c429b
RT
2098 // set correct datatype to match with getdate()
2099 $getdate['seconds'] = (int)$getdate['seconds'];
2100 $getdate['yday'] = (int)$getdate['yday'] - 1; // gettime returns 0 through 365
2101 $getdate['year'] = (int)$getdate['year'];
2102 $getdate['mon'] = (int)$getdate['mon'];
2103 $getdate['wday'] = (int)$getdate['wday'];
2104 $getdate['mday'] = (int)$getdate['mday'];
2105 $getdate['hours'] = (int)$getdate['hours'];
2106 $getdate['minutes'] = (int)$getdate['minutes'];
d2d6171f 2107 return $getdate;
d552ead0 2108}
2109
7cf1c7bd 2110/**
2111 * Given a GMT timestamp (seconds since epoch), offsets it by
2112 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2113 *
9df12115
RT
2114 * @package core
2115 * @category time
2f87145b 2116 * @uses HOURSECS
9df12115
RT
2117 * @param int $date Timestamp in GMT
2118 * @param float|int|string $timezone timezone to calculate GMT time offset before
2119 * calculating user time, 99 is default user timezone
2120 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
c6d15803 2121 * @return int
7cf1c7bd 2122 */
d552ead0 2123function usertime($date, $timezone=99) {
a36166d3 2124
494b9296 2125 $timezone = get_user_timezone_offset($timezone);
2665e47a 2126
0431bd7c 2127 if (abs($timezone) > 13) {
d552ead0 2128 return $date;
2129 }
7a5672c9 2130 return $date - (int)($timezone * HOURSECS);
d552ead0 2131}
2132
8c3dba73 2133/**
2134 * Given a time, return the GMT timestamp of the most recent midnight
2135 * for the current user.
2136 *
9df12115
RT
2137 * @package core
2138 * @category time
e34d817e 2139 * @param int $date Timestamp in GMT
9df12115
RT
2140 * @param float|int|string $timezone timezone to calculate GMT time offset before
2141 * calculating user midnight time, 99 is default user timezone
2142 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
0d0a8bf6 2143 * @return int Returns a GMT timestamp
8c3dba73 2144 */
edf7fe8c 2145function usergetmidnight($date, $timezone=99) {
edf7fe8c 2146
edf7fe8c 2147 $userdate = usergetdate($date, $timezone);
4606d9bb 2148
02f0527d 2149 // Time of midnight of this user's day, in GMT
2150 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
edf7fe8c 2151
2152}
2153
7cf1c7bd 2154/**
2155 * Returns a string that prints the user's timezone
2156 *
9df12115
RT
2157 * @package core
2158 * @category time
2159 * @param float|int|string $timezone timezone to calculate GMT time offset before
2160 * calculating user timezone, 99 is default user timezone
2161 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
7cf1c7bd 2162 * @return string
2163 */
d552ead0 2164function usertimezone($timezone=99) {
d552ead0 2165
0c244315 2166 $tz = get_user_timezone($timezone);
f30fe8d0 2167
0c244315 2168 if (!is_float($tz)) {
2169 return $tz;
d552ead0 2170 }
0c244315 2171
2172 if(abs($tz) > 13) { // Server time
2173 return get_string('serverlocaltime');
2174 }
2175
2176 if($tz == intval($tz)) {
2177 // Don't show .0 for whole hours
2178 $tz = intval($tz);
2179 }
2180
2181 if($tz == 0) {
61b420ac 2182 return 'UTC';
d552ead0 2183 }
0c244315 2184 else if($tz > 0) {
61b420ac 2185 return 'UTC+'.$tz;
0c244315 2186 }
2187 else {
61b420ac 2188 return 'UTC'.$tz;
d552ead0 2189 }
e1ecf0a0 2190
f9903ed0 2191}
2192
7cf1c7bd 2193/**
2194 * Returns a float which represents the user's timezone difference from GMT in hours
2195 * Checks various settings and picks the most dominant of those which have a value
2196 *
9df12115
RT
2197 * @package core
2198 * @category time
2199 * @param float|int|string $tz timezone to calculate GMT time offset for user,
2200 * 99 is default user timezone
2201 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
0d0a8bf6 2202 * @return float
7cf1c7bd 2203 */
494b9296 2204function get_user_timezone_offset($tz = 99) {
f30fe8d0 2205
43b59916 2206 global $USER, $CFG;
2207
e8904995 2208 $tz = get_user_timezone($tz);
c9e55a25 2209
7b9e355e 2210 if (is_float($tz)) {
2211 return $tz;
2212 } else {
e8904995 2213 $tzrecord = get_timezone_record($tz);
7b9e355e 2214 if (empty($tzrecord)) {
e8904995 2215 return 99.0;
2216 }
4f2dbde9 2217 return (float)$tzrecord->gmtoff / HOURMINS;
e8904995 2218 }
2219}
2220
61460dd6 2221/**
2222 * Returns an int which represents the systems's timezone difference from GMT in seconds
0d0a8bf6 2223 *
9df12115
RT
2224 * @package core
2225 * @category time
2226 * @param float|int|string $tz timezone for which offset is required.
2227 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2228 * @return int|bool if found, false is timezone 99 or error
61460dd6 2229 */
2230function get_timezone_offset($tz) {
2231 global $CFG;
2232
2233 if ($tz == 99) {
2234 return false;
2235 }
2236
2237 if (is_numeric($tz)) {
2238 return intval($tz * 60*60);
2239 }
2240
2241 if (!$tzrecord = get_timezone_record($tz)) {
2242 return false;
2243 }
2244 return intval($tzrecord->gmtoff * 60);
2245}
2246
bbd3f2c4 2247/**
b2b68362 2248 * Returns a float or a string which denotes the user's timezone
2249 * 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)
2250 * means that for this timezone there are also DST rules to be taken into account
2251 * Checks various settings and picks the most dominant of those which have a value
bbd3f2c4 2252 *
9df12115
RT
2253 * @package core
2254 * @category time
2255 * @param float|int|string $tz timezone to calculate GMT time offset before
2256 * calculating user timezone, 99 is default user timezone
2257 * {@link http://docs.moodle.org/dev/Time_API#Timezone}
2258 * @return float|string
bbd3f2c4 2259 */
e8904995 2260function get_user_timezone($tz = 99) {
2261 global $USER, $CFG;
43b59916 2262
f30fe8d0 2263 $timezones = array(
e8904995 2264 $tz,
2265 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
43b59916 2266 isset($USER->timezone) ? $USER->timezone : 99,
2267 isset($CFG->timezone) ? $CFG->timezone : 99,
f30fe8d0 2268 );
43b59916 2269
e8904995 2270 $tz = 99;
43b59916 2271
33998d30 2272 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
e8904995 2273 $tz = $next['value'];
43b59916 2274 }
e8904995 2275
2276 return is_numeric($tz) ? (float) $tz : $tz;
43b59916 2277}
2278
bbd3f2c4 2279/**
f33e1ed4 2280 * Returns cached timezone record for given $timezonename
bbd3f2c4 2281 *
9df12115
RT
2282 * @package core
2283 * @param string $timezonename name of the timezone
2284 * @return stdClass|bool timezonerecord or false
bbd3f2c4 2285 */
43b59916 2286function get_timezone_record($timezonename) {
f33e1ed4 2287 global $CFG, $DB;
43b59916 2288 static $cache = NULL;
2289
8edffd15 2290 if ($cache === NULL) {
43b59916 2291 $cache = array();
2292 }
2293
8edffd15 2294 if (isset($cache[$timezonename])) {
43b59916 2295 return $cache[$timezonename];
f30fe8d0 2296 }
2297
f33e1ed4 2298 return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
daac3835 2299 WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
f30fe8d0 2300}
f9903ed0 2301
bbd3f2c4 2302/**
0d0a8bf6 2303 * Build and store the users Daylight Saving Time (DST) table
bbd3f2c4 2304 *
9df12115
RT
2305 * @package core
2306 * @param int $from_year Start year for the table, defaults to 1971
2307 * @param int $to_year End year for the table, defaults to 2035
2308 * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
bbd3f2c4 2309 * @return bool
2310 */
94c82430 2311function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
ae040d4b 2312 global $CFG, $SESSION, $DB;
85cafb3e 2313
33998d30 2314 $usertz = get_user_timezone($strtimezone);
7cb29a3d 2315
989585e9 2316 if (is_float($usertz)) {
2317 // Trivial timezone, no DST
2318 return false;
2319 }
2320
2280ecf5 2321 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
989585e9 2322 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2280ecf5 2323 unset($SESSION->dst_offsets);
2324 unset($SESSION->dst_range);
830a2bbd 2325 }
2326
2280ecf5 2327 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
830a2bbd 2328 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
2329 // This will be the return path most of the time, pretty light computationally
2330 return true;
85cafb3e 2331 }
2332
830a2bbd 2333 // Reaching here means we either need to extend our table or create it from scratch
989585e9 2334
2335 // Remember which TZ we calculated these changes for
2280ecf5 2336 $SESSION->dst_offsettz = $usertz;
989585e9 2337
2280ecf5 2338 if(empty($SESSION->dst_offsets)) {
830a2bbd 2339 // If we 're creating from scratch, put the two guard elements in there
2280ecf5 2340 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
830a2bbd 2341 }
2280ecf5 2342 if(empty($SESSION->dst_range)) {
830a2bbd 2343 // If creating from scratch
2344 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
2345 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
2346
2347 // Fill in the array with the extra years we need to process
2348 $yearstoprocess = array();
2349 for($i = $from; $i <= $to; ++$i) {
2350 $yearstoprocess[] = $i;
2351 }
2352
2353 // Take note of which years we have processed for future calls
2280ecf5 2354 $SESSION->dst_range = array($from, $to);
830a2bbd 2355 }
2356 else {
2357 // If needing to extend the table, do the same
2358 $yearstoprocess = array();
2359
2280ecf5 2360 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
2361 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
830a2bbd 2362
2280ecf5 2363 if($from < $SESSION->dst_range[0]) {
830a2bbd 2364 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 2365 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
830a2bbd 2366 $yearstoprocess[] = $i;
2367 }
2280ecf5 2368 $SESSION->dst_range[0] = $from;
830a2bbd 2369 }
2280ecf5 2370 if($to > $SESSION->dst_range[1]) {
830a2bbd 2371 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 2372 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
830a2bbd 2373 $yearstoprocess[] = $i;
2374 }
2280ecf5 2375 $SESSION->dst_range[1] = $to;
830a2bbd 2376 }
2377 }
2378
2379 if(empty($yearstoprocess)) {
2380 // This means that there was a call requesting a SMALLER range than we have already calculated
2381 return true;
2382 }
2383
2384 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
2385 // Also, the array is sorted in descending timestamp order!
2386
2387 // Get DB data
6a5dc27c 2388
2389 static $presets_cache = array();
2390 if (!isset($presets_cache[$usertz])) {
ae040d4b 2391 $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 2392 }
2393 if(empty($presets_cache[$usertz])) {
e789650d 2394 return false;
2395 }
57f1191c 2396
830a2bbd 2397 // Remove ending guard (first element of the array)
2280ecf5 2398 reset($SESSION->dst_offsets);
2399 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
830a2bbd 2400
2401 // Add all required change timestamps
2402 foreach($yearstoprocess as $y) {
2403 // Find the record which is in effect for the year $y
6a5dc27c 2404 foreach($presets_cache[$usertz] as $year => $preset) {
830a2bbd 2405 if($year <= $y) {
2406 break;
c9e72798 2407 }
830a2bbd 2408 }
2409
2410 $changes = dst_changes_for_year($y, $preset);
2411
2412 if($changes === NULL) {
2413 continue;
2414 }
2415 if($changes['dst'] != 0) {
2280ecf5 2416 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
830a2bbd 2417 }
2418 if($changes['std'] != 0) {
2280ecf5 2419 $SESSION->dst_offsets[$changes['std']] = 0;
c9e72798 2420 }
85cafb3e 2421 }
42d36497 2422
830a2bbd 2423 // Put in a guard element at the top
2280ecf5 2424 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
2425 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
830a2bbd 2426
2427 // Sort again
2280ecf5 2428 krsort($SESSION->dst_offsets);
830a2bbd 2429
e789650d 2430 return true;
2431}
42d36497 2432
0d0a8bf6 2433/**
2434 * Calculates the required DST change and returns a Timestamp Array
2435 *
9df12115
RT
2436 * @package core
2437 * @category time
0d0a8bf6 2438 * @uses HOURSECS
2439 * @uses MINSECS
9df12115 2440 * @param int|string $year Int or String Year to focus on
0d0a8bf6 2441 * @param object $timezone Instatiated Timezone object
9df12115 2442 * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
0d0a8bf6 2443 */
e789650d 2444function dst_changes_for_year($year, $timezone) {
7cb29a3d 2445
e789650d 2446 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
2447 return NULL;
42d36497 2448 }
7cb29a3d 2449
e789650d 2450 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
2451 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
2452
2453 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
2454 list($std_hour, $std_min) = explode(':', $timezone->std_time);
d2a9f7cc 2455
6dc8dddc 2456 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
2457 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
830a2bbd 2458
2459 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
2460 // This has the advantage of being able to have negative values for hour, i.e. for timezones
2461 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
2462
2463 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
2464 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
42d36497 2465
e789650d 2466 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
42d36497 2467}
2468
0d0a8bf6 2469/**
efb8c375 2470 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
6a0bf5c4 2471 * - Note: Daylight saving only works for string timezones and not for float.
0d0a8bf6 2472 *
9df12115
RT
2473 * @package core
2474 * @category time
0d0a8bf6 2475 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
9df12115
RT
2476 * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
2477 * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
0d0a8bf6 2478 * @return int
2479 */
94c82430 2480function dst_offset_on($time, $strtimezone = NULL) {
2280ecf5 2481 global $SESSION;
02f0527d 2482
94c82430 2483 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
c9e72798 2484 return 0;
85cafb3e 2485 }
2486
2280ecf5 2487 reset($SESSION->dst_offsets);
2488 while(list($from, $offset) = each($SESSION->dst_offsets)) {
59556d48 2489 if($from <= $time) {
c9e72798 2490 break;
2491 }
2492 }
2493
830a2bbd 2494 // This is the normal return path
2495 if($offset !== NULL) {
2496 return $offset;
02f0527d 2497 }
02f0527d 2498
830a2bbd 2499 // Reaching this point means we haven't calculated far enough, do it now:
2500 // Calculate extra DST changes if needed and recurse. The recursion always
2501 // moves toward the stopping condition, so will always end.
2502
2503 if($from == 0) {
2280ecf5 2504 // We need a year smaller than $SESSION->dst_range[0]
2505 if($SESSION->dst_range[0] == 1971) {
830a2bbd 2506 return 0;
2507 }
94c82430 2508 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
2509 return dst_offset_on($time, $strtimezone);
830a2bbd 2510 }
2511 else {
2280ecf5 2512 // We need a year larger than $SESSION->dst_range[1]
2513 if($SESSION->dst_range[1] == 2035) {
830a2bbd 2514 return 0;
2515 }
94c82430 2516 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
2517 return dst_offset_on($time, $strtimezone);
830a2bbd 2518 }
85cafb3e 2519}
02f0527d 2520
0d0a8bf6 2521/**
9df12115 2522 * Calculates when the day appears in specific month
0d0a8bf6 2523 *
9df12115
RT
2524 * @package core
2525 * @category time
2526 * @param int $startday starting day of the month
2527 * @param int $weekday The day when week starts (normally taken from user preferences)
2528 * @param int $month The month whose day is sought
2529 * @param int $year The year of the month whose day is sought
0d0a8bf6 2530 * @return int
2531 */
28902d99 2532function find_day_in_month($startday, $weekday, $month, $year) {
8dc3f6cf 2533
2534 $daysinmonth = days_in_month($month, $year);
2535
42d36497 2536 if($weekday == -1) {
28902d99 2537 // Don't care about weekday, so return:
2538 // abs($startday) if $startday != -1
2539 // $daysinmonth otherwise
2540 return ($startday == -1) ? $daysinmonth : abs($startday);
8dc3f6cf 2541 }
2542
2543 // From now on we 're looking for a specific weekday
8dc3f6cf 2544
28902d99 2545 // Give "end of month" its actual value, since we know it
2546 if($startday == -1) {
2547 $startday = -1 * $daysinmonth;
2548 }
2549
2550 // Starting from day $startday, the sign is the direction
8dc3f6cf 2551
28902d99 2552 if($startday < 1) {
8dc3f6cf 2553
28902d99 2554 $startday = abs($startday);
ef7af3dd 2555 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
8dc3f6cf 2556
2557 // This is the last such weekday of the month
2558 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2559 if($lastinmonth > $daysinmonth) {
2560 $lastinmonth -= 7;
42d36497 2561 }
8dc3f6cf 2562
28902d99 2563 // Find the first such weekday <= $startday
2564 while($lastinmonth > $startday) {
8dc3f6cf 2565 $lastinmonth -= 7;
42d36497 2566 }
8dc3f6cf 2567
2568 return $lastinmonth;
e1ecf0a0 2569
42d36497 2570 }
2571 else {
42d36497 2572
ef7af3dd 2573 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
42d36497 2574
8dc3f6cf 2575 $diff = $weekday - $indexweekday;
2576 if($diff < 0) {
2577 $diff += 7;
42d36497 2578 }
42d36497 2579
28902d99 2580 // This is the first such weekday of the month equal to or after $startday
2581 $firstfromindex = $startday + $diff;
42d36497 2582
8dc3f6cf 2583 return $firstfromindex;
2584
2585 }
42d36497 2586}
2587
bbd3f2c4 2588/**
2589 * Calculate the number of days in a given month
2590 *
9df12115
RT
2591 * @package core
2592 * @category time
bbd3f2c4 2593 * @param int $month The month whose day count is sought
2594 * @param int $year The year of the month whose day count is sought
2595 * @return int
2596 */
42d36497 2597function days_in_month($month, $year) {
ef7af3dd 2598 return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
42d36497 2599}
2600
bbd3f2c4 2601/**
2602 * Calculate the position in the week of a specific calendar day
2603 *
9df12115
RT
2604 * @package core
2605 * @category time
bbd3f2c4 2606 * @param int $day The day of the date whose position in the week is sought
2607 * @param int $month The month of the date whose position in the week is sought
2608 * @param int $year The year of the date whose position in the week is sought
2609 * @return int
2610 */
8dc3f6cf 2611function dayofweek($day, $month, $year) {
2612 // I wonder if this is any different from
2613 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
d7eeb39e 2614 return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
8dc3f6cf 2615}
2616
9fa49e22 2617/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 2618
93f66983 2619/**
2620 * Returns full login url.
2621 *
93f66983 2622 * @return string login url
2623 */
999b54af 2624function get_login_url() {
93f66983 2625 global $CFG;
2626
999b54af 2627 $url = "$CFG->wwwroot/login/index.php";
93f66983 2628
999b54af
PS
2629 if (!empty($CFG->loginhttps)) {
2630 $url = str_replace('http:', 'https:', $url);
93f66983 2631 }
2632
2633 return $url;
2634}
2635
7cf1c7bd 2636/**
ec81373f 2637 * This function checks that the current user is logged in and has the
2638 * required privileges
2639 *
7cf1c7bd 2640 * This function checks that the current user is logged in, and optionally
ec81373f 2641 * whether they are allowed to be in a particular course and view a particular
2642 * course module.
2643 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 2644 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 2645 * case they are automatically logged in as guests.
2646 * If $courseid is given and the user is not enrolled in that course then the
2647 * user is redirected to the course enrolment page.
efb8c375 2648 * If $cm is given and the course module is hidden and the user is not a teacher
ec81373f 2649 * in the course then the user is redirected to the course home page.
7cf1c7bd 2650 *
191b267b 2651 * When $cm parameter specified, this function sets page layout to 'module'.
4f0c2d00 2652 * You need to change it manually later if some other layout needed.
191b267b 2653 *
f76249cc
PS
2654 * @package core_access
2655 * @category access
2656 *
33ebaf7c 2657 * @param mixed $courseorid id of the course or course object
0d0a8bf6 2658 * @param bool $autologinguest default true
bbd3f2c4 2659 * @param object $cm course module object
f4013c10 2660 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2661 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2662 * in order to keep redirects working properly. MDL-14495
df997f84 2663 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
0d0a8bf6 2664 * @return mixed Void, exit, and die depending on path
7cf1c7bd 2665 */
df997f84 2666function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
f0202ae9 2667 global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
d8ba183c 2668
df997f84 2669 // setup global $COURSE, themes, language and locale
c13a5e71 2670 if (!empty($courseorid)) {
2671 if (is_object($courseorid)) {
2672 $course = $courseorid;
2673 } else if ($courseorid == SITEID) {
2674 $course = clone($SITE);
2675 } else {
df997f84 2676 $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
c13a5e71 2677 }
95d28870 2678 if ($cm) {
df997f84
PS
2679 if ($cm->course != $course->id) {
2680 throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2681 }
0d8b6a69 2682 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
47148151 2683 if (!($cm instanceof cm_info)) {
0d8b6a69 2684 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
2685 // db queries so this is not really a performance concern, however it is obviously
2686 // better if you use get_fast_modinfo to get the cm before calling this.
2687 $modinfo = get_fast_modinfo($course);
2688 $cm = $modinfo->get_cm($cm->id);
2689 }
00dadbe1 2690 $PAGE->set_cm($cm, $course); // set's up global $COURSE
191b267b 2691 $PAGE->set_pagelayout('incourse');
95d28870 2692 } else {
00dadbe1 2693 $PAGE->set_course($course); // set's up global $COURSE
95d28870 2694 }
e88462a0 2695 } else {
df997f84
PS
2696 // do not touch global $COURSE via $PAGE->set_course(),
2697 // the reasons is we need to be able to call require_login() at any time!!
2698 $course = $SITE;
2699 if ($cm) {
2700 throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2701 }
c13a5e71 2702 }
be933850 2703
aa4a6566
SH
2704 // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2705 // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2706 // risk leading the user back to the AJAX request URL.
2707 if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2708 $setwantsurltome = false;
2709 }
2710
df997f84 2711 // If the user is not even logged in yet then make sure they are
083c3743 2712 if (!isloggedin()) {
df997f84 2713 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
999b54af
PS
2714 if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2715 // misconfigured site guest, just redirect to login page
2716 redirect(get_login_url());
2717 exit; // never reached
df997f84 2718 }
999b54af 2719 $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
0342fc36 2720 complete_user_login($guest);
d9e07264 2721 $USER->autologinguest = true;
999b54af 2722 $SESSION->lang = $lang;
8a33e371 2723 } else {
999b54af
PS
2724 //NOTE: $USER->site check was obsoleted by session test cookie,
2725 // $USER->confirmed test is in login/index.php
2726 if ($preventredirect) {
2727 throw new require_login_exception('You are not logged in');
2728 }
2729
2730 if ($setwantsurltome) {
f0202ae9 2731 $SESSION->wantsurl = qualified_me();
999b54af
PS
2732 }
2733 if (!empty($_SERVER['HTTP_REFERER'])) {
2734 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
2735 }
2736 redirect(get_login_url());
2737 exit; // never reached
8a33e371 2738 }
f9903ed0 2739 }
808a3baa 2740
df997f84
PS
2741 // loginas as redirection if needed
2742 if ($course->id != SITEID and session_is_loggedinas()) {
f6f66b03 2743 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
df997f84 2744 if ($USER->loginascontext->instanceid != $course->id) {
3887fe4a 2745 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
5e623a33 2746 }
f6f66b03 2747 }
2748 }
2749
df997f84 2750 // check whether the user should be changing password (but only if it is REALLY them)
b7b64ff2 2751 if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
21e2dcd9 2752 $userauth = get_auth_plugin($USER->auth);
df997f84 2753 if ($userauth->can_change_password() and !$preventredirect) {
af572078 2754 if ($setwantsurltome) {
f0202ae9 2755 $SESSION->wantsurl = qualified_me();
af572078 2756 }
80274abf 2757 if ($changeurl = $userauth->change_password_url()) {
9696bd89 2758 //use plugin custom url
80274abf 2759 redirect($changeurl);
1437f0a5 2760 } else {
9696bd89 2761 //use moodle internal method
2762 if (empty($CFG->loginhttps)) {
2763 redirect($CFG->wwwroot .'/login/change_password.php');
2764 } else {
2765 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
2766 redirect($wwwroot .'/login/change_password.php');
2767 }
1437f0a5 2768 }
d35757eb 2769 } else {
a8ee7194 2770 print_error('nopasswordchangeforced', 'auth');
d35757eb 2771 }
2772 }
083c3743 2773
df997f84 2774 // Check that the user account is properly set up
808a3baa 2775 if (user_not_fully_set_up($USER)) {
df997f84
PS
2776 if ($preventredirect) {
2777 throw new require_login_exception('User not fully set-up');
2778 }
af572078 2779 if ($setwantsurltome) {
f0202ae9 2780 $SESSION->wantsurl = qualified_me();
af572078 2781 }
b0ccd3fb 2782 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 2783 }
d8ba183c 2784
df997f84 2785 // Make sure the USER has a sesskey set up. Used for CSRF protection.
04280e85 2786 sesskey();
366dfa60 2787
1560760f 2788 // Do not bother admins with any formalities
df997f84 2789 if (is_siteadmin()) {
1560760f
AD
2790 //set accesstime or the user will appear offline which messes up messaging
2791 user_accesstime_log($course->id);
df997f84
PS
2792 return;
2793 }
2794
b593d49d
PS
2795 // Check that the user has agreed to a site policy if there is one - do not test in case of admins
2796 if (!$USER->policyagreed and !is_siteadmin()) {
2797 if (!empty($CFG->sitepolicy) and !isguestuser()) {
2798 if ($preventredirect) {
2799 throw new require_login_exception('Policy not agreed');
2800 }
af572078 2801 if ($setwantsurltome) {
f0202ae9 2802 $SESSION->wantsurl = qualified_me();
af572078 2803 }
b593d49d
PS
2804 redirect($CFG->wwwroot .'/user/policy.php');
2805 } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
2806 if ($preventredirect) {
2807 throw new require_login_exception('Policy not agreed');
2808 }
af572078 2809 if ($setwantsurltome) {
f0202ae9 2810 $SESSION->wantsurl = qualified_me();
af572078 2811 }
027a1604 2812 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 2813 }
1695b680 2814 }
2815
df997f84 2816 // Fetch the system context, the course context, and prefetch its child contexts
21e2dcd9 2817 $sysctx = get_context_instance(CONTEXT_SYSTEM);
df997f84
PS
2818 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
2819 if ($cm) {
2820 $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
2821 } else {
2822 $cmcontext = null;
2823 }
21e2dcd9 2824
df997f84 2825 // If the site is currently under maintenance, then print a message
4fe2250a 2826 if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
df997f84
PS
2827 if ($preventredirect) {
2828 throw new require_login_exception('Maintenance in progress');
2829 }
2830
4fe2250a 2831 print_maintenance_message();
027a1604 2832 }
2833
df997f84
PS
2834 // make sure the course itself is not hidden
2835 if ($course->id == SITEID) {
2836 // frontpage can not be hidden
2837 } else {
f5c1e621 2838 if (is_role_switched($course->id)) {
df997f84
PS
2839 // when switching roles ignore the hidden flag - user had to be in course to do the switch
2840 } else {
2841 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2842 // originally there was also test of parent category visibility,
2843 // BUT is was very slow in complex queries involving "my courses"
2844 // now it is also possible to simply hide all courses user is not enrolled in :-)
2845 if ($preventredirect) {
2846 throw new require_login_exception('Course is hidden');
2847 }
a0a39b0d
SH
2848 // We need to override the navigation URL as the course won't have
2849 // been added to the navigation and thus the navigation will mess up
2850 // when trying to find it.
2851 navigation_node::override_active_url(new moodle_url('/'));
df997f84
PS
2852 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2853 }
2854 }
2855 }
2856
2857 // is the user enrolled?
2858 if ($course->id == SITEID) {
2859 // everybody is enrolled on the frontpage
2860
2861 } else {
2862 if (session_is_loggedinas()) {
2863 // Make sure the REAL person can access this course first
2864 $realuser = session_get_realuser();
2865 if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2866 if ($preventredirect) {
2867 throw new require_login_exception('Invalid course login-as access');
2868 }
2869 echo $OUTPUT->header();
2870 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2871 }
2872 }
2873
df997f84
PS
2874 $access = false;
2875
dbd7282c
PS
2876 if (is_role_switched($course->id)) {
2877 // ok, user had to be inside this course before the switch
2878 $access = true;
2879
2880 } else if (is_viewing($coursecontext, $USER)) {
df997f84
PS
2881 // ok, no need to mess with enrol
2882 $access = true;
2883
2884 } else {
2885 if (isset($USER->enrol['enrolled'][$course->id])) {
bbfdff34 2886 if ($USER->enrol['enrolled'][$course->id] > time()) {
df997f84 2887 $access = true;
bbfdff34
PS
2888 if (isset($USER->enrol['tempguest'][$course->id])) {
2889 unset($USER->enrol['tempguest'][$course->id]);
2890 remove_temp_course_roles($coursecontext);
2891 }
df997f84
PS
2892 } else {
2893 //expired
2894 unset($USER->enrol['enrolled'][$course->id]);
2895 }
2896 }
2897 if (isset($USER->enrol['tempguest'][$course->id])) {
2898 if ($USER->enrol['tempguest'][$course->id] == 0) {
2899 $access = true;
2900 } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2901 $access = true;
2902 } else {
2903 //expired
2904 unset($USER->enrol['tempguest'][$course->id]);
e922fe23 2905 remove_temp_course_roles($coursecontext);
df997f84
PS
2906 }
2907 }
2908
2909 if ($access) {
2910 // cache ok
df997f84 2911 } else {
bbfdff34
PS
2912 $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2913 if ($until !== false) {
2914 // active participants may always access, a timestamp in the future, 0 (always) or false.
2915 if ($until == 0) {
2916 $until = ENROL_MAX_TIMESTAMP;
df997f84 2917 }
bbfdff34
PS
2918 $USER->enrol['enrolled'][$course->id] = $until;
2919 $access = true;
2920
2921 } else {
2922 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2923 $enrols = enrol_get_plugins(true);
2924 // first ask all enabled enrol instances in course if they want to auto enrol user
df997f84
PS
2925 foreach($instances as $instance) {
2926 if (!isset($enrols[$instance->enrol])) {
2927 continue;
2928 }
bbfdff34
PS
2929 // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2930 $until = $enrols[$instance->enrol]->try_autoenrol($instance);
df997f84 2931 if ($until !== false) {
bbfdff34
PS
2932 if ($until == 0) {
2933 $until = ENROL_MAX_TIMESTAMP;
2934 }
2935 $USER->enrol['enrolled'][$course->id] = $until;
df997f84
PS
2936 $access = true;
2937 break;
2938 }
2939 }
bbfdff34
PS
2940 // if not enrolled yet try to gain temporary guest access
2941 if (!$access) {
2942 foreach($instances as $instance) {
2943 if (!isset($enrols[$instance->enrol])) {
2944 continue;
2945 }
2946 // Get a duration for the guest access, a timestamp in the future or false.
2947 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2948 if ($until !== false and $until > time()) {
2949 $USER->enrol['tempguest'][$course->id] = $until;
2950 $access = true;
2951 break;
2952 }
2953 }
2954 }
df997f84
PS
2955 }
2956 }
2957 }
2958
2959 if (!$access) {
2960 if ($preventredirect) {
2961 throw new require_login_exception('Not enrolled');
2962 }
af572078 2963 if ($setwantsurltome) {
f0202ae9 2964 $SESSION->wantsurl = qualified_me();
af572078 2965 }
df997f84
PS
2966 redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2967 }
2968 }
2969
0d8b6a69 2970 // Check visibility of activity to current user; includes visible flag, groupmembersonly,
2971 // conditional availability, etc
2972 if ($cm && !$cm->uservisible) {
df997f84
PS
2973 if ($preventredirect) {
2974 throw new require_login_exception('Activity is hidden');
2975 }
2976 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
2977 }
2978
df997f84
PS
2979 // Finally access granted, update lastaccess times
2980 user_accesstime_log($course->id);
f9903ed0 2981}
2982
c4d0753b 2983
c4d0753b 2984/**
2985 * This function just makes sure a user is logged out.
2986 *
f76249cc 2987 * @package core_access
c4d0753b 2988 */
2989function require_logout() {
dd9e22f8 2990 global $USER;
c4d0753b 2991
a8e3b008
DC
2992 $params = $USER;
2993
111e2360 2994 if (isloggedin()) {
c4d0753b 2995 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2996
533f7910 2997 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2998 foreach($authsequence as $authname) {
2999 $authplugin = get_auth_plugin($authname);
3000 $authplugin->prelogout_hook();
81693ac7 3001 }
c4d0753b 3002 }
3003
a8e3b008 3004 events_trigger('user_logout', $params);
56949c17 3005 session_get_instance()->terminate_current();
a8e3b008 3006 unset($params);
c4d0753b 3007}
3008
7cf1c7bd 3009/**
0d0a8bf6 3010 * Weaker version of require_login()
3011 *
7cf1c7bd 3012 * This is a weaker version of {@link require_login()} which only requires login
3013 * when called from within a course rather than the site page, unless
3014 * the forcelogin option is turned on.
0d0a8bf6 3015 * @see require_login()
7cf1c7bd 3016 *
f76249cc
PS
3017 * @package core_access
3018 * @category access
3019 *
33ebaf7c 3020 * @param mixed $courseorid The course object or id in question
bbd3f2c4 3021 * @param bool $autologinguest Allow autologin guests if that is wanted
4febb58f 3022 * @param object $cm Course activity module if known
f4013c10 3023 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3024 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3025 * in order to keep redirects working properly. MDL-14495
df997f84
PS
3026 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3027 * @return void
7cf1c7bd 3028 */
df997f84 3029function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
862940c0 3030 global $CFG, $PAGE, $SITE;
0d8b6a69 3031 $issite = (is_object($courseorid) and $courseorid->id == SITEID)
3032 or (!is_object($courseorid) and $courseorid == SITEID);
d4fb0e26 3033 if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
0d8b6a69 3034 // note: nearly all pages call get_fast_modinfo anyway and it does not make any
3035 // db queries so this is not really a performance concern, however it is obviously
3036 // better if you use get_fast_modinfo to get the cm before calling this.
3037 if (is_object($courseorid)) {
3038 $course = $courseorid;
3039 } else {
3040 $course = clone($SITE);
3041 }
3042 $modinfo = get_fast_modinfo($course);
3043 $cm = $modinfo->get_cm($cm->id);
3044 }
1596edff 3045 if (!empty($CFG->forcelogin)) {
33ebaf7c 3046 // login required for both SITE and courses
df997f84 3047 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
63c9ee99 3048
0d8b6a69 3049 } else if ($issite && !empty($cm) and !$cm->uservisible) {
63c9ee99 3050 // always login for hidden activities
df997f84 3051 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
63c9ee99 3052
0d8b6a69 3053 } else if ($issite) {
9950c88f 3054 //login for SITE not required
3055 if ($cm and empty($cm->visible)) {
3056 // hidden activities are not accessible without login
df997f84 3057 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
98da6021 3058 } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
9950c88f 3059 // not-logged-in users do not have any group membership
df997f84 3060 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
9950c88f 3061 } else {
862940c0
SH
3062 // We still need to instatiate PAGE vars properly so that things
3063 // that rely on it like navigation function correctly.
3064 if (!empty($courseorid)) {
3065 if (is_object($courseorid)) {
3066 $course = $courseorid;
3067 } else {
3068 $course = clone($SITE);
3069 }
3070 if ($cm) {
df997f84
PS
3071 if ($cm->course != $course->id) {
3072 throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3073 }
862940c0 3074 $PAGE->set_cm($cm, $course);
191b267b 3075 $PAGE->set_pagelayout('incourse');
862940c0
SH
3076 } else {
3077 $PAGE->set_course($course);
3078 }
3079 } else {
3080 // If $PAGE->course, and hence $PAGE->context, have not already been set
3081 // up properly, set them up now.
3082 $PAGE->set_course($PAGE->course);
3083 }
9950c88f 3084 //TODO: verify conditional activities here
3085 user_accesstime_log(SITEID);
3086 return;
3087 }
63c9ee99 3088
33ebaf7c 3089 } else {
3090 // course login always required
df997f84 3091 require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
f950af3c 3092 }
3093}
3094
61c6071f 3095/**
3096 * Require key login. Function terminates with error if key not found or incorrect.
0d0a8bf6 3097 *
3098 * @global object
3099 * @global object
3100 * @global object
3101 * @global object
3102 * @uses NO_MOODLE_COOKIES
3103 * @uses PARAM_ALPHANUM
61c6071f 3104 * @param string $script unique script identifier
3105 * @param int $instance optional instance id
0d0a8bf6 3106 * @return int Instance ID
61c6071f 3107 */
3108function require_user_key_login($script, $instance=null) {
82dd4f42 3109 global $USER, $SESSION, $CFG, $DB;
61c6071f 3110
82dd4f42 3111 if (!NO_MOODLE_COOKIES) {
2f137aa1 3112 print_error('sessioncookiesdisable');
61c6071f 3113 }
3114
3115/// extra safety
3116 @session_write_close();
3117
3118 $keyvalue = required_param('key', PARAM_ALPHANUM);
3119
ae040d4b 3120 if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
2f137aa1 3121 print_error('invalidkey');
61c6071f 3122 }
3123
3124 if (!empty($key->validuntil) and $key->validuntil < time()) {
2f137aa1 3125 print_error('expiredkey');
61c6071f 3126 }
3127
e436033f 3128 if ($key->iprestriction) {
765a1d4b
MD
3129 $remoteaddr = getremoteaddr(null);
3130 if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2f137aa1 3131 print_error('ipmismatch');
e436033f 3132 }
61c6071f 3133 }
3134
ae040d4b 3135 if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
2f137aa1 3136 print_error('invaliduserid');
61c6071f 3137 }
3138
3139/// emulate normal session
e922fe23 3140 enrol_check_plugins($user);
27df7ae8 3141 session_set_user($user);
61c6071f 3142
e2fa911b 3143/// note we are not using normal login
3144 if (!defined('USER_KEY_LOGIN')) {
3145 define('USER_KEY_LOGIN', true);
3146 }
3147
792881f0 3148/// return instance id - it might be empty
61c6071f 3149 return $key->instance;
3150}
3151
3152/**
3153 * Creates a new private user access key.
0d0a8bf6 3154 *
3155 * @global object
61c6071f 3156 * @param string $script unique target identifier
3157 * @param int $userid