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