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