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