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