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