Commit | Line | Data |
---|---|---|
0d0a8bf6 | 1 | <?php |
2 | ||
6759ad2f | 3 | // This file is part of Moodle - http://moodle.org/ |
4 | // | |
0d0a8bf6 | 5 | // Moodle is free software: you can redistribute it and/or modify |
6 | // it under the terms of the GNU General Public License as published by | |
7 | // the Free Software Foundation, either version 3 of the License, or | |
8 | // (at your option) any later version. | |
9 | // | |
10 | // Moodle is distributed in the hope that it will be useful, | |
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of | |
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
13 | // GNU General Public License for more details. | |
6759ad2f | 14 | // |
0d0a8bf6 | 15 | // You should have received a copy of the GNU General Public License |
16 | // along with Moodle. If not, see <http://www.gnu.org/licenses/>. | |
65ccdd8c | 17 | |
7cf1c7bd | 18 | /** |
89dcb99d | 19 | * moodlelib.php - Moodle main library |
7cf1c7bd | 20 | * |
21 | * Main library file of miscellaneous general-purpose Moodle functions. | |
22 | * Other main libraries: | |
8c3dba73 | 23 | * - weblib.php - functions that produce web output |
24 | * - datalib.php - functions that access the database | |
0d0a8bf6 | 25 | * |
78bfb562 PS |
26 | * @package core |
27 | * @subpackage lib | |
28 | * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com | |
29 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later | |
7cf1c7bd | 30 | */ |
e1ecf0a0 | 31 | |
78bfb562 PS |
32 | defined('MOODLE_INTERNAL') || die(); |
33 | ||
bbd3f2c4 | 34 | /// CONSTANTS (Encased in phpdoc proper comments)///////////////////////// |
f374fb10 | 35 | |
bbd3f2c4 | 36 | /// Date and time constants /// |
5602f7cf | 37 | /** |
38 | * Time constant - the number of seconds in a year | |
39 | */ | |
5602f7cf | 40 | define('YEARSECS', 31536000); |
41 | ||
7a5672c9 | 42 | /** |
2f87145b | 43 | * Time constant - the number of seconds in a week |
7a5672c9 | 44 | */ |
361855e6 | 45 | define('WEEKSECS', 604800); |
2f87145b | 46 | |
47 | /** | |
48 | * Time constant - the number of seconds in a day | |
49 | */ | |
7a5672c9 | 50 | define('DAYSECS', 86400); |
2f87145b | 51 | |
52 | /** | |
53 | * Time constant - the number of seconds in an hour | |
54 | */ | |
7a5672c9 | 55 | define('HOURSECS', 3600); |
2f87145b | 56 | |
57 | /** | |
58 | * Time constant - the number of seconds in a minute | |
59 | */ | |
7a5672c9 | 60 | define('MINSECS', 60); |
2f87145b | 61 | |
62 | /** | |
63 | * Time constant - the number of minutes in a day | |
64 | */ | |
7a5672c9 | 65 | define('DAYMINS', 1440); |
2f87145b | 66 | |
67 | /** | |
68 | * Time constant - the number of minutes in an hour | |
69 | */ | |
7a5672c9 | 70 | define('HOURMINS', 60); |
f9903ed0 | 71 | |
c59733ef | 72 | /// Parameter constants - every call to optional_param(), required_param() /// |
73 | /// or clean_param() should have a specified type of parameter. ////////////// | |
74 | ||
03b31ea3 | 75 | |
76 | ||
e0d346ff | 77 | /** |
03b31ea3 | 78 | * PARAM_ALPHA - contains only english ascii letters a-zA-Z. |
e0d346ff | 79 | */ |
03b31ea3 | 80 | define('PARAM_ALPHA', 'alpha'); |
bbd3f2c4 | 81 | |
82 | /** | |
03b31ea3 | 83 | * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed |
84 | * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed | |
bbd3f2c4 | 85 | */ |
03b31ea3 | 86 | define('PARAM_ALPHAEXT', 'alphaext'); |
bbd3f2c4 | 87 | |
88 | /** | |
03b31ea3 | 89 | * PARAM_ALPHANUM - expected numbers and letters only. |
bbd3f2c4 | 90 | */ |
03b31ea3 | 91 | define('PARAM_ALPHANUM', 'alphanum'); |
bbd3f2c4 | 92 | |
93 | /** | |
03b31ea3 | 94 | * PARAM_ALPHANUMEXT - expected numbers, letters only and _-. |
bbd3f2c4 | 95 | */ |
03b31ea3 | 96 | define('PARAM_ALPHANUMEXT', 'alphanumext'); |
bbd3f2c4 | 97 | |
9dae915a | 98 | /** |
03b31ea3 | 99 | * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin |
6e73ae10 | 100 | */ |
03b31ea3 | 101 | define('PARAM_AUTH', 'auth'); |
6e73ae10 | 102 | |
103 | /** | |
03b31ea3 | 104 | * PARAM_BASE64 - Base 64 encoded format |
9dae915a | 105 | */ |
03b31ea3 | 106 | define('PARAM_BASE64', 'base64'); |
9dae915a | 107 | |
bbd3f2c4 | 108 | /** |
03b31ea3 | 109 | * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls. |
bbd3f2c4 | 110 | */ |
03b31ea3 | 111 | define('PARAM_BOOL', 'bool'); |
bbd3f2c4 | 112 | |
113 | /** | |
03b31ea3 | 114 | * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually |
efb8c375 | 115 | * checked against the list of capabilities in the database. |
6e73ae10 | 116 | */ |
03b31ea3 | 117 | define('PARAM_CAPABILITY', 'capability'); |
6e73ae10 | 118 | |
119 | /** | |
86f6eec3 | 120 | * PARAM_CLEANHTML - cleans submitted HTML code. use only for text in HTML format. This cleaning may fix xhtml strictness too. |
bbd3f2c4 | 121 | */ |
03b31ea3 | 122 | define('PARAM_CLEANHTML', 'cleanhtml'); |
bbd3f2c4 | 123 | |
79f1d953 | 124 | /** |
125 | * PARAM_EMAIL - an email address following the RFC | |
126 | */ | |
127 | define('PARAM_EMAIL', 'email'); | |
128 | ||
bbd3f2c4 | 129 | /** |
03b31ea3 | 130 | * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals |
bbd3f2c4 | 131 | */ |
03b31ea3 | 132 | define('PARAM_FILE', 'file'); |
6e73ae10 | 133 | |
134 | /** | |
03b31ea3 | 135 | * PARAM_FLOAT - a real/floating point number. |
6e73ae10 | 136 | */ |
03b31ea3 | 137 | define('PARAM_FLOAT', 'float'); |
6e73ae10 | 138 | |
139 | /** | |
03b31ea3 | 140 | * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address) |
141 | */ | |
142 | define('PARAM_HOST', 'host'); | |
143 | ||
144 | /** | |
145 | * PARAM_INT - integers only, use when expecting only numbers. | |
6e73ae10 | 146 | */ |
03b31ea3 | 147 | define('PARAM_INT', 'int'); |
148 | ||
149 | /** | |
150 | * PARAM_LANG - checks to see if the string is a valid installed language in the current site. | |
151 | */ | |
152 | define('PARAM_LANG', 'lang'); | |
153 | ||
154 | /** | |
155 | * 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!) | |
156 | */ | |
157 | define('PARAM_LOCALURL', 'localurl'); | |
bbd3f2c4 | 158 | |
159 | /** | |
c59733ef | 160 | * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type. |
bbd3f2c4 | 161 | */ |
03b31ea3 | 162 | define('PARAM_NOTAGS', 'notags'); |
bbd3f2c4 | 163 | |
6e73ae10 | 164 | /** |
03b31ea3 | 165 | * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals |
166 | * note: the leading slash is not removed, window drive letter is not allowed | |
31f26796 | 167 | */ |
03b31ea3 | 168 | define('PARAM_PATH', 'path'); |
31f26796 | 169 | |
6e73ae10 | 170 | /** |
03b31ea3 | 171 | * PARAM_PEM - Privacy Enhanced Mail format |
c4ea5e78 | 172 | */ |
03b31ea3 | 173 | define('PARAM_PEM', 'pem'); |
c4ea5e78 | 174 | |
bbd3f2c4 | 175 | /** |
03b31ea3 | 176 | * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. |
bbd3f2c4 | 177 | */ |
03b31ea3 | 178 | define('PARAM_PERMISSION', 'permission'); |
bbd3f2c4 | 179 | |
bed79931 | 180 | /** |
78fcdb5f | 181 | * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters |
bed79931 | 182 | */ |
03b31ea3 | 183 | define('PARAM_RAW', 'raw'); |
bed79931 | 184 | |
652599ec TH |
185 | /** |
186 | * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped. | |
187 | */ | |
188 | define('PARAM_RAW_TRIMMED', 'raw_trimmed'); | |
189 | ||
bcef0319 | 190 | /** |
03b31ea3 | 191 | * PARAM_SAFEDIR - safe directory name, suitable for include() and require() |
bcef0319 | 192 | */ |
03b31ea3 | 193 | define('PARAM_SAFEDIR', 'safedir'); |
bcef0319 | 194 | |
e032888c | 195 | /** |
03b31ea3 | 196 | * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc. |
38fb8190 | 197 | */ |
03b31ea3 | 198 | define('PARAM_SAFEPATH', 'safepath'); |
e032888c | 199 | |
bbd3f2c4 | 200 | /** |
03b31ea3 | 201 | * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only. |
bbd3f2c4 | 202 | */ |
03b31ea3 | 203 | define('PARAM_SEQUENCE', 'sequence'); |
bbd3f2c4 | 204 | |
205 | /** | |
03b31ea3 | 206 | * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported |
bbd3f2c4 | 207 | */ |
03b31ea3 | 208 | define('PARAM_TAG', 'tag'); |
bbd3f2c4 | 209 | |
210 | /** | |
03b31ea3 | 211 | * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.) |
bbd3f2c4 | 212 | */ |
03b31ea3 | 213 | define('PARAM_TAGLIST', 'taglist'); |
bbd3f2c4 | 214 | |
215 | /** | |
b6059edc | 216 | * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here. |
bbd3f2c4 | 217 | */ |
03b31ea3 | 218 | define('PARAM_TEXT', 'text'); |
bbd3f2c4 | 219 | |
bbd3f2c4 | 220 | /** |
03b31ea3 | 221 | * PARAM_THEME - Checks to see if the string is a valid theme name in the current site |
bbd3f2c4 | 222 | */ |
03b31ea3 | 223 | define('PARAM_THEME', 'theme'); |
bbd3f2c4 | 224 | |
225 | /** | |
efb8c375 | 226 | * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok. |
bbd3f2c4 | 227 | */ |
03b31ea3 | 228 | define('PARAM_URL', 'url'); |
229 | ||
07ed083e | 230 | /** |
6b8ad965 | 231 | * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user accounts, do NOT use when syncing with external systems!! |
07ed083e RW |
232 | */ |
233 | define('PARAM_USERNAME', 'username'); | |
bbd3f2c4 | 234 | |
fe6a248f DM |
235 | /** |
236 | * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string() | |
237 | */ | |
238 | define('PARAM_STRINGID', 'stringid'); | |
03b31ea3 | 239 | |
240 | ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE ///// | |
bbd3f2c4 | 241 | /** |
03b31ea3 | 242 | * PARAM_CLEAN - obsoleted, please use a more specific type of parameter. |
243 | * It was one of the first types, that is why it is abused so much ;-) | |
44913c8d | 244 | * @deprecated since 2.0 |
bbd3f2c4 | 245 | */ |
03b31ea3 | 246 | define('PARAM_CLEAN', 'clean'); |
bbd3f2c4 | 247 | |
248 | /** | |
03b31ea3 | 249 | * PARAM_INTEGER - deprecated alias for PARAM_INT |
bbd3f2c4 | 250 | */ |
03b31ea3 | 251 | define('PARAM_INTEGER', 'int'); |
bbd3f2c4 | 252 | |
0e4af166 | 253 | /** |
03b31ea3 | 254 | * PARAM_NUMBER - deprecated alias of PARAM_FLOAT |
0e4af166 | 255 | */ |
03b31ea3 | 256 | define('PARAM_NUMBER', 'float'); |
0e4af166 | 257 | |
03d820c7 | 258 | /** |
efb8c375 | 259 | * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls |
03b31ea3 | 260 | * NOTE: originally alias for PARAM_APLHA |
03d820c7 | 261 | */ |
03b31ea3 | 262 | define('PARAM_ACTION', 'alphanumext'); |
03d820c7 | 263 | |
264 | /** | |
03b31ea3 | 265 | * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc. |
266 | * NOTE: originally alias for PARAM_APLHA | |
03d820c7 | 267 | */ |
03b31ea3 | 268 | define('PARAM_FORMAT', 'alphanumext'); |
03d820c7 | 269 | |
ad944e78 | 270 | /** |
03b31ea3 | 271 | * PARAM_MULTILANG - deprecated alias of PARAM_TEXT. |
ad944e78 | 272 | */ |
03b31ea3 | 273 | define('PARAM_MULTILANG', 'text'); |
03d820c7 | 274 | |
ccc77f91 RT |
275 | /** |
276 | * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or | |
4a9e5fbe | 277 | * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem |
ccc77f91 RT |
278 | * America/Port-au-Prince) |
279 | */ | |
280 | define('PARAM_TIMEZONE', 'timezone'); | |
281 | ||
faf75fe7 | 282 | /** |
03b31ea3 | 283 | * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too |
faf75fe7 | 284 | */ |
03b31ea3 | 285 | define('PARAM_CLEANFILE', 'file'); |
286 | ||
382b9cea | 287 | /// Web Services /// |
03b31ea3 | 288 | |
382b9cea | 289 | /** |
290 | * VALUE_REQUIRED - if the parameter is not supplied, there is an error | |
291 | */ | |
292 | define('VALUE_REQUIRED', 1); | |
293 | ||
294 | /** | |
295 | * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value | |
296 | */ | |
297 | define('VALUE_OPTIONAL', 2); | |
298 | ||
299 | /** | |
300 | * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used | |
301 | */ | |
302 | define('VALUE_DEFAULT', 0); | |
03b31ea3 | 303 | |
5a1861ee | 304 | /** |
305 | * NULL_NOT_ALLOWED - the parameter can not be set to null in the database | |
306 | */ | |
307 | define('NULL_NOT_ALLOWED', false); | |
308 | ||
309 | /** | |
310 | * NULL_ALLOWED - the parameter can be set to null in the database | |
311 | */ | |
312 | define('NULL_ALLOWED', true); | |
faf75fe7 | 313 | |
bbd3f2c4 | 314 | /// Page types /// |
315 | /** | |
316 | * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php. | |
8bd3fad3 | 317 | */ |
318 | define('PAGE_COURSE_VIEW', 'course-view'); | |
8bd3fad3 | 319 | |
9bda43e6 | 320 | /** Get remote addr constant */ |
321 | define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1'); | |
322 | /** Get remote addr constant */ | |
323 | define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2'); | |
6e73ae10 | 324 | |
325 | /// Blog access level constant declaration /// | |
feaf5d06 | 326 | define ('BLOG_USER_LEVEL', 1); |
327 | define ('BLOG_GROUP_LEVEL', 2); | |
328 | define ('BLOG_COURSE_LEVEL', 3); | |
329 | define ('BLOG_SITE_LEVEL', 4); | |
330 | define ('BLOG_GLOBAL_LEVEL', 5); | |
331 | ||
6e73ae10 | 332 | |
333 | ///Tag constants/// | |
4eb718d8 | 334 | /** |
a905364a | 335 | * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the |
6e73ae10 | 336 | * length of "varchar(255) / 3 (bytes / utf-8 character) = 85". |
337 | * TODO: this is not correct, varchar(255) are 255 unicode chars ;-) | |
0d0a8bf6 | 338 | * |
339 | * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-) | |
4eb718d8 | 340 | */ |
ae040d4b | 341 | define('TAG_MAX_LENGTH', 50); |
4eb718d8 | 342 | |
6e73ae10 | 343 | /// Password policy constants /// |
6499395e | 344 | define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz'); |
345 | define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'); | |
346 | define ('PASSWORD_DIGITS', '0123456789'); | |
347 | define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$'); | |
348 | ||
6e73ae10 | 349 | /// Feature constants /// |
350 | // Used for plugin_supports() to report features that are, or are not, supported by a module. | |
49f6e5f4 | 351 | |
352 | /** True if module can provide a grade */ | |
61fceb86 | 353 | define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade'); |
42f103be | 354 | /** True if module supports outcomes */ |
355 | define('FEATURE_GRADE_OUTCOMES', 'outcomes'); | |
356 | ||
49f6e5f4 | 357 | /** True if module has code to track whether somebody viewed it */ |
61fceb86 | 358 | define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views'); |
49f6e5f4 | 359 | /** True if module has custom completion rules */ |
61fceb86 | 360 | define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules'); |
49f6e5f4 | 361 | |
0d8b6a69 | 362 | /** True if module has no 'view' page (like label) */ |
363 | define('FEATURE_NO_VIEW_LINK', 'viewlink'); | |
42f103be | 364 | /** True if module supports outcomes */ |
365 | define('FEATURE_IDNUMBER', 'idnumber'); | |
366 | /** True if module supports groups */ | |
367 | define('FEATURE_GROUPS', 'groups'); | |
368 | /** True if module supports groupings */ | |
369 | define('FEATURE_GROUPINGS', 'groupings'); | |
370 | /** True if module supports groupmembersonly */ | |
371 | define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly'); | |
372 | ||
aa54ed7b | 373 | /** Type of module */ |
374 | define('FEATURE_MOD_ARCHETYPE', 'mod_archetype'); | |
42f103be | 375 | /** True if module supports intro editor */ |
dc5c2bd9 | 376 | define('FEATURE_MOD_INTRO', 'mod_intro'); |
42f103be | 377 | /** True if module has default completion */ |
378 | define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion'); | |
49f6e5f4 | 379 | |
1bcb7eb5 | 380 | define('FEATURE_COMMENT', 'comment'); |
381 | ||
6c5fcef7 | 382 | define('FEATURE_RATE', 'rate'); |
4bfdcfcf EL |
383 | /** True if module supports backup/restore of moodle2 format */ |
384 | define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2'); | |
a09aeee4 | 385 | |
aa54ed7b | 386 | /** Unspecified module archetype */ |
387 | define('MOD_ARCHETYPE_OTHER', 0); | |
388 | /** Resource-like type module */ | |
389 | define('MOD_ARCHETYPE_RESOURCE', 1); | |
efb8c375 | 390 | /** Assignment module archetype */ |
aa54ed7b | 391 | define('MOD_ARCHETYPE_ASSIGNMENT', 2); |
392 | ||
eec99048 | 393 | /** |
394 | * Security token used for allowing access | |
395 | * from external application such as web services. | |
396 | * Scripts do not use any session, performance is relatively | |
397 | * low because we need to load access info in each request. | |
efb8c375 | 398 | * Scripts are executed in parallel. |
eec99048 | 399 | */ |
400 | define('EXTERNAL_TOKEN_PERMANENT', 0); | |
401 | ||
402 | /** | |
403 | * Security token used for allowing access | |
404 | * of embedded applications, the code is executed in the | |
405 | * active user session. Token is invalidated after user logs out. | |
406 | * Scripts are executed serially - normal session locking is used. | |
407 | */ | |
408 | define('EXTERNAL_TOKEN_EMBEDDED', 1); | |
49f6e5f4 | 409 | |
4766a50c SH |
410 | /** |
411 | * The home page should be the site home | |
412 | */ | |
413 | define('HOMEPAGE_SITE', 0); | |
414 | /** | |
415 | * The home page should be the users my page | |
416 | */ | |
417 | define('HOMEPAGE_MY', 1); | |
418 | /** | |
419 | * The home page can be chosen by the user | |
420 | */ | |
421 | define('HOMEPAGE_USER', 2); | |
fcce139a | 422 | |
94788de2 | 423 | /** |
424 | * Hub directory url (should be moodle.org) | |
425 | */ | |
426 | define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org"); | |
427 | ||
428 | ||
429 | /** | |
430 | * Moodle.org url (should be moodle.org) | |
431 | */ | |
432 | define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org"); | |
433 | ||
c1b65883 JM |
434 | /** |
435 | * Moodle mobile app service name | |
436 | */ | |
437 | define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app'); | |
94788de2 | 438 | |
9fa49e22 | 439 | /// PARAMETER HANDLING //////////////////////////////////////////////////// |
6b174680 | 440 | |
e0d346ff | 441 | /** |
361855e6 | 442 | * Returns a particular value for the named variable, taken from |
443 | * POST or GET. If the parameter doesn't exist then an error is | |
e0d346ff | 444 | * thrown because we require this variable. |
445 | * | |
361855e6 | 446 | * This function should be used to initialise all required values |
447 | * in a script that are based on parameters. Usually it will be | |
e0d346ff | 448 | * used like this: |
622365d2 | 449 | * $id = required_param('id', PARAM_INT); |
e0d346ff | 450 | * |
2ca3bffa | 451 | * Please note the $type parameter is now required and the value can not be array. |
44913c8d PS |
452 | * |
453 | * @param string $parname the name of the page parameter we want | |
454 | * @param string $type expected type of parameter | |
e0d346ff | 455 | * @return mixed |
456 | */ | |
44913c8d | 457 | function required_param($parname, $type) { |
2ca3bffa PS |
458 | if (func_num_args() != 2 or empty($parname) or empty($type)) { |
459 | throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')'); | |
44913c8d | 460 | } |
a083b93c | 461 | if (isset($_POST[$parname])) { // POST has precedence |
462 | $param = $_POST[$parname]; | |
463 | } else if (isset($_GET[$parname])) { | |
464 | $param = $_GET[$parname]; | |
e0d346ff | 465 | } else { |
2f137aa1 | 466 | print_error('missingparam', '', '', $parname); |
e0d346ff | 467 | } |
468 | ||
2ca3bffa PS |
469 | if (is_array($param)) { |
470 | debugging('Invalid array parameter detected in required_param(): '.$parname); | |
471 | // TODO: switch to fatal error in Moodle 2.3 | |
472 | //print_error('missingparam', '', '', $parname); | |
473 | return required_param_array($parname, $type); | |
474 | } | |
475 | ||
ebdeccca | 476 | return clean_param($param, $type); |
2ca3bffa PS |
477 | } |
478 | ||
479 | /** | |
480 | * Returns a particular array value for the named variable, taken from | |
481 | * POST or GET. If the parameter doesn't exist then an error is | |
482 | * thrown because we require this variable. | |
483 | * | |
484 | * This function should be used to initialise all required values | |
485 | * in a script that are based on parameters. Usually it will be | |
486 | * used like this: | |
487 | * $ids = required_param_array('ids', PARAM_INT); | |
488 | * | |
489 | * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported | |
490 | * | |
491 | * @param string $parname the name of the page parameter we want | |
492 | * @param string $type expected type of parameter | |
493 | * @return array | |
494 | */ | |
495 | function required_param_array($parname, $type) { | |
496 | if (func_num_args() != 2 or empty($parname) or empty($type)) { | |
497 | throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')'); | |
498 | } | |
499 | if (isset($_POST[$parname])) { // POST has precedence | |
500 | $param = $_POST[$parname]; | |
501 | } else if (isset($_GET[$parname])) { | |
502 | $param = $_GET[$parname]; | |
503 | } else { | |
504 | print_error('missingparam', '', '', $parname); | |
505 | } | |
506 | if (!is_array($param)) { | |
507 | print_error('missingparam', '', '', $parname); | |
508 | } | |
509 | ||
510 | $result = array(); | |
511 | foreach($param as $key=>$value) { | |
512 | if (!preg_match('/^[a-z0-9_-]+$/i', $key)) { | |
513 | debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname); | |
514 | continue; | |
515 | } | |
ebdeccca | 516 | $result[$key] = clean_param($value, $type); |
2ca3bffa PS |
517 | } |
518 | ||
519 | return $result; | |
e0d346ff | 520 | } |
521 | ||
522 | /** | |
361855e6 | 523 | * Returns a particular value for the named variable, taken from |
e0d346ff | 524 | * POST or GET, otherwise returning a given default. |
525 | * | |
361855e6 | 526 | * This function should be used to initialise all optional values |
527 | * in a script that are based on parameters. Usually it will be | |
e0d346ff | 528 | * used like this: |
622365d2 | 529 | * $name = optional_param('name', 'Fred', PARAM_TEXT); |
e0d346ff | 530 | * |
2ca3bffa | 531 | * Please note the $type parameter is now required and the value can not be array. |
44913c8d | 532 | * |
a083b93c | 533 | * @param string $parname the name of the page parameter we want |
e0d346ff | 534 | * @param mixed $default the default value to return if nothing is found |
44913c8d | 535 | * @param string $type expected type of parameter |
e0d346ff | 536 | * @return mixed |
537 | */ | |
44913c8d | 538 | function optional_param($parname, $default, $type) { |
2ca3bffa PS |
539 | if (func_num_args() != 3 or empty($parname) or empty($type)) { |
540 | throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')'); | |
44913c8d PS |
541 | } |
542 | if (!isset($default)) { | |
543 | $default = null; | |
544 | } | |
545 | ||
a083b93c | 546 | if (isset($_POST[$parname])) { // POST has precedence |
547 | $param = $_POST[$parname]; | |
548 | } else if (isset($_GET[$parname])) { | |
549 | $param = $_GET[$parname]; | |
e0d346ff | 550 | } else { |
551 | return $default; | |
552 | } | |
c7f4e3e2 | 553 | |
2ca3bffa PS |
554 | if (is_array($param)) { |
555 | debugging('Invalid array parameter detected in required_param(): '.$parname); | |
556 | // TODO: switch to $default in Moodle 2.3 | |
557 | //return $default; | |
558 | return optional_param_array($parname, $default, $type); | |
559 | } | |
560 | ||
ebdeccca | 561 | return clean_param($param, $type); |
2ca3bffa PS |
562 | } |
563 | ||
564 | /** | |
565 | * Returns a particular array value for the named variable, taken from | |
566 | * POST or GET, otherwise returning a given default. | |
567 | * | |
568 | * This function should be used to initialise all optional values | |
569 | * in a script that are based on parameters. Usually it will be | |
570 | * used like this: | |
571 | * $ids = optional_param('id', array(), PARAM_INT); | |
572 | * | |
573 | * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported | |
574 | * | |
575 | * @param string $parname the name of the page parameter we want | |
576 | * @param mixed $default the default value to return if nothing is found | |
577 | * @param string $type expected type of parameter | |
578 | * @return array | |
579 | */ | |
580 | function optional_param_array($parname, $default, $type) { | |
581 | if (func_num_args() != 3 or empty($parname) or empty($type)) { | |
582 | throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')'); | |
583 | } | |
584 | ||
585 | if (isset($_POST[$parname])) { // POST has precedence | |
586 | $param = $_POST[$parname]; | |
587 | } else if (isset($_GET[$parname])) { | |
588 | $param = $_GET[$parname]; | |
589 | } else { | |
590 | return $default; | |
591 | } | |
592 | if (!is_array($param)) { | |
593 | debugging('optional_param_array() expects array parameters only: '.$parname); | |
594 | return $default; | |
595 | } | |
596 | ||
597 | $result = array(); | |
598 | foreach($param as $key=>$value) { | |
599 | if (!preg_match('/^[a-z0-9_-]+$/i', $key)) { | |
600 | debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname); | |
601 | continue; | |
602 | } | |
ebdeccca | 603 | $result[$key] = clean_param($value, $type); |
2ca3bffa PS |
604 | } |
605 | ||
606 | return $result; | |
e0d346ff | 607 | } |
608 | ||
a3f7cbf6 | 609 | /** |
610 | * Strict validation of parameter values, the values are only converted | |
611 | * to requested PHP type. Internally it is using clean_param, the values | |
612 | * before and after cleaning must be equal - otherwise | |
613 | * an invalid_parameter_exception is thrown. | |
efb8c375 | 614 | * Objects and classes are not accepted. |
a3f7cbf6 | 615 | * |
616 | * @param mixed $param | |
2ca3bffa | 617 | * @param string $type PARAM_ constant |
a3f7cbf6 | 618 | * @param bool $allownull are nulls valid value? |
619 | * @param string $debuginfo optional debug information | |
620 | * @return mixed the $param value converted to PHP type or invalid_parameter_exception | |
621 | */ | |
5a1861ee | 622 | function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') { |
a3f7cbf6 | 623 | if (is_null($param)) { |
5a1861ee | 624 | if ($allownull == NULL_ALLOWED) { |
a3f7cbf6 | 625 | return null; |
626 | } else { | |
627 | throw new invalid_parameter_exception($debuginfo); | |
628 | } | |
629 | } | |
630 | if (is_array($param) or is_object($param)) { | |
631 | throw new invalid_parameter_exception($debuginfo); | |
632 | } | |
633 | ||
ebdeccca | 634 | $cleaned = clean_param($param, $type); |
a3f7cbf6 | 635 | if ((string)$param !== (string)$cleaned) { |
636 | // conversion to string is usually lossless | |
637 | throw new invalid_parameter_exception($debuginfo); | |
638 | } | |
639 | ||
640 | return $cleaned; | |
641 | } | |
642 | ||
2ca3bffa PS |
643 | /** |
644 | * Makes sure array contains only the allowed types, | |
645 | * this function does not validate array key names! | |
646 | * <code> | |
647 | * $options = clean_param($options, PARAM_INT); | |
648 | * </code> | |
649 | * | |
650 | * @param array $param the variable array we are cleaning | |
651 | * @param string $type expected format of param after cleaning. | |
652 | * @param bool $recursive clean recursive arrays | |
653 | * @return array | |
654 | */ | |
655 | function clean_param_array(array $param = null, $type, $recursive = false) { | |
656 | $param = (array)$param; // convert null to empty array | |
657 | foreach ($param as $key => $value) { | |
658 | if (is_array($value)) { | |
659 | if ($recursive) { | |
660 | $param[$key] = clean_param_array($value, $type, true); | |
661 | } else { | |
662 | throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.'); | |
663 | } | |
664 | } else { | |
665 | $param[$key] = clean_param($value, $type); | |
666 | } | |
667 | } | |
668 | return $param; | |
669 | } | |
670 | ||
e0d346ff | 671 | /** |
361855e6 | 672 | * Used by {@link optional_param()} and {@link required_param()} to |
673 | * clean the variables and/or cast to specific types, based on | |
e0d346ff | 674 | * an options field. |
bbd3f2c4 | 675 | * <code> |
676 | * $course->format = clean_param($course->format, PARAM_ALPHA); | |
9f75f77d | 677 | * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT); |
bbd3f2c4 | 678 | * </code> |
e0d346ff | 679 | * |
680 | * @param mixed $param the variable we are cleaning | |
2ca3bffa | 681 | * @param string $type expected format of param after cleaning. |
e0d346ff | 682 | * @return mixed |
683 | */ | |
a083b93c | 684 | function clean_param($param, $type) { |
e0d346ff | 685 | |
7744ea12 | 686 | global $CFG; |
c7f4e3e2 | 687 | |
2ca3bffa PS |
688 | if (is_object($param) or is_array($param)) { |
689 | throw new coding_exception('clean_param() can not process objects or arrays, please use clean_param_array() instead.'); | |
80bfd470 | 690 | } |
691 | ||
a083b93c | 692 | switch ($type) { |
96e98ea6 | 693 | case PARAM_RAW: // no cleaning at all |
78fcdb5f | 694 | $param = fix_utf8($param); |
96e98ea6 | 695 | return $param; |
696 | ||
652599ec | 697 | case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace. |
78fcdb5f | 698 | $param = fix_utf8($param); |
652599ec TH |
699 | return trim($param); |
700 | ||
a083b93c | 701 | case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible |
9f75f77d | 702 | // this is deprecated!, please use more specific type instead |
a083b93c | 703 | if (is_numeric($param)) { |
704 | return $param; | |
705 | } | |
78fcdb5f | 706 | $param = fix_utf8($param); |
294ce987 | 707 | return clean_text($param); // Sweep for scripts, etc |
3af57507 | 708 | |
86f6eec3 | 709 | case PARAM_CLEANHTML: // clean html fragment |
78fcdb5f | 710 | $param = fix_utf8($param); |
86f6eec3 | 711 | $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc |
a083b93c | 712 | return trim($param); |
e0d346ff | 713 | |
a083b93c | 714 | case PARAM_INT: |
715 | return (int)$param; // Convert to integer | |
e0d346ff | 716 | |
6e73ae10 | 717 | case PARAM_FLOAT: |
9dae915a | 718 | case PARAM_NUMBER: |
6e73ae10 | 719 | return (float)$param; // Convert to float |
9dae915a | 720 | |
a083b93c | 721 | case PARAM_ALPHA: // Remove everything not a-z |
6dbcacee | 722 | return preg_replace('/[^a-zA-Z]/i', '', $param); |
e0d346ff | 723 | |
6e73ae10 | 724 | case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too) |
6dbcacee | 725 | return preg_replace('/[^a-zA-Z_-]/i', '', $param); |
6e73ae10 | 726 | |
a083b93c | 727 | case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9 |
6dbcacee | 728 | return preg_replace('/[^A-Za-z0-9]/i', '', $param); |
f24148ef | 729 | |
6e73ae10 | 730 | case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_- |
6dbcacee | 731 | return preg_replace('/[^A-Za-z0-9_-]/i', '', $param); |
0ed442f8 | 732 | |
0e4af166 | 733 | case PARAM_SEQUENCE: // Remove everything not 0-9, |
6dbcacee | 734 | return preg_replace('/[^0-9,]/i', '', $param); |
0e4af166 | 735 | |
a083b93c | 736 | case PARAM_BOOL: // Convert to 1 or 0 |
737 | $tempstr = strtolower($param); | |
6e73ae10 | 738 | if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') { |
a083b93c | 739 | $param = 1; |
6e73ae10 | 740 | } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') { |
a083b93c | 741 | $param = 0; |
742 | } else { | |
743 | $param = empty($param) ? 0 : 1; | |
744 | } | |
745 | return $param; | |
f24148ef | 746 | |
a083b93c | 747 | case PARAM_NOTAGS: // Strip all tags |
78fcdb5f | 748 | $param = fix_utf8($param); |
a083b93c | 749 | return strip_tags($param); |
3af57507 | 750 | |
c4ea5e78 | 751 | case PARAM_TEXT: // leave only tags needed for multilang |
78fcdb5f | 752 | $param = fix_utf8($param); |
b6059edc PS |
753 | // if the multilang syntax is not correct we strip all tags |
754 | // because it would break xhtml strict which is required for accessibility standards | |
755 | // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons | |
756 | do { | |
757 | if (strpos($param, '</lang>') !== false) { | |
758 | // old and future mutilang syntax | |
759 | $param = strip_tags($param, '<lang>'); | |
760 | if (!preg_match_all('/<.*>/suU', $param, $matches)) { | |
761 | break; | |
762 | } | |
763 | $open = false; | |
764 | foreach ($matches[0] as $match) { | |
765 | if ($match === '</lang>') { | |
766 | if ($open) { | |
767 | $open = false; | |
768 | continue; | |
769 | } else { | |
770 | break 2; | |
771 | } | |
772 | } | |
773 | if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) { | |
774 | break 2; | |
775 | } else { | |
776 | $open = true; | |
777 | } | |
778 | } | |
779 | if ($open) { | |
780 | break; | |
781 | } | |
782 | return $param; | |
783 | ||
784 | } else if (strpos($param, '</span>') !== false) { | |
785 | // current problematic multilang syntax | |
786 | $param = strip_tags($param, '<span>'); | |
787 | if (!preg_match_all('/<.*>/suU', $param, $matches)) { | |
788 | break; | |
789 | } | |
790 | $open = false; | |
791 | foreach ($matches[0] as $match) { | |
792 | if ($match === '</span>') { | |
793 | if ($open) { | |
794 | $open = false; | |
795 | continue; | |
796 | } else { | |
797 | break 2; | |
798 | } | |
799 | } | |
800 | if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) { | |
801 | break 2; | |
802 | } else { | |
803 | $open = true; | |
804 | } | |
805 | } | |
806 | if ($open) { | |
807 | break; | |
808 | } | |
809 | return $param; | |
810 | } | |
811 | } while (false); | |
812 | // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string() | |
813 | return strip_tags($param); | |
31f26796 | 814 | |
a083b93c | 815 | case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_- |
6dbcacee | 816 | return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param); |
95bfd207 | 817 | |
6e73ae10 | 818 | case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_- |
6759ad2f | 819 | return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param); |
6e73ae10 | 820 | |
a083b93c | 821 | case PARAM_FILE: // Strip all suspicious characters from filename |
78fcdb5f | 822 | $param = fix_utf8($param); |
14f3ad15 | 823 | $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param); |
6dbcacee | 824 | $param = preg_replace('~\.\.+~', '', $param); |
6e73ae10 | 825 | if ($param === '.') { |
371a2ed0 | 826 | $param = ''; |
827 | } | |
a083b93c | 828 | return $param; |
829 | ||
830 | case PARAM_PATH: // Strip all suspicious characters from file path | |
78fcdb5f | 831 | $param = fix_utf8($param); |
a083b93c | 832 | $param = str_replace('\\', '/', $param); |
4d51214a | 833 | $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param); |
6dbcacee | 834 | $param = preg_replace('~\.\.+~', '', $param); |
835 | $param = preg_replace('~//+~', '/', $param); | |
836 | return preg_replace('~/(\./)+~', '/', $param); | |
a083b93c | 837 | |
838 | case PARAM_HOST: // allow FQDN or IPv4 dotted quad | |
3e475991 | 839 | $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars |
a083b93c | 840 | // match ipv4 dotted quad |
841 | if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){ | |
842 | // confirm values are ok | |
843 | if ( $match[0] > 255 | |
844 | || $match[1] > 255 | |
845 | || $match[3] > 255 | |
846 | || $match[4] > 255 ) { | |
847 | // hmmm, what kind of dotted quad is this? | |
848 | $param = ''; | |
849 | } | |
850 | } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers | |
851 | && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens | |
852 | && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens | |
853 | ) { | |
854 | // all is ok - $param is respected | |
855 | } else { | |
856 | // all is not ok... | |
857 | $param=''; | |
858 | } | |
859 | return $param; | |
7744ea12 | 860 | |
a083b93c | 861 | case PARAM_URL: // allow safe ftp, http, mailto urls |
78fcdb5f | 862 | $param = fix_utf8($param); |
a083b93c | 863 | include_once($CFG->dirroot . '/lib/validateurlsyntax.php'); |
5301205a | 864 | if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) { |
a083b93c | 865 | // all is ok, param is respected |
d2a9f7cc | 866 | } else { |
a083b93c | 867 | $param =''; // not really ok |
868 | } | |
869 | return $param; | |
870 | ||
871 | case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot | |
93684765 | 872 | $param = clean_param($param, PARAM_URL); |
a083b93c | 873 | if (!empty($param)) { |
874 | if (preg_match(':^/:', $param)) { | |
875 | // root-relative, ok! | |
876 | } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) { | |
877 | // absolute, and matches our wwwroot | |
7744ea12 | 878 | } else { |
a083b93c | 879 | // relative - let's make sure there are no tricks |
4bea5e85 | 880 | if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) { |
a083b93c | 881 | // looks ok. |
882 | } else { | |
883 | $param = ''; | |
884 | } | |
d2a9f7cc | 885 | } |
7744ea12 | 886 | } |
a083b93c | 887 | return $param; |
bcef0319 | 888 | |
03d820c7 | 889 | case PARAM_PEM: |
890 | $param = trim($param); | |
891 | // PEM formatted strings may contain letters/numbers and the symbols | |
892 | // forward slash: / | |
893 | // plus sign: + | |
894 | // equal sign: = | |
895 | // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes | |
896 | if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) { | |
897 | list($wholething, $body) = $matches; | |
898 | unset($wholething, $matches); | |
899 | $b64 = clean_param($body, PARAM_BASE64); | |
900 | if (!empty($b64)) { | |
901 | return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n"; | |
902 | } else { | |
903 | return ''; | |
904 | } | |
905 | } | |
906 | return ''; | |
bcef0319 | 907 | |
03d820c7 | 908 | case PARAM_BASE64: |
909 | if (!empty($param)) { | |
910 | // PEM formatted strings may contain letters/numbers and the symbols | |
911 | // forward slash: / | |
912 | // plus sign: + | |
913 | // equal sign: = | |
03d820c7 | 914 | if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) { |
915 | return ''; | |
916 | } | |
917 | $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY); | |
918 | // Each line of base64 encoded data must be 64 characters in | |
919 | // length, except for the last line which may be less than (or | |
920 | // equal to) 64 characters long. | |
921 | for ($i=0, $j=count($lines); $i < $j; $i++) { | |
922 | if ($i + 1 == $j) { | |
923 | if (64 < strlen($lines[$i])) { | |
924 | return ''; | |
925 | } | |
926 | continue; | |
927 | } | |
7744ea12 | 928 | |
03d820c7 | 929 | if (64 != strlen($lines[$i])) { |
930 | return ''; | |
931 | } | |
932 | } | |
933 | return implode("\n",$lines); | |
934 | } else { | |
935 | return ''; | |
936 | } | |
bcef0319 | 937 | |
938 | case PARAM_TAG: | |
78fcdb5f | 939 | $param = fix_utf8($param); |
34b93e39 PS |
940 | // Please note it is not safe to use the tag name directly anywhere, |
941 | // it must be processed with s(), urlencode() before embedding anywhere. | |
942 | // remove some nasties | |
6b24e35e | 943 | $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param); |
3d535996 | 944 | //convert many whitespace chars into one |
bcef0319 | 945 | $param = preg_replace('/\s+/', ' ', $param); |
8e1ec6be | 946 | $textlib = textlib_get_instance(); |
3d535996 | 947 | $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH); |
c93c6b3b | 948 | return $param; |
bcef0319 | 949 | |
ae040d4b | 950 | case PARAM_TAGLIST: |
78fcdb5f | 951 | $param = fix_utf8($param); |
ae040d4b | 952 | $tags = explode(',', $param); |
953 | $result = array(); | |
954 | foreach ($tags as $tag) { | |
955 | $res = clean_param($tag, PARAM_TAG); | |
6e73ae10 | 956 | if ($res !== '') { |
ae040d4b | 957 | $result[] = $res; |
958 | } | |
959 | } | |
960 | if ($result) { | |
961 | return implode(',', $result); | |
962 | } else { | |
963 | return ''; | |
0d626493 | 964 | } |
965 | ||
ad944e78 | 966 | case PARAM_CAPABILITY: |
4f0c2d00 | 967 | if (get_capability_info($param)) { |
ad944e78 | 968 | return $param; |
969 | } else { | |
970 | return ''; | |
971 | } | |
972 | ||
faf75fe7 | 973 | case PARAM_PERMISSION: |
974 | $param = (int)$param; | |
975 | if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) { | |
976 | return $param; | |
977 | } else { | |
978 | return CAP_INHERIT; | |
979 | } | |
980 | ||
03b31ea3 | 981 | case PARAM_AUTH: |
982 | $param = clean_param($param, PARAM_SAFEDIR); | |
983 | if (exists_auth_plugin($param)) { | |
984 | return $param; | |
985 | } else { | |
986 | return ''; | |
987 | } | |
988 | ||
989 | case PARAM_LANG: | |
990 | $param = clean_param($param, PARAM_SAFEDIR); | |
ef686eb5 | 991 | if (get_string_manager()->translation_exists($param)) { |
03b31ea3 | 992 | return $param; |
993 | } else { | |
ef686eb5 | 994 | return ''; // Specified language is not installed or param malformed |
03b31ea3 | 995 | } |
996 | ||
997 | case PARAM_THEME: | |
998 | $param = clean_param($param, PARAM_SAFEDIR); | |
73e504bc PS |
999 | if (file_exists("$CFG->dirroot/theme/$param/config.php")) { |
1000 | return $param; | |
1001 | } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) { | |
03b31ea3 | 1002 | return $param; |
1003 | } else { | |
1004 | return ''; // Specified theme is not installed | |
1005 | } | |
1006 | ||
07ed083e | 1007 | case PARAM_USERNAME: |
78fcdb5f | 1008 | $param = fix_utf8($param); |
07ed083e | 1009 | $param = str_replace(" " , "", $param); |
34d2b19a RW |
1010 | $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919 |
1011 | if (empty($CFG->extendedusernamechars)) { | |
07ed083e RW |
1012 | // regular expression, eliminate all chars EXCEPT: |
1013 | // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters. | |
1014 | $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param); | |
4f0c2d00 | 1015 | } |
07ed083e RW |
1016 | return $param; |
1017 | ||
79f1d953 | 1018 | case PARAM_EMAIL: |
78fcdb5f | 1019 | $param = fix_utf8($param); |
79f1d953 | 1020 | if (validate_email($param)) { |
1021 | return $param; | |
1022 | } else { | |
1023 | return ''; | |
1024 | } | |
1025 | ||
fe6a248f DM |
1026 | case PARAM_STRINGID: |
1027 | if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) { | |
1028 | return $param; | |
1029 | } else { | |
1030 | return ''; | |
1031 | } | |
1032 | ||
ccc77f91 | 1033 | case PARAM_TIMEZONE: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_' |
78fcdb5f | 1034 | $param = fix_utf8($param); |
ccc77f91 RT |
1035 | $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/'; |
1036 | if (preg_match($timezonepattern, $param)) { | |
1037 | return $param; | |
1038 | } else { | |
1039 | return ''; | |
1040 | } | |
1041 | ||
a083b93c | 1042 | default: // throw error, switched parameters in optional_param or another serious problem |
03b31ea3 | 1043 | print_error("unknownparamtype", '', '', $type); |
2ae28153 | 1044 | } |
e0d346ff | 1045 | } |
1046 | ||
78fcdb5f PS |
1047 | /** |
1048 | * Makes sure the data is using valid utf8, invalid characters are discarded. | |
1049 | * | |
1050 | * Note: this function is not intended for full objects with methods and private properties. | |
1051 | * | |
1052 | * @param mixed $value | |
1053 | * @return mixed with proper utf-8 encoding | |
1054 | */ | |
1055 | function fix_utf8($value) { | |
1056 | if (is_null($value) or $value === '') { | |
1057 | return $value; | |
1058 | ||
1059 | } else if (is_string($value)) { | |
1060 | if ((string)(int)$value === $value) { | |
1061 | // shortcut | |
1062 | return $value; | |
1063 | } | |
1064 | return iconv('UTF-8', 'UTF-8//IGNORE', $value); | |
1065 | ||
1066 | } else if (is_array($value)) { | |
1067 | foreach ($value as $k=>$v) { | |
1068 | $value[$k] = fix_utf8($v); | |
1069 | } | |
1070 | return $value; | |
1071 | ||
1072 | } else if (is_object($value)) { | |
1073 | $value = clone($value); // do not modify original | |
1074 | foreach ($value as $k=>$v) { | |
1075 | $value->$k = fix_utf8($v); | |
1076 | } | |
1077 | return $value; | |
1078 | ||
1079 | } else { | |
1080 | // this is some other type, no utf-8 here | |
1081 | return $value; | |
1082 | } | |
1083 | } | |
1084 | ||
6e73ae10 | 1085 | /** |
1086 | * Return true if given value is integer or string with integer value | |
0d0a8bf6 | 1087 | * |
1088 | * @param mixed $value String or Int | |
1089 | * @return bool true if number, false if not | |
6e73ae10 | 1090 | */ |
1091 | function is_number($value) { | |
1092 | if (is_int($value)) { | |
1093 | return true; | |
1094 | } else if (is_string($value)) { | |
1095 | return ((string)(int)$value) === $value; | |
1096 | } else { | |
1097 | return false; | |
1098 | } | |
1099 | } | |
7a530277 | 1100 | |
aa282b10 | 1101 | /** |
1102 | * Returns host part from url | |
1103 | * @param string $url full url | |
1104 | * @return string host, null if not found | |
1105 | */ | |
1106 | function get_host_from_url($url) { | |
1107 | preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches); | |
1108 | if ($matches) { | |
1109 | return $matches[1]; | |
1110 | } | |
1111 | return null; | |
1112 | } | |
1113 | ||
94a6d656 | 1114 | /** |
0d0a8bf6 | 1115 | * Tests whether anything was returned by text editor |
1116 | * | |
94a6d656 | 1117 | * This function is useful for testing whether something you got back from |
1118 | * the HTML editor actually contains anything. Sometimes the HTML editor | |
1119 | * appear to be empty, but actually you get back a <br> tag or something. | |
1120 | * | |
1121 | * @param string $string a string containing HTML. | |
1122 | * @return boolean does the string contain any actual content - that is text, | |
efb8c375 | 1123 | * images, objects, etc. |
94a6d656 | 1124 | */ |
1125 | function html_is_blank($string) { | |
1126 | return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == ''; | |
1127 | } | |
1128 | ||
7cf1c7bd | 1129 | /** |
1130 | * Set a key in global configuration | |
1131 | * | |
89dcb99d | 1132 | * Set a key/value pair in both this session's {@link $CFG} global variable |
7cf1c7bd | 1133 | * and in the 'config' database table for future sessions. |
e1ecf0a0 | 1134 | * |
1135 | * Can also be used to update keys for plugin-scoped configs in config_plugin table. | |
1136 | * In that case it doesn't affect $CFG. | |
7cf1c7bd | 1137 | * |
6fd511eb | 1138 | * A NULL value will delete the entry. |
1139 | * | |
0d0a8bf6 | 1140 | * @global object |
1141 | * @global object | |
7cf1c7bd | 1142 | * @param string $name the key to set |
9cdb766d | 1143 | * @param string $value the value to set (without magic quotes) |
0d0a8bf6 | 1144 | * @param string $plugin (optional) the plugin scope, default NULL |
5e2f308b | 1145 | * @return bool true or exception |
7cf1c7bd | 1146 | */ |
a4080313 | 1147 | function set_config($name, $value, $plugin=NULL) { |
ae040d4b | 1148 | global $CFG, $DB; |
42282810 | 1149 | |
a4080313 | 1150 | if (empty($plugin)) { |
220a90c5 | 1151 | if (!array_key_exists($name, $CFG->config_php_settings)) { |
1152 | // So it's defined for this invocation at least | |
1153 | if (is_null($value)) { | |
1154 | unset($CFG->$name); | |
1155 | } else { | |
9c305ba1 | 1156 | $CFG->$name = (string)$value; // settings from db are always strings |
220a90c5 | 1157 | } |
1158 | } | |
e1ecf0a0 | 1159 | |
ae040d4b | 1160 | if ($DB->get_field('config', 'name', array('name'=>$name))) { |
5e2f308b | 1161 | if ($value === null) { |
1162 | $DB->delete_records('config', array('name'=>$name)); | |
6fd511eb | 1163 | } else { |
5e2f308b | 1164 | $DB->set_field('config', 'value', $value, array('name'=>$name)); |
6fd511eb | 1165 | } |
a4080313 | 1166 | } else { |
5e2f308b | 1167 | if ($value !== null) { |
365a5941 | 1168 | $config = new stdClass(); |
5e2f308b | 1169 | $config->name = $name; |
1170 | $config->value = $value; | |
1171 | $DB->insert_record('config', $config, false); | |
6fd511eb | 1172 | } |
a4080313 | 1173 | } |
ae040d4b | 1174 | |
a4080313 | 1175 | } else { // plugin scope |
ae040d4b | 1176 | if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) { |
6fd511eb | 1177 | if ($value===null) { |
5e2f308b | 1178 | $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin)); |
6fd511eb | 1179 | } else { |
5e2f308b | 1180 | $DB->set_field('config_plugins', 'value', $value, array('id'=>$id)); |
6fd511eb | 1181 | } |
a4080313 | 1182 | } else { |
5e2f308b | 1183 | if ($value !== null) { |
365a5941 | 1184 | $config = new stdClass(); |
5e2f308b | 1185 | $config->plugin = $plugin; |
1186 | $config->name = $name; | |
1187 | $config->value = $value; | |
1188 | $DB->insert_record('config_plugins', $config, false); | |
6fd511eb | 1189 | } |
a4080313 | 1190 | } |
1191 | } | |
5e2f308b | 1192 | |
1193 | return true; | |
a4080313 | 1194 | } |
1195 | ||
1196 | /** | |
e1ecf0a0 | 1197 | * Get configuration values from the global config table |
a4080313 | 1198 | * or the config_plugins table. |
1199 | * | |
13daf6a2 | 1200 | * If called with one parameter, it will load all the config |
12bb0c3e | 1201 | * variables for one plugin, and return them as an object. |
13daf6a2 | 1202 | * |
12bb0c3e PS |
1203 | * If called with 2 parameters it will return a string single |
1204 | * value or false if the value is not found. | |
9220fba5 | 1205 | * |
12bb0c3e | 1206 | * @param string $plugin full component name |
0d0a8bf6 | 1207 | * @param string $name default NULL |
07ab0c80 | 1208 | * @return mixed hash-like object or single value, return false no config found |
a4080313 | 1209 | */ |
12bb0c3e | 1210 | function get_config($plugin, $name = NULL) { |
ae040d4b | 1211 | global $CFG, $DB; |
dfc9ba9b | 1212 | |
12bb0c3e PS |
1213 | // normalise component name |
1214 | if ($plugin === 'moodle' or $plugin === 'core') { | |
1215 | $plugin = NULL; | |
1216 | } | |
1217 | ||
a4080313 | 1218 | if (!empty($name)) { // the user is asking for a specific value |
1219 | if (!empty($plugin)) { | |
12bb0c3e PS |
1220 | if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) { |
1221 | // setting forced in config file | |
1222 | return $CFG->forced_plugin_settings[$plugin][$name]; | |
1223 | } else { | |
1224 | return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name)); | |
1225 | } | |
a4080313 | 1226 | } else { |
12bb0c3e PS |
1227 | if (array_key_exists($name, $CFG->config_php_settings)) { |
1228 | // setting force in config file | |
1229 | return $CFG->config_php_settings[$name]; | |
1230 | } else { | |
1231 | return $DB->get_field('config', 'value', array('name'=>$name)); | |
1232 | } | |
a4080313 | 1233 | } |
1234 | } | |
1235 | ||
1236 | // the user is after a recordset | |
12bb0c3e | 1237 | if ($plugin) { |
13daf6a2 | 1238 | $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value'); |
12bb0c3e PS |
1239 | if (isset($CFG->forced_plugin_settings[$plugin])) { |
1240 | foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) { | |
1241 | if (is_null($v) or is_array($v) or is_object($v)) { | |
1242 | // we do not want any extra mess here, just real settings that could be saved in db | |
1243 | unset($localcfg[$n]); | |
1244 | } else { | |
1245 | //convert to string as if it went through the DB | |
1246 | $localcfg[$n] = (string)$v; | |
a4080313 | 1247 | } |
1248 | } | |
a4080313 | 1249 | } |
bfb82da3 TH |
1250 | if ($localcfg) { |
1251 | return (object)$localcfg; | |
1252 | } else { | |
1253 | return null; | |
1254 | } | |
e1ecf0a0 | 1255 | |
12bb0c3e PS |
1256 | } else { |
1257 | // this part is not really used any more, but anyway... | |
1258 | $localcfg = $DB->get_records_menu('config', array(), '', 'name,value'); | |
1259 | foreach($CFG->config_php_settings as $n=>$v) { | |
1260 | if (is_null($v) or is_array($v) or is_object($v)) { | |
1261 | // we do not want any extra mess here, just real settings that could be saved in db | |
1262 | unset($localcfg[$n]); | |
1263 | } else { | |
1264 | //convert to string as if it went through the DB | |
1265 | $localcfg[$n] = (string)$v; | |
1266 | } | |
1267 | } | |
1268 | return (object)$localcfg; | |
39917a09 | 1269 | } |
39917a09 | 1270 | } |
1271 | ||
b0270f84 | 1272 | /** |
1273 | * Removes a key from global configuration | |
1274 | * | |
1275 | * @param string $name the key to set | |
1276 | * @param string $plugin (optional) the plugin scope | |
0d0a8bf6 | 1277 | * @global object |
4b600aa0 | 1278 | * @return boolean whether the operation succeeded. |
b0270f84 | 1279 | */ |
1280 | function unset_config($name, $plugin=NULL) { | |
ae040d4b | 1281 | global $CFG, $DB; |
b0270f84 | 1282 | |
b0270f84 | 1283 | if (empty($plugin)) { |
4b600aa0 | 1284 | unset($CFG->$name); |
013376de | 1285 | $DB->delete_records('config', array('name'=>$name)); |
5e623a33 | 1286 | } else { |
013376de | 1287 | $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin)); |
b0270f84 | 1288 | } |
013376de | 1289 | |
1290 | return true; | |
b0270f84 | 1291 | } |
1292 | ||
4b600aa0 | 1293 | /** |
1294 | * Remove all the config variables for a given plugin. | |
1295 | * | |
1296 | * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice'; | |
1297 | * @return boolean whether the operation succeeded. | |
1298 | */ | |
1299 | function unset_all_config_for_plugin($plugin) { | |
1300 | global $DB; | |
013376de | 1301 | $DB->delete_records('config_plugins', array('plugin' => $plugin)); |
1302 | $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%')); | |
1303 | return true; | |
4b600aa0 | 1304 | } |
1305 | ||
4413941f | 1306 | /** |
efb8c375 | 1307 | * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability. |
adf176d7 PS |
1308 | * |
1309 | * All users are verified if they still have the necessary capability. | |
1310 | * | |
b3d960e6 | 1311 | * @param string $value the value of the config setting. |
4413941f | 1312 | * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor. |
efb8c375 | 1313 | * @param bool $include admins, include administrators |
4413941f | 1314 | * @return array of user objects. |
1315 | */ | |
adf176d7 PS |
1316 | function get_users_from_config($value, $capability, $includeadmins = true) { |
1317 | global $CFG, $DB; | |
1318 | ||
1319 | if (empty($value) or $value === '$@NONE@$') { | |
1320 | return array(); | |
4413941f | 1321 | } |
adf176d7 PS |
1322 | |
1323 | // we have to make sure that users still have the necessary capability, | |
1324 | // it should be faster to fetch them all first and then test if they are present | |
6b8ad965 | 1325 | // instead of validating them one-by-one |
adf176d7 PS |
1326 | $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability); |
1327 | if ($includeadmins) { | |
1328 | $admins = get_admins(); | |
1329 | foreach ($admins as $admin) { | |
1330 | $users[$admin->id] = $admin; | |
1331 | } | |
1332 | } | |
1333 | ||
1334 | if ($value === '$@ALL@$') { | |
1335 | return $users; | |
1336 | } | |
1337 | ||
1338 | $result = array(); // result in correct order | |
1339 | $allowed = explode(',', $value); | |
1340 | foreach ($allowed as $uid) { | |
1341 | if (isset($users[$uid])) { | |
1342 | $user = $users[$uid]; | |
1343 | $result[$user->id] = $user; | |
1344 | } | |
1345 | } | |
1346 | ||
1347 | return $result; | |
4413941f | 1348 | } |
1349 | ||
f87eab7e PS |
1350 | |
1351 | /** | |
1352 | * Invalidates browser caches and cached data in temp | |
1353 | * @return void | |
1354 | */ | |
1355 | function purge_all_caches() { | |
1356 | global $CFG; | |
1357 | ||
f87eab7e PS |
1358 | reset_text_filters_cache(); |
1359 | js_reset_all_caches(); | |
1360 | theme_reset_all_caches(); | |
1361 | get_string_manager()->reset_caches(); | |
1362 | ||
dc2c9bd7 | 1363 | // purge all other caches: rss, simplepie, etc. |
f87eab7e PS |
1364 | remove_dir($CFG->dataroot.'/cache', true); |
1365 | ||
c426ef3a PS |
1366 | // make sure cache dir is writable, throws exception if not |
1367 | make_upload_directory('cache'); | |
f87eab7e | 1368 | |
b216a820 PS |
1369 | // hack: this script may get called after the purifier was initialised, |
1370 | // but we do not want to verify repeatedly this exists in each call | |
1371 | make_upload_directory('cache/htmlpurifier'); | |
1372 | ||
f87eab7e PS |
1373 | clearstatcache(); |
1374 | } | |
1375 | ||
bafd7e78 | 1376 | /** |
1377 | * Get volatile flags | |
1378 | * | |
1379 | * @param string $type | |
0d0a8bf6 | 1380 | * @param int $changedsince default null |
bafd7e78 | 1381 | * @return records array |
bafd7e78 | 1382 | */ |
1383 | function get_cache_flags($type, $changedsince=NULL) { | |
ae040d4b | 1384 | global $DB; |
bafd7e78 | 1385 | |
ae040d4b | 1386 | $params = array('type'=>$type, 'expiry'=>time()); |
1387 | $sqlwhere = "flagtype = :type AND expiry >= :expiry"; | |
bafd7e78 | 1388 | if ($changedsince !== NULL) { |
ae040d4b | 1389 | $params['changedsince'] = $changedsince; |
1390 | $sqlwhere .= " AND timemodified > :changedsince"; | |
bafd7e78 | 1391 | } |
1392 | $cf = array(); | |
ae040d4b | 1393 | |
1394 | if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) { | |
bafd7e78 | 1395 | foreach ($flags as $flag) { |
1396 | $cf[$flag->name] = $flag->value; | |
1397 | } | |
1398 | } | |
1399 | return $cf; | |
1400 | } | |
1401 | ||
a489cf72 | 1402 | /** |
1403 | * Get volatile flags | |
1404 | * | |
1405 | * @param string $type | |
1406 | * @param string $name | |
0d0a8bf6 | 1407 | * @param int $changedsince default null |
a489cf72 | 1408 | * @return records array |
a489cf72 | 1409 | */ |
1410 | function get_cache_flag($type, $name, $changedsince=NULL) { | |
ae040d4b | 1411 | global $DB; |
a489cf72 | 1412 | |
ae040d4b | 1413 | $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time()); |
a489cf72 | 1414 | |
ae040d4b | 1415 | $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry"; |
a489cf72 | 1416 | if ($changedsince !== NULL) { |
ae040d4b | 1417 | $params['changedsince'] = $changedsince; |
1418 | $sqlwhere .= " AND timemodified > :changedsince"; | |
a489cf72 | 1419 | } |
ae040d4b | 1420 | |
1421 | return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params); | |
a489cf72 | 1422 | } |
bafd7e78 | 1423 | |
1424 | /** | |
1425 | * Set a volatile flag | |
1426 | * | |
1427 | * @param string $type the "type" namespace for the key | |
1428 | * @param string $name the key to set | |
1429 | * @param string $value the value to set (without magic quotes) - NULL will remove the flag | |
1430 | * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs | |
0d0a8bf6 | 1431 | * @return bool Always returns true |
bafd7e78 | 1432 | */ |
1433 | function set_cache_flag($type, $name, $value, $expiry=NULL) { | |
ae040d4b | 1434 | global $DB; |
bafd7e78 | 1435 | |
1436 | $timemodified = time(); | |
1437 | if ($expiry===NULL || $expiry < $timemodified) { | |
1438 | $expiry = $timemodified + 24 * 60 * 60; | |
1439 | } else { | |
1440 | $expiry = (int)$expiry; | |
1441 | } | |
1442 | ||
1443 | if ($value === NULL) { | |
013376de | 1444 | unset_cache_flag($type,$name); |
1445 | return true; | |
bafd7e78 | 1446 | } |
1447 | ||
39461de3 | 1448 | if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER |
128f0984 | 1449 | if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) { |
1450 | return true; //no need to update; helps rcache too | |
1451 | } | |
ae040d4b | 1452 | $f->value = $value; |
bafd7e78 | 1453 | $f->expiry = $expiry; |
1454 | $f->timemodified = $timemodified; | |
013376de | 1455 | $DB->update_record('cache_flags', $f); |
bafd7e78 | 1456 | } else { |
365a5941 | 1457 | $f = new stdClass(); |
bafd7e78 | 1458 | $f->flagtype = $type; |
1459 | $f->name = $name; | |
ae040d4b | 1460 | $f->value = $value; |
bafd7e78 | 1461 | $f->expiry = $expiry; |
1462 | $f->timemodified = $timemodified; | |
013376de | 1463 | $DB->insert_record('cache_flags', $f); |
bafd7e78 | 1464 | } |
013376de | 1465 | return true; |
bafd7e78 | 1466 | } |
1467 | ||
1468 | /** | |
1469 | * Removes a single volatile flag | |
1470 | * | |
0d0a8bf6 | 1471 | * @global object |
bafd7e78 | 1472 | * @param string $type the "type" namespace for the key |
1473 | * @param string $name the key to set | |
bafd7e78 | 1474 | * @return bool |
1475 | */ | |
1476 | function unset_cache_flag($type, $name) { | |
ae040d4b | 1477 | global $DB; |
013376de | 1478 | $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type)); |
1479 | return true; | |
bafd7e78 | 1480 | } |
1481 | ||
1482 | /** | |
1483 | * Garbage-collect volatile flags | |
1484 | * | |
0d0a8bf6 | 1485 | * @return bool Always returns true |
bafd7e78 | 1486 | */ |
1487 | function gc_cache_flags() { | |
ae040d4b | 1488 | global $DB; |
013376de | 1489 | $DB->delete_records_select('cache_flags', 'expiry < ?', array(time())); |
1490 | return true; | |
bafd7e78 | 1491 | } |
a4080313 | 1492 | |
2660377f | 1493 | /// FUNCTIONS FOR HANDLING USER PREFERENCES //////////////////////////////////// |
1494 | ||
7cf1c7bd | 1495 | /** |
39461de3 PS |
1496 | * Refresh user preference cache. This is used most often for $USER |
1497 | * object that is stored in session, but it also helps with performance in cron script. | |
0d0a8bf6 | 1498 | * |
39461de3 PS |
1499 | * Preferences for each user are loaded on first use on every page, then again after the timeout expires. |
1500 | * | |
1501 | * @param stdClass $user user object, preferences are preloaded into ->preference property | |
1502 | * @param int $cachelifetime cache life time on the current page (ins seconds) | |
0d0a8bf6 | 1503 | * @return void |
7cf1c7bd | 1504 | */ |
39461de3 PS |
1505 | function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) { |
1506 | global $DB; | |
1507 | static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes. | |
2660377f | 1508 | |
39461de3 PS |
1509 | if (!isset($user->id)) { |
1510 | throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field'); | |
1511 | } | |
2660377f | 1512 | |
39461de3 PS |
1513 | if (empty($user->id) or isguestuser($user->id)) { |
1514 | // No permanent storage for not-logged-in users and guest | |
1515 | if (!isset($user->preference)) { | |
1516 | $user->preference = array(); | |
2660377f | 1517 | } |
39461de3 | 1518 | return; |
2660377f | 1519 | } |
70812e39 | 1520 | |
39461de3 | 1521 | $timenow = time(); |
070e2616 | 1522 | |
39461de3 PS |
1523 | if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) { |
1524 | // Already loaded at least once on this page. Are we up to date? | |
1525 | if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) { | |
1526 | // no need to reload - we are on the same page and we loaded prefs just a moment ago | |
1527 | return; | |
70812e39 | 1528 | |
39461de3 PS |
1529 | } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) { |
1530 | // no change since the lastcheck on this page | |
1531 | $user->preference['_lastloaded'] = $timenow; | |
1532 | return; | |
70812e39 | 1533 | } |
c6d15803 | 1534 | } |
346c3e2f | 1535 | |
39461de3 PS |
1536 | // OK, so we have to reload all preferences |
1537 | $loadedusers[$user->id] = true; | |
1538 | $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values | |
1539 | $user->preference['_lastloaded'] = $timenow; | |
2660377f | 1540 | } |
1541 | ||
1542 | /** | |
39461de3 PS |
1543 | * Called from set/delete_user_preferences, so that the prefs can |
1544 | * be correctly reloaded in different sessions. | |
1545 | * | |
1546 | * NOTE: internal function, do not call from other code. | |
0d0a8bf6 | 1547 | * |
2660377f | 1548 | * @param integer $userid the user whose prefs were changed. |
39461de3 | 1549 | * @return void |
2660377f | 1550 | */ |
1551 | function mark_user_preferences_changed($userid) { | |
39461de3 PS |
1552 | global $CFG; |
1553 | ||
1554 | if (empty($userid) or isguestuser($userid)) { | |
1555 | // no cache flags for guest and not-logged-in users | |
1556 | return; | |
2660377f | 1557 | } |
39461de3 | 1558 | |
2660377f | 1559 | set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout); |
70812e39 | 1560 | } |
1561 | ||
7cf1c7bd | 1562 | /** |
39461de3 | 1563 | * Sets a preference for the specified user. |
0d0a8bf6 | 1564 | * |
39461de3 | 1565 | * If user object submitted, 'preference' property contains the preferences cache. |
0d0a8bf6 | 1566 | * |
7cf1c7bd | 1567 | * @param string $name The key to set as preference for the specified user |
39461de3 PS |
1568 | * @param string $value The value to set for the $name key in the specified user's record, |
1569 | * null means delete current value | |
1570 | * @param stdClass|int $user A moodle user object or id, null means current user | |
1571 | * @return bool always true or exception | |
7cf1c7bd | 1572 | */ |
39461de3 | 1573 | function set_user_preference($name, $value, $user = null) { |
ae040d4b | 1574 | global $USER, $DB; |
70812e39 | 1575 | |
39461de3 PS |
1576 | if (empty($name) or is_numeric($name) or $name === '_lastloaded') { |
1577 | throw new coding_exception('Invalid preference name in set_user_preference() call'); | |
70812e39 | 1578 | } |
1579 | ||
39461de3 PS |
1580 | if (is_null($value)) { |
1581 | // null means delete current | |
1582 | return unset_user_preference($name, $user); | |
1583 | } else if (is_object($value)) { | |
1584 | throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed'); | |
1585 | } else if (is_array($value)) { | |
1586 | throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed'); | |
1587 | } | |
1588 | $value = (string)$value; | |
1589 | ||
1590 | if (is_null($user)) { | |
1591 | $user = $USER; | |
1592 | } else if (isset($user->id)) { | |
1593 | // $user is valid object | |
1594 | } else if (is_numeric($user)) { | |
1595 | $user = (object)array('id'=>(int)$user); | |
346c3e2f | 1596 | } else { |
39461de3 | 1597 | throw new coding_exception('Invalid $user parameter in set_user_preference() call'); |
346c3e2f | 1598 | } |
1599 | ||
39461de3 PS |
1600 | check_user_preferences_loaded($user); |
1601 | ||
1602 | if (empty($user->id) or isguestuser($user->id)) { | |
1603 | // no permanent storage for not-logged-in users and guest | |
1604 | $user->preference[$name] = $value; | |
1605 | return true; | |
1606 | } | |
346c3e2f | 1607 | |
39461de3 PS |
1608 | if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) { |
1609 | if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) { | |
1610 | // preference already set to this value | |
a1244706 | 1611 | return true; |
1612 | } | |
39461de3 | 1613 | $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id)); |
70812e39 | 1614 | |
1615 | } else { | |
365a5941 | 1616 | $preference = new stdClass(); |
39461de3 | 1617 | $preference->userid = $user->id; |
ae040d4b | 1618 | $preference->name = $name; |
39461de3 | 1619 | $preference->value = $value; |
013376de | 1620 | $DB->insert_record('user_preferences', $preference); |
2660377f | 1621 | } |
1622 | ||
39461de3 PS |
1623 | // update value in cache |
1624 | $user->preference[$name] = $value; | |
1625 | ||
1626 | // set reload flag for other sessions | |
1627 | mark_user_preferences_changed($user->id); | |
346c3e2f | 1628 | |
013376de | 1629 | return true; |
2660377f | 1630 | } |
1631 | ||
1632 | /** | |
1633 | * Sets a whole array of preferences for the current user | |
0d0a8bf6 | 1634 | * |
39461de3 PS |
1635 | * If user object submitted, 'preference' property contains the preferences cache. |
1636 | * | |
2660377f | 1637 | * @param array $prefarray An array of key/value pairs to be set |
39461de3 PS |
1638 | * @param stdClass|int $user A moodle user object or id, null means current user |
1639 | * @return bool always true or exception | |
2660377f | 1640 | */ |
39461de3 | 1641 | function set_user_preferences(array $prefarray, $user = null) { |
2660377f | 1642 | foreach ($prefarray as $name => $value) { |
39461de3 | 1643 | set_user_preference($name, $value, $user); |
2660377f | 1644 | } |
013376de | 1645 | return true; |
70812e39 | 1646 | } |
1647 | ||
6eb3e776 | 1648 | /** |
1649 | * Unsets a preference completely by deleting it from the database | |
0d0a8bf6 | 1650 | * |
39461de3 | 1651 | * If user object submitted, 'preference' property contains the preferences cache. |
0d0a8bf6 | 1652 | * |
6eb3e776 | 1653 | * @param string $name The key to unset as preference for the specified user |
39461de3 PS |
1654 | * @param stdClass|int $user A moodle user object or id, null means current user |
1655 | * @return bool always true or exception | |
6eb3e776 | 1656 | */ |
39461de3 | 1657 | function unset_user_preference($name, $user = null) { |
ae040d4b | 1658 | global $USER, $DB; |
6eb3e776 | 1659 | |
39461de3 PS |
1660 | if (empty($name) or is_numeric($name) or $name === '_lastloaded') { |
1661 | throw new coding_exception('Invalid preference name in unset_user_preference() call'); | |
1662 | } | |
1663 | ||
1664 | if (is_null($user)) { | |
1665 | $user = $USER; | |
1666 | } else if (isset($user->id)) { | |
1667 | // $user is valid object | |
1668 | } else if (is_numeric($user)) { | |
1669 | $user = (object)array('id'=>(int)$user); | |
346c3e2f | 1670 | } else { |
39461de3 | 1671 | throw new coding_exception('Invalid $user parameter in unset_user_preference() call'); |
346c3e2f | 1672 | } |
1673 | ||
39461de3 | 1674 | check_user_preferences_loaded($user); |
013376de | 1675 | |
39461de3 PS |
1676 | if (empty($user->id) or isguestuser($user->id)) { |
1677 | // no permanent storage for not-logged-in user and guest | |
1678 | unset($user->preference[$name]); | |
1679 | return true; | |
70812e39 | 1680 | } |
1681 | ||
39461de3 PS |
1682 | // delete from DB |
1683 | $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name)); | |
1684 | ||
1685 | // delete the preference from cache | |
1686 | unset($user->preference[$name]); | |
1687 | ||
1688 | // set reload flag for other sessions | |
1689 | mark_user_preferences_changed($user->id); | |
1690 | ||
013376de | 1691 | return true; |
70812e39 | 1692 | } |
1693 | ||
7cf1c7bd | 1694 | /** |
0d0a8bf6 | 1695 | * Used to fetch user preference(s) |
1696 | * | |
7cf1c7bd | 1697 | * If no arguments are supplied this function will return |
361855e6 | 1698 | * all of the current user preferences as an array. |
0d0a8bf6 | 1699 | * |
7cf1c7bd | 1700 | * If a name is specified then this function |
1701 | * attempts to return that particular preference value. If | |
1702 | * none is found, then the optional value $default is returned, | |
1703 | * otherwise NULL. | |
0d0a8bf6 | 1704 | * |
39461de3 PS |
1705 | * If user object submitted, 'preference' property contains the preferences cache. |
1706 | * | |
7cf1c7bd | 1707 | * @param string $name Name of the key to use in finding a preference value |
39461de3 PS |
1708 | * @param mixed $default Value to be returned if the $name key is not set in the user preferences |
1709 | * @param stdClass|int $user A moodle user object or id, null means current user | |
1710 | * @return mixed string value or default | |
7cf1c7bd | 1711 | */ |
39461de3 PS |
1712 | function get_user_preferences($name = null, $default = null, $user = null) { |
1713 | global $USER; | |
70812e39 | 1714 | |
39461de3 PS |
1715 | if (is_null($name)) { |
1716 | // all prefs | |
1717 | } else if (is_numeric($name) or $name === '_lastloaded') { | |
1718 | throw new coding_exception('Invalid preference name in get_user_preferences() call'); | |
1719 | } | |
346c3e2f | 1720 | |
39461de3 PS |
1721 | if (is_null($user)) { |
1722 | $user = $USER; | |
1723 | } else if (isset($user->id)) { | |
1724 | // $user is valid object | |
1725 | } else if (is_numeric($user)) { | |
1726 | $user = (object)array('id'=>(int)$user); | |
1727 | } else { | |
1728 | throw new coding_exception('Invalid $user parameter in get_user_preferences() call'); | |
1729 | } | |
1730 | ||
1731 | check_user_preferences_loaded($user); | |
346c3e2f | 1732 | |
39461de3 PS |
1733 | if (empty($name)) { |
1734 | return $user->preference; // All values | |
1735 | } else if (isset($user->preference[$name])) { | |
1736 | return $user->preference[$name]; // The single string value | |
346c3e2f | 1737 | } else { |
39461de3 | 1738 | return $default; // Default value (null if not specified) |
70812e39 | 1739 | } |
70812e39 | 1740 | } |
1741 | ||
9fa49e22 | 1742 | /// FUNCTIONS FOR HANDLING TIME //////////////////////////////////////////// |
39917a09 | 1743 | |
7cf1c7bd | 1744 | /** |
c6d15803 | 1745 | * Given date parts in user time produce a GMT timestamp. |
7cf1c7bd | 1746 | * |
0d0a8bf6 | 1747 | * @todo Finish documenting this function |
68fbd8e1 | 1748 | * @param int $year The year part to create timestamp of |
1749 | * @param int $month The month part to create timestamp of | |
1750 | * @param int $day The day part to create timestamp of | |
1751 | * @param int $hour The hour part to create timestamp of | |
1752 | * @param int $minute The minute part to create timestamp of | |
1753 | * @param int $second The second part to create timestamp of | |
6a0bf5c4 RT |
1754 | * @param mixed $timezone Timezone modifier, if 99 then use default user's timezone |
1755 | * @param bool $applydst Toggle Daylight Saving Time, default true, will be | |
1756 | * applied only if timezone is 99 or string. | |
e34d817e | 1757 | * @return int timestamp |
7cf1c7bd | 1758 | */ |
9f1f6daf | 1759 | function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) { |
39917a09 | 1760 | |
6a0bf5c4 RT |
1761 | //save input timezone, required for dst offset check. |
1762 | $passedtimezone = $timezone; | |
33998d30 | 1763 | |
dddb014a | 1764 | $timezone = get_user_timezone_offset($timezone); |
1765 | ||
6a0bf5c4 | 1766 | if (abs($timezone) > 13) { //server time |
68fbd8e1 | 1767 | $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year); |
03c17ddf | 1768 | } else { |
68fbd8e1 | 1769 | $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year); |
196f2619 | 1770 | $time = usertime($time, $timezone); |
6a0bf5c4 RT |
1771 | |
1772 | //Apply dst for string timezones or if 99 then try dst offset with user's default timezone | |
1773 | if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) { | |
1774 | $time -= dst_offset_on($time, $passedtimezone); | |
28c66824 | 1775 | } |
9f1f6daf | 1776 | } |
1777 | ||
196f2619 | 1778 | return $time; |
85cafb3e | 1779 | |
39917a09 | 1780 | } |
1781 | ||
7cf1c7bd | 1782 | /** |
0d0a8bf6 | 1783 | * Format a date/time (seconds) as weeks, days, hours etc as needed |
1784 | * | |
7cf1c7bd | 1785 | * Given an amount of time in seconds, returns string |
5602f7cf | 1786 | * formatted nicely as weeks, days, hours etc as needed |
7cf1c7bd | 1787 | * |
2f87145b | 1788 | * @uses MINSECS |
1789 | * @uses HOURSECS | |
1790 | * @uses DAYSECS | |
5602f7cf | 1791 | * @uses YEARSECS |
0d0a8bf6 | 1792 | * @param int $totalsecs Time in seconds |
1793 | * @param object $str Should be a time object | |
1794 | * @return string A nicely formatted date/time string | |
7cf1c7bd | 1795 | */ |
1796 | function format_time($totalsecs, $str=NULL) { | |
c7e3ac2a | 1797 | |
6b174680 | 1798 | $totalsecs = abs($totalsecs); |
c7e3ac2a | 1799 | |
8dbed6be | 1800 | if (!$str) { // Create the str structure the slow way |
b0ccd3fb | 1801 | $str->day = get_string('day'); |
1802 | $str->days = get_string('days'); | |
1803 | $str->hour = get_string('hour'); | |
1804 | $str->hours = get_string('hours'); | |
1805 | $str->min = get_string('min'); | |
1806 | $str->mins = get_string('mins'); | |
1807 | $str->sec = get_string('sec'); | |
1808 | $str->secs = get_string('secs'); | |
5602f7cf | 1809 | $str->year = get_string('year'); |
1810 | $str->years = get_string('years'); | |
8dbed6be | 1811 | } |
1812 | ||
5602f7cf | 1813 | |
1814 | $years = floor($totalsecs/YEARSECS); | |
1815 | $remainder = $totalsecs - ($years*YEARSECS); | |
5602f7cf | 1816 | $days = floor($remainder/DAYSECS); |
7a5672c9 | 1817 | $remainder = $totalsecs - ($days*DAYSECS); |
1818 | $hours = floor($remainder/HOURSECS); | |
1819 | $remainder = $remainder - ($hours*HOURSECS); | |
1820 | $mins = floor($remainder/MINSECS); | |
1821 | $secs = $remainder - ($mins*MINSECS); | |
8dbed6be | 1822 | |
1823 | $ss = ($secs == 1) ? $str->sec : $str->secs; | |
1824 | $sm = ($mins == 1) ? $str->min : $str->mins; | |
1825 | $sh = ($hours == 1) ? $str->hour : $str->hours; | |
1826 | $sd = ($days == 1) ? $str->day : $str->days; | |
5602f7cf | 1827 | $sy = ($years == 1) ? $str->year : $str->years; |
8dbed6be | 1828 | |
5602f7cf | 1829 | $oyears = ''; |
b0ccd3fb | 1830 | $odays = ''; |
1831 | $ohours = ''; | |
1832 | $omins = ''; | |
1833 | $osecs = ''; | |
9c9f7d77 | 1834 | |
5602f7cf | 1835 | if ($years) $oyears = $years .' '. $sy; |
b0ccd3fb | 1836 | if ($days) $odays = $days .' '. $sd; |
1837 | if ($hours) $ohours = $hours .' '. $sh; | |
1838 | if ($mins) $omins = $mins .' '. $sm; | |
1839 | if ($secs) $osecs = $secs .' '. $ss; | |
6b174680 | 1840 | |
77ac808e | 1841 | if ($years) return trim($oyears .' '. $odays); |
1842 | if ($days) return trim($odays .' '. $ohours); | |
1843 | if ($hours) return trim($ohours .' '. $omins); | |
1844 | if ($mins) return trim($omins .' '. $osecs); | |
b0ccd3fb | 1845 | if ($secs) return $osecs; |
1846 | return get_string('now'); | |
6b174680 | 1847 | } |
f9903ed0 | 1848 | |
7cf1c7bd | 1849 | /** |
0d0a8bf6 | 1850 | * Returns a formatted string that represents a date in user time |
1851 | * | |
7cf1c7bd | 1852 | * Returns a formatted string that represents a date in user time |
1853 | * <b>WARNING: note that the format is for strftime(), not date().</b> | |
1854 | * Because of a bug in most Windows time libraries, we can't use | |
1855 | * the nicer %e, so we have to use %d which has leading zeroes. | |
1856 | * A lot of the fuss in the function is just getting rid of these leading | |
1857 | * zeroes as efficiently as possible. | |
361855e6 | 1858 | * |
8c3dba73 | 1859 | * If parameter fixday = true (default), then take off leading |
efb8c375 | 1860 | * zero from %d, else maintain it. |
7cf1c7bd | 1861 | * |
0a0cf09a | 1862 | * @param int $date the timestamp in UTC, as obtained from the database. |
1863 | * @param string $format strftime format. You should probably get this using | |
1864 | * get_string('strftime...', 'langconfig'); | |
6a0bf5c4 RT |
1865 | * @param mixed $timezone by default, uses the user's time zone. if numeric and |
1866 | * not 99 then daylight saving will not be added. | |
0a0cf09a | 1867 | * @param bool $fixday If true (default) then the leading zero from %d is removed. |
efb8c375 | 1868 | * If false then the leading zero is maintained. |
0a0cf09a | 1869 | * @return string the formatted date/time. |
7cf1c7bd | 1870 | */ |
0a0cf09a | 1871 | function userdate($date, $format = '', $timezone = 99, $fixday = true) { |
7a302afc | 1872 | |
1ac7ee24 | 1873 | global $CFG; |
1874 | ||
1306c5ea | 1875 | if (empty($format)) { |
0a0cf09a | 1876 | $format = get_string('strftimedaydatetime', 'langconfig'); |
5fa51a39 | 1877 | } |
035cdbff | 1878 | |
c3a3c5b8 | 1879 | if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed. |
1880 | $fixday = false; | |
1881 | } else if ($fixday) { | |
1882 | $formatnoday = str_replace('%d', 'DD', $format); | |
61ae5d36 | 1883 | $fixday = ($formatnoday != $format); |
1884 | } | |
dcde9f02 | 1885 | |
6a0bf5c4 RT |
1886 | //add daylight saving offset for string timezones only, as we can't get dst for |
1887 | //float values. if timezone is 99 (user default timezone), then try update dst. | |
1888 | if ((99 == $timezone) || !is_numeric($timezone)) { | |
1889 | $date += dst_offset_on($date, $timezone); | |
1890 | } | |
85351042 | 1891 | |
494b9296 | 1892 | $timezone = get_user_timezone_offset($timezone); |
102dc313 | 1893 | |
1894 | if (abs($timezone) > 13) { /// Server time | |
d2a9f7cc | 1895 | if ($fixday) { |
102dc313 | 1896 | $datestring = strftime($formatnoday, $date); |
35f7287f | 1897 | $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date))); |
102dc313 | 1898 | $datestring = str_replace('DD', $daystring, $datestring); |
1899 | } else { | |
1900 | $datestring = strftime($format, $date); | |
1901 | } | |
88ec5b7c | 1902 | } else { |
102dc313 | 1903 | $date += (int)($timezone * 3600); |
1904 | if ($fixday) { | |
1905 | $datestring = gmstrftime($formatnoday, $date); | |
35f7287f | 1906 | $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date))); |
102dc313 | 1907 | $datestring = str_replace('DD', $daystring, $datestring); |
1908 | } else { | |
1909 | $datestring = gmstrftime($format, $date); | |
1910 | } | |
88ec5b7c | 1911 | } |
102dc313 | 1912 | |
fb773106 | 1913 | /// If we are running under Windows convert from windows encoding to UTF-8 |
1914 | /// (because it's impossible to specify UTF-8 to fetch locale info in Win32) | |
11f7b25d | 1915 | |
fb773106 | 1916 | if ($CFG->ostype == 'WINDOWS') { |
bf69b06d | 1917 | if ($localewincharset = get_string('localewincharset', 'langconfig')) { |
11f7b25d | 1918 | $textlib = textlib_get_instance(); |
810944af | 1919 | $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8'); |
11f7b25d | 1920 | } |
1921 | } | |
1922 | ||
035cdbff | 1923 | return $datestring; |
873960de | 1924 | } |
1925 | ||
7cf1c7bd | 1926 | /** |
196f2619 | 1927 | * Given a $time timestamp in GMT (seconds since epoch), |
c6d15803 | 1928 | * returns an array that represents the date in user time |
7cf1c7bd | 1929 | * |
0d0a8bf6 | 1930 | * @todo Finish documenting this function |
2f87145b | 1931 | * @uses HOURSECS |
196f2619 | 1932 | * @param int $time Timestamp in GMT |
6a0bf5c4 RT |
1933 | * @param mixed $timezone offset time with timezone, if float and not 99, then no |
1934 | * dst offset is applyed | |
c6d15803 | 1935 | * @return array An array that represents the date in user time |
7cf1c7bd | 1936 | */ |
196f2619 | 1937 | function usergetdate($time, $timezone=99) { |
6b174680 | 1938 | |
6a0bf5c4 RT |
1939 | //save input timezone, required for dst offset check. |
1940 | $passedtimezone = $timezone; | |
94c82430 | 1941 | |
494b9296 | 1942 | $timezone = get_user_timezone_offset($timezone); |
a36166d3 | 1943 | |
e34d817e | 1944 | if (abs($timezone) > 13) { // Server time |
ed1f69b0 | 1945 | return getdate($time); |
d2a9f7cc | 1946 | } |
1947 | ||
6a0bf5c4 RT |
1948 | //add daylight saving offset for string timezones only, as we can't get dst for |
1949 | //float values. if timezone is 99 (user default timezone), then try update dst. | |
1950 | if ($passedtimezone == 99 || !is_numeric($passedtimezone)) { | |
1951 | $time += dst_offset_on($time, $passedtimezone); | |
1952 | } | |
1953 | ||
e34d817e | 1954 | $time += intval((float)$timezone * HOURSECS); |
3bba1e6e | 1955 | |
24d38a6e | 1956 | $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time); |
02f0527d | 1957 | |
24d38a6e | 1958 | //be careful to ensure the returned array matches that produced by getdate() above |
9f1f6daf | 1959 | list( |
24d38a6e AD |
1960 | $getdate['month'], |
1961 | $getdate['weekday'], | |
1962 | $getdate['yday'], | |
9f1f6daf | 1963 | $getdate['year'], |
24d38a6e | 1964 | $getdate['mon'], |
9f1f6daf | 1965 | $getdate['wday'], |
24d38a6e AD |
1966 | $getdate['mday'], |
1967 | $getdate['hours'], | |
1968 | $getdate['minutes'], | |
1969 | $getdate['seconds'] | |
3bba1e6e | 1970 | ) = explode('_', $datestring); |
9f1f6daf | 1971 | |
d2d6171f | 1972 | return $getdate; |
d552ead0 | 1973 | } |
1974 | ||
7cf1c7bd | 1975 | /** |
1976 | * Given a GMT timestamp (seconds since epoch), offsets it by | |
1977 | * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds | |
1978 | * | |
2f87145b | 1979 | * @uses HOURSECS |
c6d15803 | 1980 | * @param int $date Timestamp in GMT |
e34d817e | 1981 | * @param float $timezone |
c6d15803 | 1982 | * @return int |
7cf1c7bd | 1983 | */ |
d552ead0 | 1984 | function usertime($date, $timezone=99) { |
a36166d3 | 1985 | |
494b9296 | 1986 | $timezone = get_user_timezone_offset($timezone); |
2665e47a | 1987 | |
0431bd7c | 1988 | if (abs($timezone) > 13) { |
d552ead0 | 1989 | return $date; |
1990 | } | |
7a5672c9 | 1991 | return $date - (int)($timezone * HOURSECS); |
d552ead0 | 1992 | } |
1993 | ||
8c3dba73 | 1994 | /** |
1995 | * Given a time, return the GMT timestamp of the most recent midnight | |
1996 | * for the current user. | |
1997 | * | |
e34d817e | 1998 | * @param int $date Timestamp in GMT |
0d0a8bf6 | 1999 | * @param float $timezone Defaults to user's timezone |
2000 | * @return int Returns a GMT timestamp | |
8c3dba73 | 2001 | */ |
edf7fe8c | 2002 | function usergetmidnight($date, $timezone=99) { |
edf7fe8c | 2003 | |
edf7fe8c | 2004 | $userdate = usergetdate($date, $timezone); |
4606d9bb | 2005 | |
02f0527d | 2006 | // Time of midnight of this user's day, in GMT |
2007 | return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone); | |
edf7fe8c | 2008 | |
2009 | } | |
2010 | ||
7cf1c7bd | 2011 | /** |
2012 | * Returns a string that prints the user's timezone | |
2013 | * | |
2014 | * @param float $timezone The user's timezone | |
2015 | * @return string | |
2016 | */ | |
d552ead0 | 2017 | function usertimezone($timezone=99) { |
d552ead0 | 2018 | |
0c244315 | 2019 | $tz = get_user_timezone($timezone); |
f30fe8d0 | 2020 | |
0c244315 | 2021 | if (!is_float($tz)) { |
2022 | return $tz; | |
d552ead0 | 2023 | } |
0c244315 | 2024 | |
2025 | if(abs($tz) > 13) { // Server time | |
2026 | return get_string('serverlocaltime'); | |
2027 | } | |
2028 | ||
2029 | if($tz == intval($tz)) { | |
2030 | // Don't show .0 for whole hours | |
2031 | $tz = intval($tz); | |
2032 | } | |
2033 | ||
2034 | if($tz == 0) { | |
61b420ac | 2035 | return 'UTC'; |
d552ead0 | 2036 | } |
0c244315 | 2037 | else if($tz > 0) { |
61b420ac | 2038 | return 'UTC+'.$tz; |
0c244315 | 2039 | } |
2040 | else { | |
61b420ac | 2041 | return 'UTC'.$tz; |
d552ead0 | 2042 | } |
e1ecf0a0 | 2043 | |
f9903ed0 | 2044 | } |
2045 | ||
7cf1c7bd | 2046 | /** |
2047 | * Returns a float which represents the user's timezone difference from GMT in hours | |
2048 | * Checks various settings and picks the most dominant of those which have a value | |
2049 | * | |
0d0a8bf6 | 2050 | * @global object |
2051 | * @global object | |
b2b68362 | 2052 | * @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 |
0d0a8bf6 | 2053 | * @return float |
7cf1c7bd | 2054 | */ |
494b9296 | 2055 | function get_user_timezone_offset($tz = 99) { |
f30fe8d0 | 2056 | |
43b59916 | 2057 | global $USER, $CFG; |
2058 | ||
e8904995 | 2059 | $tz = get_user_timezone($tz); |
c9e55a25 | 2060 | |
7b9e355e | 2061 | if (is_float($tz)) { |
2062 | return $tz; | |
2063 | } else { | |
e8904995 | 2064 | $tzrecord = get_timezone_record($tz); |
7b9e355e | 2065 | if (empty($tzrecord)) { |
e8904995 | 2066 | return 99.0; |
2067 | } | |
4f2dbde9 | 2068 | return (float)$tzrecord->gmtoff / HOURMINS; |
e8904995 | 2069 | } |
2070 | } | |
2071 | ||
61460dd6 | 2072 | /** |
2073 | * Returns an int which represents the systems's timezone difference from GMT in seconds | |
0d0a8bf6 | 2074 | * |
2075 | * @global object | |
61460dd6 | 2076 | * @param mixed $tz timezone |
2077 | * @return int if found, false is timezone 99 or error | |
2078 | */ | |
2079 | function get_timezone_offset($tz) { | |
2080 | global $CFG; | |
2081 | ||
2082 | if ($tz == 99) { | |
2083 | return false; | |
2084 | } | |
2085 | ||
2086 | if (is_numeric($tz)) { | |
2087 | return intval($tz * 60*60); | |
2088 | } | |
2089 | ||
2090 | if (!$tzrecord = get_timezone_record($tz)) { | |
2091 | return false; | |
2092 | } | |
2093 | return intval($tzrecord->gmtoff * 60); | |
2094 | } | |
2095 | ||
bbd3f2c4 | 2096 | /** |
b2b68362 | 2097 | * Returns a float or a string which denotes the user's timezone |
2098 | * 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) | |
2099 | * means that for this timezone there are also DST rules to be taken into account | |
2100 | * Checks various settings and picks the most dominant of those which have a value | |
bbd3f2c4 | 2101 | * |
0d0a8bf6 | 2102 | * @global object |
2103 | * @global object | |
6a0bf5c4 | 2104 | * @param mixed $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked |
b2b68362 | 2105 | * @return mixed |
bbd3f2c4 | 2106 | */ |
e8904995 | 2107 | function get_user_timezone($tz = 99) { |
2108 | global $USER, $CFG; | |
43b59916 | 2109 | |
f30fe8d0 | 2110 | $timezones = array( |
e8904995 | 2111 | $tz, |
2112 | isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99, | |
43b59916 | 2113 | isset($USER->timezone) ? $USER->timezone : 99, |
2114 | isset($CFG->timezone) ? $CFG->timezone : 99, | |
f30fe8d0 | 2115 | ); |
43b59916 | 2116 | |
e8904995 | 2117 | $tz = 99; |
43b59916 | 2118 | |
33998d30 | 2119 | while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) { |
e8904995 | 2120 | $tz = $next['value']; |
43b59916 | 2121 | } |
e8904995 | 2122 | |
2123 | return is_numeric($tz) ? (float) $tz : $tz; | |
43b59916 | 2124 | } |
2125 | ||
bbd3f2c4 | 2126 | /** |
f33e1ed4 | 2127 | * Returns cached timezone record for given $timezonename |
bbd3f2c4 | 2128 | * |
0d0a8bf6 | 2129 | * @global object |
2130 | * @global object | |
f33e1ed4 | 2131 | * @param string $timezonename |
2132 | * @return mixed timezonerecord object or false | |
bbd3f2c4 | 2133 | */ |
43b59916 | 2134 | function get_timezone_record($timezonename) { |
f33e1ed4 | 2135 | global $CFG, $DB; |
43b59916 | 2136 | static $cache = NULL; |
2137 | ||
8edffd15 | 2138 | if ($cache === NULL) { |
43b59916 | 2139 | $cache = array(); |
2140 | } | |
2141 | ||
8edffd15 | 2142 | if (isset($cache[$timezonename])) { |
43b59916 | 2143 | return $cache[$timezonename]; |
f30fe8d0 | 2144 | } |
2145 | ||
f33e1ed4 | 2146 | return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone} |
ae040d4b | 2147 | WHERE name = ? ORDER BY year DESC', array($timezonename), true); |
f30fe8d0 | 2148 | } |
f9903ed0 | 2149 | |
bbd3f2c4 | 2150 | /** |
0d0a8bf6 | 2151 | * Build and store the users Daylight Saving Time (DST) table |
bbd3f2c4 | 2152 | * |
0d0a8bf6 | 2153 | * @global object |
2154 | * @global object | |
2155 | * @global object | |
2156 | * @param mixed $from_year Start year for the table, defaults to 1971 | |
2157 | * @param mixed $to_year End year for the table, defaults to 2035 | |
6a0bf5c4 | 2158 | * @param mixed $strtimezone, if null or 99 then user's default timezone is used |
bbd3f2c4 | 2159 | * @return bool |
2160 | */ | |
94c82430 | 2161 | function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) { |
ae040d4b | 2162 | global $CFG, $SESSION, $DB; |
85cafb3e | 2163 | |
33998d30 | 2164 | $usertz = get_user_timezone($strtimezone); |
7cb29a3d | 2165 | |
989585e9 | 2166 | if (is_float($usertz)) { |
2167 | // Trivial timezone, no DST | |
2168 | return false; | |
2169 | } | |
2170 | ||
2280ecf5 | 2171 | if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) { |
989585e9 | 2172 | // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset |
2280ecf5 | 2173 | unset($SESSION->dst_offsets); |
2174 | unset($SESSION->dst_range); | |
830a2bbd | 2175 | } |
2176 | ||
2280ecf5 | 2177 | if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) { |
830a2bbd | 2178 | // Repeat calls which do not request specific year ranges stop here, we have already calculated the table |
2179 | // This will be the return path most of the time, pretty light computationally | |
2180 | return true; | |
85cafb3e | 2181 | } |
2182 | ||
830a2bbd | 2183 | // Reaching here means we either need to extend our table or create it from scratch |
989585e9 | 2184 | |
2185 | // Remember which TZ we calculated these changes for | |
2280ecf5 | 2186 | $SESSION->dst_offsettz = $usertz; |
989585e9 | 2187 | |
2280ecf5 | 2188 | if(empty($SESSION->dst_offsets)) { |
830a2bbd | 2189 | // If we 're creating from scratch, put the two guard elements in there |
2280ecf5 | 2190 | $SESSION->dst_offsets = array(1 => NULL, 0 => NULL); |
830a2bbd | 2191 | } |
2280ecf5 | 2192 | if(empty($SESSION->dst_range)) { |
830a2bbd | 2193 | // If creating from scratch |
2194 | $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971); | |
2195 | $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035); | |
2196 | ||
2197 | // Fill in the array with the extra years we need to process | |
2198 | $yearstoprocess = array(); | |
2199 | for($i = $from; $i <= $to; ++$i) { | |
2200 | $yearstoprocess[] = $i; | |
2201 | } | |
2202 | ||
2203 | // Take note of which years we have processed for future calls | |
2280ecf5 | 2204 | $SESSION->dst_range = array($from, $to); |
830a2bbd | 2205 | } |
2206 | else { | |
2207 | // If needing to extend the table, do the same | |
2208 | $yearstoprocess = array(); | |
2209 | ||
2280ecf5 | 2210 | $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971); |
2211 | $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035); | |
830a2bbd | 2212 | |
2280ecf5 | 2213 | if($from < $SESSION->dst_range[0]) { |
830a2bbd | 2214 | // Take note of which years we need to process and then note that we have processed them for future calls |
2280ecf5 | 2215 | for($i = $from; $i < $SESSION->dst_range[0]; ++$i) { |
830a2bbd | 2216 | $yearstoprocess[] = $i; |
2217 | } | |
2280ecf5 | 2218 | $SESSION->dst_range[0] = $from; |
830a2bbd | 2219 | } |
2280ecf5 | 2220 | if($to > $SESSION->dst_range[1]) { |
830a2bbd | 2221 | // Take note of which years we need to process and then note that we have processed them for future calls |
2280ecf5 | 2222 | for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) { |
830a2bbd | 2223 | $yearstoprocess[] = $i; |
2224 | } | |
2280ecf5 | 2225 | $SESSION->dst_range[1] = $to; |
830a2bbd | 2226 | } |
2227 | } | |
2228 | ||
2229 | if(empty($yearstoprocess)) { | |
2230 | // This means that there was a call requesting a SMALLER range than we have already calculated | |
2231 | return true; | |
2232 | } | |
2233 | ||
2234 | // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need | |
2235 | // Also, the array is sorted in descending timestamp order! | |
2236 | ||
2237 | // Get DB data | |
6a5dc27c | 2238 | |
2239 | static $presets_cache = array(); | |
2240 | if (!isset($presets_cache[$usertz])) { | |
ae040d4b | 2241 | $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 | 2242 | } |
2243 | if(empty($presets_cache[$usertz])) { | |
e789650d | 2244 | return false; |
2245 | } | |
57f1191c | 2246 | |
830a2bbd | 2247 | // Remove ending guard (first element of the array) |
2280ecf5 | 2248 | reset($SESSION->dst_offsets); |
2249 | unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]); | |
830a2bbd | 2250 | |
2251 | // Add all required change timestamps | |
2252 | foreach($yearstoprocess as $y) { | |
2253 | // Find the record which is in effect for the year $y | |
6a5dc27c | 2254 | foreach($presets_cache[$usertz] as $year => $preset) { |
830a2bbd | 2255 | if($year <= $y) { |
2256 | break; | |
c9e72798 | 2257 | } |
830a2bbd | 2258 | } |
2259 | ||
2260 | $changes = dst_changes_for_year($y, $preset); | |
2261 | ||
2262 | if($changes === NULL) { | |
2263 | continue; | |
2264 | } | |
2265 | if($changes['dst'] != 0) { | |
2280ecf5 | 2266 | $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS; |
830a2bbd | 2267 | } |
2268 | if($changes['std'] != 0) { | |
2280ecf5 | 2269 | $SESSION->dst_offsets[$changes['std']] = 0; |
c9e72798 | 2270 | } |
85cafb3e | 2271 | } |
42d36497 | 2272 | |
830a2bbd | 2273 | // Put in a guard element at the top |
2280ecf5 | 2274 | $maxtimestamp = max(array_keys($SESSION->dst_offsets)); |
2275 | $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do | |
830a2bbd | 2276 | |
2277 | // Sort again | |
2280ecf5 | 2278 | krsort($SESSION->dst_offsets); |
830a2bbd | 2279 | |
e789650d | 2280 | return true; |
2281 | } | |
42d36497 | 2282 | |
0d0a8bf6 | 2283 | /** |
2284 | * Calculates the required DST change and returns a Timestamp Array | |
2285 | * | |
2286 | * @uses HOURSECS | |
2287 | * @uses MINSECS | |
2288 | * @param mixed $year Int or String Year to focus on | |
2289 | * @param object $timezone Instatiated Timezone object | |
2290 | * @return mixed Null, or Array dst=>xx, 0=>xx, std=>yy, 1=>yy | |
2291 | */ | |
e789650d | 2292 | function dst_changes_for_year($year, $timezone) { |
7cb29a3d | 2293 | |
e789650d | 2294 | if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) { |
2295 | return NULL; | |
42d36497 | 2296 | } |
7cb29a3d | 2297 | |
e789650d | 2298 | $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year); |
2299 | $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year); | |
2300 | ||
2301 | list($dst_hour, $dst_min) = explode(':', $timezone->dst_time); | |
2302 | list($std_hour, $std_min) = explode(':', $timezone->std_time); | |
d2a9f7cc | 2303 | |
6dc8dddc | 2304 | $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false); |
2305 | $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false); | |
830a2bbd | 2306 | |
2307 | // Instead of putting hour and minute in make_timestamp(), we add them afterwards. | |
2308 | // This has the advantage of being able to have negative values for hour, i.e. for timezones | |
2309 | // where GMT time would be in the PREVIOUS day than the local one on which DST changes. | |
2310 | ||
2311 | $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS; | |
2312 | $timestd += $std_hour * HOURSECS + $std_min * MINSECS; | |
42d36497 | 2313 | |
e789650d | 2314 | return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd); |
42d36497 | 2315 | } |
2316 | ||
0d0a8bf6 | 2317 | /** |
efb8c375 | 2318 | * Calculates the Daylight Saving Offset for a given date/time (timestamp) |
6a0bf5c4 | 2319 | * - Note: Daylight saving only works for string timezones and not for float. |
0d0a8bf6 | 2320 | * |
2321 | * @global object | |
2322 | * @param int $time must NOT be compensated at all, it has to be a pure timestamp | |
6a0bf5c4 RT |
2323 | * @param mixed $strtimezone timezone for which offset is expected, if 99 or null |
2324 | * then user's default timezone is used. | |
0d0a8bf6 | 2325 | * @return int |
2326 | */ | |
94c82430 | 2327 | function dst_offset_on($time, $strtimezone = NULL) { |
2280ecf5 | 2328 | global $SESSION; |
02f0527d | 2329 | |
94c82430 | 2330 | if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) { |
c9e72798 | 2331 | return 0; |
85cafb3e | 2332 | } |
2333 | ||
2280ecf5 | 2334 | reset($SESSION->dst_offsets); |
2335 | while(list($from, $offset) = each($SESSION->dst_offsets)) { | |
59556d48 | 2336 | if($from <= $time) { |
c9e72798 | 2337 | break; |
2338 | } | |
2339 | } | |
2340 | ||
830a2bbd | 2341 | // This is the normal return path |
2342 | if($offset !== NULL) { | |
2343 | return $offset; | |
02f0527d | 2344 | } |
02f0527d | 2345 | |
830a2bbd | 2346 | // Reaching this point means we haven't calculated far enough, do it now: |
2347 | // Calculate extra DST changes if needed and recurse. The recursion always | |
2348 | // moves toward the stopping condition, so will always end. | |
2349 | ||
2350 | if($from == 0) { | |
2280ecf5 | 2351 | // We need a year smaller than $SESSION->dst_range[0] |
2352 | if($SESSION->dst_range[0] == 1971) { | |
830a2bbd | 2353 | return 0; |
2354 | } | |
94c82430 | 2355 | calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone); |
2356 | return dst_offset_on($time, $strtimezone); | |
830a2bbd | 2357 | } |
2358 | else { | |
2280ecf5 | 2359 | // We need a year larger than $SESSION->dst_range[1] |
2360 | if($SESSION->dst_range[1] == 2035) { | |
830a2bbd | 2361 | return 0; |
2362 | } | |
94c82430 | 2363 | calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone); |
2364 | return dst_offset_on($time, $strtimezone); | |
830a2bbd | 2365 | } |
85cafb3e | 2366 | } |
02f0527d | 2367 | |
0d0a8bf6 | 2368 | /** |
2369 | * ? | |
2370 | * | |
2371 | * @todo Document what this function does | |
2372 | * @param int $startday | |
2373 | * @param int $weekday | |
2374 | * @param int $month | |
2375 | * @param int $year | |
2376 | * @return int | |
2377 | */ | |
28902d99 | 2378 | function find_day_in_month($startday, $weekday, $month, $year) { |
8dc3f6cf | 2379 | |
2380 | $daysinmonth = days_in_month($month, $year); | |
2381 | ||
42d36497 | 2382 | if($weekday == -1) { |
28902d99 | 2383 | // Don't care about weekday, so return: |
2384 | // abs($startday) if $startday != -1 | |
2385 | // $daysinmonth otherwise | |
2386 | return ($startday == -1) ? $daysinmonth : abs($startday); | |
8dc3f6cf | 2387 | } |
2388 | ||
2389 | // From now on we 're looking for a specific weekday | |
8dc3f6cf | 2390 | |
28902d99 | 2391 | // Give "end of month" its actual value, since we know it |
2392 | if($startday == -1) { | |
2393 | $startday = -1 * $daysinmonth; | |
2394 | } | |
2395 | ||
2396 | // Starting from day $startday, the sign is the direction | |
8dc3f6cf | 2397 | |
28902d99 | 2398 | if($startday < 1) { |
8dc3f6cf | 2399 | |
28902d99 | 2400 | $startday = abs($startday); |
ef7af3dd | 2401 | $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year)); |
8dc3f6cf | 2402 | |
2403 | // This is the last such weekday of the month | |
2404 | $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday; | |
2405 | if($lastinmonth > $daysinmonth) { | |
2406 | $lastinmonth -= 7; | |
42d36497 | 2407 | } |
8dc3f6cf | 2408 | |
28902d99 | 2409 | // Find the first such weekday <= $startday |
2410 | while($lastinmonth > $startday) { | |
8dc3f6cf | 2411 | $lastinmonth -= 7; |
42d36497 | 2412 | } |
8dc3f6cf | 2413 | |
2414 | return $lastinmonth; | |
e1ecf0a0 | 2415 | |
42d36497 | 2416 | } |
2417 | else { | |
42d36497 | 2418 | |
ef7af3dd | 2419 | $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year)); |
42d36497 | 2420 | |
8dc3f6cf | 2421 | $diff = $weekday - $indexweekday; |
2422 | if($diff < 0) { | |
2423 | $diff += 7; | |
42d36497 | 2424 | } |
42d36497 | 2425 | |
28902d99 | 2426 | // This is the first such weekday of the month equal to or after $startday |
2427 | $firstfromindex = $startday + $diff; | |
42d36497 | 2428 | |
8dc3f6cf | 2429 | return $firstfromindex; |
2430 | ||
2431 | } | |
42d36497 | 2432 | } |
2433 | ||
bbd3f2c4 | 2434 | /** |
2435 | * Calculate the number of days in a given month | |
2436 | * | |
2437 | * @param int $month The month whose day count is sought | |
2438 | * @param int $year The year of the month whose day count is sought | |
2439 | * @return int | |
2440 | */ | |
42d36497 | 2441 | function days_in_month($month, $year) { |
ef7af3dd | 2442 | return intval(date('t', mktime(12, 0, 0, $month, 1, $year))); |
42d36497 | 2443 | } |
2444 | ||
bbd3f2c4 | 2445 | /** |
2446 | * Calculate the position in the week of a specific calendar day | |
2447 | * | |
2448 | * @param int $day The day of the date whose position in the week is sought | |
2449 | * @param int $month The month of the date whose position in the week is sought | |
2450 | * @param int $year The year of the date whose position in the week is sought | |
2451 | * @return int | |
2452 | */ | |
8dc3f6cf | 2453 | function dayofweek($day, $month, $year) { |
2454 | // I wonder if this is any different from | |
2455 | // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0)); | |
d7eeb39e | 2456 | return intval(date('w', mktime(12, 0, 0, $month, $day, $year))); |
8dc3f6cf | 2457 | } |
2458 | ||
9fa49e22 | 2459 | /// USER AUTHENTICATION AND LOGIN //////////////////////////////////////// |
f9903ed0 | 2460 | |
93f66983 | 2461 | /** |
2462 | * Returns full login url. | |
2463 | * | |
93f66983 | 2464 | * @return string login url |
2465 | */ | |
999b54af | 2466 | function get_login_url() { |
93f66983 | 2467 | global $CFG; |
2468 | ||
999b54af | 2469 | $url = "$CFG->wwwroot/login/index.php"; |
93f66983 | 2470 | |
999b54af PS |
2471 | if (!empty($CFG->loginhttps)) { |
2472 | $url = str_replace('http:', 'https:', $url); | |
93f66983 | 2473 | } |
2474 | ||
2475 | return $url; | |
2476 | } | |
2477 | ||
7cf1c7bd | 2478 | /** |
ec81373f | 2479 | * This function checks that the current user is logged in and has the |
2480 | * required privileges | |
2481 | * | |
7cf1c7bd | 2482 | * This function checks that the current user is logged in, and optionally |
ec81373f | 2483 | * whether they are allowed to be in a particular course and view a particular |
2484 | * course module. | |
2485 | * If they are not logged in, then it redirects them to the site login unless | |
d2a9f7cc | 2486 | * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which |
ec81373f | 2487 | * case they are automatically logged in as guests. |
2488 | * If $courseid is given and the user is not enrolled in that course then the | |
2489 | * user is redirected to the course enrolment page. | |
efb8c375 | 2490 | * If $cm is given and the course module is hidden and the user is not a teacher |
ec81373f | 2491 | * in the course then the user is redirected to the course home page. |
7cf1c7bd | 2492 | * |
191b267b | 2493 | * When $cm parameter specified, this function sets page layout to 'module'. |
4f0c2d00 | 2494 | * You need to change it manually later if some other layout needed. |
191b267b | 2495 | * |
33ebaf7c | 2496 | * @param mixed $courseorid id of the course or course object |
0d0a8bf6 | 2497 | * @param bool $autologinguest default true |
bbd3f2c4 | 2498 | * @param object $cm course module object |
f4013c10 | 2499 | * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to |
2500 | * true. Used to avoid (=false) some scripts (file.php...) to set that variable, | |
2501 | * in order to keep redirects working properly. MDL-14495 | |
df997f84 | 2502 | * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions |
0d0a8bf6 | 2503 | * @return mixed Void, exit, and die depending on path |
7cf1c7bd | 2504 | */ |
df997f84 PS |
2505 | function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) { |
2506 | global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT; | |
d8ba183c | 2507 | |
df997f84 | 2508 | // setup global $COURSE, themes, language and locale |
c13a5e71 | 2509 | if (!empty($courseorid)) { |
2510 | if (is_object($courseorid)) { | |
2511 | $course = $courseorid; | |
2512 | } else if ($courseorid == SITEID) { | |
2513 | $course = clone($SITE); | |
2514 | } else { | |
df997f84 | 2515 | $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST); |
c13a5e71 | 2516 | } |
95d28870 | 2517 | if ($cm) { |
df997f84 PS |
2518 | if ($cm->course != $course->id) { |
2519 | throw new coding_exception('course and cm parameters in require_login() call do not match!!'); | |
2520 | } | |
0d8b6a69 | 2521 | // make sure we have a $cm from get_fast_modinfo as this contains activity access details |
47148151 | 2522 | if (!($cm instanceof cm_info)) { |
0d8b6a69 | 2523 | // note: nearly all pages call get_fast_modinfo anyway and it does not make any |
2524 | // db queries so this is not really a performance concern, however it is obviously | |
2525 | // better if you use get_fast_modinfo to get the cm before calling this. | |
2526 | $modinfo = get_fast_modinfo($course); | |
2527 | $cm = $modinfo->get_cm($cm->id); | |
2528 | } | |
00dadbe1 | 2529 | $PAGE->set_cm($cm, $course); // set's up global $COURSE |
191b267b | 2530 | $PAGE->set_pagelayout('incourse'); |
95d28870 | 2531 | } else { |
00dadbe1 | 2532 | $PAGE->set_course($course); // set's up global $COURSE |
95d28870 | 2533 | } |
e88462a0 | 2534 | } else { |
df997f84 PS |
2535 | // do not touch global $COURSE via $PAGE->set_course(), |
2536 | // the reasons is we need to be able to call require_login() at any time!! | |
2537 | $course = $SITE; | |
2538 | if ($cm) { | |
2539 | throw new coding_exception('cm parameter in require_login() requires valid course parameter!'); | |
2540 | } | |
c13a5e71 | 2541 | } |
be933850 | 2542 | |
df997f84 | 2543 | // If the user is not even logged in yet then make sure they are |
083c3743 | 2544 | if (!isloggedin()) { |
df997f84 | 2545 | if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) { |
999b54af PS |
2546 | if (!$guest = get_complete_user_data('id', $CFG->siteguest)) { |
2547 | // misconfigured site guest, just redirect to login page | |
2548 | redirect(get_login_url()); | |
2549 | exit; // never reached | |
df997f84 | 2550 | } |
999b54af | 2551 | $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang; |
0342fc36 | 2552 | complete_user_login($guest); |
d9e07264 | 2553 | $USER->autologinguest = true; |
999b54af | 2554 | $SESSION->lang = $lang; |
8a33e371 | 2555 | } else { |
999b54af PS |
2556 | //NOTE: $USER->site check was obsoleted by session test cookie, |
2557 | // $USER->confirmed test is in login/index.php | |
2558 | if ($preventredirect) { | |
2559 | throw new require_login_exception('You are not logged in'); | |
2560 | } | |
2561 | ||
2562 | if ($setwantsurltome) { | |
2563 | // TODO: switch to PAGE->url | |
2564 | $SESSION->wantsurl = $FULLME; | |
2565 | } | |
2566 | if (!empty($_SERVER['HTTP_REFERER'])) { | |
2567 | $SESSION->fromurl = $_SERVER['HTTP_REFERER']; | |
2568 | } | |
2569 | redirect(get_login_url()); | |
2570 | exit; // never reached | |
8a33e371 | 2571 | } |
f9903ed0 | 2572 | } |
808a3baa | 2573 | |
df997f84 PS |
2574 | // loginas as redirection if needed |
2575 | if ($course->id != SITEID and session_is_loggedinas()) { | |
f6f66b03 | 2576 | if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) { |
df997f84 | 2577 | if ($USER->loginascontext->instanceid != $course->id) { |
3887fe4a | 2578 | print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid); |
5e623a33 | 2579 | } |
f6f66b03 | 2580 | } |
2581 | } | |
2582 | ||
df997f84 | 2583 | // check whether the user should be changing password (but only if it is REALLY them) |
b7b64ff2 | 2584 | if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) { |
21e2dcd9 | 2585 | $userauth = get_auth_plugin($USER->auth); |
df997f84 | 2586 | if ($userauth->can_change_password() and !$preventredirect) { |
20fde7b1 | 2587 | $SESSION->wantsurl = $FULLME; |
80274abf | 2588 | if ($changeurl = $userauth->change_password_url()) { |
9696bd89 | 2589 | //use plugin custom url |
80274abf | 2590 | redirect($changeurl); |
1437f0a5 | 2591 | } else { |
9696bd89 | 2592 | //use moodle internal method |
2593 | if (empty($CFG->loginhttps)) { | |
2594 | redirect($CFG->wwwroot .'/login/change_password.php'); | |
2595 | } else { | |
2596 | $wwwroot = str_replace('http:','https:', $CFG->wwwroot); | |
2597 | redirect($wwwroot .'/login/change_password.php'); | |
2598 | } | |
1437f0a5 | 2599 | } |
d35757eb | 2600 | } else { |
a8ee7194 | 2601 | print_error('nopasswordchangeforced', 'auth'); |
d35757eb | 2602 | } |
2603 | } | |
083c3743 | 2604 | |
df997f84 | 2605 | // Check that the user account is properly set up |
808a3baa | 2606 | if (user_not_fully_set_up($USER)) { |
df997f84 PS |
2607 | if ($preventredirect) { |
2608 | throw new require_login_exception('User not fully set-up'); | |
2609 | } | |
20fde7b1 | 2610 | $SESSION->wantsurl = $FULLME; |
b0ccd3fb | 2611 | redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&course='. SITEID); |
808a3baa | 2612 | } |
d8ba183c | 2613 | |
df997f84 | 2614 | // Make sure the USER has a sesskey set up. Used for CSRF protection. |
04280e85 | 2615 | sesskey(); |
366dfa60 | 2616 | |
1560760f | 2617 | // Do not bother admins with any formalities |
df997f84 | 2618 | if (is_siteadmin()) { |
1560760f AD |
2619 | //set accesstime or the user will appear offline which messes up messaging |
2620 | user_accesstime_log($course->id); | |
df997f84 PS |
2621 | return; |
2622 | } | |
2623 | ||
b593d49d PS |
2624 | // Check that the user has agreed to a site policy if there is one - do not test in case of admins |
2625 | if (!$USER->policyagreed and !is_siteadmin()) { | |
2626 | if (!empty($CFG->sitepolicy) and !isguestuser()) { | |
2627 | if ($preventredirect) { | |
2628 | throw new require_login_exception('Policy not agreed'); | |
2629 | } | |
2630 | $SESSION->wantsurl = $FULLME; | |
2631 | redirect($CFG->wwwroot .'/user/policy.php'); | |
2632 | } else if (!empty($CFG->sitepolicyguest) and isguestuser()) { | |
2633 | if ($preventredirect) { | |
2634 | throw new require_login_exception('Policy not agreed'); | |
2635 | } | |
957b5198 | 2636 | $SESSION->wantsurl = $FULLME; |
027a1604 | 2637 | redirect($CFG->wwwroot .'/user/policy.php'); |
027a1604 | 2638 | } |
1695b680 | 2639 | } |
2640 | ||
df997f84 | 2641 | // Fetch the system context, the course context, and prefetch its child contexts |
21e2dcd9 | 2642 | $sysctx = get_context_instance(CONTEXT_SYSTEM); |
df997f84 PS |
2643 | $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); |
2644 | if ($cm) { | |
2645 | $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST); | |
2646 | } else { | |
2647 | $cmcontext = null; | |
2648 | } | |
21e2dcd9 | 2649 | |
df997f84 | 2650 | // If the site is currently under maintenance, then print a message |
4fe2250a | 2651 | if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) { |
df997f84 PS |
2652 | if ($preventredirect) { |
2653 | throw new require_login_exception('Maintenance in progress'); | |
2654 | } | |
2655 | ||
4fe2250a | 2656 | print_maintenance_message(); |
027a1604 | 2657 | } |
2658 | ||
df997f84 PS |
2659 | // make sure the course itself is not hidden |
2660 | if ($course->id == SITEID) { | |
2661 | // frontpage can not be hidden | |
2662 | } else { | |
f5c1e621 | 2663 | if (is_role_switched($course->id)) { |
df997f84 PS |
2664 | // when switching roles ignore the hidden flag - user had to be in course to do the switch |
2665 | } else { | |
2666 | if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) { | |
2667 | // originally there was also test of parent category visibility, | |
2668 | // BUT is was very slow in complex queries involving "my courses" | |
2669 | // now it is also possible to simply hide all courses user is not enrolled in :-) | |
2670 | if ($preventredirect) { | |
2671 | throw new require_login_exception('Course is hidden'); | |
2672 | } | |
2673 | notice(get_string('coursehidden'), $CFG->wwwroot .'/'); | |
2674 | } | |
2675 | } | |
2676 | } | |
2677 | ||
2678 | // is the user enrolled? | |
2679 | if ($course->id == SITEID) { | |
2680 | // everybody is enrolled on the frontpage | |
2681 | ||
2682 | } else { | |
2683 | if (session_is_loggedinas()) { | |
2684 | // Make sure the REAL person can access this course first | |
2685 | $realuser = session_get_realuser(); | |
2686 | if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) { | |
2687 | if ($preventredirect) { | |
2688 | throw new require_login_exception('Invalid course login-as access'); | |
2689 | } | |
2690 | echo $OUTPUT->header(); | |
2691 | notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/'); | |
2692 | } | |
2693 | } | |
2694 | ||
2695 | // very simple enrolment caching - changes in course setting are not reflected immediately | |
2696 | if (!isset($USER->enrol)) { | |
2697 | $USER->enrol = array(); | |
2698 | $USER->enrol['enrolled'] = array(); | |
2699 | $USER->enrol['tempguest'] = array(); | |
2700 | } | |
2701 | ||
2702 | $access = false; | |
2703 | ||
2704 | if (is_viewing($coursecontext, $USER)) { | |
2705 | // ok, no need to mess with enrol | |
2706 | $access = true; | |
2707 | ||
2708 | } else { | |
2709 | if (isset($USER->enrol['enrolled'][$course->id])) { | |
2710 | if ($USER->enrol['enrolled'][$course->id] == 0) { | |
2711 | $access = true; | |
2712 | } else if ($USER->enrol['enrolled'][$course->id] > time()) { | |
2713 | $access = true; | |
2714 | } else { | |
2715 | //expired | |
2716 | unset($USER->enrol['enrolled'][$course->id]); | |
2717 | } | |
2718 | } | |
2719 | if (isset($USER->enrol['tempguest'][$course->id])) { | |
2720 | if ($USER->enrol['tempguest'][$course->id] == 0) { | |
2721 | $access = true; | |
2722 | } else if ($USER->enrol['tempguest'][$course->id] > time()) { | |
2723 | $access = true; | |
2724 | } else { | |
2725 | //expired | |
2726 | unset($USER->enrol['tempguest'][$course->id]); | |
2727 | $USER->access = remove_temp_roles($coursecontext, $USER->access); | |
2728 | } | |
2729 | } | |
2730 | ||
2731 | if ($access) { | |
2732 | // cache ok | |
2733 | } else if (is_enrolled($coursecontext, $USER, '', true)) { | |
2734 | // active participants may always access | |
2735 | // TODO: refactor this into some new function | |
2736 | $now = time(); | |
2737 | $sql = "SELECT MAX(ue.timeend) | |
2738 | FROM {user_enrolments} ue | |
2739 | JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid) | |
2740 | JOIN {user} u ON u.id = ue.userid | |
2741 | WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0 | |
2742 | AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)"; | |
2743 | $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, | |
2744 | 'userid'=>$USER->id, 'courseid'=>$coursecontext->instanceid, 'now1'=>$now, 'now2'=>$now); | |
2745 | $until = $DB->get_field_sql($sql, $params); | |
2746 | if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) { | |
2747 | $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD; | |
2748 | } | |
2749 | ||
2750 | $USER->enrol['enrolled'][$course->id] = $until; | |
2751 | $access = true; | |
2752 | ||
2753 | // remove traces of previous temp guest access | |
2754 | $USER->access = remove_temp_roles($coursecontext, $USER->access); | |
2755 | ||
2756 | } else { | |
2757 | $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC'); | |
2758 | $enrols = enrol_get_plugins(true); | |
2759 | // first ask all enabled enrol instances in course if they want to auto enrol user | |
2760 | foreach($instances as $instance) { | |
2761 | if (!isset($enrols[$instance->enrol])) { | |
2762 | continue; | |
2763 | } | |
ed1d72ea | 2764 | // Get a duration for the guestaccess, a timestamp in the future or false. |
df997f84 PS |
2765 | $until = $enrols[$instance->enrol]->try_autoenrol($instance); |
2766 | if ($until !== false) { | |
2767 | $USER->enrol['enrolled'][$course->id] = $until; | |
2768 | $USER->access = remove_temp_roles($coursecontext, $USER->access); | |
2769 | $access = true; | |
2770 | break; | |
2771 | } | |
2772 | } | |
2773 | // if not enrolled yet try to gain temporary guest access | |
2774 | if (!$access) { | |
2775 | foreach($instances as $instance) { | |
2776 | if (!isset($enrols[$instance->enrol])) { | |
2777 | continue; | |
2778 | } | |
ed1d72ea | 2779 | // Get a duration for the guestaccess, a timestamp in the future or false. |
df997f84 PS |
2780 | $until = $enrols[$instance->enrol]->try_guestaccess($instance); |
2781 | if ($until !== false) { | |
2782 | $USER->enrol['tempguest'][$course->id] = $until; | |
2783 | $access = true; | |
2784 | break; | |
2785 | } | |
2786 | } | |
2787 | } | |
2788 | } | |
2789 | } | |
2790 | ||
2791 | if (!$access) { | |
2792 | if ($preventredirect) { | |
2793 | throw new require_login_exception('Not enrolled'); | |
2794 | } | |
2795 | $SESSION->wantsurl = $FULLME; | |
2796 | redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id); | |
2797 | } | |
2798 | } | |
2799 | ||
0d8b6a69 | 2800 | // Check visibility of activity to current user; includes visible flag, groupmembersonly, |
2801 | // conditional availability, etc | |
2802 | if ($cm && !$cm->uservisible) { | |
df997f84 PS |
2803 | if ($preventredirect) { |
2804 | throw new require_login_exception('Activity is hidden'); | |
2805 | } | |
2806 | redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden')); | |
2807 | } | |
2808 | ||
df997f84 PS |
2809 | // Finally access granted, update lastaccess times |
2810 | user_accesstime_log($course->id); | |
f9903ed0 | 2811 | } |
2812 | ||
c4d0753b | 2813 | |
c4d0753b | 2814 | /** |
2815 | * This function just makes sure a user is logged out. | |
2816 | * | |
0d0a8bf6 | 2817 | * @global object |
c4d0753b | 2818 | */ |
2819 | function require_logout() { | |
dd9e22f8 | 2820 | global $USER; |
c4d0753b | 2821 | |
a8e3b008 DC |
2822 | $params = $USER; |
2823 | ||
111e2360 | 2824 | if (isloggedin()) { |
c4d0753b | 2825 | add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id); |
2826 | ||
533f7910 | 2827 | $authsequence = get_enabled_auth_plugins(); // auths, in sequence |
2828 | foreach($authsequence as $authname) { | |
2829 | $authplugin = get_auth_plugin($authname); | |
2830 | $authplugin->prelogout_hook(); | |
81693ac7 | 2831 | } |
c4d0753b | 2832 | } |
2833 | ||
a8e3b008 | 2834 | events_trigger('user_logout', $params); |
56949c17 | 2835 | session_get_instance()->terminate_current(); |
a8e3b008 | 2836 | unset($params); |
c4d0753b | 2837 | } |
2838 | ||
7cf1c7bd | 2839 | /** |
0d0a8bf6 | 2840 | * Weaker version of require_login() |
2841 | * | |
7cf1c7bd | 2842 | * This is a weaker version of {@link require_login()} which only requires login |
2843 | * when called from within a course rather than the site page, unless | |
2844 | * the forcelogin option is turned on. | |
0d0a8bf6 | 2845 | * @see require_login() |
7cf1c7bd | 2846 | * |
0d0a8bf6 | 2847 | * @global object |
33ebaf7c | 2848 | * @param mixed $courseorid The course object or id in question |
bbd3f2c4 | 2849 | * @param bool $autologinguest Allow autologin guests if that is wanted |
4febb58f | 2850 | * @param object $cm Course activity module if known |
f4013c10 | 2851 | * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to |
2852 | * true. Used to avoid (=false) some scripts (file.php...) to set that variable, | |
2853 | * in order to keep redirects working properly. MDL-14495 | |
df997f84 PS |
2854 | * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions |
2855 | * @return void | |
7cf1c7bd | 2856 | */ |
df997f84 | 2857 | function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) { |
862940c0 | 2858 | global $CFG, $PAGE, $SITE; |
0d8b6a69 | 2859 | $issite = (is_object($courseorid) and $courseorid->id == SITEID) |
2860 | or (!is_object($courseorid) and $courseorid == SITEID); | |
d4fb0e26 | 2861 | if ($issite && !empty($cm) && !($cm instanceof cm_info)) { |
0d8b6a69 | 2862 | // note: nearly all pages call get_fast_modinfo anyway and it does not make any |
2863 | // db queries so this is not really a performance concern, however it is obviously | |
2864 | // better if you use get_fast_modinfo to get the cm before calling this. | |
2865 | if (is_object($courseorid)) { | |
2866 | $course = $courseorid; | |
2867 | } else { | |
2868 | $course = clone($SITE); | |
2869 | } | |
2870 | $modinfo = get_fast_modinfo($course); | |
2871 | $cm = $modinfo->get_cm($cm->id); | |
2872 | } | |
1596edff | 2873 | if (!empty($CFG->forcelogin)) { |
33ebaf7c | 2874 | // login required for both SITE and courses |
df997f84 | 2875 | require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect); |
63c9ee99 | 2876 | |
0d8b6a69 | 2877 | } else if ($issite && !empty($cm) and !$cm->uservisible) { |
63c9ee99 | 2878 | // always login for hidden activities |
df997f84 | 2879 | require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect); |
63c9ee99 | 2880 | |
0d8b6a69 | 2881 | } else if ($issite) { |
9950c88f | 2882 | //login for SITE not required |
2883 | if ($cm and empty($cm->visible)) { | |
2884 | // hidden activities are not accessible without login | |
df997f84 | 2885 | require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect); |
98da6021 | 2886 | } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) { |
9950c88f | 2887 | // not-logged-in users do not have any group membership |
df997f84 | 2888 | require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect); |
9950c88f | 2889 | } else { |
862940c0 SH |
2890 | // We still need to instatiate PAGE vars properly so that things |
2891 | // that rely on it like navigation function correctly. | |
2892 | if (!empty($courseorid)) { | |
2893 | if (is_object($courseorid)) { | |
2894 | $course = $courseorid; | |
2895 | } else { | |
2896 | $course = clone($SITE); | |
2897 | } | |
2898 | if ($cm) { | |
df997f84 PS |
2899 | if ($cm->course != $course->id) { |
2900 | throw new coding_exception('course and cm parameters in require_course_login() call do not match!!'); | |
2901 | } | |
862940c0 | 2902 | $PAGE->set_cm($cm, $course); |
191b267b | 2903 | $PAGE->set_pagelayout('incourse'); |
862940c0 SH |
2904 | } else { |
2905 | $PAGE->set_course($course); | |
2906 | } | |
2907 | } else { | |
2908 | // If $PAGE->course, and hence $PAGE->context, have not already been set | |
2909 | // up properly, set them up now. | |
2910 | $PAGE->set_course($PAGE->course); | |
2911 | } | |
9950c88f | 2912 | //TODO: verify conditional activities here |
2913 | user_accesstime_log(SITEID); | |
2914 | return; | |
2915 | } | |
63c9ee99 | 2916 | |
33ebaf7c | 2917 | } else { |
2918 | // course login always required | |
df997f84 | 2919 | require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect); |
f950af3c | 2920 | } |
2921 | } | |
2922 | ||
61c6071f | 2923 | /** |
2924 | * Require key login. Function terminates with error if key not found or incorrect. | |
0d0a8bf6 | 2925 | * |
2926 | * @global object | |
2927 | * @global object | |
2928 | * @global object | |
2929 | * @global object | |
2930 | * @uses NO_MOODLE_COOKIES | |
2931 | * @uses PARAM_ALPHANUM | |
61c6071f | 2932 | * @param string $script unique script identifier |
2933 | * @param int $instance optional instance id | |
0d0a8bf6 | 2934 | * @return int Instance ID |
61c6071f | 2935 | */ |
2936 | function require_user_key_login($script, $instance=null) { | |
82dd4f42 | 2937 | global $USER, $SESSION, $CFG, $DB; |
61c6071f | 2938 | |
82dd4f42 | 2939 | if (!NO_MOODLE_COOKIES) { |
2f137aa1 | 2940 | print_error('sessioncookiesdisable'); |
61c6071f | 2941 | } |
2942 | ||
2943 | /// extra safety | |
2944 | @session_write_close(); | |
2945 | ||
2946 | $keyvalue = required_param('key', PARAM_ALPHANUM); | |
2947 | ||
ae040d4b | 2948 | if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) { |
2f137aa1 | 2949 | print_error('invalidkey'); |
61c6071f | 2950 | } |
2951 | ||
2952 | if (!empty($key->validuntil) and $key->validuntil < time()) { | |
2f137aa1 | 2953 | print_error('expiredkey'); |
61c6071f | 2954 | } |
2955 | ||
e436033f | 2956 | if ($key->iprestriction) { |
765a1d4b MD |
2957 | $remoteaddr = getremoteaddr(null); |
2958 | if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) { | |
2f137aa1 | 2959 | print_error('ipmismatch'); |
e436033f | 2960 | } |
61c6071f | 2961 | } |
2962 | ||
ae040d4b | 2963 | if (!$user = $DB->get_record('user', array('id'=>$key->userid))) { |
2f137aa1 | 2964 | print_error('invaliduserid'); |
61c6071f | 2965 | } |
2966 | ||
2967 | /// emulate normal session | |
27df7ae8 | 2968 | session_set_user($user); |
61c6071f | 2969 | |
e2fa911b | 2970 | /// note we are not using normal login |
2971 | if (!defined('USER_KEY_LOGIN')) { | |
2972 | define('USER_KEY_LOGIN', true); | |
2973 | } | |
2974 | ||
792881f0 | 2975 | /// return instance id - it might be empty |
61c6071f | 2976 | return $key->instance; |
2977 | } | |
2978 | ||
2979 | /** | |
2980 | * Creates a new private user access key. | |
0d0a8bf6 | 2981 | * |
2982 | * @global object | |
61c6071f | 2983 | * @param string $script unique target identifier |
2984 | * @param int $userid | |
0d0a8bf6 | 2985 | * @param int $instance optional instance id |
61c6071f | 2986 | * @param string $iprestriction optional ip restricted access |
2987 | * @param timestamp $validuntil key valid only until given data | |
2988 | * @return string access key value | |
2989 | */ | |
2990 | function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) { | |
ae040d4b | 2991 | global $DB; |
2992 | ||
365a5941 | 2993 | $key = new stdClass(); |
61c6071f | 2994 | $key->script = $script; |
2995 | $key->userid = $userid; | |
2996 | $key->instance = $instance; | |
2997 | $key->iprestriction = $iprestriction; | |
2998 | $key->validuntil = $validuntil; | |
2999 | $key->timecreated = time(); | |
3000 | ||
3001 | $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique | |
ae040d4b | 3002 | while ($DB->record_exists('user_private_key', array('value'=>$key->value))) { |
61c6071f | 3003 | // must be unique |
3004 | $key->value = md5($userid.'_'.time().random_string(40)); | |
3005 | } | |
a8d6ef8c | 3006 | $DB->insert_record('user_private_key', $key); |
61c6071f | 3007 | return $key->value; |
3008 | } | |
3009 | ||
ffa3bfb3 AD |
3010 | /** |
3011 | * Delete the user's new private user access keys for a particular script. | |
3012 | * | |
3013 | * @global object | |
3014 | * @param string $script unique target identifier | |
3015 | * @param int $userid | |
3016 | * @return void | |
3017 | */ | |
3018 | function delete_user_key($script,$userid) { | |
3019 | global $DB; | |
3020 | $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid)); | |
3021 | } | |
3022 | ||
fe67f492 MD |
3023 | /** |
3024 | * Gets a private user access key (and creates one if one doesn't exist). | |
3025 | * | |
3026 | * @global object | |
3027 | * @param string $script unique target identifier | |
3028 | * @param int $userid | |
3029 | * @param int $instance optional instance id | |
3030 | * @param string $iprestriction optional ip restricted access | |
3031 | * @param timestamp $validuntil key valid only until given data | |
3032 | * @return string access key value | |
3033 | */ | |
3034 | function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) { | |
3035 | global $DB; | |
3036 | ||
6b8ad965 PS |
3037 | if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid, |
3038 | 'instance'=>$instance, 'iprestriction'=>$iprestriction, | |
fe67f492 MD |
3039 | 'validuntil'=>$validuntil))) { |
3040 | return $key->value; | |
3041 | } else { | |
3042 | return create_user_key($script, $userid, $instance, $iprestriction, $validuntil); | |
3043 | } | |
3044 | } | |
3045 | ||
3046 | ||
7cf1c7bd | 3047 | /** |
3048 | * Modify the user table by setting the currently logged in user's | |
3049 | * last login to now. | |
3050 | * | |
0d0a8bf6 | 3051 | * @global object |
3052 | * @global object | |
3053 | * @return bool Always returns true | |
7cf1c7bd | 3054 | */ |
1d881d92 | 3055 | function update_user_login_times() { |
ae040d4b | 3056 | global $USER, $DB; |
1d881d92 | 3057 | |
365a5941 | 3058 | $user = new stdClass(); |
1d881d92 | 3059 | $USER->lastlogin = $user->lastlogin = $USER->currentlogin; |
2a2f5f11 | 3060 | $USER->currentlogin = $user->lastaccess = $user->currentlogin = time(); |
1d881d92 | 3061 | |
3062 | $user->id = $USER->id; | |
3063 | ||
013376de | 3064 | $DB->update_record('user', $user); |
3065 | return true; | |
1d881d92 | 3066 | } |
3067 | ||
7cf1c7bd | 3068 | /** |
3069 | * Determines if a user has completed setting up their account. | |
3070 | * | |
efb8c375 | 3071 | * @param user $user A {@link $USER} object to test for the existence of a valid name and email |
bbd3f2c4 | 3072 | * @return bool |
7cf1c7bd | 3073 | */ |
808a3baa | 3074 | function user_not_fully_set_up($user) { |
999b54af PS |
3075 | if (isguestuser($user)) { |
3076 | return false; | |
3077 | } | |
3078 | return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)); | |
bb64b51a | 3079 | } |
3080 | ||
0d0a8bf6 | 3081 | /** |
3082 | * Check whether the user has exceeded the bounce threshold | |
3083 | * | |
3084 | * @global object | |
3085 | * @global object | |
3086 | * @param user $user A {@link $USER} object | |
3087 | * @return bool true=>User has exceeded bounce threshold | |
3088 | */ | |
bb64b51a | 3089 | function over_bounce_threshold($user) { |
ae040d4b | 3090 | global $CFG, $DB; |
d2a9f7cc | 3091 | |
bb64b51a | 3092 | if (empty($CFG->handlebounces)) { |
3093 | return false; | |
3094 | } | |
e0ec2d45 | 3095 | |
3096 | if (empty($user->id)) { /// No real (DB) user, nothing to do here. | |
3097 | return false; | |
3098 | } | |
3099 | ||
bb64b51a | 3100 | // set sensible defaults |
3101 | if (empty($CFG->minbounces)) { | |
3102 | $CFG->minbounces = 10; | |
3103 | } | |
3104 | if (empty($CFG->bounceratio)) { | |
3105 | $CFG->bounceratio = .20; | |
3106 | } | |
3107 | $bouncecount = 0; | |
3108 | $sendcount = 0; | |
ae040d4b | 3109 | if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) { |
bb64b51a | 3110 | $bouncecount = $bounce->value; |
3111 | } | |
ae040d4b | 3112 | if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) { |
bb64b51a | 3113 | $sendcount = $send->value; |
3114 | } | |
3115 | return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio); | |
3116 | } | |
3117 | ||
d2a9f7cc | 3118 | /** |
6759ad2f | 3119 | * Used to increment or reset email sent count |
0d0a8bf6 | 3120 | * |
3121 | * @global object | |
3122 | * @param user $user object containing an id | |
3123 | * @param bool $reset will reset the count to 0 | |
3124 | * @return void | |
bb64b51a | 3125 | */ |
3126 | function set_send_count($user,$reset=false) { | |
ae040d4b | 3127 | global $DB; |
3128 | ||
e0ec2d45 | 3129 | if (empty($user->id)) { /// No real (DB) user, nothing to do here. |
3130 | return; | |
3131 | } | |
3132 | ||
ae040d4b | 3133 | if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) { |
bb64b51a | 3134 | $pref->value = (!empty($reset)) ? 0 : $pref->value+1; |
ae040d4b | 3135 | $DB->update_record('user_preferences', $pref); |
bb64b51a | 3136 | } |
3137 | else if (!empty($reset)) { // if it's not there and we're resetting, don't bother. | |
3138 | // make a new one | |
365a5941 | 3139 | $pref = new stdClass(); |
ae040d4b | 3140 | $pref->name = 'email_send_count'; |
3141 | $pref->value = 1; | |
bb64b51a | 3142 | $pref->userid = $user->id; |
ae040d4b | 3143 | $DB->insert_record('user_preferences', $pref, false); |
bb64b51a | 3144 | } |
3145 | } | |
3146 | ||
d2a9f7cc | 3147 | /** |
6759ad2f | 3148 | * Increment or reset user's email bounce count |
0d0a8bf6 | 3149 | * |
3150 | * @global object | |
3151 | * @param user $user object containing an id | |
3152 | * @param bool $reset will reset the count to 0 | |
bb64b51a | 3153 | */ |
3154 | function set_bounce_count($user,$reset=false) { | |
ae040d4b | 3155 | global $DB; |
3156 | ||
3157 | if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) { | |
bb64b51a | 3158 | $pref->value = (!empty($reset)) ? 0 : $pref->value+1; |
ae040d4b | 3159 | $DB->update_record('user_preferences', $pref); |
bb64b51a | 3160 | } |
3161 | else if (!empty($reset)) { // if it's not there and we're resetting, don't bother. | |
3162 | // make a new one | |
365a5941 | 3163 | $pref = new stdClass(); |
ae040d4b | 3164 | $pref->name = 'email_bounce_count'; |
3165 | $pref->value = 1; | |
bb64b51a | 3166 | $pref->userid = $user->id; |
ae040d4b | 3167 | $DB->insert_record('user_preferences', $pref, false); |
bb64b51a | 3168 | } |
808a3baa | 3169 | } |
f9903ed0 | 3170 | |
7cf1c7bd | 3171 | /** |
3172 | * Keeps track of login attempts | |
3173 | * | |
0d0a8bf6 | 3174 | * @global object |
7cf1c7bd | 3175 | */ |
f9903ed0 | 3176 | function update_login_count() { |
3177 | global $SESSION; | |
3178 | ||
3179 | $max_logins = 10; | |
3180 | ||
3181 | if (empty($SESSION->log |