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