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