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