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