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