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