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