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