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