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