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