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