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