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