MDL-11048 adding new method to textlib strtotitle() - please note that is may not...
[moodle.git] / lib / moodlelib.php
CommitLineData
ef1e97c7 1<?php // $Id$
f9903ed0 2
9fa49e22 3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
abc3b857 8// http://moodle.org //
9fa49e22 9// //
abc3b857 10// Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
9fa49e22 11// //
12// This program is free software; you can redistribute it and/or modify //
13// it under the terms of the GNU General Public License as published by //
14// the Free Software Foundation; either version 2 of the License, or //
15// (at your option) any later version. //
16// //
17// This program is distributed in the hope that it will be useful, //
18// but WITHOUT ANY WARRANTY; without even the implied warranty of //
19// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20// GNU General Public License for more details: //
21// //
22// http://www.gnu.org/copyleft/gpl.html //
23// //
24///////////////////////////////////////////////////////////////////////////
65ccdd8c 25
7cf1c7bd 26/**
89dcb99d 27 * moodlelib.php - Moodle main library
7cf1c7bd 28 *
29 * Main library file of miscellaneous general-purpose Moodle functions.
30 * Other main libraries:
8c3dba73 31 * - weblib.php - functions that produce web output
32 * - datalib.php - functions that access the database
7cf1c7bd 33 * @author Martin Dougiamas
34 * @version $Id$
89dcb99d 35 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7cf1c7bd 36 * @package moodlecore
37 */
e1ecf0a0 38
bbd3f2c4 39/// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
f374fb10 40
6b94a807 41/**
42 * Used by some scripts to check they are being called by Moodle
43 */
44define('MOODLE_INTERNAL', true);
45
bbd3f2c4 46/// Date and time constants ///
5602f7cf 47/**
48 * Time constant - the number of seconds in a year
49 */
50
51define('YEARSECS', 31536000);
52
7a5672c9 53/**
2f87145b 54 * Time constant - the number of seconds in a week
7a5672c9 55 */
361855e6 56define('WEEKSECS', 604800);
2f87145b 57
58/**
59 * Time constant - the number of seconds in a day
60 */
7a5672c9 61define('DAYSECS', 86400);
2f87145b 62
63/**
64 * Time constant - the number of seconds in an hour
65 */
7a5672c9 66define('HOURSECS', 3600);
2f87145b 67
68/**
69 * Time constant - the number of seconds in a minute
70 */
7a5672c9 71define('MINSECS', 60);
2f87145b 72
73/**
74 * Time constant - the number of minutes in a day
75 */
7a5672c9 76define('DAYMINS', 1440);
2f87145b 77
78/**
79 * Time constant - the number of minutes in an hour
80 */
7a5672c9 81define('HOURMINS', 60);
f9903ed0 82
c59733ef 83/// Parameter constants - every call to optional_param(), required_param() ///
84/// or clean_param() should have a specified type of parameter. //////////////
85
e0d346ff 86/**
038ba6aa 87 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way;
88 * originally was 0, but changed because we need to detect unknown
89 * parameter types and swiched order in clean_param().
e0d346ff 90 */
038ba6aa 91define('PARAM_RAW', 666);
bbd3f2c4 92
93/**
c59733ef 94 * PARAM_CLEAN - obsoleted, please try to use more specific type of parameter.
95 * It was one of the first types, that is why it is abused so much ;-)
bbd3f2c4 96 */
2ae28153 97define('PARAM_CLEAN', 0x0001);
bbd3f2c4 98
99/**
c59733ef 100 * PARAM_INT - integers only, use when expecting only numbers.
bbd3f2c4 101 */
2ae28153 102define('PARAM_INT', 0x0002);
bbd3f2c4 103
104/**
105 * PARAM_INTEGER - an alias for PARAM_INT
106 */
107define('PARAM_INTEGER', 0x0002);
108
9dae915a 109/**
5e623a33 110 * PARAM_NUMBER - a real/floating point number.
9dae915a 111 */
112define('PARAM_NUMBER', 0x000a);
113
bbd3f2c4 114/**
c59733ef 115 * PARAM_ALPHA - contains only english letters.
bbd3f2c4 116 */
2ae28153 117define('PARAM_ALPHA', 0x0004);
bbd3f2c4 118
119/**
c59733ef 120 * PARAM_ACTION - an alias for PARAM_ALPHA, use for various actions in formas and urls
121 * @TODO: should we alias it to PARAM_ALPHANUM ?
bbd3f2c4 122 */
123define('PARAM_ACTION', 0x0004);
124
125/**
c59733ef 126 * PARAM_FORMAT - an alias for PARAM_ALPHA, use for names of plugins, formats, etc.
127 * @TODO: should we alias it to PARAM_ALPHANUM ?
bbd3f2c4 128 */
129define('PARAM_FORMAT', 0x0004);
130
131/**
c59733ef 132 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
bbd3f2c4 133 */
2ae28153 134define('PARAM_NOTAGS', 0x0008);
bbd3f2c4 135
31f26796 136 /**
c4ea5e78 137 * PARAM_MULTILANG - alias of PARAM_TEXT.
31f26796 138 */
139define('PARAM_MULTILANG', 0x0009);
140
c4ea5e78 141 /**
142 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
143 */
144define('PARAM_TEXT', 0x0009);
145
bbd3f2c4 146/**
c59733ef 147 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
bbd3f2c4 148 */
2ae28153 149define('PARAM_FILE', 0x0010);
bbd3f2c4 150
151/**
c59733ef 152 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
153 * note: the leading slash is not removed, window drive letter is not allowed
bbd3f2c4 154 */
2ae28153 155define('PARAM_PATH', 0x0020);
bbd3f2c4 156
157/**
c59733ef 158 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
bbd3f2c4 159 */
160define('PARAM_HOST', 0x0040);
161
162/**
c59733ef 163 * PARAM_URL - expected properly formatted URL.
bbd3f2c4 164 */
2ae28153 165define('PARAM_URL', 0x0080);
bbd3f2c4 166
167/**
c59733ef 168 * 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!)
bbd3f2c4 169 */
170define('PARAM_LOCALURL', 0x0180);
171
172/**
c59733ef 173 * PARAM_CLEANFILE - safe file name, all dangerous and regional chars are removed,
174 * use when you want to store a new file submitted by students
bbd3f2c4 175 */
14d6c233 176define('PARAM_CLEANFILE',0x0200);
e0d346ff 177
8bd3fad3 178/**
c59733ef 179 * PARAM_ALPHANUM - expected numbers and letters only.
bbd3f2c4 180 */
181define('PARAM_ALPHANUM', 0x0400);
182
183/**
c59733ef 184 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
bbd3f2c4 185 */
186define('PARAM_BOOL', 0x0800);
187
188/**
c59733ef 189 * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes
190 * note: do not forget to addslashes() before storing into database!
bbd3f2c4 191 */
192define('PARAM_CLEANHTML',0x1000);
193
194/**
c59733ef 195 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "/-_" allowed,
196 * suitable for include() and require()
197 * @TODO: should we rename this function to PARAM_SAFEDIRS??
bbd3f2c4 198 */
199define('PARAM_ALPHAEXT', 0x2000);
200
201/**
c59733ef 202 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
bbd3f2c4 203 */
204define('PARAM_SAFEDIR', 0x4000);
205
0e4af166 206/**
207 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
208 */
209define('PARAM_SEQUENCE', 0x8000);
210
03d820c7 211/**
212 * PARAM_PEM - Privacy Enhanced Mail format
213 */
214define('PARAM_PEM', 0x10000);
215
216/**
217 * PARAM_BASE64 - Base 64 encoded format
218 */
219define('PARAM_BASE64', 0x20000);
220
221
bbd3f2c4 222/// Page types ///
223/**
224 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
8bd3fad3 225 */
226define('PAGE_COURSE_VIEW', 'course-view');
8bd3fad3 227
7eb0b60a 228/// Debug levels ///
229/** no warnings at all */
230define ('DEBUG_NONE', 0);
231/** E_ERROR | E_PARSE */
232define ('DEBUG_MINIMAL', 5);
233/** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
234define ('DEBUG_NORMAL', 15);
235/** E_ALL without E_STRICT and E_RECOVERABLE_ERROR for now */
236define ('DEBUG_ALL', 2047);
237/** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
238define ('DEBUG_DEVELOPER', 34815);
bbd3f2c4 239
feaf5d06 240/**
241 * Blog access level constant declaration
242 */
243define ('BLOG_USER_LEVEL', 1);
244define ('BLOG_GROUP_LEVEL', 2);
245define ('BLOG_COURSE_LEVEL', 3);
246define ('BLOG_SITE_LEVEL', 4);
247define ('BLOG_GLOBAL_LEVEL', 5);
248
249
03d820c7 250
9fa49e22 251/// PARAMETER HANDLING ////////////////////////////////////////////////////
6b174680 252
e0d346ff 253/**
361855e6 254 * Returns a particular value for the named variable, taken from
255 * POST or GET. If the parameter doesn't exist then an error is
e0d346ff 256 * thrown because we require this variable.
257 *
361855e6 258 * This function should be used to initialise all required values
259 * in a script that are based on parameters. Usually it will be
e0d346ff 260 * used like this:
261 * $id = required_param('id');
262 *
a083b93c 263 * @param string $parname the name of the page parameter we want
264 * @param int $type expected type of parameter
e0d346ff 265 * @return mixed
266 */
a083b93c 267function required_param($parname, $type=PARAM_CLEAN) {
e0d346ff 268
5d7a9f56 269 // detect_unchecked_vars addition
270 global $CFG;
271 if (!empty($CFG->detect_unchecked_vars)) {
272 global $UNCHECKED_VARS;
a083b93c 273 unset ($UNCHECKED_VARS->vars[$parname]);
5d7a9f56 274 }
275
a083b93c 276 if (isset($_POST[$parname])) { // POST has precedence
277 $param = $_POST[$parname];
278 } else if (isset($_GET[$parname])) {
279 $param = $_GET[$parname];
e0d346ff 280 } else {
a083b93c 281 error('A required parameter ('.$parname.') was missing');
e0d346ff 282 }
283
a083b93c 284 return clean_param($param, $type);
e0d346ff 285}
286
287/**
361855e6 288 * Returns a particular value for the named variable, taken from
e0d346ff 289 * POST or GET, otherwise returning a given default.
290 *
361855e6 291 * This function should be used to initialise all optional values
292 * in a script that are based on parameters. Usually it will be
e0d346ff 293 * used like this:
294 * $name = optional_param('name', 'Fred');
295 *
a083b93c 296 * @param string $parname the name of the page parameter we want
e0d346ff 297 * @param mixed $default the default value to return if nothing is found
a083b93c 298 * @param int $type expected type of parameter
e0d346ff 299 * @return mixed
300 */
a083b93c 301function optional_param($parname, $default=NULL, $type=PARAM_CLEAN) {
e0d346ff 302
5d7a9f56 303 // detect_unchecked_vars addition
304 global $CFG;
305 if (!empty($CFG->detect_unchecked_vars)) {
306 global $UNCHECKED_VARS;
a083b93c 307 unset ($UNCHECKED_VARS->vars[$parname]);
5d7a9f56 308 }
309
a083b93c 310 if (isset($_POST[$parname])) { // POST has precedence
311 $param = $_POST[$parname];
312 } else if (isset($_GET[$parname])) {
313 $param = $_GET[$parname];
e0d346ff 314 } else {
315 return $default;
316 }
317
a083b93c 318 return clean_param($param, $type);
e0d346ff 319}
320
321/**
361855e6 322 * Used by {@link optional_param()} and {@link required_param()} to
323 * clean the variables and/or cast to specific types, based on
e0d346ff 324 * an options field.
bbd3f2c4 325 * <code>
326 * $course->format = clean_param($course->format, PARAM_ALPHA);
327 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
328 * </code>
e0d346ff 329 *
bbd3f2c4 330 * @uses $CFG
331 * @uses PARAM_CLEAN
332 * @uses PARAM_INT
333 * @uses PARAM_INTEGER
334 * @uses PARAM_ALPHA
335 * @uses PARAM_ALPHANUM
336 * @uses PARAM_NOTAGS
f4f65990 337 * @uses PARAM_ALPHAEXT
bbd3f2c4 338 * @uses PARAM_BOOL
339 * @uses PARAM_SAFEDIR
340 * @uses PARAM_CLEANFILE
341 * @uses PARAM_FILE
342 * @uses PARAM_PATH
343 * @uses PARAM_HOST
344 * @uses PARAM_URL
345 * @uses PARAM_LOCALURL
346 * @uses PARAM_CLEANHTML
0e4af166 347 * @uses PARAM_SEQUENCE
e0d346ff 348 * @param mixed $param the variable we are cleaning
a083b93c 349 * @param int $type expected format of param after cleaning.
e0d346ff 350 * @return mixed
351 */
a083b93c 352function clean_param($param, $type) {
e0d346ff 353
7744ea12 354 global $CFG;
355
80bfd470 356 if (is_array($param)) { // Let's loop
357 $newparam = array();
358 foreach ($param as $key => $value) {
a083b93c 359 $newparam[$key] = clean_param($value, $type);
80bfd470 360 }
361 return $newparam;
362 }
363
a083b93c 364 switch ($type) {
96e98ea6 365 case PARAM_RAW: // no cleaning at all
366 return $param;
367
a083b93c 368 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
369 if (is_numeric($param)) {
370 return $param;
371 }
372 $param = stripslashes($param); // Needed for kses to work fine
373 $param = clean_text($param); // Sweep for scripts, etc
374 return addslashes($param); // Restore original request parameter slashes
3af57507 375
a083b93c 376 case PARAM_CLEANHTML: // prepare html fragment for display, do not store it into db!!
377 $param = stripslashes($param); // Remove any slashes
378 $param = clean_text($param); // Sweep for scripts, etc
379 return trim($param);
e0d346ff 380
a083b93c 381 case PARAM_INT:
382 return (int)$param; // Convert to integer
e0d346ff 383
9dae915a 384 case PARAM_NUMBER:
385 return (float)$param; // Convert to integer
386
a083b93c 387 case PARAM_ALPHA: // Remove everything not a-z
388 return eregi_replace('[^a-zA-Z]', '', $param);
e0d346ff 389
a083b93c 390 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
391 return eregi_replace('[^A-Za-z0-9]', '', $param);
f24148ef 392
a083b93c 393 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z/_-
394 return eregi_replace('[^a-zA-Z/_-]', '', $param);
0ed442f8 395
0e4af166 396 case PARAM_SEQUENCE: // Remove everything not 0-9,
397 return eregi_replace('[^0-9,]', '', $param);
398
a083b93c 399 case PARAM_BOOL: // Convert to 1 or 0
400 $tempstr = strtolower($param);
eb59ac27 401 if ($tempstr == 'on' or $tempstr == 'yes' ) {
a083b93c 402 $param = 1;
eb59ac27 403 } else if ($tempstr == 'off' or $tempstr == 'no') {
a083b93c 404 $param = 0;
405 } else {
406 $param = empty($param) ? 0 : 1;
407 }
408 return $param;
f24148ef 409
a083b93c 410 case PARAM_NOTAGS: // Strip all tags
411 return strip_tags($param);
3af57507 412
c4ea5e78 413 case PARAM_TEXT: // leave only tags needed for multilang
31f26796 414 return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN);
415
a083b93c 416 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
417 return eregi_replace('[^a-zA-Z0-9_-]', '', $param);
95bfd207 418
a083b93c 419 case PARAM_CLEANFILE: // allow only safe characters
420 return clean_filename($param);
14d6c233 421
a083b93c 422 case PARAM_FILE: // Strip all suspicious characters from filename
423 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':\\/]', '', $param);
424 $param = ereg_replace('\.\.+', '', $param);
425 if($param == '.') {
371a2ed0 426 $param = '';
427 }
a083b93c 428 return $param;
429
430 case PARAM_PATH: // Strip all suspicious characters from file path
431 $param = str_replace('\\\'', '\'', $param);
432 $param = str_replace('\\"', '"', $param);
433 $param = str_replace('\\', '/', $param);
434 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':]', '', $param);
435 $param = ereg_replace('\.\.+', '', $param);
436 $param = ereg_replace('//+', '/', $param);
437 return ereg_replace('/(\./)+', '/', $param);
438
439 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
440 preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
441 // match ipv4 dotted quad
442 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
443 // confirm values are ok
444 if ( $match[0] > 255
445 || $match[1] > 255
446 || $match[3] > 255
447 || $match[4] > 255 ) {
448 // hmmm, what kind of dotted quad is this?
449 $param = '';
450 }
451 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
452 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
453 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
454 ) {
455 // all is ok - $param is respected
456 } else {
457 // all is not ok...
458 $param='';
459 }
460 return $param;
7744ea12 461
a083b93c 462 case PARAM_URL: // allow safe ftp, http, mailto urls
463 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
5301205a 464 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
a083b93c 465 // all is ok, param is respected
d2a9f7cc 466 } else {
a083b93c 467 $param =''; // not really ok
468 }
469 return $param;
470
471 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
93684765 472 $param = clean_param($param, PARAM_URL);
a083b93c 473 if (!empty($param)) {
474 if (preg_match(':^/:', $param)) {
475 // root-relative, ok!
476 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
477 // absolute, and matches our wwwroot
7744ea12 478 } else {
a083b93c 479 // relative - let's make sure there are no tricks
480 if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
481 // looks ok.
482 } else {
483 $param = '';
484 }
d2a9f7cc 485 }
7744ea12 486 }
a083b93c 487 return $param;
03d820c7 488 case PARAM_PEM:
489 $param = trim($param);
490 // PEM formatted strings may contain letters/numbers and the symbols
491 // forward slash: /
492 // plus sign: +
493 // equal sign: =
494 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
495 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
496 list($wholething, $body) = $matches;
497 unset($wholething, $matches);
498 $b64 = clean_param($body, PARAM_BASE64);
499 if (!empty($b64)) {
500 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
501 } else {
502 return '';
503 }
504 }
505 return '';
506 case PARAM_BASE64:
507 if (!empty($param)) {
508 // PEM formatted strings may contain letters/numbers and the symbols
509 // forward slash: /
510 // plus sign: +
511 // equal sign: =
03d820c7 512 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
513 return '';
514 }
515 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
516 // Each line of base64 encoded data must be 64 characters in
517 // length, except for the last line which may be less than (or
518 // equal to) 64 characters long.
519 for ($i=0, $j=count($lines); $i < $j; $i++) {
520 if ($i + 1 == $j) {
521 if (64 < strlen($lines[$i])) {
522 return '';
523 }
524 continue;
525 }
7744ea12 526
03d820c7 527 if (64 != strlen($lines[$i])) {
528 return '';
529 }
530 }
531 return implode("\n",$lines);
532 } else {
533 return '';
534 }
a083b93c 535 default: // throw error, switched parameters in optional_param or another serious problem
536 error("Unknown parameter type: $type");
2ae28153 537 }
e0d346ff 538}
539
6b174680 540
7a530277 541
7cf1c7bd 542/**
543 * Set a key in global configuration
544 *
89dcb99d 545 * Set a key/value pair in both this session's {@link $CFG} global variable
7cf1c7bd 546 * and in the 'config' database table for future sessions.
e1ecf0a0 547 *
548 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
549 * In that case it doesn't affect $CFG.
7cf1c7bd 550 *
551 * @param string $name the key to set
9cdb766d 552 * @param string $value the value to set (without magic quotes)
a4080313 553 * @param string $plugin (optional) the plugin scope
7cf1c7bd 554 * @uses $CFG
555 * @return bool
556 */
a4080313 557function set_config($name, $value, $plugin=NULL) {
9fa49e22 558/// No need for get_config because they are usually always available in $CFG
70812e39 559
42282810 560 global $CFG;
561
a4080313 562 if (empty($plugin)) {
563 $CFG->$name = $value; // So it's defined for this invocation at least
e1ecf0a0 564
a4080313 565 if (get_field('config', 'name', 'name', $name)) {
9cdb766d 566 return set_field('config', 'value', addslashes($value), 'name', $name);
a4080313 567 } else {
9cdb766d 568 $config = new object();
a4080313 569 $config->name = $name;
9cdb766d 570 $config->value = addslashes($value);
a4080313 571 return insert_record('config', $config);
572 }
573 } else { // plugin scope
574 if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
9cdb766d 575 return set_field('config_plugins', 'value', addslashes($value), 'id', $id);
a4080313 576 } else {
9cdb766d 577 $config = new object();
578 $config->plugin = addslashes($plugin);
a4080313 579 $config->name = $name;
f855cdad 580 $config->value = addslashes($value);
a4080313 581 return insert_record('config_plugins', $config);
582 }
583 }
584}
585
586/**
e1ecf0a0 587 * Get configuration values from the global config table
a4080313 588 * or the config_plugins table.
589 *
590 * If called with no parameters it will do the right thing
591 * generating $CFG safely from the database without overwriting
e1ecf0a0 592 * existing values.
a4080313 593 *
9220fba5 594 * If called with 2 parameters it will return a $string single
595 * value or false of the value is not found.
596 *
e1ecf0a0 597 * @param string $plugin
598 * @param string $name
a4080313 599 * @uses $CFG
600 * @return hash-like object or single value
601 *
602 */
603function get_config($plugin=NULL, $name=NULL) {
7cf1c7bd 604
a4080313 605 global $CFG;
dfc9ba9b 606
a4080313 607 if (!empty($name)) { // the user is asking for a specific value
608 if (!empty($plugin)) {
9220fba5 609 return get_field('config_plugins', 'value', 'plugin' , $plugin, 'name', $name);
a4080313 610 } else {
9220fba5 611 return get_field('config', 'value', 'name', $name);
a4080313 612 }
613 }
614
615 // the user is after a recordset
616 if (!empty($plugin)) {
617 if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
618 $configs = (array)$configs;
619 $localcfg = array();
620 foreach ($configs as $config) {
621 $localcfg[$config->name] = $config->value;
622 }
623 return (object)$localcfg;
624 } else {
625 return false;
626 }
d897cae4 627 } else {
a4080313 628 // this was originally in setup.php
629 if ($configs = get_records('config')) {
630 $localcfg = (array)$CFG;
631 foreach ($configs as $config) {
632 if (!isset($localcfg[$config->name])) {
633 $localcfg[$config->name] = $config->value;
634 } else {
e1ecf0a0 635 if ($localcfg[$config->name] != $config->value ) {
a4080313 636 // complain if the DB has a different
637 // value than config.php does
638 error_log("\$CFG->{$config->name} in config.php ({$localcfg[$config->name]}) overrides database setting ({$config->value})");
639 }
640 }
641 }
e1ecf0a0 642
a4080313 643 $localcfg = (object)$localcfg;
644 return $localcfg;
645 } else {
646 // preserve $CFG if DB returns nothing or error
647 return $CFG;
648 }
e1ecf0a0 649
39917a09 650 }
39917a09 651}
652
b0270f84 653/**
654 * Removes a key from global configuration
655 *
656 * @param string $name the key to set
657 * @param string $plugin (optional) the plugin scope
658 * @uses $CFG
659 * @return bool
660 */
661function unset_config($name, $plugin=NULL) {
662
663 global $CFG;
664
665 unset($CFG->$name);
666
667 if (empty($plugin)) {
668 return delete_records('config', 'name', $name);
5e623a33 669 } else {
b0270f84 670 return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
671 }
672}
673
a4080313 674
7cf1c7bd 675/**
676 * Refresh current $USER session global variable with all their current preferences.
677 * @uses $USER
678 */
70812e39 679function reload_user_preferences() {
70812e39 680
681 global $USER;
682
346c3e2f 683 //reset preference
684 $USER->preference = array();
070e2616 685
346c3e2f 686 if (!isloggedin() or isguestuser()) {
687 // no pernament storage for not-logged-in user and guest
70812e39 688
346c3e2f 689 } else if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
70812e39 690 foreach ($preferences as $preference) {
691 $USER->preference[$preference->name] = $preference->value;
692 }
c6d15803 693 }
346c3e2f 694
695 return true;
70812e39 696}
697
7cf1c7bd 698/**
699 * Sets a preference for the current user
700 * Optionally, can set a preference for a different user object
701 * @uses $USER
68fbd8e1 702 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
703
7cf1c7bd 704 * @param string $name The key to set as preference for the specified user
705 * @param string $value The value to set forthe $name key in the specified user's record
346c3e2f 706 * @param int $otheruserid A moodle user ID
bbd3f2c4 707 * @return bool
7cf1c7bd 708 */
346c3e2f 709function set_user_preference($name, $value, $otheruserid=NULL) {
70812e39 710
711 global $USER;
712
346c3e2f 713 if (!isset($USER->preference)) {
714 reload_user_preferences();
d35757eb 715 }
716
70812e39 717 if (empty($name)) {
718 return false;
719 }
720
346c3e2f 721 $nostore = false;
722
723 if (empty($otheruserid)){
724 if (!isloggedin() or isguestuser()) {
725 $nostore = true;
726 }
727 $userid = $USER->id;
728 } else {
729 if (isguestuser($otheruserid)) {
730 $nostore = true;
731 }
732 $userid = $otheruserid;
733 }
734
735 $return = true;
736 if ($nostore) {
737 // no pernament storage for not-logged-in user and guest
738
739 } else if ($preference = get_record('user_preferences', 'userid', $userid, 'name', addslashes($name))) {
740 if (!set_field('user_preferences', 'value', addslashes((string)$value), 'id', $preference->id)) {
741 $return = false;
066af654 742 }
70812e39 743
744 } else {
346c3e2f 745 $preference = new object();
a3f1f815 746 $preference->userid = $userid;
346c3e2f 747 $preference->name = addslashes($name);
748 $preference->value = addslashes((string)$value);
749 if (!insert_record('user_preferences', $preference)) {
750 $return = false;
70812e39 751 }
752 }
346c3e2f 753
754 // update value in USER session if needed
755 if ($userid == $USER->id) {
756 $USER->preference[$name] = (string)$value;
757 }
758
759 return $return;
70812e39 760}
761
6eb3e776 762/**
763 * Unsets a preference completely by deleting it from the database
764 * Optionally, can set a preference for a different user id
765 * @uses $USER
766 * @param string $name The key to unset as preference for the specified user
346c3e2f 767 * @param int $otheruserid A moodle user ID
6eb3e776 768 */
346c3e2f 769function unset_user_preference($name, $otheruserid=NULL) {
6eb3e776 770
771 global $USER;
772
346c3e2f 773 if (!isset($USER->preference)) {
774 reload_user_preferences();
6eb3e776 775 }
776
346c3e2f 777 if (empty($otheruserid)){
778 $userid = $USER->id;
779 } else {
780 $userid = $otheruserid;
781 }
782
783 //Delete the preference from $USER if needed
784 if ($userid == $USER->id) {
49d005ee 785 unset($USER->preference[$name]);
786 }
e1ecf0a0 787
49d005ee 788 //Then from DB
346c3e2f 789 return delete_records('user_preferences', 'userid', $userid, 'name', addslashes($name));
6eb3e776 790}
791
792
7cf1c7bd 793/**
794 * Sets a whole array of preferences for the current user
795 * @param array $prefarray An array of key/value pairs to be set
346c3e2f 796 * @param int $otheruserid A moodle user ID
bbd3f2c4 797 * @return bool
7cf1c7bd 798 */
346c3e2f 799function set_user_preferences($prefarray, $otheruserid=NULL) {
70812e39 800
801 if (!is_array($prefarray) or empty($prefarray)) {
802 return false;
803 }
804
805 $return = true;
806 foreach ($prefarray as $name => $value) {
346c3e2f 807 // The order is important; test for return is done first
808 $return = (set_user_preference($name, $value, $otheruserid) && $return);
70812e39 809 }
810 return $return;
811}
812
7cf1c7bd 813/**
814 * If no arguments are supplied this function will return
361855e6 815 * all of the current user preferences as an array.
7cf1c7bd 816 * If a name is specified then this function
817 * attempts to return that particular preference value. If
818 * none is found, then the optional value $default is returned,
819 * otherwise NULL.
820 * @param string $name Name of the key to use in finding a preference value
821 * @param string $default Value to be returned if the $name key is not set in the user preferences
346c3e2f 822 * @param int $otheruserid A moodle user ID
7cf1c7bd 823 * @uses $USER
824 * @return string
825 */
346c3e2f 826function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
70812e39 827 global $USER;
828
346c3e2f 829 if (!isset($USER->preference)) {
830 reload_user_preferences();
831 }
a3f1f815 832
346c3e2f 833 if (empty($otheruserid)){
834 $userid = $USER->id;
a3f1f815 835 } else {
346c3e2f 836 $userid = $otheruserid;
837 }
a3f1f815 838
346c3e2f 839 if ($userid == $USER->id) {
840 $preference = $USER->preference;
841
842 } else {
843 $preference = array();
844 if ($prefdata = get_records('user_preferences', 'userid', $userid)) {
845 foreach ($prefdata as $pref) {
846 $preference[$pref->name] = $pref->value;
847 }
a3f1f815 848 }
346c3e2f 849 }
850
851 if (empty($name)) {
852 return $preference; // All values
853
854 } else if (array_key_exists($name, $preference)) {
855 return $preference[$name]; // The single value
856
857 } else {
858 return $default; // Default value (or NULL)
70812e39 859 }
70812e39 860}
861
862
9fa49e22 863/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 864
7cf1c7bd 865/**
c6d15803 866 * Given date parts in user time produce a GMT timestamp.
7cf1c7bd 867 *
68fbd8e1 868 * @param int $year The year part to create timestamp of
869 * @param int $month The month part to create timestamp of
870 * @param int $day The day part to create timestamp of
871 * @param int $hour The hour part to create timestamp of
872 * @param int $minute The minute part to create timestamp of
873 * @param int $second The second part to create timestamp of
874 * @param float $timezone ?
875 * @param bool $applydst ?
e34d817e 876 * @return int timestamp
7cf1c7bd 877 * @todo Finish documenting this function
878 */
9f1f6daf 879function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
39917a09 880
dddb014a 881 $timezone = get_user_timezone_offset($timezone);
882
94e34118 883 if (abs($timezone) > 13) {
68fbd8e1 884 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
03c17ddf 885 } else {
68fbd8e1 886 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
196f2619 887 $time = usertime($time, $timezone);
28c66824 888 if($applydst) {
889 $time -= dst_offset_on($time);
890 }
9f1f6daf 891 }
892
196f2619 893 return $time;
85cafb3e 894
39917a09 895}
896
7cf1c7bd 897/**
898 * Given an amount of time in seconds, returns string
5602f7cf 899 * formatted nicely as weeks, days, hours etc as needed
7cf1c7bd 900 *
2f87145b 901 * @uses MINSECS
902 * @uses HOURSECS
903 * @uses DAYSECS
5602f7cf 904 * @uses YEARSECS
c6d15803 905 * @param int $totalsecs ?
906 * @param array $str ?
89dcb99d 907 * @return string
7cf1c7bd 908 */
909 function format_time($totalsecs, $str=NULL) {
c7e3ac2a 910
6b174680 911 $totalsecs = abs($totalsecs);
c7e3ac2a 912
8dbed6be 913 if (!$str) { // Create the str structure the slow way
b0ccd3fb 914 $str->day = get_string('day');
915 $str->days = get_string('days');
916 $str->hour = get_string('hour');
917 $str->hours = get_string('hours');
918 $str->min = get_string('min');
919 $str->mins = get_string('mins');
920 $str->sec = get_string('sec');
921 $str->secs = get_string('secs');
5602f7cf 922 $str->year = get_string('year');
923 $str->years = get_string('years');
8dbed6be 924 }
925
5602f7cf 926
927 $years = floor($totalsecs/YEARSECS);
928 $remainder = $totalsecs - ($years*YEARSECS);
5602f7cf 929 $days = floor($remainder/DAYSECS);
7a5672c9 930 $remainder = $totalsecs - ($days*DAYSECS);
931 $hours = floor($remainder/HOURSECS);
932 $remainder = $remainder - ($hours*HOURSECS);
933 $mins = floor($remainder/MINSECS);
934 $secs = $remainder - ($mins*MINSECS);
8dbed6be 935
936 $ss = ($secs == 1) ? $str->sec : $str->secs;
937 $sm = ($mins == 1) ? $str->min : $str->mins;
938 $sh = ($hours == 1) ? $str->hour : $str->hours;
939 $sd = ($days == 1) ? $str->day : $str->days;
5602f7cf 940 $sy = ($years == 1) ? $str->year : $str->years;
8dbed6be 941
5602f7cf 942 $oyears = '';
b0ccd3fb 943 $odays = '';
944 $ohours = '';
945 $omins = '';
946 $osecs = '';
9c9f7d77 947
5602f7cf 948 if ($years) $oyears = $years .' '. $sy;
b0ccd3fb 949 if ($days) $odays = $days .' '. $sd;
950 if ($hours) $ohours = $hours .' '. $sh;
951 if ($mins) $omins = $mins .' '. $sm;
952 if ($secs) $osecs = $secs .' '. $ss;
6b174680 953
77ac808e 954 if ($years) return trim($oyears .' '. $odays);
955 if ($days) return trim($odays .' '. $ohours);
956 if ($hours) return trim($ohours .' '. $omins);
957 if ($mins) return trim($omins .' '. $osecs);
b0ccd3fb 958 if ($secs) return $osecs;
959 return get_string('now');
6b174680 960}
f9903ed0 961
7cf1c7bd 962/**
963 * Returns a formatted string that represents a date in user time
964 * <b>WARNING: note that the format is for strftime(), not date().</b>
965 * Because of a bug in most Windows time libraries, we can't use
966 * the nicer %e, so we have to use %d which has leading zeroes.
967 * A lot of the fuss in the function is just getting rid of these leading
968 * zeroes as efficiently as possible.
361855e6 969 *
8c3dba73 970 * If parameter fixday = true (default), then take off leading
7cf1c7bd 971 * zero from %d, else mantain it.
972 *
2f87145b 973 * @uses HOURSECS
e34d817e 974 * @param int $date timestamp in GMT
975 * @param string $format strftime format
d2a9f7cc 976 * @param float $timezone
bbd3f2c4 977 * @param bool $fixday If true (default) then the leading
c6d15803 978 * zero from %d is removed. If false then the leading zero is mantained.
979 * @return string
7cf1c7bd 980 */
b0ccd3fb 981function userdate($date, $format='', $timezone=99, $fixday = true) {
7a302afc 982
1ac7ee24 983 global $CFG;
984
1306c5ea 985 if (empty($format)) {
986 $format = get_string('strftimedaydatetime');
5fa51a39 987 }
035cdbff 988
c3a3c5b8 989 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
990 $fixday = false;
991 } else if ($fixday) {
992 $formatnoday = str_replace('%d', 'DD', $format);
61ae5d36 993 $fixday = ($formatnoday != $format);
994 }
dcde9f02 995
88ec5b7c 996 $date += dst_offset_on($date);
85351042 997
494b9296 998 $timezone = get_user_timezone_offset($timezone);
102dc313 999
1000 if (abs($timezone) > 13) { /// Server time
d2a9f7cc 1001 if ($fixday) {
102dc313 1002 $datestring = strftime($formatnoday, $date);
1003 $daystring = str_replace(' 0', '', strftime(' %d', $date));
1004 $datestring = str_replace('DD', $daystring, $datestring);
1005 } else {
1006 $datestring = strftime($format, $date);
1007 }
88ec5b7c 1008 } else {
102dc313 1009 $date += (int)($timezone * 3600);
1010 if ($fixday) {
1011 $datestring = gmstrftime($formatnoday, $date);
1012 $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
1013 $datestring = str_replace('DD', $daystring, $datestring);
1014 } else {
1015 $datestring = gmstrftime($format, $date);
1016 }
88ec5b7c 1017 }
102dc313 1018
fb773106 1019/// If we are running under Windows convert from windows encoding to UTF-8
1020/// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
11f7b25d 1021
fb773106 1022 if ($CFG->ostype == 'WINDOWS') {
11f7b25d 1023 if ($localewincharset = get_string('localewincharset')) {
1024 $textlib = textlib_get_instance();
810944af 1025 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
11f7b25d 1026 }
1027 }
1028
035cdbff 1029 return $datestring;
873960de 1030}
1031
7cf1c7bd 1032/**
196f2619 1033 * Given a $time timestamp in GMT (seconds since epoch),
c6d15803 1034 * returns an array that represents the date in user time
7cf1c7bd 1035 *
2f87145b 1036 * @uses HOURSECS
196f2619 1037 * @param int $time Timestamp in GMT
68fbd8e1 1038 * @param float $timezone ?
c6d15803 1039 * @return array An array that represents the date in user time
7cf1c7bd 1040 * @todo Finish documenting this function
1041 */
196f2619 1042function usergetdate($time, $timezone=99) {
6b174680 1043
494b9296 1044 $timezone = get_user_timezone_offset($timezone);
a36166d3 1045
e34d817e 1046 if (abs($timezone) > 13) { // Server time
ed1f69b0 1047 return getdate($time);
d2a9f7cc 1048 }
1049
e34d817e 1050 // There is no gmgetdate so we use gmdate instead
02f0527d 1051 $time += dst_offset_on($time);
e34d817e 1052 $time += intval((float)$timezone * HOURSECS);
3bba1e6e 1053
1054 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
02f0527d 1055
9f1f6daf 1056 list(
1057 $getdate['seconds'],
1058 $getdate['minutes'],
1059 $getdate['hours'],
1060 $getdate['mday'],
1061 $getdate['mon'],
1062 $getdate['year'],
1063 $getdate['wday'],
1064 $getdate['yday'],
1065 $getdate['weekday'],
1066 $getdate['month']
3bba1e6e 1067 ) = explode('_', $datestring);
9f1f6daf 1068
d2d6171f 1069 return $getdate;
d552ead0 1070}
1071
7cf1c7bd 1072/**
1073 * Given a GMT timestamp (seconds since epoch), offsets it by
1074 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1075 *
2f87145b 1076 * @uses HOURSECS
c6d15803 1077 * @param int $date Timestamp in GMT
e34d817e 1078 * @param float $timezone
c6d15803 1079 * @return int
7cf1c7bd 1080 */
d552ead0 1081function usertime($date, $timezone=99) {
a36166d3 1082
494b9296 1083 $timezone = get_user_timezone_offset($timezone);
2665e47a 1084
0431bd7c 1085 if (abs($timezone) > 13) {
d552ead0 1086 return $date;
1087 }
7a5672c9 1088 return $date - (int)($timezone * HOURSECS);
d552ead0 1089}
1090
8c3dba73 1091/**
1092 * Given a time, return the GMT timestamp of the most recent midnight
1093 * for the current user.
1094 *
e34d817e 1095 * @param int $date Timestamp in GMT
1096 * @param float $timezone ?
c6d15803 1097 * @return ?
8c3dba73 1098 */
edf7fe8c 1099function usergetmidnight($date, $timezone=99) {
edf7fe8c 1100
494b9296 1101 $timezone = get_user_timezone_offset($timezone);
edf7fe8c 1102 $userdate = usergetdate($date, $timezone);
4606d9bb 1103
02f0527d 1104 // Time of midnight of this user's day, in GMT
1105 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
edf7fe8c 1106
1107}
1108
7cf1c7bd 1109/**
1110 * Returns a string that prints the user's timezone
1111 *
1112 * @param float $timezone The user's timezone
1113 * @return string
1114 */
d552ead0 1115function usertimezone($timezone=99) {
d552ead0 1116
0c244315 1117 $tz = get_user_timezone($timezone);
f30fe8d0 1118
0c244315 1119 if (!is_float($tz)) {
1120 return $tz;
d552ead0 1121 }
0c244315 1122
1123 if(abs($tz) > 13) { // Server time
1124 return get_string('serverlocaltime');
1125 }
1126
1127 if($tz == intval($tz)) {
1128 // Don't show .0 for whole hours
1129 $tz = intval($tz);
1130 }
1131
1132 if($tz == 0) {
b0ccd3fb 1133 return 'GMT';
d552ead0 1134 }
0c244315 1135 else if($tz > 0) {
1136 return 'GMT+'.$tz;
1137 }
1138 else {
1139 return 'GMT'.$tz;
d552ead0 1140 }
e1ecf0a0 1141
f9903ed0 1142}
1143
7cf1c7bd 1144/**
1145 * Returns a float which represents the user's timezone difference from GMT in hours
1146 * Checks various settings and picks the most dominant of those which have a value
1147 *
7cf1c7bd 1148 * @uses $CFG
1149 * @uses $USER
b2b68362 1150 * @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
c6d15803 1151 * @return int
7cf1c7bd 1152 */
494b9296 1153function get_user_timezone_offset($tz = 99) {
f30fe8d0 1154
43b59916 1155 global $USER, $CFG;
1156
e8904995 1157 $tz = get_user_timezone($tz);
c9e55a25 1158
7b9e355e 1159 if (is_float($tz)) {
1160 return $tz;
1161 } else {
e8904995 1162 $tzrecord = get_timezone_record($tz);
7b9e355e 1163 if (empty($tzrecord)) {
e8904995 1164 return 99.0;
1165 }
4f2dbde9 1166 return (float)$tzrecord->gmtoff / HOURMINS;
e8904995 1167 }
1168}
1169
bbd3f2c4 1170/**
b2b68362 1171 * Returns a float or a string which denotes the user's timezone
1172 * 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)
1173 * means that for this timezone there are also DST rules to be taken into account
1174 * Checks various settings and picks the most dominant of those which have a value
bbd3f2c4 1175 *
1176 * @uses $USER
1177 * @uses $CFG
b2b68362 1178 * @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
1179 * @return mixed
bbd3f2c4 1180 */
e8904995 1181function get_user_timezone($tz = 99) {
1182 global $USER, $CFG;
43b59916 1183
f30fe8d0 1184 $timezones = array(
e8904995 1185 $tz,
1186 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
43b59916 1187 isset($USER->timezone) ? $USER->timezone : 99,
1188 isset($CFG->timezone) ? $CFG->timezone : 99,
f30fe8d0 1189 );
43b59916 1190
e8904995 1191 $tz = 99;
43b59916 1192
e8904995 1193 while(($tz == '' || $tz == 99) && $next = each($timezones)) {
1194 $tz = $next['value'];
43b59916 1195 }
e8904995 1196
1197 return is_numeric($tz) ? (float) $tz : $tz;
43b59916 1198}
1199
bbd3f2c4 1200/**
1201 * ?
1202 *
1203 * @uses $CFG
1204 * @uses $db
1205 * @param string $timezonename ?
1206 * @return object
1207 */
43b59916 1208function get_timezone_record($timezonename) {
1209 global $CFG, $db;
1210 static $cache = NULL;
1211
8edffd15 1212 if ($cache === NULL) {
43b59916 1213 $cache = array();
1214 }
1215
8edffd15 1216 if (isset($cache[$timezonename])) {
43b59916 1217 return $cache[$timezonename];
f30fe8d0 1218 }
1219
952d8dc8 1220 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix.'timezone
1221 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
f30fe8d0 1222}
f9903ed0 1223
bbd3f2c4 1224/**
1225 * ?
1226 *
1227 * @uses $CFG
1228 * @uses $USER
1229 * @param ? $fromyear ?
1230 * @param ? $to_year ?
1231 * @return bool
1232 */
830a2bbd 1233function calculate_user_dst_table($from_year = NULL, $to_year = NULL) {
2280ecf5 1234 global $CFG, $SESSION;
85cafb3e 1235
989585e9 1236 $usertz = get_user_timezone();
7cb29a3d 1237
989585e9 1238 if (is_float($usertz)) {
1239 // Trivial timezone, no DST
1240 return false;
1241 }
1242
2280ecf5 1243 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
989585e9 1244 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
2280ecf5 1245 unset($SESSION->dst_offsets);
1246 unset($SESSION->dst_range);
830a2bbd 1247 }
1248
2280ecf5 1249 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
830a2bbd 1250 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1251 // This will be the return path most of the time, pretty light computationally
1252 return true;
85cafb3e 1253 }
1254
830a2bbd 1255 // Reaching here means we either need to extend our table or create it from scratch
989585e9 1256
1257 // Remember which TZ we calculated these changes for
2280ecf5 1258 $SESSION->dst_offsettz = $usertz;
989585e9 1259
2280ecf5 1260 if(empty($SESSION->dst_offsets)) {
830a2bbd 1261 // If we 're creating from scratch, put the two guard elements in there
2280ecf5 1262 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
830a2bbd 1263 }
2280ecf5 1264 if(empty($SESSION->dst_range)) {
830a2bbd 1265 // If creating from scratch
1266 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1267 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1268
1269 // Fill in the array with the extra years we need to process
1270 $yearstoprocess = array();
1271 for($i = $from; $i <= $to; ++$i) {
1272 $yearstoprocess[] = $i;
1273 }
1274
1275 // Take note of which years we have processed for future calls
2280ecf5 1276 $SESSION->dst_range = array($from, $to);
830a2bbd 1277 }
1278 else {
1279 // If needing to extend the table, do the same
1280 $yearstoprocess = array();
1281
2280ecf5 1282 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1283 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
830a2bbd 1284
2280ecf5 1285 if($from < $SESSION->dst_range[0]) {
830a2bbd 1286 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1287 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
830a2bbd 1288 $yearstoprocess[] = $i;
1289 }
2280ecf5 1290 $SESSION->dst_range[0] = $from;
830a2bbd 1291 }
2280ecf5 1292 if($to > $SESSION->dst_range[1]) {
830a2bbd 1293 // Take note of which years we need to process and then note that we have processed them for future calls
2280ecf5 1294 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
830a2bbd 1295 $yearstoprocess[] = $i;
1296 }
2280ecf5 1297 $SESSION->dst_range[1] = $to;
830a2bbd 1298 }
1299 }
1300
1301 if(empty($yearstoprocess)) {
1302 // This means that there was a call requesting a SMALLER range than we have already calculated
1303 return true;
1304 }
1305
1306 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1307 // Also, the array is sorted in descending timestamp order!
1308
1309 // Get DB data
989585e9 1310 $presetrecords = get_records('timezone', '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');
e789650d 1311 if(empty($presetrecords)) {
1312 return false;
1313 }
57f1191c 1314
830a2bbd 1315 // Remove ending guard (first element of the array)
2280ecf5 1316 reset($SESSION->dst_offsets);
1317 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
830a2bbd 1318
1319 // Add all required change timestamps
1320 foreach($yearstoprocess as $y) {
1321 // Find the record which is in effect for the year $y
1322 foreach($presetrecords as $year => $preset) {
1323 if($year <= $y) {
1324 break;
c9e72798 1325 }
830a2bbd 1326 }
1327
1328 $changes = dst_changes_for_year($y, $preset);
1329
1330 if($changes === NULL) {
1331 continue;
1332 }
1333 if($changes['dst'] != 0) {
2280ecf5 1334 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
830a2bbd 1335 }
1336 if($changes['std'] != 0) {
2280ecf5 1337 $SESSION->dst_offsets[$changes['std']] = 0;
c9e72798 1338 }
85cafb3e 1339 }
42d36497 1340
830a2bbd 1341 // Put in a guard element at the top
2280ecf5 1342 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1343 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
830a2bbd 1344
1345 // Sort again
2280ecf5 1346 krsort($SESSION->dst_offsets);
830a2bbd 1347
e789650d 1348 return true;
1349}
42d36497 1350
e789650d 1351function dst_changes_for_year($year, $timezone) {
7cb29a3d 1352
e789650d 1353 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1354 return NULL;
42d36497 1355 }
7cb29a3d 1356
e789650d 1357 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1358 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1359
1360 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1361 list($std_hour, $std_min) = explode(':', $timezone->std_time);
d2a9f7cc 1362
6dc8dddc 1363 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1364 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
830a2bbd 1365
1366 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1367 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1368 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1369
1370 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1371 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
42d36497 1372
e789650d 1373 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
42d36497 1374}
1375
02f0527d 1376// $time must NOT be compensated at all, it has to be a pure timestamp
1377function dst_offset_on($time) {
2280ecf5 1378 global $SESSION;
02f0527d 1379
2280ecf5 1380 if(!calculate_user_dst_table() || empty($SESSION->dst_offsets)) {
c9e72798 1381 return 0;
85cafb3e 1382 }
1383
2280ecf5 1384 reset($SESSION->dst_offsets);
1385 while(list($from, $offset) = each($SESSION->dst_offsets)) {
59556d48 1386 if($from <= $time) {
c9e72798 1387 break;
1388 }
1389 }
1390
830a2bbd 1391 // This is the normal return path
1392 if($offset !== NULL) {
1393 return $offset;
02f0527d 1394 }
02f0527d 1395
830a2bbd 1396 // Reaching this point means we haven't calculated far enough, do it now:
1397 // Calculate extra DST changes if needed and recurse. The recursion always
1398 // moves toward the stopping condition, so will always end.
1399
1400 if($from == 0) {
2280ecf5 1401 // We need a year smaller than $SESSION->dst_range[0]
1402 if($SESSION->dst_range[0] == 1971) {
830a2bbd 1403 return 0;
1404 }
2280ecf5 1405 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL);
830a2bbd 1406 return dst_offset_on($time);
1407 }
1408 else {
2280ecf5 1409 // We need a year larger than $SESSION->dst_range[1]
1410 if($SESSION->dst_range[1] == 2035) {
830a2bbd 1411 return 0;
1412 }
2280ecf5 1413 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5);
830a2bbd 1414 return dst_offset_on($time);
1415 }
85cafb3e 1416}
02f0527d 1417
28902d99 1418function find_day_in_month($startday, $weekday, $month, $year) {
8dc3f6cf 1419
1420 $daysinmonth = days_in_month($month, $year);
1421
42d36497 1422 if($weekday == -1) {
28902d99 1423 // Don't care about weekday, so return:
1424 // abs($startday) if $startday != -1
1425 // $daysinmonth otherwise
1426 return ($startday == -1) ? $daysinmonth : abs($startday);
8dc3f6cf 1427 }
1428
1429 // From now on we 're looking for a specific weekday
8dc3f6cf 1430
28902d99 1431 // Give "end of month" its actual value, since we know it
1432 if($startday == -1) {
1433 $startday = -1 * $daysinmonth;
1434 }
1435
1436 // Starting from day $startday, the sign is the direction
8dc3f6cf 1437
28902d99 1438 if($startday < 1) {
8dc3f6cf 1439
28902d99 1440 $startday = abs($startday);
8dc3f6cf 1441 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1442
1443 // This is the last such weekday of the month
1444 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
1445 if($lastinmonth > $daysinmonth) {
1446 $lastinmonth -= 7;
42d36497 1447 }
8dc3f6cf 1448
28902d99 1449 // Find the first such weekday <= $startday
1450 while($lastinmonth > $startday) {
8dc3f6cf 1451 $lastinmonth -= 7;
42d36497 1452 }
8dc3f6cf 1453
1454 return $lastinmonth;
e1ecf0a0 1455
42d36497 1456 }
1457 else {
42d36497 1458
28902d99 1459 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
42d36497 1460
8dc3f6cf 1461 $diff = $weekday - $indexweekday;
1462 if($diff < 0) {
1463 $diff += 7;
42d36497 1464 }
42d36497 1465
28902d99 1466 // This is the first such weekday of the month equal to or after $startday
1467 $firstfromindex = $startday + $diff;
42d36497 1468
8dc3f6cf 1469 return $firstfromindex;
1470
1471 }
42d36497 1472}
1473
bbd3f2c4 1474/**
1475 * Calculate the number of days in a given month
1476 *
1477 * @param int $month The month whose day count is sought
1478 * @param int $year The year of the month whose day count is sought
1479 * @return int
1480 */
42d36497 1481function days_in_month($month, $year) {
1482 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1483}
1484
bbd3f2c4 1485/**
1486 * Calculate the position in the week of a specific calendar day
1487 *
1488 * @param int $day The day of the date whose position in the week is sought
1489 * @param int $month The month of the date whose position in the week is sought
1490 * @param int $year The year of the date whose position in the week is sought
1491 * @return int
1492 */
8dc3f6cf 1493function dayofweek($day, $month, $year) {
1494 // I wonder if this is any different from
1495 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1496 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1497}
1498
9fa49e22 1499/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 1500
bbd3f2c4 1501/**
1502 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1503 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1504 * sesskey string if $USER exists, or boolean false if not.
1505 *
1506 * @uses $USER
1507 * @return string
1508 */
04280e85 1509function sesskey() {
1a33f699 1510 global $USER;
1511
1512 if(!isset($USER)) {
1513 return false;
1514 }
1515
1516 if (empty($USER->sesskey)) {
1517 $USER->sesskey = random_string(10);
1518 }
1519
1520 return $USER->sesskey;
1521}
1522
0302c52f 1523
c4d0753b 1524/**
1525 * For security purposes, this function will check that the currently
1526 * given sesskey (passed as a parameter to the script or this function)
1527 * matches that of the current user.
1528 *
1529 * @param string $sesskey optionally provided sesskey
1530 * @return bool
1531 */
1532function confirm_sesskey($sesskey=NULL) {
1533 global $USER;
0302c52f 1534
c4d0753b 1535 if (!empty($USER->ignoresesskey) || !empty($CFG->ignoresesskey)) {
1536 return true;
0302c52f 1537 }
1538
c4d0753b 1539 if (empty($sesskey)) {
1540 $sesskey = required_param('sesskey', PARAM_RAW); // Check script parameters
0302c52f 1541 }
1542
c4d0753b 1543 if (!isset($USER->sesskey)) {
1544 return false;
1545 }
0302c52f 1546
c4d0753b 1547 return ($USER->sesskey === $sesskey);
0302c52f 1548}
c4d0753b 1549
dcf6d93c 1550/**
9152fc99 1551 * Setup all global $CFG course variables, set locale and also themes
1552 * This function can be used on pages that do not require login instead of require_login()
1553 *
dcf6d93c 1554 * @param mixed $courseorid id of the course or course object
1555 */
1556function course_setup($courseorid=0) {
1306c5ea 1557 global $COURSE, $CFG, $SITE;
dcf6d93c 1558
1559/// Redefine global $COURSE if needed
1560 if (empty($courseorid)) {
1561 // no change in global $COURSE - for backwards compatibiltiy
5e623a33 1562 // if require_rogin() used after require_login($courseid);
dcf6d93c 1563 } else if (is_object($courseorid)) {
1564 $COURSE = clone($courseorid);
1565 } else {
1566 global $course; // used here only to prevent repeated fetching from DB - may be removed later
9152fc99 1567 if (!empty($course->id) and $course->id == SITEID) {
1568 $COURSE = clone($SITE);
1569 } else if (!empty($course->id) and $course->id == $courseorid) {
dcf6d93c 1570 $COURSE = clone($course);
1571 } else {
1572 if (!$COURSE = get_record('course', 'id', $courseorid)) {
1573 error('Invalid course ID');
1574 }
1575 }
1576 }
1577
9152fc99 1578/// set locale and themes
dcf6d93c 1579 moodle_setlocale();
dcf6d93c 1580 theme_setup();
1581
dcf6d93c 1582}
c4d0753b 1583
7cf1c7bd 1584/**
ec81373f 1585 * This function checks that the current user is logged in and has the
1586 * required privileges
1587 *
7cf1c7bd 1588 * This function checks that the current user is logged in, and optionally
ec81373f 1589 * whether they are allowed to be in a particular course and view a particular
1590 * course module.
1591 * If they are not logged in, then it redirects them to the site login unless
d2a9f7cc 1592 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
ec81373f 1593 * case they are automatically logged in as guests.
1594 * If $courseid is given and the user is not enrolled in that course then the
1595 * user is redirected to the course enrolment page.
1596 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1597 * in the course then the user is redirected to the course home page.
7cf1c7bd 1598 *
7cf1c7bd 1599 * @uses $CFG
c6d15803 1600 * @uses $SESSION
7cf1c7bd 1601 * @uses $USER
1602 * @uses $FULLME
c6d15803 1603 * @uses SITEID
f07fa644 1604 * @uses $COURSE
33ebaf7c 1605 * @param mixed $courseorid id of the course or course object
bbd3f2c4 1606 * @param bool $autologinguest
1607 * @param object $cm course module object
7cf1c7bd 1608 */
33ebaf7c 1609function require_login($courseorid=0, $autologinguest=true, $cm=null) {
f9903ed0 1610
083c3743 1611 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
d8ba183c 1612
083c3743 1613/// setup global $COURSE, themes, language and locale
dcf6d93c 1614 course_setup($courseorid);
be933850 1615
1845f8b8 1616/// If the user is not even logged in yet then make sure they are
083c3743 1617 if (!isloggedin()) {
1618 //NOTE: $USER->site check was obsoleted by session test cookie,
1619 // $USER->confirmed test is in login/index.php
f9903ed0 1620 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1621 if (!empty($_SERVER['HTTP_REFERER'])) {
1622 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
9f44d972 1623 }
ad56b737 1624 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
8e8d0524 1625 $loginguest = '?loginguest=true';
1626 } else {
1627 $loginguest = '';
a2ebe6a5 1628 }
2c040c29 1629 if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
b0ccd3fb 1630 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
8a33e371 1631 } else {
2c3432e6 1632 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
083c3743 1633 redirect($wwwroot .'/login/index.php');
8a33e371 1634 }
20fde7b1 1635 exit;
f9903ed0 1636 }
808a3baa 1637
f6f66b03 1638/// loginas as redirection if needed
1639 if ($COURSE->id != SITEID and !empty($USER->realuser)) {
1640 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
1641 if ($USER->loginascontext->instanceid != $COURSE->id) {
3887fe4a 1642 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
5e623a33 1643 }
f6f66b03 1644 }
1645 }
1646
1647
5602f7cf 1648/// check whether the user should be changing password (but only if it is REALLY them)
03d820c7 1649 $userauth = get_auth_plugin($USER->auth);
346c3e2f 1650 if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser)) {
03d820c7 1651 if ($userauth->can_change_password()) {
20fde7b1 1652 $SESSION->wantsurl = $FULLME;
80274abf 1653 if ($changeurl = $userauth->change_password_url()) {
9696bd89 1654 //use plugin custom url
80274abf 1655 redirect($changeurl);
1437f0a5 1656 } else {
9696bd89 1657 //use moodle internal method
1658 if (empty($CFG->loginhttps)) {
1659 redirect($CFG->wwwroot .'/login/change_password.php');
1660 } else {
1661 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1662 redirect($wwwroot .'/login/change_password.php');
1663 }
1437f0a5 1664 }
d35757eb 1665 } else {
4fa94a56 1666 error(get_string('nopasswordchangeforced', 'auth'));
d35757eb 1667 }
1668 }
083c3743 1669
1845f8b8 1670/// Check that the user account is properly set up
808a3baa 1671 if (user_not_fully_set_up($USER)) {
20fde7b1 1672 $SESSION->wantsurl = $FULLME;
b0ccd3fb 1673 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 1674 }
d8ba183c 1675
1845f8b8 1676/// Make sure current IP matches the one for this session (if required)
361855e6 1677 if (!empty($CFG->tracksessionip)) {
366dfa60 1678 if ($USER->sessionIP != md5(getremoteaddr())) {
1679 error(get_string('sessionipnomatch', 'error'));
1680 }
1681 }
6d8f47d6 1682
1845f8b8 1683/// Make sure the USER has a sesskey set up. Used for checking script parameters.
04280e85 1684 sesskey();
366dfa60 1685
027a1604 1686 // Check that the user has agreed to a site policy if there is one
1687 if (!empty($CFG->sitepolicy)) {
1688 if (!$USER->policyagreed) {
957b5198 1689 $SESSION->wantsurl = $FULLME;
027a1604 1690 redirect($CFG->wwwroot .'/user/policy.php');
027a1604 1691 }
1695b680 1692 }
1693
1845f8b8 1694/// If the site is currently under maintenance, then print a message
f8e3d5f0 1695 if (!has_capability('moodle/site:config',get_context_instance(CONTEXT_SYSTEM))) {
eeefd0b0 1696 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
1695b680 1697 print_maintenance_message();
20fde7b1 1698 exit;
1695b680 1699 }
027a1604 1700 }
1701
f8e3d5f0 1702/// groupmembersonly access control
1703 if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
1704 if (isguestuser() or !groups_has_membership($cm)) {
1705 error(get_string('groupmembersonlyerror', 'group'), $CFG->wwwroot.'/course/view.php?id='.$cm->course);
1706 }
1707 }
1845f8b8 1708
33ebaf7c 1709 if ($COURSE->id == SITEID) {
1710/// We can eliminate hidden site activities straight away
5e623a33 1711 if (!empty($cm) && !$cm->visible and !has_capability('moodle/course:viewhiddenactivities',
f8e3d5f0 1712 get_context_instance(CONTEXT_SYSTEM))) {
33ebaf7c 1713 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
e3512050 1714 }
33ebaf7c 1715 return;
881a77bf 1716
5e623a33 1717 } else {
33ebaf7c 1718/// Check if the user can be in a particular course
1719 if (!$context = get_context_instance(CONTEXT_COURSE, $COURSE->id)) {
1845f8b8 1720 print_error('nocontext');
1721 }
1722
881a77bf 1723 if (empty($USER->switchrole[$context->id]) &&
33ebaf7c 1724 !($COURSE->visible && course_parent_visible($COURSE)) &&
1725 !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $COURSE->id)) ){
881a77bf 1726 print_header_simple();
1727 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
5e623a33 1728 }
1729
f71346e2 1730 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1731
1732 if ($USER->username != 'guest' and !has_capability('moodle/course:view', $context)) {
33ebaf7c 1733 if ($COURSE->guest == 1) {
eef879ec 1734 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
1735 has_capability('clearcache'); // Must clear cache
1736 $guestcaps = get_role_context_caps($CFG->guestroleid, $context);
1737 $USER->capabilities = merge_role_caps($USER->capabilities, $guestcaps);
f71346e2 1738 }
1739 }
1740
1845f8b8 1741 /// If the user is a guest then treat them according to the course policy about guests
1742
1743 if (has_capability('moodle/legacy:guest', $context, NULL, false)) {
33ebaf7c 1744 switch ($COURSE->guest) { /// Check course policy about guest access
1845f8b8 1745
5e623a33 1746 case 1: /// Guests always allowed
1845f8b8 1747 if (!has_capability('moodle/course:view', $context)) { // Prohibited by capability
1748 print_header_simple();
6ba65fa0 1749 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
1845f8b8 1750 }
1751 if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
5e623a33 1752 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
1845f8b8 1753 get_string('activityiscurrentlyhidden'));
1754 }
1755
1756 return; // User is allowed to see this course
1757
1758 break;
1759
5e623a33 1760 case 2: /// Guests allowed with key
33ebaf7c 1761 if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
b1f318a6 1762 return true;
1763 }
1764 // otherwise drop through to logic below (--> enrol.php)
1845f8b8 1765 break;
bbbf2d40 1766
1845f8b8 1767 default: /// Guests not allowed
0be6f678 1768 $strloggedinasguest = get_string('loggedinasguest');
1769 print_header_simple('', '',
1770 build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc'))));
21596567 1771 if (empty($USER->switchrole[$context->id])) { // Normal guest
6ba65fa0 1772 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
21596567 1773 } else {
6ba65fa0 1774 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
33ebaf7c 1775 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
1776 print_footer($COURSE);
21596567 1777 exit;
1778 }
1845f8b8 1779 break;
1780 }
1781
1782 /// For non-guests, check if they have course view access
1783
1784 } else if (has_capability('moodle/course:view', $context)) {
1785 if (!empty($USER->realuser)) { // Make sure the REAL person can also access this course
d02eeded 1786 if (!has_capability('moodle/course:view', $context, $USER->realuser)) {
1845f8b8 1787 print_header_simple();
b0ccd3fb 1788 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
cb909d74 1789 }
3ce2f1e0 1790 }
1845f8b8 1791
1792 /// Make sure they can read this activity too, if specified
1793
5e623a33 1794 if (!empty($cm) and !$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $context)) {
ec81373f 1795 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1796 }
1845f8b8 1797 return; // User is allowed to see this course
1798
da5c172a 1799 }
f9903ed0 1800
9ca3b4f3 1801
1845f8b8 1802 /// Currently not enrolled in the course, so see if they want to enrol
da5c172a 1803 $SESSION->wantsurl = $FULLME;
33ebaf7c 1804 redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
da5c172a 1805 die;
1806 }
f9903ed0 1807}
1808
c4d0753b 1809
1810
1811/**
1812 * This function just makes sure a user is logged out.
1813 *
1814 * @uses $CFG
1815 * @uses $USER
1816 */
1817function require_logout() {
1818
2d4beaff 1819 global $USER, $CFG, $SESSION;
c4d0753b 1820
111e2360 1821 if (isloggedin()) {
c4d0753b 1822 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
1823
533f7910 1824 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
1825 foreach($authsequence as $authname) {
1826 $authplugin = get_auth_plugin($authname);
1827 $authplugin->prelogout_hook();
81693ac7 1828 }
c4d0753b 1829 }
1830
1831 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
1832 // This method is just to try to avoid silly warnings from PHP 4.3.0
1833 session_unregister("USER");
1834 session_unregister("SESSION");
1835 }
1836
f8bd7030 1837 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
1838 $file = $line = null;
1839 if (headers_sent($file, $line)) {
1840 error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__);
1841 error_log('Headers were already sent in file: '.$file.' on line '.$line);
1842 } else {
1843 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
1844 }
1845
c4d0753b 1846 unset($_SESSION['USER']);
1847 unset($_SESSION['SESSION']);
1848
1849 unset($SESSION);
1850 unset($USER);
1851
1852}
1853
7cf1c7bd 1854/**
1855 * This is a weaker version of {@link require_login()} which only requires login
1856 * when called from within a course rather than the site page, unless
1857 * the forcelogin option is turned on.
1858 *
1859 * @uses $CFG
33ebaf7c 1860 * @param mixed $courseorid The course object or id in question
bbd3f2c4 1861 * @param bool $autologinguest Allow autologin guests if that is wanted
4febb58f 1862 * @param object $cm Course activity module if known
7cf1c7bd 1863 */
33ebaf7c 1864function require_course_login($courseorid, $autologinguest=true, $cm=null) {
f950af3c 1865 global $CFG;
1596edff 1866 if (!empty($CFG->forcelogin)) {
33ebaf7c 1867 // login required for both SITE and courses
1868 require_login($courseorid, $autologinguest, $cm);
63c9ee99 1869
1870 } else if (!empty($cm) and !$cm->visible) {
1871 // always login for hidden activities
1872 require_login($courseorid, $autologinguest, $cm);
1873
39de90ac 1874 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
1875 or (!is_object($courseorid) and $courseorid == SITEID)) {
33ebaf7c 1876 //login for SITE not required
63c9ee99 1877 return;
1878
33ebaf7c 1879 } else {
1880 // course login always required
1881 require_login($courseorid, $autologinguest, $cm);
f950af3c 1882 }
1883}
1884
61c6071f 1885/**
1886 * Require key login. Function terminates with error if key not found or incorrect.
1887 * @param string $script unique script identifier
1888 * @param int $instance optional instance id
1889 */
1890function require_user_key_login($script, $instance=null) {
1891 global $nomoodlecookie, $USER, $SESSION;
1892
1893 if (empty($nomoodlecookie)) {
1894 error('Incorrect use of require_key_login() - session cookies must be disabled!');
1895 }
1896
1897/// extra safety
1898 @session_write_close();
1899
1900 $keyvalue = required_param('key', PARAM_ALPHANUM);
1901
1902 if (!$key = get_record('user_private_key', 'script', $script, 'value', $keyvalue, 'instance', $instance)) {
1903 error('Incorrect key');
1904 }
1905
1906 if (!empty($key->validuntil) and $key->validuntil < time()) {
1907 error('Expired key');
1908 }
1909
e436033f 1910 if ($key->iprestriction) {
1911 $remoteaddr = getremoteaddr();
1912 if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction)) {
1913 error('Client IP address mismatch');
1914 }
61c6071f 1915 }
1916
1917 if (!$user = get_record('user', 'id', $key->userid)) {
1918 error('Incorrect user record');
1919 }
1920
1921/// emulate normal session
1922 $SESSION = new object();
1923 $USER = $user;
1924
1925/// return isntance id - it might be empty
1926 return $key->instance;
1927}
1928
1929/**
1930 * Creates a new private user access key.
1931 * @param string $script unique target identifier
1932 * @param int $userid
1933 * @param instance $int optional instance id
1934 * @param string $iprestriction optional ip restricted access
1935 * @param timestamp $validuntil key valid only until given data
1936 * @return string access key value
1937 */
1938function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
1939 $key = new object();
1940 $key->script = $script;
1941 $key->userid = $userid;
1942 $key->instance = $instance;
1943 $key->iprestriction = $iprestriction;
1944 $key->validuntil = $validuntil;
1945 $key->timecreated = time();
1946
1947 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
1948 while (record_exists('user_private_key', 'value', $key->value)) {
1949 // must be unique
1950 $key->value = md5($userid.'_'.time().random_string(40));
1951 }
1952
1953 if (!insert_record('user_private_key', $key)) {
1954 error('Can not insert new key');
1955 }
1956
1957 return $key->value;
1958}
1959
7cf1c7bd 1960/**
1961 * Modify the user table by setting the currently logged in user's
1962 * last login to now.
1963 *
1964 * @uses $USER
bbd3f2c4 1965 * @return bool
7cf1c7bd 1966 */
1d881d92 1967function update_user_login_times() {
1968 global $USER;
1969
53467aa6 1970 $user = new object();
1d881d92 1971 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2a2f5f11 1972 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1d881d92 1973
1974 $user->id = $USER->id;
1975
b0ccd3fb 1976 return update_record('user', $user);
1d881d92 1977}
1978
7cf1c7bd 1979/**
1980 * Determines if a user has completed setting up their account.
1981 *
89dcb99d 1982 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
bbd3f2c4 1983 * @return bool
7cf1c7bd 1984 */
808a3baa 1985function user_not_fully_set_up($user) {
bb64b51a 1986 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
1987}
1988
1989function over_bounce_threshold($user) {
d2a9f7cc 1990
bb64b51a 1991 global $CFG;
d2a9f7cc 1992
bb64b51a 1993 if (empty($CFG->handlebounces)) {
1994 return false;
1995 }
1996 // set sensible defaults
1997 if (empty($CFG->minbounces)) {
1998 $CFG->minbounces = 10;
1999 }
2000 if (empty($CFG->bounceratio)) {
2001 $CFG->bounceratio = .20;
2002 }
2003 $bouncecount = 0;
2004 $sendcount = 0;
2005 if ($bounce = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
2006 $bouncecount = $bounce->value;
2007 }
2008 if ($send = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
2009 $sendcount = $send->value;
2010 }
2011 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2012}
2013
d2a9f7cc 2014/**
bb64b51a 2015 * @param $user - object containing an id
2016 * @param $reset - will reset the count to 0
2017 */
2018function set_send_count($user,$reset=false) {
d2a9f7cc 2019 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
bb64b51a 2020 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2021 update_record('user_preferences',$pref);
2022 }
2023 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2024 // make a new one
2025 $pref->name = 'email_send_count';
2026 $pref->value = 1;
2027 $pref->userid = $user->id;
06ba0b04 2028 insert_record('user_preferences',$pref, false);
bb64b51a 2029 }
2030}
2031
d2a9f7cc 2032/**
bb64b51a 2033* @param $user - object containing an id
2034 * @param $reset - will reset the count to 0
2035 */
2036function set_bounce_count($user,$reset=false) {
d2a9f7cc 2037 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
bb64b51a 2038 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2039 update_record('user_preferences',$pref);
2040 }
2041 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2042 // make a new one
2043 $pref->name = 'email_bounce_count';
2044 $pref->value = 1;
2045 $pref->userid = $user->id;
06ba0b04 2046 insert_record('user_preferences',$pref, false);
bb64b51a 2047 }
808a3baa 2048}
f9903ed0 2049
7cf1c7bd 2050/**
2051 * Keeps track of login attempts
2052 *
2053 * @uses $SESSION
2054 */
f9903ed0 2055function update_login_count() {
9fa49e22 2056
f9903ed0 2057 global $SESSION;
2058
2059 $max_logins = 10;
2060
2061 if (empty($SESSION->logincount)) {
2062 $SESSION->logincount = 1;
2063 } else {
2064 $SESSION->logincount++;
2065 }
2066
2067 if ($SESSION->logincount > $max_logins) {
9fa49e22 2068 unset($SESSION->wantsurl);
b0ccd3fb 2069 error(get_string('errortoomanylogins'));
d578afc8 2070 }
2071}
2072
7cf1c7bd 2073/**
2074 * Resets login attempts
2075 *
2076 * @uses $SESSION
2077 */
9fa49e22 2078function reset_login_count() {
9fa49e22 2079 global $SESSION;
d578afc8 2080
9fa49e22 2081 $SESSION->logincount = 0;
d578afc8 2082}
2083
b61efafb 2084function sync_metacourses() {
2085
2086 global $CFG;
2087
1aad4310 2088 if (!$courses = get_records('course', 'metacourse', 1)) {
b61efafb 2089 return;
2090 }
d2a9f7cc 2091
b61efafb 2092 foreach ($courses as $course) {
1aad4310 2093 sync_metacourse($course);
b61efafb 2094 }
2095}
2096
b61efafb 2097/**
2098 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
5e623a33 2099 *
123545bc 2100 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
d2a9f7cc 2101 */
1aad4310 2102function sync_metacourse($course) {
755c8d58 2103 global $CFG;
b61efafb 2104
123545bc 2105 // Check the course is valid.
1aad4310 2106 if (!is_object($course)) {
2107 if (!$course = get_record('course', 'id', $course)) {
2108 return false; // invalid course id
b61efafb 2109 }
b61efafb 2110 }
5e623a33 2111
123545bc 2112 // Check that we actually have a metacourse.
1aad4310 2113 if (empty($course->metacourse)) {
123545bc 2114 return false;
755c8d58 2115 }
87671466 2116
b3170072 2117 // Get a list of roles that should not be synced.
4db9bff7 2118 if (!empty($CFG->nonmetacoursesyncroleids)) {
b3170072 2119 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
5e623a33 2120 } else {
b3170072 2121 $roleexclusions = '';
2122 }
2123
123545bc 2124 // Get the context of the metacourse.
1aad4310 2125 $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
e1ecf0a0 2126
123545bc 2127 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
b79da3ac 2128 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
1aad4310 2129 $managers = array_keys($users);
2130 } else {
2131 $managers = array();
b61efafb 2132 }
2133
123545bc 2134 // Get assignments of a user to a role that exist in a child course, but
2135 // not in the meta coure. That is, get a list of the assignments that need to be made.
2136 if (!$assignments = get_records_sql("
2137 SELECT
2138 ra.id, ra.roleid, ra.userid
2139 FROM
2140 {$CFG->prefix}role_assignments ra,
2141 {$CFG->prefix}context con,
2142 {$CFG->prefix}course_meta cm
2143 WHERE
2144 ra.contextid = con.id AND
2145 con.contextlevel = " . CONTEXT_COURSE . " AND
2146 con.instanceid = cm.child_course AND
2147 cm.parent_course = {$course->id} AND
b3170072 2148 $roleexclusions
123545bc 2149 NOT EXISTS (
2150 SELECT 1 FROM
2151 {$CFG->prefix}role_assignments ra2
2152 WHERE
2153 ra2.userid = ra.userid AND
2154 ra2.roleid = ra.roleid AND
2155 ra2.contextid = {$context->id}
2156 )
2157 ")) {
2158 $assignments = array();
2159 }
2160
2161 // Get assignments of a user to a role that exist in the meta course, but
2162 // not in any child courses. That is, get a list of the unassignments that need to be made.
2163 if (!$unassignments = get_records_sql("
2164 SELECT
2165 ra.id, ra.roleid, ra.userid
2166 FROM
2167 {$CFG->prefix}role_assignments ra
2168 WHERE
2169 ra.contextid = {$context->id} AND
b3170072 2170 $roleexclusions
123545bc 2171 NOT EXISTS (
2172 SELECT 1 FROM
2173 {$CFG->prefix}role_assignments ra2,
2174 {$CFG->prefix}context con2,
2175 {$CFG->prefix}course_meta cm
2176 WHERE
2177 ra2.userid = ra.userid AND
2178 ra2.roleid = ra.roleid AND
2179 ra2.contextid = con2.id AND
2180 con2.contextlevel = " . CONTEXT_COURSE . " AND
2181 con2.instanceid = cm.child_course AND
2182 cm.parent_course = {$course->id}
2183 )
2184 ")) {
2185 $unassignments = array();
2186 }
2187
2188 $success = true;
2189
2190 // Make the unassignments, if they are not managers.
2191 foreach ($unassignments as $unassignment) {
2192 if (!in_array($unassignment->userid, $managers)) {
2193 $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
1aad4310 2194 }
755c8d58 2195 }
e1ecf0a0 2196
123545bc 2197 // Make the assignments.
2198 foreach ($assignments as $assignment) {
2199 $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id) && $success;
b61efafb 2200 }
755c8d58 2201
123545bc 2202 return $success;
5e623a33 2203
1aad4310 2204// TODO: finish timeend and timestart
2205// maybe we could rely on cron job to do the cleaning from time to time
b61efafb 2206}
2207
d2a9f7cc 2208/**
b61efafb 2209 * Adds a record to the metacourse table and calls sync_metacoures
2210 */
2211function add_to_metacourse ($metacourseid, $courseid) {
d2a9f7cc 2212
b61efafb 2213 if (!$metacourse = get_record("course","id",$metacourseid)) {
2214 return false;
2215 }
d2a9f7cc 2216
b61efafb 2217 if (!$course = get_record("course","id",$courseid)) {
2218 return false;
2219 }
2220
5f37b628 2221 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
53467aa6 2222 $rec = new object();
b61efafb 2223 $rec->parent_course = $metacourseid;
2224 $rec->child_course = $courseid;
5f37b628 2225 if (!insert_record('course_meta',$rec)) {
b61efafb 2226 return false;
2227 }
2228 return sync_metacourse($metacourseid);
2229 }
2230 return true;
d2a9f7cc 2231
b61efafb 2232}
2233
d2a9f7cc 2234/**
b61efafb 2235 * Removes the record from the metacourse table and calls sync_metacourse
2236 */
2237function remove_from_metacourse($metacourseid, $courseid) {
2238
5f37b628 2239 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
b61efafb 2240 return sync_metacourse($metacourseid);
2241 }
2242 return false;
2243}
2244
2245
7c12949d 2246/**
2247 * Determines if a user is currently logged in
2248 *
2249 * @uses $USER
bbd3f2c4 2250 * @return bool
7c12949d 2251 */
2252function isloggedin() {
2253 global $USER;
2254
2255 return (!empty($USER->id));
2256}
2257
2a919fd7 2258/**
2259 * Determines if a user is logged in as real guest user with username 'guest'.
2260 * This function is similar to original isguest() in 1.6 and earlier.
2261 * Current isguest() is deprecated - do not use it anymore.
2262 *
2263 * @param $user mixed user object or id, $USER if not specified
2264 * @return bool true if user is the real guest user, false if not logged in or other user
2265 */
2266function isguestuser($user=NULL) {
2267 global $USER;
2268 if ($user === NULL) {
2269 $user = $USER;
2270 } else if (is_numeric($user)) {
2271 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2272 }
2273
2274 if (empty($user->id)) {
2275 return false; // not logged in, can not be guest
2276 }
2277
2278 return ($user->username == 'guest');
2279}
7c12949d 2280
7cf1c7bd 2281/**
e6260a45 2282 * Determines if the currently logged in user is in editing mode.
2283 * Note: originally this function had $userid parameter - it was not usable anyway
7cf1c7bd 2284 *
2285 * @uses $USER
c6d15803 2286 * @param int $courseid The id of the course being tested
bbd3f2c4 2287 * @return bool
7cf1c7bd 2288 */
e6260a45 2289function isediting($courseid) {
3cf4fa0c 2290 global $USER;
e6260a45 2291
2292 if (empty($USER->editing)) {
9c9f7d77 2293 return false;
e6260a45 2294
2295 } else {
2296 return editcourseallowed($courseid);
9c9f7d77 2297 }
e6260a45 2298}
2299
2300/**
2301 * Verifies if user allowed to edit something in the course page.
2302 * @param int $courseid The id of the course being tested
2303 * @return bool
2304 */
2305function editcourseallowed($courseid) {
2306 global $USER;
5e623a33 2307
e6260a45 2308 // cache the result per course, it is automatically reset when using switchrole or loginas
2309 if (!array_key_exists('courseeditallowed', $USER)) {
2310 $USER->courseeditallowed = array();
2311 }
5e623a33 2312
e6260a45 2313 if (!array_key_exists($courseid, $USER->courseeditallowed)) {
2314 $USER->courseeditallowed[$courseid] = has_capability_including_child_contexts(get_context_instance(CONTEXT_COURSE, $courseid),
2315 array('moodle/site:manageblocks', 'moodle/course:manageactivities'));
217a8ee9 2316 }
5e623a33 2317
e6260a45 2318 return $USER->courseeditallowed[$courseid];
2c309dc2 2319}
2320
7cf1c7bd 2321/**
2322 * Determines if the logged in user is currently moving an activity
2323 *
2324 * @uses $USER
c6d15803 2325 * @param int $courseid The id of the course being tested
bbd3f2c4 2326 * @return bool
7cf1c7bd 2327 */
7977cffd 2328function ismoving($courseid) {
7977cffd 2329 global $USER;
2330
2331 if (!empty($USER->activitycopy)) {
2332 return ($USER->activitycopycourse == $courseid);
2333 }
2334 return false;
2335}
2336
7cf1c7bd 2337/**
2338 * Given an object containing firstname and lastname
2339 * values, this function returns a string with the
2340 * full name of the person.
2341 * The result may depend on system settings
2342 * or language. 'override' will force both names
361855e6 2343 * to be used even if system settings specify one.
68fbd8e1 2344 *
7cf1c7bd 2345 * @uses $CFG
2346 * @uses $SESSION
68fbd8e1 2347 * @param object $user A {@link $USER} object to get full name of
2348 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
7cf1c7bd 2349 */
e2cd5065 2350function fullname($user, $override=false) {
b5cbb64d 2351
f374fb10 2352 global $CFG, $SESSION;
2353
6527c077 2354 if (!isset($user->firstname) and !isset($user->lastname)) {
2355 return '';
2356 }
2357
4c202228 2358 if (!$override) {
2359 if (!empty($CFG->forcefirstname)) {
2360 $user->firstname = $CFG->forcefirstname;
2361 }
2362 if (!empty($CFG->forcelastname)) {
2363 $user->lastname = $CFG->forcelastname;
2364 }
2365 }
2366
f374fb10 2367 if (!empty($SESSION->fullnamedisplay)) {
2368 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
2369 }
e2cd5065 2370
b5cbb64d 2371 if ($CFG->fullnamedisplay == 'firstname lastname') {
b0ccd3fb 2372 return $user->firstname .' '. $user->lastname;
b5cbb64d 2373
2374 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 2375 return $user->lastname .' '. $user->firstname;
e2cd5065 2376
b5cbb64d 2377 } else if ($CFG->fullnamedisplay == 'firstname') {
2378 if ($override) {
2379 return get_string('fullnamedisplay', '', $user);
2380 } else {
2381 return $user->firstname;
2382 }
2383 }
e2cd5065 2384
b5cbb64d 2385 return get_string('fullnamedisplay', '', $user);
e2cd5065 2386}
2387
7cf1c7bd 2388/**
2389 * Sets a moodle cookie with an encrypted string
2390 *
2391 * @uses $CFG
2f87145b 2392 * @uses DAYSECS
2393 * @uses HOURSECS
7cf1c7bd 2394 * @param string $thing The string to encrypt and place in a cookie
2395 */
f9903ed0 2396function set_moodle_cookie($thing) {
7185e073 2397 global $CFG;
482b6e6e 2398
7cbe6afe 2399 if ($thing == 'guest') { // Ignore guest account
2400 return;
2401 }
2402
482b6e6e 2403 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
f9903ed0 2404
2405 $days = 60;
7a5672c9 2406 $seconds = DAYSECS*$days;
f9903ed0 2407
7a5672c9 2408 setCookie($cookiename, '', time() - HOURSECS, '/');
b0ccd3fb 2409 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, '/');
f9903ed0 2410}
2411
7cf1c7bd 2412/**
2413 * Gets a moodle cookie with an encrypted string
2414 *
2415 * @uses $CFG
2416 * @return string
2417 */
f9903ed0 2418function get_moodle_cookie() {
7185e073 2419 global $CFG;
2420
482b6e6e 2421 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
7185e073 2422
1079c8a8 2423 if (empty($_COOKIE[$cookiename])) {
b0ccd3fb 2424 return '';
1079c8a8 2425 } else {
7cbe6afe 2426 $thing = rc4decrypt($_COOKIE[$cookiename]);
2427 return ($thing == 'guest') ? '': $thing; // Ignore guest account
1079c8a8 2428 }
f9903ed0 2429}
2430
7cf1c7bd 2431/**
03d820c7 2432 * Returns whether a given authentication plugin exists.
7cf1c7bd 2433 *
2434 * @uses $CFG
03d820c7 2435 * @param string $auth Form of authentication to check for. Defaults to the
2436 * global setting in {@link $CFG}.
2437 * @return boolean Whether the plugin is available.
7cf1c7bd 2438 */
16793340 2439function exists_auth_plugin($auth) {
03d820c7 2440 global $CFG;
5e623a33 2441
03d820c7 2442 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2443 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2444 }
2445 return false;
2446}
ba7166c3 2447
03d820c7 2448/**
2449 * Checks if a given plugin is in the list of enabled authentication plugins.
5e623a33 2450 *
03d820c7 2451 * @param string $auth Authentication plugin.
2452 * @return boolean Whether the plugin is enabled.
2453 */
16793340 2454function is_enabled_auth($auth) {
16793340 2455 if (empty($auth)) {
2456 return false;
03d820c7 2457 }
16793340 2458
c7b10b5f 2459 $enabled = get_enabled_auth_plugins();
2460
2461 return in_array($auth, $enabled);
03d820c7 2462}
2463
2464/**
2465 * Returns an authentication plugin instance.
2466 *
2467 * @uses $CFG
9696bd89 2468 * @param string $auth name of authentication plugin
03d820c7 2469 * @return object An instance of the required authentication plugin.
2470 */
9696bd89 2471function get_auth_plugin($auth) {
03d820c7 2472 global $CFG;
5e623a33 2473
03d820c7 2474 // check the plugin exists first
2475 if (! exists_auth_plugin($auth)) {
2476 error("Authentication plugin '$auth' not found.");
2477 }
5e623a33 2478
03d820c7 2479 // return auth plugin instance
2480 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2481 $class = "auth_plugin_$auth";
2482 return new $class;
2483}
2484
c7b10b5f 2485/**
2486 * Returns array of active auth plugins.
2487 *
2488 * @param bool $fix fix $CFG->auth if needed
2489 * @return array
2490 */
2491function get_enabled_auth_plugins($fix=false) {
2492 global $CFG;
2493
2494 $default = array('manual', 'nologin');
2495
2496 if (empty($CFG->auth)) {
2497 $auths = array();
2498 } else {
2499 $auths = explode(',', $CFG->auth);
2500 }
2501
2502 if ($fix) {
2503 $auths = array_unique($auths);
2504 foreach($auths as $k=>$authname) {
2505 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
2506 unset($auths[$k]);
2507 }
2508 }
2509 $newconfig = implode(',', $auths);
2510 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
2511 set_config('auth', $newconfig);
2512 }
2513 }
2514
2515 return (array_merge($default, $auths));
2516}
2517
03d820c7 2518/**
2519 * Returns true if an internal authentication method is being used.
2520 * if method not specified then, global default is assumed
2521 *
2522 * @uses $CFG
2523 * @param string $auth Form of authentication required
2524 * @return bool
03d820c7 2525 */
16793340 2526function is_internal_auth($auth) {
03d820c7 2527 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2528 return $authplugin->is_internal();
a3f1f815 2529}
2530
8c3dba73 2531/**
2532 * Returns an array of user fields
2533 *
c6d15803 2534 * @uses $CFG
2535 * @uses $db
2536 * @return array User field/column names
8c3dba73 2537 */
a3f1f815 2538function get_user_fieldnames() {
a3f1f815 2539
2540 global $CFG, $db;
2541
2542 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
2543 unset($fieldarray['ID']);
2544
2545 return $fieldarray;
ba7166c3 2546}
f9903ed0 2547
08103c93
ML
2548/**
2549 * Creates the default "guest" user. Used both from
2550 * admin/index.php and login/index.php
2551 * @return mixed user object created or boolean false if the creation has failed
2552 */
2553function create_guest_record() {
2554
2555 global $CFG;
2556
c824d478 2557 $guest = new stdClass();
08103c93
ML
2558 $guest->auth = 'manual';
2559 $guest->username = 'guest';
2560 $guest->password = hash_internal_user_password('guest');
2561 $guest->firstname = addslashes(get_string('guestuser'));
2562 $guest->lastname = ' ';
2563 $guest->email = 'root@localhost';
2564 $guest->description = addslashes(get_string('guestuserinfo'));
2565 $guest->mnethostid = $CFG->mnet_localhost_id;
2566 $guest->confirmed = 1;
2567 $guest->lang = $CFG->lang;
2568 $guest->timemodified= time();
2569
2570 if (! $guest->id = insert_record("user", $guest)) {
2571 return false;
2572 }
2573
2574 return $guest;
2575}
2576
7cf1c7bd 2577/**
2578 * Creates a bare-bones user record
2579 *
2580 * @uses $CFG
7cf1c7bd 2581 * @param string $username New user's username to add to record
2582 * @param string $password New user's password to add to record
2583 * @param string $auth Form of authentication required
68fbd8e1 2584 * @return object A {@link $USER} object
7cf1c7bd 2585 * @todo Outline auth types and provide code example
2586 */
f76cfc7a 2587function create_user_record($username, $password, $auth='manual') {
366dfa60 2588 global $CFG;
71f9abf9 2589
1e22bc9c 2590 //just in case check text case
2591 $username = trim(moodle_strtolower($username));
71f9abf9 2592
03d820c7 2593 $authplugin = get_auth_plugin($auth);
2594
6bc1e5d5 2595 if ($newinfo = $authplugin->get_userinfo($username)) {
2596 $newinfo = truncate_userinfo($newinfo);
2597 foreach ($newinfo as $key => $value){
2598 $newuser->$key = addslashes($value);
e858f9da 2599 }
2600 }
f9903ed0 2601
85a1d4c9 2602 if (!empty($newuser->email)) {
2603 if (email_is_not_allowed($newuser->email)) {
2604 unset($newuser->email);
2605 }
2606 }
2607
f76cfc7a 2608 $newuser->auth = $auth;
faebaf0f 2609 $newuser->username = $username;
5e623a33 2610
e51917eb 2611 // fix for MDL-8480
2612 // user CFG lang for user if $newuser->lang is empty
2613 // or $user->lang is not an installed language
2614 $sitelangs = array_keys(get_list_of_languages());
2615 if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
2616 $newuser -> lang = $CFG->lang;
5e623a33 2617 }
faebaf0f 2618 $newuser->confirmed = 1;
d96466d2 2619 $newuser->lastip = getremoteaddr();
faebaf0f 2620 $newuser->timemodified = time();
03d820c7 2621 $newuser->mnethostid = $CFG->mnet_localhost_id;
f9903ed0 2622
b0ccd3fb 2623 if (insert_record('user', $newuser)) {
16793340 2624 $user = get_complete_user_data('username', $newuser->username);
da5bcc9f 2625 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
16793340 2626 set_user_preference('auth_forcepasswordchange', 1, $user->id);
2627 }
2628 update_internal_user_password($user, $password);
2629 return $user;
faebaf0f 2630 }
2631 return false;
2632}
2633
7cf1c7bd 2634/**
2635 * Will update a local user record from an external source
2636 *
2637 * @uses $CFG
2638 * @param string $username New user's username to add to record
89dcb99d 2639 * @return user A {@link $USER} object
7cf1c7bd 2640 */
03d820c7 2641function update_user_record($username, $authplugin) {
6bc1e5d5 2642 $username = trim(moodle_strtolower($username)); /// just in case check text case
2643
2644 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2645 $userauth = get_auth_plugin($oldinfo->auth);
2646
2647 if ($newinfo = $userauth->get_userinfo($username)) {
2648 $newinfo = truncate_userinfo($newinfo);
2649 foreach ($newinfo as $key => $value){
2650 $confkey = 'field_updatelocal_' . $key;
2651 if (!empty($userauth->config->$confkey) and $userauth->config->$confkey === 'onlogin') {
2652 $value = addslashes(stripslashes($value)); // Just in case
2653 set_field('user', $key, $value, 'username', $username)
2654 or error_log("Error updating $key for $username");
d35757eb 2655 }
2656 }
2657 }
6bc1e5d5 2658
7c12949d 2659 return get_complete_user_data('username', $username);
d35757eb 2660}
0609562b 2661
b36a8fc4 2662function truncate_userinfo($info) {
2663/// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2664/// which may have large fields
2665
2666 // define the limits
2667 $limit = array(
2668 'username' => 100,
1c66bf59 2669 'idnumber' => 64,
8bcd295c 2670 'firstname' => 100,
2671 'lastname' => 100,
b36a8fc4 2672 'email' => 100,
2673 'icq' => 15,
2674 'phone1' => 20,
2675 'phone2' => 20,
2676 'institution' => 40,
2677 'department' => 30,
2678 'address' => 70,
2679 'city' => 20,
2680 'country' => 2,
2681 'url' => 255,
2682 );
361855e6 2683
b36a8fc4 2684 // apply where needed
2685 foreach (array_keys($info) as $key) {
2686 if (!empty($limit[$key])) {
adfc03f9 2687 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
361855e6 2688 }
b36a8fc4 2689 }
361855e6 2690
b36a8fc4 2691 return $info;
90afcf32 2692}
2693
2694/**
2695 * Marks user deleted in internal user database and notifies the auth plugin.
2696 * Also unenrols user from all roles and does other cleanup.
2697 * @param object $user Userobject before delete (without system magic quotes)
2698 * @return boolean success
2699 */
2700function delete_user($user) {
2701 global $CFG;
2702 require_once($CFG->libdir.'/grouplib.php');
2703
2704 begin_sql();
2705
2706 // delete all grades - backup is kept in grade_grades_history table
2707 if ($grades = grade_grade::fetch_all(array('userid'=>$user->id))) {
2708 foreach ($grades as $grade) {
2709 $grade->delete('userdelete');
2710 }
2711 }
2712
2713 // remove from all groups
2714 delete_records('groups_members', 'userid', $user->id);
2715
2716 // unenrol from all roles in all contexts
2717 role_unassign(0, $user->id); // this might be slow but it is really needed - modules might do some extra cleanup!
2718
2719 // now do a final accesslib cleanup - removes all role assingments in user context and context itself
2720 delete_context(CONTEXT_USER, $user->id);
2721
2722 // mark internal user record as "deleted"
2723 $updateuser = new object();
2724 $updateuser->id = $user->id;
2725 $updateuser->deleted = 1;
2726 $updateuser->username = addslashes("$user->email.".time()); // Remember it just in case
2727 $updateuser->email = ''; // Clear this field to free it up
2728 $updateuser->idnumber = ''; // Clear this field to free it up
2729 $updateuser->timemodified = time();
2730
2731 if (update_record('user', $updateuser)) {
2732 commit_sql();
2733 // notify auth plugin - do not block the delete even when plugin fails
2734 $authplugin = get_auth_plugin($user->auth);
2735 $authplugin->user_delete($user);
2736 return true;
2737
2738 } else {
2739 rollback_sql();
2740 return false;
2741 }
b36a8fc4 2742}
2743
7cf1c7bd 2744/**
2745 * Retrieve the guest user object
2746 *
2747 * @uses $CFG
89dcb99d 2748 * @return user A {@link $USER} object
7cf1c7bd 2749 */
0609562b 2750function guest_user() {
2751 global $CFG;
2752
b59c7ec0 2753 if ($newuser = get_record('user', 'username', 'guest', 'mnethostid', $CFG->mnet_localhost_id)) {
0609562b 2754 $newuser->confirmed = 1;
0609562b 2755 $newuser->lang = $CFG->lang;
d96466d2 2756 $newuser->lastip = getremoteaddr();
0609562b 2757 }
2758
2759 return $newuser;
2760}
2761
7cf1c7bd 2762/**
2763 * Given a username and password, this function looks them
2764 * up using the currently selected authentication mechanism,
2765 * and if the authentication is successful, it returns a
2766 * valid $user object from the 'user' table.
361855e6 2767 *
7cf1c7bd 2768 * Uses auth_ functions from the currently active auth module
2769 *
2770 * @uses $CFG
f5fd4347 2771 * @param string $username User's username (with system magic quotes)
2772 * @param string $password User's password (with system magic quotes)
89dcb99d 2773 * @return user|flase A {@link $USER} object or false if error
7cf1c7bd 2774 */
faebaf0f 2775function authenticate_user_login($username, $password) {
faebaf0f 2776
2777 global $CFG;
2778
c7b10b5f 2779 $authsenabled = get_enabled_auth_plugins();
39a5a35d 2780
16793340 2781 if ($user = get_complete_user_data('username', $username)) {
2782 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
2783 if ($auth=='nologin' or !is_enabled_auth($auth)) {
2784 add_to_log(0, 'login', 'error', 'index.php', $username);
2785 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2786 return false;
27286aeb 2787 }
16793340 2788 if (!empty($user->deleted)) {
2789 add_to_log(0, 'login', 'error', 'index.php', $username);
2790 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2791 return false;
d35757eb 2792 }
16793340 2793 $auths = array($auth);
2794
71f9abf9 2795 } else {
16793340 2796 $auths = $authsenabled;
2797 $user = new object();
2798 $user->id = 0; // User does not exist
27286aeb 2799 }
8f0cd6ef 2800
03d820c7 2801 foreach ($auths as $auth) {
2802 $authplugin = get_auth_plugin($auth);
466558e3 2803
16793340 2804 // on auth fail fall through to the next plugin
03d820c7 2805 if (!$authplugin->user_login($username, $password)) {
03d820c7 2806 continue;
2807 }
faebaf0f 2808
03d820c7 2809 // successful authentication
d613daf0 2810 if ($user->id) { // User already exists in database
71f9abf9 2811 if (empty($user->auth)) { // For some reason auth isn't set yet
2812 set_field('user', 'auth', $auth, 'username', $username);
16793340 2813 $user->auth = $auth;
71f9abf9 2814 }
16793340 2815
2816 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
2817
03d820c7 2818 if (!$authplugin->is_internal()) { // update user record from external DB
2819 $user = update_user_record($username, get_auth_plugin($user->auth));
d35757eb 2820 }
faebaf0f 2821 } else {
16793340 2822 // if user not found, create him
71f9abf9 2823 $user = create_user_record($username, $password, $auth);
faebaf0f 2824 }
01af6da6 2825
6bc1e5d5 2826 $authplugin->sync_roles($user);
2827
f5fd4347 2828 foreach ($authsenabled as $hau) {
2829 $hauth = get_auth_plugin($hau);
2830 $hauth->user_authenticated_hook($user, $username, $password);
2831 }
2832
2833 /// Log in to a second system if necessary
2834 /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
2835 if (!empty($CFG->sso)) {
2836 include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
2837 if (function_exists('sso_user_login')) {
2838 if (!sso_user_login($username, $password)) { // Perform the signon process
2839 notify('Second sign-on failed');
2840 }
2841 }
2842 }
01af6da6 2843
e582b65e 2844 return $user;
9d3c795c 2845
5e623a33 2846 }
2847
03d820c7 2848 // failed if all the plugins have failed
2849 add_to_log(0, 'login', 'error', 'index.php', $username);
2850 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2851 return false;
f9903ed0 2852}
2853
df193157 2854/**
4908ad3e 2855 * Compare password against hash stored in internal user table.
df193157 2856 * If necessary it also updates the stored hash to new format.
5e623a33 2857 *
df193157 2858 * @param object user
2859 * @param string plain text password
2860 * @return bool is password valid?
2861 */
2862function validate_internal_user_password(&$user, $password) {
2863 global $CFG;
2864
4908ad3e 2865 if (!isset($CFG->passwordsaltmain)) {
2866 $CFG->passwordsaltmain = '';
2867 }
2868
df193157 2869 $validated = false;
2870
a044c05d 2871 // get password original encoding in case it was not updated to unicode yet
fb773106 2872 $textlib = textlib_get_instance();
810944af 2873 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
df193157 2874
4908ad3e 2875 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
2876 or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
df193157 2877 $validated = true;
4908ad3e 2878 } else {
aaeaa4b0 2879 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
4908ad3e 2880 $alt = 'passwordsaltalt'.$i;
2881 if (!empty($CFG->$alt)) {
2882 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
2883 $validated = true;
2884 break;
2885 }
2886 }
2887 }
df193157 2888 }
2889
2890 if ($validated) {
4908ad3e 2891 // force update of password hash using latest main password salt and encoding if needed
df193157 2892 update_internal_user_password($user, $password);
2893 }
2894
2895 return $validated;
2896}
2897
2898/**
2899 * Calculate hashed value from password using current hash mechanism.
5e623a33 2900 *
df193157 2901 * @param string password
2902 * @return string password hash
2903 */
2904function hash_internal_user_password($password) {
4908ad3e 2905 global $CFG;
2906
2907 if (isset($CFG->passwordsaltmain)) {
2908 return md5($password.$CFG->passwordsaltmain);
2909 } else {
2910 return md5($password);
2911 }
df193157 2912}
2913
2914/**
2915 * Update pssword hash in user object.
5e623a33 2916 *
df193157 2917 * @param object user
2918 * @param string plain text password
2919 * @param bool store changes also in db, default true
2920 * @return true if hash changed
2921 */
16793340 2922function update_internal_user_password(&$user, $password) {
df193157 2923 global $CFG;
2924
03d820c7 2925 $authplugin = get_auth_plugin($user->auth);
16793340 2926 if (!empty($authplugin->config->preventpassindb)) {
df193157 2927 $hashedpassword = 'not cached';
2928 } else {
2929 $hashedpassword = hash_internal_user_password($password);
2930 }
2931
b7b50143 2932 return set_field('user', 'password', $hashedpassword, 'id', $user->id);
df193157 2933}
2934
7c12949d 2935/**
2936 * Get a complete user record, which includes all the info
5c98bf9e 2937 * in the user record
7c12949d 2938 * Intended for setting as $USER session variable
2939 *
2940 * @uses $CFG
2941 * @uses SITEID
e1ecf0a0 2942 * @param string $field The user field to be checked for a given value.
7c12949d 2943 * @param string $value The value to match for $field.
2944 * @return user A {@link $USER} object.
2945 */
b7b50143 2946function get_complete_user_data($field, $value, $mnethostid=null) {
7c12949d 2947
2948 global $CFG;
2949
2950 if (!$field || !$value) {
2951 return false;
2952 }
2953
b7b50143 2954/// Build the WHERE clause for an SQL query
2955
2956 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
2957
e5edab1b 2958 if (is_null($mnethostid)) {
2959 // if null, we restrict to local users
2960 // ** testing for local user can be done with
5e623a33 2961 // mnethostid = $CFG->mnet_localhost_id
e5edab1b 2962 // or with
5e623a33 2963 // auth != 'mnet'
e5edab1b 2964 // but the first one is FAST with our indexes
2965 $mnethostid = $CFG->mnet_localhost_id;
2966 }
2967 $mnethostid = (int)$mnethostid;
2968 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
b7b50143 2969
7c12949d 2970/// Get all the basic user data
2971
b7b50143 2972 if (! $user = get_record_select('user', $constraints)) {
7c12949d 2973 return false;
2974 }
2975
7c12949d 2976/// Get various settings and preferences
2977
2978 if ($displays = get_records('course_display', 'userid', $user->id)) {
2979 foreach ($displays as $display) {
2980 $user->display[$display->course] = $display->display;
2981 }
2982 }
2983
346c3e2f 2984 $user->preference = get_user_preferences(null, null, $user->id);
7c12949d 2985
721d14cb 2986 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id)) {
2987 foreach ($lastaccesses as $lastaccess) {
2988 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
2989 }
2990 }
2991
5bf243d1 2992 $sql = "SELECT g.id, g.courseid
2993 FROM {$CFG->prefix}groups g, {$CFG->prefix}groups_members gm
2994 WHERE gm.groupid=g.id AND gm.userid={$user->id}";
2995
2996 // this is a special hack to speedup calendar display
2997 $user->groupmember = array();
2998 if ($groups = get_records_sql($sql)) {
2999 foreach ($groups as $group) {
3000 if (!array_key_exists($group->courseid, $user->groupmember)) {
3001 $user->groupmember[$group->courseid] = array();
3002 }
3003 $user->groupmember[$group->courseid][$group->id] = $group->id;
7c12949d 3004 }
3005 }
3006
3007/// Rewrite some variables if necessary
3008 if (!empty($user->description)) {
3009 $user->description = true; // No need to cart all of it around
3010 }
3011 if ($user->username == 'guest') {
3012 $user->lang = $CFG->lang; // Guest language always same as site
3013 $user->firstname = get_string('guestuser'); // Name always in current language
3014 $user->lastname = ' ';
3015 }
3016
7c12949d 3017 $user->sesskey = random_string(10);
3018 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
3019
3020 return $user;
7c12949d 3021}
3022
83022298 3023/**
3024 * @uses $CFG
3025 * @param string $password the password to be checked agains the password policy
3026 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
3027 * @return bool true if the password is valid according to the policy. false otherwise.
3028 */
3029function check_password_policy($password, &$errmsg) {
3030 global $CFG;
3031
3032 if (empty($CFG->passwordpolicy)) {
3033 return true;
3034 }
3035
3036 $textlib = new textlib();
3037 $errmsg = '';
3038 if ($textlib->strlen($password) < $CFG->minpasswordlength) {
3039 $errmsg = get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength);
3040
3041 } else if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
3042 $errmsg = get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits);
3043
3044 } else if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
3045 $errmsg = get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower);
3046
3047 } else if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
3048 $errmsg = get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper);
7c12949d 3049
83022298 3050 } else if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
3051 $errmsg = get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
5c98bf9e 3052
83022298 3053 } else if ($password == 'admin' or $password == 'password') {
3054 $errmsg = get_string('unsafepassword');
3055 }
3056
3057 if ($errmsg == '') {
3058 return true;
3059 } else {
3060 return false;
3061 }
3062}
3063
3064
3065/**
7c12949d 3066 * When logging in, this function is run to set certain preferences
3067 * for the current SESSION
3068 */
3069function set_login_session_preferences() {
7c7ca1b5 3070 global $SESSION, $CFG;
7c12949d 3071
3072 $SESSION->justloggedin = true;
3073
3074 unset($SESSION->lang);
7c12949d 3075
3076 // Restore the calendar filters, if saved
3077 if (intval(get_user_preferences('calendar_persistflt', 0))) {
3078 include_once($CFG->dirroot.'/calendar/lib.php');
a266c904 3079 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
7c12949d 3080 }
3081}
3082
3083
b97c4164 3084/**
3085 * Delete a course, including all related data from the database,
3086 * and any associated files from the moodledata folder.
e1ecf0a0 3087 *
b97c4164 3088 * @param int $courseid The id of the course to delete.
3089 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3090 * @return bool true if all the removals succeeded. false if there were any failures. If this
3091 * method returns false, some of the removals will probably have succeeded, and others
3092 * failed, but you have no way of knowing which.
3093 */
3094function delete_course($courseid, $showfeedback = true) {
3095 global $CFG;
f615fbab 3096 require_once($CFG->libdir.'/gradelib.php');
b97c4164 3097 $result = true;
e1ecf0a0 3098
b97c4164 3099 if (!remove_course_contents($courseid, $showfeedback)) {
3100 if ($showfeedback) {
3101 notify("An error occurred while deleting some of the course contents.");
3102 }
3103 $result = false;
3104 }
3105
f615fbab 3106 remove_course_grades($courseid, $showfeedback);
3107
b97c4164 3108 if (!delete_records("course", "id", $courseid)) {
3109 if ($showfeedback) {
3110 notify("An error occurred while deleting the main course record.");
3111 }
3112 $result = false;
3113 }
3114
9991d157 3115 if (!delete_records('context', 'contextlevel', CONTEXT_COURSE, 'instanceid', $courseid)) {
eaa79489 3116 if ($showfeedback) {
3117 notify("An error occurred while deleting the main context record.");
3118 }
3119 $result = false;
3120 }
3121
b97c4164 3122 if (!fulldelete($CFG->dataroot.'/'.$courseid)) {
3123 if ($showfeedback) {
3124 notify("An error occurred while deleting the course files.");
3125 }
3126 $result = false;
3127 }
e1ecf0a0 3128
b97c4164 3129 return $result;
3130}
3131
7cf1c7bd 3132/**
3133 * Clear a course out completely, deleting all content
3134 * but don't delete the course itself
3135 *
7cf1c7bd 3136 * @uses $CFG
1f8ede91 3137 * @param int $courseid The id of the course that is being deleted
3138 * @param bool $showfeedback Whether to display notifications of each action the function performs.
b97c4164 3139 * @return bool true if all the removals succeeded. false if there were any failures. If this
3140 * method returns false, some of the removals will probably have succeeded, and others
3141 * failed, but you have no way of knowing which.
7cf1c7bd 3142 */
07aeb7b0 3143function remove_course_contents($courseid, $showfeedback=true) {
07aeb7b0 3144
1f8ede91 3145 global $CFG;
681666ab 3146 include_once($CFG->libdir.'/questionlib.php');
07aeb7b0 3147
3148 $result = true;
3149
b0ccd3fb 3150 if (! $course = get_record('course', 'id', $courseid)) {
3151 error('Course ID was incorrect (can\'t find it)');
07aeb7b0 3152 }
3153
b0ccd3fb 3154 $strdeleted = get_string('deleted');
07aeb7b0 3155
9991d157 3156/// First delete every instance of every module
d8ba183c 3157
b0ccd3fb 3158 if ($allmods = get_records('modules') ) {
07aeb7b0 3159 foreach ($allmods as $mod) {
3160 $modname = $mod->name;
b0ccd3fb 3161 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
3162 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
3163 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
07aeb7b0 3164 $count=0;
3165 if (file_exists($modfile)) {
3166 include_once($modfile);
3167 if (function_exists($moddelete)) {
b0ccd3fb 3168 if ($instances = get_records($modname, 'course', $course->id)) {
07aeb7b0 3169 foreach ($instances as $instance) {
eaa79489 3170 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
3bee1ead 3171 /// Delete activity context questions and question categories
3172 question_delete_activity($cm, $showfeedback);
9991d157 3173 delete_context(CONTEXT_MODULE, $cm->id);
eaa79489 3174 }
07aeb7b0 3175 if ($moddelete($instance->id)) {
3176 $count++;
eaa79489 3177
07aeb7b0 3178 } else {
7eec3390 3179 notify('Could not delete '. $modname .' instance '. $instance->id .' ('. format_string($instance->name) .')');
07aeb7b0 3180 $result = false;
3181 }
3182 }
3183 }
3184 } else {
b0ccd3fb 3185 notify('Function '. $moddelete() .'doesn\'t exist!');
07aeb7b0 3186 $result = false;
3187 }
3188
ca952b03 3189 if (function_exists($moddeletecourse)) {
f67172b6 3190 $moddeletecourse($course, $showfeedback);
ca952b03 3191 }
07aeb7b0 3192 }
3193 if ($showfeedback) {
b0ccd3fb 3194 notify($strdeleted .' '. $count .' x '. $modname);
07aeb7b0 3195 }
3196 }
3197 } else {
b0ccd3fb 3198 error('No modules are installed!');
07aeb7b0 3199 }
3200
9991d157 3201/// Give local code a chance to delete its references to this course.
c0b5b31a 3202 require_once('locallib.php');
3203 notify_local_delete_course($courseid, $showfeedback);
3204
9991d157 3205/// Delete course blocks
7f869120 3206
5e623a33 3207 if ($blocks = get_records_sql("SELECT *
7f869120 3208 FROM {$CFG->prefix}block_instance
3209 WHERE pagetype = '".PAGE_COURSE_VIEW."'
3210 AND pageid = $course->id")) {
eaa79489 3211 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW, 'pageid', $course->id)) {
3212 if ($showfeedback) {
3213 notify($strdeleted .' block_instance');
3214 }
5e623a33 3215
f38dfd49 3216 require_once($CFG->libdir.'/blocklib.php');
9991d157 3217 foreach ($blocks as $block) { /// Delete any associated contexts for this block
5e623a33 3218
f38dfd49 3219 // Block instances are rarely created. Since the block instance is gone from the above delete
3220 // statement, calling delete_context() will generate a warning as get_context_instance could
5e623a33 3221 // no longer create the context as the block is already gone.
f38dfd49 3222 if (record_exists('context', 'contextlevel', CONTEXT_BLOCK, 'instanceid', $block->id)) {
3223 delete_context(CONTEXT_BLOCK, $block->id);
3224 }
5e623a33 3225
3226 // fix for MDL-7164
f38dfd49 3227 // Get the block object and call instance_delete()
3228 if (!$record = blocks_get_record($block->blockid)) {
3229 $result = false;
3230 continue;
3231 }
3232 if (!$obj = block_instance($record->name, $block)) {
3233 $result = false;
3234 continue;
3235 }
3236 // Return value ignored, in core mods this does not do anything, but just in case
3237 // third party blocks might have stuff to clean up
3238 // we execute this anyway
3239 $obj->instance_delete();
9991d157 3240 }
3241 } else {
3242 $result = false;
3243 }
3244 }
3245
2dee6abd 3246/// Delete any groups, removing members and grouping/course links first.
5bf243d1 3247 require_once($CFG->dirroot.'/group/lib.php');
3248 groups_delete_groupings($courseid, true);
3249 groups_delete_groups($courseid, true);
251af423 3250
9991d157 3251/// Delete all related records in other tables that may have a courseid
3252/// This array stores the tables that need to be cleared, as
3253/// table_name => column_name that contains the course id.
3254
09481160 3255 $tablestoclear = array(
09481160 3256 'event' => 'courseid', // Delete events
3257 'log' => 'course', // Delete logs
3258 'course_sections' => 'course', // Delete any course stuff
3259 'course_modules' => 'course',
d148c0ed 3260 'backup_courses' => 'courseid', // Delete scheduled backup stuff
3261 'backup_log' => 'courseid'
09481160 3262 );
3263 foreach ($tablestoclear as $table => $col) {
3264 if (delete_records($table, $col, $course->id)) {
3265 if ($showfeedback) {
3266 notify($strdeleted . ' ' . $table);
3267 }
3268 } else {
3269 $result = false;
07aeb7b0 3270 }