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