2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
22 * Unit tests for (some of) ../moodlelib.php.
26 * @copyright © 2006 The Open University
27 * @author T.J.Hunt@open.ac.uk
28 * @author nicolas@moodle.com
30 class moodlelib_test
extends \advanced_testcase
{
33 * Define a local decimal separator.
35 * It is not possible to directly change the result of get_string in
36 * a unit test. Instead, we create a language pack for language 'xx' in
37 * dataroot and make langconfig.php with the string we need to change.
38 * The default example separator used here is 'X'; on PHP 5.3 and before this
39 * must be a single byte character due to PHP bug/limitation in
40 * number_format, so you can't use UTF-8 characters.
42 * @param string $decsep Separator character. Defaults to `'X'`.
44 protected function define_local_decimal_separator(string $decsep = 'X') {
45 global $SESSION, $CFG;
47 $SESSION->lang
= 'xx';
48 $langconfig = "<?php\n\$string['decsep'] = '$decsep';";
49 $langfolder = $CFG->dataroot
. '/lang/xx';
50 check_dir_exists($langfolder);
51 file_put_contents($langfolder . '/langconfig.php', $langconfig);
53 // Ensure the new value is picked up and not taken from the cache.
54 $stringmanager = get_string_manager();
55 $stringmanager->reset_caches(true);
58 public function test_cleanremoteaddr() {
60 $this->assertNull(cleanremoteaddr('1023.121.234.1'));
61 $this->assertSame('123.121.234.1', cleanremoteaddr('123.121.234.01 '));
64 $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:0:0'));
65 $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:abh'));
66 $this->assertNull(cleanremoteaddr('0:0:0:::0:0:1'));
67 $this->assertSame('::', cleanremoteaddr('0:0:0:0:0:0:0:0', true));
68 $this->assertSame('::1:1', cleanremoteaddr('0:0:0:0:0:0:1:1', true));
69 $this->assertSame('abcd:ef::', cleanremoteaddr('abcd:00ef:0:0:0:0:0:0', true));
70 $this->assertSame('1::1', cleanremoteaddr('1:0:0:0:0:0:0:1', true));
71 $this->assertSame('0:0:0:0:0:0:10:1', cleanremoteaddr('::10:1', false));
72 $this->assertSame('1:1:0:0:0:0:0:0', cleanremoteaddr('01:1::', false));
73 $this->assertSame('10:0:0:0:0:0:0:10', cleanremoteaddr('10::10', false));
74 $this->assertSame('::ffff:c0a8:11', cleanremoteaddr('::ffff:192.168.1.1', true));
77 public function test_address_in_subnet() {
78 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask).
79 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.1/32'));
80 $this->assertFalse(address_in_subnet('123.121.23.1', '123.121.23.0/32'));
81 $this->assertTrue(address_in_subnet('10.10.10.100', '123.121.23.45/0'));
82 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/24'));
83 $this->assertFalse(address_in_subnet('123.121.34.1', '123.121.234.0/24'));
84 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/30'));
85 $this->assertFalse(address_in_subnet('123.121.23.8', '123.121.23.0/30'));
86 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
87 $this->assertFalse(address_in_subnet('bab:baba::baba', 'bab:baba::cece/128'));
88 $this->assertTrue(address_in_subnet('baba:baba::baba', 'cece:cece::cece/0'));
89 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
90 $this->assertTrue(address_in_subnet('baba:baba::00ba', 'baba:baba::/120'));
91 $this->assertFalse(address_in_subnet('baba:baba::aba', 'baba:baba::/120'));
92 $this->assertTrue(address_in_subnet('baba::baba:00ba', 'baba::baba:0/112'));
93 $this->assertFalse(address_in_subnet('baba::aba:00ba', 'baba::baba:0/112'));
94 $this->assertFalse(address_in_subnet('aba::baba:0000', 'baba::baba:0/112'));
97 $this->assertTrue(address_in_subnet('123.121.23.1 ', ' 123.121.23.0 / 24'));
98 $this->assertTrue(address_in_subnet('::ffff:10.1.1.1', ' 0:0:0:000:0:ffff:a1:10 / 126'));
101 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/-2'));
102 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/64'));
103 $this->assertFalse(address_in_subnet('123.121.234.x', '123.121.234.1/24'));
104 $this->assertFalse(address_in_subnet('123.121.234.0', '123.121.234.xx/24'));
105 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/xx0'));
106 $this->assertFalse(address_in_subnet('::1', '::aa:0/xx0'));
107 $this->assertFalse(address_in_subnet('::1', '::aa:0/-5'));
108 $this->assertFalse(address_in_subnet('::1', '::aa:0/130'));
109 $this->assertFalse(address_in_subnet('x:1', '::aa:0/130'));
110 $this->assertFalse(address_in_subnet('::1', '::ax:0/130'));
112 // 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy (a range of IP addresses in the last group).
113 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12-14'));
114 $this->assertTrue(address_in_subnet('123.121.234.13', '123.121.234.12-14'));
115 $this->assertTrue(address_in_subnet('123.121.234.14', '123.121.234.12-14'));
116 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.12-14'));
117 $this->assertFalse(address_in_subnet('123.121.234.20', '123.121.234.12-14'));
118 $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.234.12-14'));
119 $this->assertFalse(address_in_subnet('123.12.234.12', '123.121.234.12-14'));
120 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba-babe'));
121 $this->assertTrue(address_in_subnet('baba:baba::babc', 'baba:baba::baba-babe'));
122 $this->assertTrue(address_in_subnet('baba:baba::babe', 'baba:baba::baba-babe'));
123 $this->assertFalse(address_in_subnet('bab:baba::bab0', 'bab:baba::baba-babe'));
124 $this->assertFalse(address_in_subnet('bab:baba::babf', 'bab:baba::baba-babe'));
125 $this->assertFalse(address_in_subnet('bab:baba::bfbe', 'bab:baba::baba-babe'));
126 $this->assertFalse(address_in_subnet('bfb:baba::babe', 'bab:baba::baba-babe'));
129 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12 - 14 '));
130 $this->assertTrue(address_in_subnet('bab:baba::babe', 'bab:baba::baba - babe '));
133 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-234.14'));
134 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-256'));
135 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12--256'));
137 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-).
138 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12'));
139 $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.23.13'));
140 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.'));
141 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234'));
142 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121'));
143 $this->assertTrue(address_in_subnet('123.121.234.12', '123'));
144 $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234.'));
145 $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234'));
146 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba::bab'));
147 $this->assertFalse(address_in_subnet('baba:baba::ba', 'baba:baba::bc'));
148 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba'));
149 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:'));
150 $this->assertFalse(address_in_subnet('bab:baba::bab', 'baba:'));
153 $this->assertTrue(address_in_subnet('123.121.234.12', '::1/64, 124., 123.121.234.10-30'));
154 $this->assertTrue(address_in_subnet('124.121.234.12', '::1/64, 124., 123.121.234.10-30'));
155 $this->assertTrue(address_in_subnet('::2', '::1/64, 124., 123.121.234.10-30'));
156 $this->assertFalse(address_in_subnet('12.121.234.12', '::1/64, 124., 123.121.234.10-30'));
158 // Other incorrect input.
159 $this->assertFalse(address_in_subnet('123.123.123.123', ''));
162 public function test_fix_utf8() {
163 // Make sure valid data including other types is not changed.
164 $this->assertSame(null, fix_utf8(null));
165 $this->assertSame(1, fix_utf8(1));
166 $this->assertSame(1.1, fix_utf8(1.1));
167 $this->assertSame(true, fix_utf8(true));
168 $this->assertSame('', fix_utf8(''));
169 $this->assertSame('abc', fix_utf8('abc'));
170 $array = array('do', 're', 'mi');
171 $this->assertSame($array, fix_utf8($array));
172 $object = new \
stdClass();
175 $this->assertEquals($object, fix_utf8($object));
178 $this->assertSame("žlutý koníček přeskočil potůček \n\t\r", fix_utf8("žlutý koníček přeskočil potůček \n\t\r\0"));
180 // Invalid utf8 string.
181 $this->assertSame('aš', fix_utf8('a'.chr(130).'š'), 'This fails with buggy iconv() when mbstring extenstion is not available as fallback.');
182 $this->assertSame('Hello ', fix_utf8('Hello '));
185 public function test_optional_param() {
188 $_POST['username'] = 'post_user';
189 $_GET['username'] = 'get_user';
190 $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW
));
192 unset($_POST['username']);
193 $this->assertSame($_GET['username'], optional_param('username', 'default_user', PARAM_RAW
));
195 unset($_GET['username']);
196 $this->assertSame('default_user', optional_param('username', 'default_user', PARAM_RAW
));
198 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
199 $_POST['username'] = 'post_user';
201 optional_param('username', 'default_user', null);
202 $this->fail('coding_exception expected');
203 } catch (\moodle_exception
$ex) {
204 $this->assertInstanceOf('coding_exception', $ex);
207 @optional_param
('username', 'default_user');
208 $this->fail('coding_exception expected');
209 } catch (\moodle_exception
$ex) {
210 $this->assertInstanceOf('coding_exception', $ex);
211 } catch (\Error
$error) {
212 // PHP 7.1 throws \Error even earlier.
213 $this->assertMatchesRegularExpression('/Too few arguments to function/', $error->getMessage());
216 @optional_param
('username');
217 $this->fail('coding_exception expected');
218 } catch (\moodle_exception
$ex) {
219 $this->assertInstanceOf('coding_exception', $ex);
220 } catch (\Error
$error) {
221 // PHP 7.1 throws \Error even earlier.
222 $this->assertMatchesRegularExpression('/Too few arguments to function/', $error->getMessage());
225 optional_param('', 'default_user', PARAM_RAW
);
226 $this->fail('coding_exception expected');
227 } catch (\moodle_exception
$ex) {
228 $this->assertInstanceOf('coding_exception', $ex);
231 // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
232 $_POST['username'] = array('a'=>'a');
233 $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW
));
234 $this->assertDebuggingCalled();
237 public function test_optional_param_array() {
240 $_POST['username'] = array('a'=>'post_user');
241 $_GET['username'] = array('a'=>'get_user');
242 $this->assertSame($_POST['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW
));
244 unset($_POST['username']);
245 $this->assertSame($_GET['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW
));
247 unset($_GET['username']);
248 $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW
));
250 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
251 $_POST['username'] = array('a'=>'post_user');
253 optional_param_array('username', array('a'=>'default_user'), null);
254 $this->fail('coding_exception expected');
255 } catch (\moodle_exception
$ex) {
256 $this->assertInstanceOf('coding_exception', $ex);
259 @optional_param_array
('username', array('a'=>'default_user'));
260 $this->fail('coding_exception expected');
261 } catch (\moodle_exception
$ex) {
262 $this->assertInstanceOf('coding_exception', $ex);
263 } catch (\Error
$error) {
264 // PHP 7.1 throws \Error even earlier.
265 $this->assertMatchesRegularExpression('/Too few arguments to function/', $error->getMessage());
268 @optional_param_array
('username');
269 $this->fail('coding_exception expected');
270 } catch (\moodle_exception
$ex) {
271 $this->assertInstanceOf('coding_exception', $ex);
272 } catch (\Error
$error) {
273 // PHP 7.1 throws \Error even earlier.
274 $this->assertMatchesRegularExpression('/Too few arguments to function/', $error->getMessage());
277 optional_param_array('', array('a'=>'default_user'), PARAM_RAW
);
278 $this->fail('coding_exception expected');
279 } catch (\moodle_exception
$ex) {
280 $this->assertInstanceOf('coding_exception', $ex);
283 // Do not allow nested arrays.
285 $_POST['username'] = array('a'=>array('b'=>'post_user'));
286 optional_param_array('username', array('a'=>'default_user'), PARAM_RAW
);
287 $this->fail('coding_exception expected');
288 } catch (\coding_exception
$ex) {
289 $this->assertTrue(true);
292 // Do not allow non-arrays.
293 $_POST['username'] = 'post_user';
294 $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW
));
295 $this->assertDebuggingCalled();
297 // Make sure array keys are sanitised.
298 $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
299 $this->assertSame(array('a1_-'=>'post_user'), optional_param_array('username', array(), PARAM_RAW
));
300 $this->assertDebuggingCalled();
303 public function test_required_param() {
304 $_POST['username'] = 'post_user';
305 $_GET['username'] = 'get_user';
306 $this->assertSame('post_user', required_param('username', PARAM_RAW
));
308 unset($_POST['username']);
309 $this->assertSame('get_user', required_param('username', PARAM_RAW
));
311 unset($_GET['username']);
313 $this->assertSame('default_user', required_param('username', PARAM_RAW
));
314 $this->fail('moodle_exception expected');
315 } catch (\moodle_exception
$ex) {
316 $this->assertInstanceOf('moodle_exception', $ex);
319 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
320 $_POST['username'] = 'post_user';
322 @required_param
('username');
323 $this->fail('coding_exception expected');
324 } catch (\moodle_exception
$ex) {
325 $this->assertInstanceOf('coding_exception', $ex);
326 } catch (\Error
$error) {
327 // PHP 7.1 throws \Error even earlier.
328 $this->assertMatchesRegularExpression('/Too few arguments to function/', $error->getMessage());
331 required_param('username', '');
332 $this->fail('coding_exception expected');
333 } catch (\moodle_exception
$ex) {
334 $this->assertInstanceOf('coding_exception', $ex);
337 required_param('', PARAM_RAW
);
338 $this->fail('coding_exception expected');
339 } catch (\moodle_exception
$ex) {
340 $this->assertInstanceOf('coding_exception', $ex);
343 // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
344 $_POST['username'] = array('a'=>'a');
345 $this->assertSame($_POST['username'], required_param('username', PARAM_RAW
));
346 $this->assertDebuggingCalled();
349 public function test_required_param_array() {
352 $_POST['username'] = array('a'=>'post_user');
353 $_GET['username'] = array('a'=>'get_user');
354 $this->assertSame($_POST['username'], required_param_array('username', PARAM_RAW
));
356 unset($_POST['username']);
357 $this->assertSame($_GET['username'], required_param_array('username', PARAM_RAW
));
359 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
360 $_POST['username'] = array('a'=>'post_user');
362 required_param_array('username', null);
363 $this->fail('coding_exception expected');
364 } catch (\moodle_exception
$ex) {
365 $this->assertInstanceOf('coding_exception', $ex);
368 @required_param_array
('username');
369 $this->fail('coding_exception expected');
370 } catch (\moodle_exception
$ex) {
371 $this->assertInstanceOf('coding_exception', $ex);
372 } catch (\Error
$error) {
373 // PHP 7.1 throws \Error.
374 $this->assertMatchesRegularExpression('/Too few arguments to function/', $error->getMessage());
377 required_param_array('', PARAM_RAW
);
378 $this->fail('coding_exception expected');
379 } catch (\moodle_exception
$ex) {
380 $this->assertInstanceOf('coding_exception', $ex);
383 // Do not allow nested arrays.
385 $_POST['username'] = array('a'=>array('b'=>'post_user'));
386 required_param_array('username', PARAM_RAW
);
387 $this->fail('coding_exception expected');
388 } catch (\moodle_exception
$ex) {
389 $this->assertInstanceOf('coding_exception', $ex);
392 // Do not allow non-arrays.
394 $_POST['username'] = 'post_user';
395 required_param_array('username', PARAM_RAW
);
396 $this->fail('moodle_exception expected');
397 } catch (\moodle_exception
$ex) {
398 $this->assertInstanceOf('moodle_exception', $ex);
401 // Make sure array keys are sanitised.
402 $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
403 $this->assertSame(array('a1_-'=>'post_user'), required_param_array('username', PARAM_RAW
));
404 $this->assertDebuggingCalled();
407 public function test_clean_param() {
408 // Forbid objects and arrays.
410 clean_param(array('x', 'y'), PARAM_RAW
);
411 $this->fail('coding_exception expected');
412 } catch (\moodle_exception
$ex) {
413 $this->assertInstanceOf('coding_exception', $ex);
416 $param = new \
stdClass();
418 clean_param($param, PARAM_RAW
);
419 $this->fail('coding_exception expected');
420 } catch (\moodle_exception
$ex) {
421 $this->assertInstanceOf('coding_exception', $ex);
424 // Require correct type.
426 clean_param('x', 'xxxxxx');
427 $this->fail('moodle_exception expected');
428 } catch (\moodle_exception
$ex) {
429 $this->assertInstanceOf('moodle_exception', $ex);
433 $this->fail('moodle_exception expected');
434 } catch (\moodle_exception
$ex) {
435 $this->assertInstanceOf('moodle_exception', $ex);
436 } catch (\Error
$error) {
437 // PHP 7.1 throws \Error even earlier.
438 $this->assertMatchesRegularExpression('/Too few arguments to function/', $error->getMessage());
442 public function test_clean_param_array() {
443 $this->assertSame(array(), clean_param_array(null, PARAM_RAW
));
444 $this->assertSame(array('a', 'b'), clean_param_array(array('a', 'b'), PARAM_RAW
));
445 $this->assertSame(array('a', array('b')), clean_param_array(array('a', array('b')), PARAM_RAW
, true));
447 // Require correct type.
449 clean_param_array(array('x'), 'xxxxxx');
450 $this->fail('moodle_exception expected');
451 } catch (\moodle_exception
$ex) {
452 $this->assertInstanceOf('moodle_exception', $ex);
455 @clean_param_array
(array('x'));
456 $this->fail('moodle_exception expected');
457 } catch (\moodle_exception
$ex) {
458 $this->assertInstanceOf('moodle_exception', $ex);
459 } catch (\Error
$error) {
460 // PHP 7.1 throws \Error even earlier.
461 $this->assertMatchesRegularExpression('/Too few arguments to function/', $error->getMessage());
465 clean_param_array(array('x', array('y')), PARAM_RAW
);
466 $this->fail('coding_exception expected');
467 } catch (\moodle_exception
$ex) {
468 $this->assertInstanceOf('coding_exception', $ex);
474 public function test_clean_param_raw() {
476 '#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)',
477 clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_RAW
));
478 $this->assertSame(null, clean_param(null, PARAM_RAW
));
481 public function test_clean_param_trim() {
482 $this->assertSame('Frog toad', clean_param(" Frog toad \r\n ", PARAM_RAW_TRIMMED
));
483 $this->assertSame('', clean_param(null, PARAM_RAW_TRIMMED
));
486 public function test_clean_param_clean() {
487 // PARAM_CLEAN is an ugly hack, do not use in new code (skodak),
488 // instead use more specific type, or submit sothing that can be verified properly.
489 $this->assertSame('xx', clean_param('xx<script>', PARAM_CLEAN
));
490 $this->assertSame('', clean_param(null, PARAM_CLEAN
));
491 $this->assertSame('', clean_param(null, PARAM_CLEANHTML
));
494 public function test_clean_param_alpha() {
495 $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHA
));
496 $this->assertSame('', clean_param(null, PARAM_ALPHA
));
499 public function test_clean_param_alphanum() {
500 $this->assertSame('978942897DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHANUM
));
501 $this->assertSame('', clean_param(null, PARAM_ALPHANUM
));
504 public function test_clean_param_alphaext() {
505 $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHAEXT
));
506 $this->assertSame('', clean_param(null, PARAM_ALPHAEXT
));
509 public function test_clean_param_sequence() {
510 $this->assertSame(',9789,42897', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_SEQUENCE
));
511 $this->assertSame('', clean_param(null, PARAM_SEQUENCE
));
514 public function test_clean_param_component() {
515 // Please note the cleaning of component names is very strict, no guessing here.
516 $this->assertSame('mod_forum', clean_param('mod_forum', PARAM_COMPONENT
));
517 $this->assertSame('block_online_users', clean_param('block_online_users', PARAM_COMPONENT
));
518 $this->assertSame('block_blond_online_users', clean_param('block_blond_online_users', PARAM_COMPONENT
));
519 $this->assertSame('mod_something2', clean_param('mod_something2', PARAM_COMPONENT
));
520 $this->assertSame('forum', clean_param('forum', PARAM_COMPONENT
));
521 $this->assertSame('user', clean_param('user', PARAM_COMPONENT
));
522 $this->assertSame('rating', clean_param('rating', PARAM_COMPONENT
));
523 $this->assertSame('feedback360', clean_param('feedback360', PARAM_COMPONENT
));
524 $this->assertSame('mod_feedback360', clean_param('mod_feedback360', PARAM_COMPONENT
));
525 $this->assertSame('', clean_param('mod_2something', PARAM_COMPONENT
));
526 $this->assertSame('', clean_param('2mod_something', PARAM_COMPONENT
));
527 $this->assertSame('', clean_param('mod_something_xx', PARAM_COMPONENT
));
528 $this->assertSame('', clean_param('auth_something__xx', PARAM_COMPONENT
));
529 $this->assertSame('', clean_param('mod_Something', PARAM_COMPONENT
));
530 $this->assertSame('', clean_param('mod_somethíng', PARAM_COMPONENT
));
531 $this->assertSame('', clean_param('mod__something', PARAM_COMPONENT
));
532 $this->assertSame('', clean_param('auth_xx-yy', PARAM_COMPONENT
));
533 $this->assertSame('', clean_param('_auth_xx', PARAM_COMPONENT
));
534 $this->assertSame('a2uth_xx', clean_param('a2uth_xx', PARAM_COMPONENT
));
535 $this->assertSame('', clean_param('auth_xx_', PARAM_COMPONENT
));
536 $this->assertSame('', clean_param('auth_xx.old', PARAM_COMPONENT
));
537 $this->assertSame('', clean_param('_user', PARAM_COMPONENT
));
538 $this->assertSame('', clean_param('2rating', PARAM_COMPONENT
));
539 $this->assertSame('', clean_param('user_', PARAM_COMPONENT
));
540 $this->assertSame('', clean_param(null, PARAM_COMPONENT
));
543 public function test_clean_param_localisedfloat() {
545 $this->assertSame(0.5, clean_param('0.5', PARAM_LOCALISEDFLOAT
));
546 $this->assertSame(false, clean_param('0X5', PARAM_LOCALISEDFLOAT
));
547 $this->assertSame(0.5, clean_param('.5', PARAM_LOCALISEDFLOAT
));
548 $this->assertSame(false, clean_param('X5', PARAM_LOCALISEDFLOAT
));
549 $this->assertSame(10.5, clean_param('10.5', PARAM_LOCALISEDFLOAT
));
550 $this->assertSame(false, clean_param('10X5', PARAM_LOCALISEDFLOAT
));
551 $this->assertSame(1000.5, clean_param('1 000.5', PARAM_LOCALISEDFLOAT
));
552 $this->assertSame(false, clean_param('1 000X5', PARAM_LOCALISEDFLOAT
));
553 $this->assertSame(false, clean_param('1.000.5', PARAM_LOCALISEDFLOAT
));
554 $this->assertSame(false, clean_param('1X000X5', PARAM_LOCALISEDFLOAT
));
555 $this->assertSame(false, clean_param('nan', PARAM_LOCALISEDFLOAT
));
556 $this->assertSame(false, clean_param('10.6blah', PARAM_LOCALISEDFLOAT
));
557 $this->assertSame(null, clean_param(null, PARAM_LOCALISEDFLOAT
));
559 // Tests with a localised decimal separator.
560 $this->define_local_decimal_separator();
562 $this->assertSame(0.5, clean_param('0.5', PARAM_LOCALISEDFLOAT
));
563 $this->assertSame(0.5, clean_param('0X5', PARAM_LOCALISEDFLOAT
));
564 $this->assertSame(0.5, clean_param('.5', PARAM_LOCALISEDFLOAT
));
565 $this->assertSame(0.5, clean_param('X5', PARAM_LOCALISEDFLOAT
));
566 $this->assertSame(10.5, clean_param('10.5', PARAM_LOCALISEDFLOAT
));
567 $this->assertSame(10.5, clean_param('10X5', PARAM_LOCALISEDFLOAT
));
568 $this->assertSame(1000.5, clean_param('1 000.5', PARAM_LOCALISEDFLOAT
));
569 $this->assertSame(1000.5, clean_param('1 000X5', PARAM_LOCALISEDFLOAT
));
570 $this->assertSame(false, clean_param('1.000.5', PARAM_LOCALISEDFLOAT
));
571 $this->assertSame(false, clean_param('1X000X5', PARAM_LOCALISEDFLOAT
));
572 $this->assertSame(false, clean_param('nan', PARAM_LOCALISEDFLOAT
));
573 $this->assertSame(false, clean_param('10X6blah', PARAM_LOCALISEDFLOAT
));
576 public function test_is_valid_plugin_name() {
577 $this->assertTrue(is_valid_plugin_name('forum'));
578 $this->assertTrue(is_valid_plugin_name('forum2'));
579 $this->assertTrue(is_valid_plugin_name('feedback360'));
580 $this->assertTrue(is_valid_plugin_name('online_users'));
581 $this->assertTrue(is_valid_plugin_name('blond_online_users'));
582 $this->assertFalse(is_valid_plugin_name('online__users'));
583 $this->assertFalse(is_valid_plugin_name('forum '));
584 $this->assertFalse(is_valid_plugin_name('forum.old'));
585 $this->assertFalse(is_valid_plugin_name('xx-yy'));
586 $this->assertFalse(is_valid_plugin_name('2xx'));
587 $this->assertFalse(is_valid_plugin_name('Xx'));
588 $this->assertFalse(is_valid_plugin_name('_xx'));
589 $this->assertFalse(is_valid_plugin_name('xx_'));
592 public function test_clean_param_plugin() {
593 // Please note the cleaning of plugin names is very strict, no guessing here.
594 $this->assertSame('forum', clean_param('forum', PARAM_PLUGIN
));
595 $this->assertSame('forum2', clean_param('forum2', PARAM_PLUGIN
));
596 $this->assertSame('feedback360', clean_param('feedback360', PARAM_PLUGIN
));
597 $this->assertSame('online_users', clean_param('online_users', PARAM_PLUGIN
));
598 $this->assertSame('blond_online_users', clean_param('blond_online_users', PARAM_PLUGIN
));
599 $this->assertSame('', clean_param('online__users', PARAM_PLUGIN
));
600 $this->assertSame('', clean_param('forum ', PARAM_PLUGIN
));
601 $this->assertSame('', clean_param('forum.old', PARAM_PLUGIN
));
602 $this->assertSame('', clean_param('xx-yy', PARAM_PLUGIN
));
603 $this->assertSame('', clean_param('2xx', PARAM_PLUGIN
));
604 $this->assertSame('', clean_param('Xx', PARAM_PLUGIN
));
605 $this->assertSame('', clean_param('_xx', PARAM_PLUGIN
));
606 $this->assertSame('', clean_param('xx_', PARAM_PLUGIN
));
607 $this->assertSame('', clean_param(null, PARAM_PLUGIN
));
610 public function test_clean_param_area() {
611 // Please note the cleaning of area names is very strict, no guessing here.
612 $this->assertSame('something', clean_param('something', PARAM_AREA
));
613 $this->assertSame('something2', clean_param('something2', PARAM_AREA
));
614 $this->assertSame('some_thing', clean_param('some_thing', PARAM_AREA
));
615 $this->assertSame('some_thing_xx', clean_param('some_thing_xx', PARAM_AREA
));
616 $this->assertSame('feedback360', clean_param('feedback360', PARAM_AREA
));
617 $this->assertSame('', clean_param('_something', PARAM_AREA
));
618 $this->assertSame('', clean_param('something_', PARAM_AREA
));
619 $this->assertSame('', clean_param('2something', PARAM_AREA
));
620 $this->assertSame('', clean_param('Something', PARAM_AREA
));
621 $this->assertSame('', clean_param('some-thing', PARAM_AREA
));
622 $this->assertSame('', clean_param('somethííng', PARAM_AREA
));
623 $this->assertSame('', clean_param('something.x', PARAM_AREA
));
624 $this->assertSame('', clean_param(null, PARAM_AREA
));
627 public function test_clean_param_text() {
628 $this->assertSame(PARAM_TEXT
, PARAM_MULTILANG
);
630 $this->assertSame('xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>', clean_param('xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>', PARAM_TEXT
));
631 $this->assertSame('<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>', clean_param('<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>', PARAM_TEXT
));
632 $this->assertSame('xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>', clean_param('xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>', PARAM_TEXT
));
634 $this->assertSame('<span lang="en" class="multilang">aa</span>', clean_param('<span lang="en" class="multilang">aa</span>', PARAM_TEXT
));
635 $this->assertSame('aa', clean_param('<span lang="en" class="nothing" class="multilang">aa</span>', PARAM_TEXT
));
636 $this->assertSame('aa', clean_param('<lang lang="en" class="multilang">aa</lang>', PARAM_TEXT
));
637 $this->assertSame('aa', clean_param('<lang lang="en!!">aa</lang>', PARAM_TEXT
));
638 $this->assertSame('aa', clean_param('<span lang="en==" class="multilang">aa</span>', PARAM_TEXT
));
639 $this->assertSame('abc', clean_param('a<em>b</em>c', PARAM_TEXT
));
640 $this->assertSame('a>c>', clean_param('a><xx >c>', PARAM_TEXT
)); // Standard strip_tags() behaviour.
641 $this->assertSame('a', clean_param('a<b', PARAM_TEXT
));
642 $this->assertSame('a>b', clean_param('a>b', PARAM_TEXT
));
643 $this->assertSame('<lang lang="en">a>a</lang>', clean_param('<lang lang="en">a>a</lang>', PARAM_TEXT
)); // Standard strip_tags() behaviour.
644 $this->assertSame('a', clean_param('<lang lang="en">a<a</lang>', PARAM_TEXT
));
645 $this->assertSame('<lang lang="en">aa</lang>', clean_param('<lang lang="en">a<br>a</lang>', PARAM_TEXT
));
646 $this->assertSame('', clean_param(null, PARAM_TEXT
));
649 public function test_clean_param_url() {
650 // Test PARAM_URL and PARAM_LOCALURL a bit.
652 $this->assertSame('http://google.com/', clean_param('http://google.com/', PARAM_URL
));
653 $this->assertSame('http://some.very.long.and.silly.domain/with/a/path/', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_URL
));
654 $this->assertSame('http://localhost/', clean_param('http://localhost/', PARAM_URL
));
655 $this->assertSame('http://0.255.1.1/numericip.php', clean_param('http://0.255.1.1/numericip.php', PARAM_URL
));
656 $this->assertSame('https://google.com/', clean_param('https://google.com/', PARAM_URL
));
657 $this->assertSame('https://some.very.long.and.silly.domain/with/a/path/', clean_param('https://some.very.long.and.silly.domain/with/a/path/', PARAM_URL
));
658 $this->assertSame('https://localhost/', clean_param('https://localhost/', PARAM_URL
));
659 $this->assertSame('https://0.255.1.1/numericip.php', clean_param('https://0.255.1.1/numericip.php', PARAM_URL
));
660 $this->assertSame('ftp://ftp.debian.org/debian/', clean_param('ftp://ftp.debian.org/debian/', PARAM_URL
));
661 $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_URL
));
663 $this->assertSame('', clean_param('funny:thing', PARAM_URL
));
664 $this->assertSame('', clean_param('http://example.ee/sdsf"f', PARAM_URL
));
665 $this->assertSame('', clean_param('javascript://comment%0Aalert(1)', PARAM_URL
));
666 $this->assertSame('', clean_param('rtmp://example.com/livestream', PARAM_URL
));
667 $this->assertSame('', clean_param('rtmp://example.com/live&foo', PARAM_URL
));
668 $this->assertSame('', clean_param('rtmp://example.com/fms&mp4:path/to/file.mp4', PARAM_URL
));
669 $this->assertSame('', clean_param('mailto:support@moodle.org', PARAM_URL
));
670 $this->assertSame('', clean_param('mailto:support@moodle.org?subject=Hello%20Moodle', PARAM_URL
));
671 $this->assertSame('', clean_param('mailto:support@moodle.org?subject=Hello%20Moodle&cc=feedback@moodle.org', PARAM_URL
));
672 $this->assertSame('', clean_param(null, PARAM_URL
));
675 public function test_clean_param_localurl() {
678 $this->resetAfterTest();
680 // External, invalid.
681 $this->assertSame('', clean_param('funny:thing', PARAM_LOCALURL
));
682 $this->assertSame('', clean_param('http://google.com/', PARAM_LOCALURL
));
683 $this->assertSame('', clean_param('https://google.com/?test=true', PARAM_LOCALURL
));
684 $this->assertSame('', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL
));
687 $this->assertSame(clean_param($CFG->wwwroot
, PARAM_LOCALURL
), $CFG->wwwroot
);
688 $this->assertSame($CFG->wwwroot
. '/with/something?else=true',
689 clean_param($CFG->wwwroot
. '/with/something?else=true', PARAM_LOCALURL
));
692 $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_LOCALURL
));
693 $this->assertSame('course/view.php?id=3', clean_param('course/view.php?id=3', PARAM_LOCALURL
));
695 // Local absolute HTTPS in a non HTTPS site.
696 $CFG->wwwroot
= str_replace('https:', 'http:', $CFG->wwwroot
); // Need to simulate non-https site.
697 $httpsroot = str_replace('http:', 'https:', $CFG->wwwroot
);
698 $this->assertSame('', clean_param($httpsroot, PARAM_LOCALURL
));
699 $this->assertSame('', clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL
));
701 // Local absolute HTTPS in a HTTPS site.
702 $CFG->wwwroot
= str_replace('http:', 'https:', $CFG->wwwroot
);
703 $httpsroot = $CFG->wwwroot
;
704 $this->assertSame($httpsroot, clean_param($httpsroot, PARAM_LOCALURL
));
705 $this->assertSame($httpsroot . '/with/something?else=true',
706 clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL
));
708 // Test open redirects are not possible.
709 $CFG->wwwroot
= 'http://www.example.com';
710 $this->assertSame('', clean_param('http://www.example.com.evil.net/hack.php', PARAM_LOCALURL
));
711 $CFG->wwwroot
= 'https://www.example.com';
712 $this->assertSame('', clean_param('https://www.example.com.evil.net/hack.php', PARAM_LOCALURL
));
714 $this->assertSame('', clean_param('', PARAM_LOCALURL
));
715 $this->assertSame('', clean_param(null, PARAM_LOCALURL
));
718 public function test_clean_param_file() {
719 $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_FILE
));
720 $this->assertSame('badfile.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE
));
721 $this->assertSame('..parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_FILE
));
722 $this->assertSame('....grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_FILE
));
723 $this->assertSame('..winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_FILE
));
724 $this->assertSame('....wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_FILE
));
725 $this->assertSame('myfile.a.b.txt', clean_param('myfile.a.b.txt', PARAM_FILE
));
726 $this->assertSame('myfile..a..b.txt', clean_param('myfile..a..b.txt', PARAM_FILE
));
727 $this->assertSame('myfile.a..b...txt', clean_param('myfile.a..b...txt', PARAM_FILE
));
728 $this->assertSame('myfile.a.txt', clean_param('myfile.a.txt', PARAM_FILE
));
729 $this->assertSame('myfile...txt', clean_param('myfile...txt', PARAM_FILE
));
730 $this->assertSame('...jpg', clean_param('...jpg', PARAM_FILE
));
731 $this->assertSame('.a.b.', clean_param('.a.b.', PARAM_FILE
));
732 $this->assertSame('', clean_param('.', PARAM_FILE
));
733 $this->assertSame('', clean_param('..', PARAM_FILE
));
734 $this->assertSame('...', clean_param('...', PARAM_FILE
));
735 $this->assertSame('. . . .', clean_param('. . . .', PARAM_FILE
));
736 $this->assertSame('dontrtrim.me. .. .. . ', clean_param('dontrtrim.me. .. .. . ', PARAM_FILE
));
737 $this->assertSame(' . .dontltrim.me', clean_param(' . .dontltrim.me', PARAM_FILE
));
738 $this->assertSame('here is a tab.txt', clean_param("here is a tab\t.txt", PARAM_FILE
));
739 $this->assertSame('here is a linebreak.txt', clean_param("here is a line\r\nbreak.txt", PARAM_FILE
));
740 $this->assertSame('', clean_param(null, PARAM_FILE
));
742 // The following behaviours have been maintained although they seem a little odd.
743 $this->assertSame('funnything', clean_param('funny:thing', PARAM_FILE
));
744 $this->assertSame('.currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_FILE
));
745 $this->assertSame('ctempwindowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_FILE
));
746 $this->assertSame('homeuserlinuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_FILE
));
747 $this->assertSame('~myfile.txt', clean_param('~/myfile.txt', PARAM_FILE
));
750 public function test_clean_param_path() {
751 $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_PATH
));
752 $this->assertSame('bad/file.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH
));
753 $this->assertSame('/parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_PATH
));
754 $this->assertSame('/grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_PATH
));
755 $this->assertSame('/winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_PATH
));
756 $this->assertSame('/wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_PATH
));
757 $this->assertSame('funnything', clean_param('funny:thing', PARAM_PATH
));
758 $this->assertSame('./here', clean_param('./././here', PARAM_PATH
));
759 $this->assertSame('./currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_PATH
));
760 $this->assertSame('c/temp/windowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_PATH
));
761 $this->assertSame('/home/user/linuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_PATH
));
762 $this->assertSame('/home../user ./.linuxfile.txt', clean_param('/home../user ./.linuxfile.txt', PARAM_PATH
));
763 $this->assertSame('~/myfile.txt', clean_param('~/myfile.txt', PARAM_PATH
));
764 $this->assertSame('~/myfile.txt', clean_param('~/../myfile.txt', PARAM_PATH
));
765 $this->assertSame('/..b../.../myfile.txt', clean_param('/..b../.../myfile.txt', PARAM_PATH
));
766 $this->assertSame('..b../.../myfile.txt', clean_param('..b../.../myfile.txt', PARAM_PATH
));
767 $this->assertSame('/super/slashes/', clean_param('/super//slashes///', PARAM_PATH
));
768 $this->assertSame('', clean_param(null, PARAM_PATH
));
771 public function test_clean_param_safepath() {
772 $this->assertSame('folder/file', clean_param('folder/file', PARAM_SAFEPATH
));
773 $this->assertSame('folder//file', clean_param('folder/../file', PARAM_SAFEPATH
));
774 $this->assertSame('', clean_param(null, PARAM_SAFEPATH
));
777 public function test_clean_param_username() {
779 $currentstatus = $CFG->extendedusernamechars
;
781 // Run tests with extended character == false;.
782 $CFG->extendedusernamechars
= false;
783 $this->assertSame('johndoe123', clean_param('johndoe123', PARAM_USERNAME
) );
784 $this->assertSame('john.doe', clean_param('john.doe', PARAM_USERNAME
));
785 $this->assertSame('john-doe', clean_param('john-doe', PARAM_USERNAME
));
786 $this->assertSame('john-doe', clean_param('john- doe', PARAM_USERNAME
));
787 $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME
));
788 $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME
));
789 $this->assertSame('johndoe', clean_param('john~doe', PARAM_USERNAME
));
790 $this->assertSame('johndoe', clean_param('john´doe', PARAM_USERNAME
));
791 $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME
), 'john_');
792 $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME
), 'john_');
793 $this->assertSame(clean_param('john#$%&() ', PARAM_USERNAME
), 'john');
794 $this->assertSame('johnd', clean_param('JOHNdóé ', PARAM_USERNAME
));
795 $this->assertSame(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýá?ý??doe ', PARAM_USERNAME
), 'john.-_a_x-d@_doe');
796 $this->assertSame('', clean_param(null, PARAM_USERNAME
));
798 // Test success condition, if extendedusernamechars == ENABLE;.
799 $CFG->extendedusernamechars
= true;
800 $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME
));
801 $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME
));
802 $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME
), 'john# $%&()+_^');
803 $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME
), 'john# $%&()+_^');
804 $this->assertSame('john~doe', clean_param('john~doe', PARAM_USERNAME
));
805 $this->assertSame('john´doe', clean_param('joHN´doe', PARAM_USERNAME
));
806 $this->assertSame('johndoe', clean_param('johnDOE', PARAM_USERNAME
));
807 $this->assertSame('johndóé', clean_param('johndóé ', PARAM_USERNAME
));
809 $CFG->extendedusernamechars
= $currentstatus;
812 public function test_clean_param_stringid() {
813 // Test string identifiers validation.
815 $this->assertSame('validstring', clean_param('validstring', PARAM_STRINGID
));
816 $this->assertSame('mod/foobar:valid_capability', clean_param('mod/foobar:valid_capability', PARAM_STRINGID
));
817 $this->assertSame('CZ', clean_param('CZ', PARAM_STRINGID
));
818 $this->assertSame('application/vnd.ms-powerpoint', clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID
));
819 $this->assertSame('grade2', clean_param('grade2', PARAM_STRINGID
));
821 $this->assertSame('', clean_param('trailing ', PARAM_STRINGID
));
822 $this->assertSame('', clean_param('space bar', PARAM_STRINGID
));
823 $this->assertSame('', clean_param('0numeric', PARAM_STRINGID
));
824 $this->assertSame('', clean_param('*', PARAM_STRINGID
));
825 $this->assertSame('', clean_param(' ', PARAM_STRINGID
));
826 $this->assertSame('', clean_param(null, PARAM_STRINGID
));
829 public function test_clean_param_timezone() {
830 // Test timezone validation.
831 $testvalues = array (
832 'America/Jamaica' => 'America/Jamaica',
833 'America/Argentina/Cordoba' => 'America/Argentina/Cordoba',
834 'America/Port-au-Prince' => 'America/Port-au-Prince',
835 'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
836 'PST8PDT' => 'PST8PDT',
838 'Wrong/.Value' => '',
839 'Wrong(Value)' => '',
866 foreach ($testvalues as $testvalue => $expectedvalue) {
867 $actualvalue = clean_param($testvalue, PARAM_TIMEZONE
);
868 $this->assertEquals($expectedvalue, $actualvalue);
872 public function test_clean_param_null_argument() {
873 $this->assertEquals(0, clean_param(null, PARAM_INT
));
874 $this->assertEquals(0, clean_param(null, PARAM_FLOAT
));
875 $this->assertEquals(0, clean_param(null, PARAM_LOCALISEDFLOAT
));
876 $this->assertEquals(false, clean_param(null, PARAM_BOOL
));
877 $this->assertEquals('', clean_param(null, PARAM_NOTAGS
));
878 $this->assertEquals('', clean_param(null, PARAM_SAFEDIR
));
879 $this->assertEquals('', clean_param(null, PARAM_HOST
));
880 $this->assertEquals('', clean_param(null, PARAM_PEM
));
881 $this->assertEquals('', clean_param(null, PARAM_BASE64
));
882 $this->assertEquals('', clean_param(null, PARAM_TAG
));
883 $this->assertEquals('', clean_param(null, PARAM_TAGLIST
));
884 $this->assertEquals('', clean_param(null, PARAM_CAPABILITY
));
885 $this->assertEquals(0, clean_param(null, PARAM_PERMISSION
));
886 $this->assertEquals('', clean_param(null, PARAM_AUTH
));
887 $this->assertEquals('', clean_param(null, PARAM_LANG
));
888 $this->assertEquals('', clean_param(null, PARAM_THEME
));
889 $this->assertEquals('', clean_param(null, PARAM_EMAIL
));
892 public function test_validate_param() {
894 $param = validate_param('11a', PARAM_INT
);
895 $this->fail('invalid_parameter_exception expected');
896 } catch (\moodle_exception
$ex) {
897 $this->assertInstanceOf('invalid_parameter_exception', $ex);
900 $param = validate_param('11', PARAM_INT
);
901 $this->assertSame(11, $param);
904 $param = validate_param(null, PARAM_INT
, false);
905 $this->fail('invalid_parameter_exception expected');
906 } catch (\moodle_exception
$ex) {
907 $this->assertInstanceOf('invalid_parameter_exception', $ex);
910 $param = validate_param(null, PARAM_INT
, true);
911 $this->assertSame(null, $param);
914 $param = validate_param(array(), PARAM_INT
);
915 $this->fail('invalid_parameter_exception expected');
916 } catch (\moodle_exception
$ex) {
917 $this->assertInstanceOf('invalid_parameter_exception', $ex);
920 $param = validate_param(new \stdClass
, PARAM_INT
);
921 $this->fail('invalid_parameter_exception expected');
922 } catch (\moodle_exception
$ex) {
923 $this->assertInstanceOf('invalid_parameter_exception', $ex);
926 $param = validate_param('1.0', PARAM_FLOAT
);
927 $this->assertSame(1.0, $param);
929 // Make sure valid floats do not cause exception.
930 validate_param(1.0, PARAM_FLOAT
);
931 validate_param(10, PARAM_FLOAT
);
932 validate_param('0', PARAM_FLOAT
);
933 validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT
);
934 validate_param('011.1', PARAM_FLOAT
);
935 validate_param('11', PARAM_FLOAT
);
936 validate_param('+.1', PARAM_FLOAT
);
937 validate_param('-.1', PARAM_FLOAT
);
938 validate_param('1e10', PARAM_FLOAT
);
939 validate_param('.1e+10', PARAM_FLOAT
);
940 validate_param('1E-1', PARAM_FLOAT
);
943 $param = validate_param('1,2', PARAM_FLOAT
);
944 $this->fail('invalid_parameter_exception expected');
945 } catch (\moodle_exception
$ex) {
946 $this->assertInstanceOf('invalid_parameter_exception', $ex);
949 $param = validate_param('', PARAM_FLOAT
);
950 $this->fail('invalid_parameter_exception expected');
951 } catch (\moodle_exception
$ex) {
952 $this->assertInstanceOf('invalid_parameter_exception', $ex);
955 $param = validate_param('.', PARAM_FLOAT
);
956 $this->fail('invalid_parameter_exception expected');
957 } catch (\moodle_exception
$ex) {
958 $this->assertInstanceOf('invalid_parameter_exception', $ex);
961 $param = validate_param('e10', PARAM_FLOAT
);
962 $this->fail('invalid_parameter_exception expected');
963 } catch (\moodle_exception
$ex) {
964 $this->assertInstanceOf('invalid_parameter_exception', $ex);
967 $param = validate_param('abc', PARAM_FLOAT
);
968 $this->fail('invalid_parameter_exception expected');
969 } catch (\moodle_exception
$ex) {
970 $this->assertInstanceOf('invalid_parameter_exception', $ex);
974 public function test_shorten_text_no_tags_already_short_enough() {
975 // ......12345678901234567890123456.
976 $text = "short text already no tags";
977 $this->assertSame($text, shorten_text($text));
980 public function test_shorten_text_with_tags_already_short_enough() {
981 // .........123456...7890....12345678.......901234567.
982 $text = "<p>short <b>text</b> already</p><p>with tags</p>";
983 $this->assertSame($text, shorten_text($text));
986 public function test_shorten_text_no_tags_needs_shortening() {
987 // Default truncation is after 30 chars, but allowing 3 for the final '...'.
988 // ......12345678901234567890123456789023456789012345678901234.
989 $text = "long text without any tags blah de blah blah blah what";
990 $this->assertSame('long text without any tags ...', shorten_text($text));
993 public function test_shorten_text_with_tags_needs_shortening() {
994 // .......................................123456789012345678901234567890...
995 $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
996 "be chopped off but <b>should be added back again</b></blockquote></p></div>";
997 $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
998 "tags that ...</blockquote></p></div>", shorten_text($text));
1001 public function test_shorten_text_with_tags_and_html_comment() {
1002 $text = "<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with ".
1003 "tags that will<!--<![endif]--> ".
1004 "be chopped off but <b>should be added back again</b></blockquote></p></div>";
1005 $this->assertEquals("<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with " .
1006 "tags that ...<!--<![endif]--></blockquote></p></div>", shorten_text($text));
1009 public function test_shorten_text_with_entities() {
1010 // Remember to allow 3 chars for the final '...'.
1011 // ......123456789012345678901234567_____890...
1012 $text = "some text which shouldn't break there";
1013 $this->assertSame("some text which shouldn't ...", shorten_text($text, 31));
1014 $this->assertSame("some text which shouldn't ...", shorten_text($text, 30));
1015 $this->assertSame("some text which shouldn't ...", shorten_text($text, 29));
1018 public function test_shorten_text_known_tricky_case() {
1019 // This case caused a bug up to 1.9.5
1020 // ..........123456789012345678901234567890123456789.....0_____1___2___...
1021 $text = "<h3>standard 'break-out' sub groups in TGs?</h3> <<There are several";
1022 $this->assertSame("<h3>standard 'break-out' sub groups in ...</h3>",
1023 shorten_text($text, 41));
1024 $this->assertSame("<h3>standard 'break-out' sub groups in TGs?...</h3>",
1025 shorten_text($text, 42));
1026 $this->assertSame("<h3>standard 'break-out' sub groups in TGs?</h3> ...",
1027 shorten_text($text, 43));
1030 public function test_shorten_text_no_spaces() {
1031 // ..........123456789.
1032 $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
1033 $this->assertSame("<h1>12345...</h1>", shorten_text($text, 8));
1036 public function test_shorten_text_utf8_european() {
1037 // Text without tags.
1038 // ......123456789012345678901234567.
1039 $text = "Žluťoučký koníček přeskočil";
1040 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
1041 $this->assertSame("Žluťoučký koníče...", shorten_text($text, 19, true));
1042 $this->assertSame("Žluťoučký ...", shorten_text($text, 19, false));
1043 // And try it with 2-less (that are, in bytes, the middle of a sequence).
1044 $this->assertSame("Žluťoučký koní...", shorten_text($text, 17, true));
1045 $this->assertSame("Žluťoučký ...", shorten_text($text, 17, false));
1047 // .........123456789012345678...901234567....89012345.
1048 $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
1049 $this->assertSame($text, shorten_text($text, 60));
1050 $this->assertSame("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
1051 $this->assertSame("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
1052 $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
1053 // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
1054 $this->assertSame("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
1055 $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
1056 // And try over one tag (start/end), it does proper text len.
1057 $this->assertSame("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
1058 $this->assertSame("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
1059 // And in the middle of one tag.
1060 $this->assertSame("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
1063 public function test_shorten_text_utf8_oriental() {
1065 // text without tags
1066 // ......123456789012345678901234.
1067 $text = '言語設定言語設定abcdefghijkl';
1068 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
1069 $this->assertSame("言語設定言語...", shorten_text($text, 9, true));
1070 $this->assertSame("言語設定言語...", shorten_text($text, 9, false));
1071 $this->assertSame("言語設定言語設定ab...", shorten_text($text, 13, true));
1072 $this->assertSame("言語設定言語設定...", shorten_text($text, 13, false));
1075 // text without tags
1076 // ......123456789012345678901234.
1077 $text = '简体中文简体中文abcdefghijkl';
1078 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
1079 $this->assertSame("简体中文简体...", shorten_text($text, 9, true));
1080 $this->assertSame("简体中文简体...", shorten_text($text, 9, false));
1081 $this->assertSame("简体中文简体中文ab...", shorten_text($text, 13, true));
1082 $this->assertSame("简体中文简体中文...", shorten_text($text, 13, false));
1085 public function test_shorten_text_multilang() {
1086 // This is not necessaryily specific to multilang. The issue is really
1087 // tags with attributes, where before we were generating invalid HTML
1088 // output like shorten_text('<span id="x" class="y">A</span> B', 1)
1089 // returning '<span id="x" ...</span>'. It is just that multilang
1090 // requires the sort of HTML that is quite likely to trigger this.
1091 // ........................................1...
1092 $text = '<span lang="en" class="multilang">A</span>' .
1093 '<span lang="fr" class="multilang">B</span>';
1094 $this->assertSame('<span lang="en" class="multilang">...</span>',
1095 shorten_text($text, 1));
1099 * Provider for long filenames and its expected result, with and without hash.
1101 * @return array of ($filename, $length, $expected, $includehash)
1103 public function shorten_filename_provider() {
1104 $filename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium totam rem';
1105 $shortfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque';
1108 'More than 100 characters' => [
1111 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot',
1114 'More than 100 characters with hash' => [
1117 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8',
1120 'More than 100 characters with extension' => [
1123 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot.zip',
1126 'More than 100 characters with extension and hash' => [
1129 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8.zip',
1132 'Limit filename to 50 chars' => [
1135 'sed ut perspiciatis unde omnis iste natus error si',
1138 'Limit filename to 50 chars with hash' => [
1141 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8',
1144 'Limit filename to 50 chars with extension' => [
1147 'sed ut perspiciatis unde omnis iste natus error si.zip',
1150 'Limit filename to 50 chars with extension and hash' => [
1153 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8.zip',
1156 'Test filename that contains less than 100 characters' => [
1162 'Test filename that contains less than 100 characters and hash' => [
1168 'Test filename that contains less than 100 characters with extension' => [
1169 "{$shortfilename}.zip",
1171 "{$shortfilename}.zip",
1174 'Test filename that contains less than 100 characters with extension and hash' => [
1175 "{$shortfilename}.zip",
1177 "{$shortfilename}.zip",
1184 * Test the {@link shorten_filename()} method.
1186 * @dataProvider shorten_filename_provider
1188 * @param string $filename
1189 * @param int $length
1190 * @param string $expected
1191 * @param boolean $includehash
1193 public function test_shorten_filename($filename, $length, $expected, $includehash) {
1194 if (null === $length) {
1195 $length = MAX_FILENAME_SIZE
;
1198 $this->assertSame($expected, shorten_filename($filename, $length, $includehash));
1202 * Provider for long filenames and its expected result, with and without hash.
1204 * @return array of ($filename, $length, $expected, $includehash)
1206 public function shorten_filenames_provider() {
1207 $shortfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque';
1208 $longfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium totam rem';
1209 $extfilename = $longfilename.'.zip';
1210 $expected = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot';
1211 $expectedwithhash = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8';
1212 $expectedext = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot.zip';
1213 $expectedextwithhash = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8.zip';
1214 $expected50 = 'sed ut perspiciatis unde omnis iste natus error si';
1215 $expected50withhash = 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8';
1216 $expected50ext = 'sed ut perspiciatis unde omnis iste natus error si.zip';
1217 $expected50extwithhash = 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8.zip';
1218 $expected50short = 'sed ut perspiciatis unde omnis iste n - 5fb6543490';
1221 'Empty array without hash' => [
1227 'Empty array with hash' => [
1233 'Array with less than 100 characters' => [
1234 [$shortfilename, $shortfilename, $shortfilename],
1236 [$shortfilename, $shortfilename, $shortfilename],
1239 'Array with more than 100 characters without hash' => [
1240 [$longfilename, $longfilename, $longfilename],
1242 [$expected, $expected, $expected],
1245 'Array with more than 100 characters with hash' => [
1246 [$longfilename, $longfilename, $longfilename],
1248 [$expectedwithhash, $expectedwithhash, $expectedwithhash],
1251 'Array with more than 100 characters with extension' => [
1252 [$extfilename, $extfilename, $extfilename],
1254 [$expectedext, $expectedext, $expectedext],
1257 'Array with more than 100 characters with extension and hash' => [
1258 [$extfilename, $extfilename, $extfilename],
1260 [$expectedextwithhash, $expectedextwithhash, $expectedextwithhash],
1263 'Array with more than 100 characters mix (short, long, with extension) without hash' => [
1264 [$shortfilename, $longfilename, $extfilename],
1266 [$shortfilename, $expected, $expectedext],
1269 'Array with more than 100 characters mix (short, long, with extension) with hash' => [
1270 [$shortfilename, $longfilename, $extfilename],
1272 [$shortfilename, $expectedwithhash, $expectedextwithhash],
1275 'Array with less than 50 characters without hash' => [
1276 [$longfilename, $longfilename, $longfilename],
1278 [$expected50, $expected50, $expected50],
1281 'Array with less than 50 characters with hash' => [
1282 [$longfilename, $longfilename, $longfilename],
1284 [$expected50withhash, $expected50withhash, $expected50withhash],
1287 'Array with less than 50 characters with extension' => [
1288 [$extfilename, $extfilename, $extfilename],
1290 [$expected50ext, $expected50ext, $expected50ext],
1293 'Array with less than 50 characters with extension and hash' => [
1294 [$extfilename, $extfilename, $extfilename],
1296 [$expected50extwithhash, $expected50extwithhash, $expected50extwithhash],
1299 'Array with less than 50 characters mix (short, long, with extension) without hash' => [
1300 [$shortfilename, $longfilename, $extfilename],
1302 [$expected50, $expected50, $expected50ext],
1305 'Array with less than 50 characters mix (short, long, with extension) with hash' => [
1306 [$shortfilename, $longfilename, $extfilename],
1308 [$expected50short, $expected50withhash, $expected50extwithhash],
1315 * Test the {@link shorten_filenames()} method.
1317 * @dataProvider shorten_filenames_provider
1319 * @param array $filenames
1320 * @param int $length
1321 * @param string $expected
1322 * @param boolean $includehash
1324 public function test_shorten_filenames($filenames, $length, $expected, $includehash) {
1325 if (null === $length) {
1326 $length = MAX_FILENAME_SIZE
;
1329 $this->assertSame($expected, shorten_filenames($filenames, $length, $includehash));
1332 public function test_usergetdate() {
1333 global $USER, $CFG, $DB;
1334 $this->resetAfterTest();
1336 $this->setAdminUser();
1338 $USER->timezone
= 2;// Set the timezone to a known state.
1340 $ts = 1261540267; // The time this function was created.
1342 $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
1343 $arr = array_values($arr);
1345 list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1346 $this->assertSame(7, $seconds);
1347 $this->assertSame(51, $minutes);
1348 $this->assertSame(4, $hours);
1349 $this->assertSame(23, $mday);
1350 $this->assertSame(3, $wday);
1351 $this->assertSame(12, $mon);
1352 $this->assertSame(2009, $year);
1353 $this->assertSame(356, $yday);
1354 $this->assertSame('Wednesday', $weekday);
1355 $this->assertSame('December', $month);
1356 $arr = usergetdate($ts); // Gets the timezone from the $USER object.
1357 $arr = array_values($arr);
1359 list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1360 $this->assertSame(7, $seconds);
1361 $this->assertSame(51, $minutes);
1362 $this->assertSame(5, $hours);
1363 $this->assertSame(23, $mday);
1364 $this->assertSame(3, $wday);
1365 $this->assertSame(12, $mon);
1366 $this->assertSame(2009, $year);
1367 $this->assertSame(356, $yday);
1368 $this->assertSame('Wednesday', $weekday);
1369 $this->assertSame('December', $month);
1371 // Edge cases - 0 and null - they all mean 1st Jan 1970. Null shows debugging message.
1372 $this->assertSame(1970, usergetdate(0)['year']);
1373 $this->assertDebuggingNotCalled();
1374 $this->assertSame(1970, usergetdate(null)['year']);
1375 $this->assertDebuggingCalled(null, DEBUG_DEVELOPER
);
1378 public function test_mark_user_preferences_changed() {
1379 $this->resetAfterTest();
1380 $otheruser = $this->getDataGenerator()->create_user();
1381 $otheruserid = $otheruser->id
;
1383 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1384 mark_user_preferences_changed($otheruserid);
1386 $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1387 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1390 public function test_check_user_preferences_loaded() {
1392 $this->resetAfterTest();
1394 $otheruser = $this->getDataGenerator()->create_user();
1395 $otheruserid = $otheruser->id
;
1397 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1398 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1400 $user = new \
stdClass();
1401 $user->id
= $otheruserid;
1404 check_user_preferences_loaded($user);
1405 $this->assertTrue(isset($user->preference
));
1406 $this->assertTrue(is_array($user->preference
));
1407 $this->assertArrayHasKey('_lastloaded', $user->preference
);
1408 $this->assertCount(1, $user->preference
);
1410 // Add preference via direct call.
1411 $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id
));
1413 // No cache reload yet.
1414 check_user_preferences_loaded($user);
1415 $this->assertCount(1, $user->preference
);
1417 // Forced reloading of cache.
1418 unset($user->preference
);
1419 check_user_preferences_loaded($user);
1420 $this->assertCount(2, $user->preference
);
1421 $this->assertSame('yyy', $user->preference
['xxx']);
1423 // Add preference via direct call.
1424 $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id
));
1426 // Test timeouts and modifications from different session.
1427 set_cache_flag('userpreferenceschanged', $user->id
, 1, time() +
1000);
1428 $user->preference
['_lastloaded'] = $user->preference
['_lastloaded'] - 20;
1429 check_user_preferences_loaded($user);
1430 $this->assertCount(2, $user->preference
);
1431 check_user_preferences_loaded($user, 10);
1432 $this->assertCount(3, $user->preference
);
1433 $this->assertSame('bbb', $user->preference
['aaa']);
1434 set_cache_flag('userpreferenceschanged', $user->id
, null);
1437 public function test_set_user_preference() {
1439 $this->resetAfterTest();
1441 $this->setAdminUser();
1443 $otheruser = $this->getDataGenerator()->create_user();
1444 $otheruserid = $otheruser->id
;
1446 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1447 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1449 $user = new \
stdClass();
1450 $user->id
= $otheruserid;
1452 set_user_preference('aaa', 'bbb', $otheruserid);
1453 $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1454 $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
1456 set_user_preference('xxx', 'yyy', $user);
1457 $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1458 $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
1459 $this->assertTrue(is_array($user->preference
));
1460 $this->assertSame('bbb', $user->preference
['aaa']);
1461 $this->assertSame('yyy', $user->preference
['xxx']);
1463 set_user_preference('xxx', null, $user);
1464 $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1465 $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
1467 set_user_preference('ooo', true, $user);
1468 $prefs = get_user_preferences(null, null, $otheruserid);
1469 $this->assertSame($user->preference
['aaa'], $prefs['aaa']);
1470 $this->assertSame($user->preference
['ooo'], $prefs['ooo']);
1471 $this->assertSame('1', $prefs['ooo']);
1473 set_user_preference('null', 0, $user);
1474 $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1476 $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1478 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1479 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1481 // Test $USER default.
1482 set_user_preference('_test_user_preferences_pref', 'ok');
1483 $this->assertSame('ok', $USER->preference
['_test_user_preferences_pref']);
1484 unset_user_preference('_test_user_preferences_pref');
1485 $this->assertTrue(!isset($USER->preference
['_test_user_preferences_pref']));
1487 // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
1488 $longvalue = str_repeat('a', 1333);
1489 set_user_preference('_test_long_user_preference', $longvalue);
1490 $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1491 $this->assertEquals($longvalue,
1492 $DB->get_field('user_preferences', 'value', array('userid' => $USER->id
, 'name' => '_test_long_user_preference')));
1494 // Test > 1333 char values, coding_exception expected.
1495 $longvalue = str_repeat('a', 1334);
1497 set_user_preference('_test_long_user_preference', $longvalue);
1498 $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1499 } catch (\moodle_exception
$ex) {
1500 $this->assertInstanceOf('coding_exception', $ex);
1503 // Test invalid params.
1505 set_user_preference('_test_user_preferences_pref', array());
1506 $this->fail('Exception expected - array not valid preference value');
1507 } catch (\moodle_exception
$ex) {
1508 $this->assertInstanceOf('coding_exception', $ex);
1511 set_user_preference('_test_user_preferences_pref', new \stdClass
);
1512 $this->fail('Exception expected - class not valid preference value');
1513 } catch (\moodle_exception
$ex) {
1514 $this->assertInstanceOf('coding_exception', $ex);
1517 set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1518 $this->fail('Exception expected - user instance expected');
1519 } catch (\moodle_exception
$ex) {
1520 $this->assertInstanceOf('coding_exception', $ex);
1523 set_user_preference('_test_user_preferences_pref', 1, 'abc');
1524 $this->fail('Exception expected - user instance expected');
1525 } catch (\moodle_exception
$ex) {
1526 $this->assertInstanceOf('coding_exception', $ex);
1529 set_user_preference('', 1);
1530 $this->fail('Exception expected - invalid name accepted');
1531 } catch (\moodle_exception
$ex) {
1532 $this->assertInstanceOf('coding_exception', $ex);
1535 set_user_preference('1', 1);
1536 $this->fail('Exception expected - invalid name accepted');
1537 } catch (\moodle_exception
$ex) {
1538 $this->assertInstanceOf('coding_exception', $ex);
1542 public function test_set_user_preference_for_current_user() {
1544 $this->resetAfterTest();
1545 $this->setAdminUser();
1547 set_user_preference('test_pref', 2);
1548 set_user_preference('test_pref', 1, $USER->id
);
1549 $this->assertEquals(1, get_user_preferences('test_pref'));
1552 public function test_unset_user_preference_for_current_user() {
1554 $this->resetAfterTest();
1555 $this->setAdminUser();
1557 set_user_preference('test_pref', 1);
1558 unset_user_preference('test_pref', $USER->id
);
1559 $this->assertNull(get_user_preferences('test_pref'));
1563 * Test essential features implementation of {@link get_extra_user_fields()} as the admin user with all capabilities.
1565 * @deprecated since Moodle 3.11 MDL-45242
1567 public function test_get_extra_user_fields_essentials() {
1568 global $CFG, $USER, $DB;
1569 $this->resetAfterTest();
1571 $this->setAdminUser();
1572 $context = \context_system
::instance();
1575 $CFG->showuseridentity
= '';
1576 $this->assertEquals(array(), get_extra_user_fields($context));
1579 $CFG->showuseridentity
= 'frog';
1580 $this->assertEquals(array('frog'), get_extra_user_fields($context));
1583 $CFG->showuseridentity
= 'frog,zombie';
1584 $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1586 // No fields, except.
1587 $CFG->showuseridentity
= '';
1588 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1591 $CFG->showuseridentity
= 'frog';
1592 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1595 $CFG->showuseridentity
= 'frog,zombie';
1596 $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1598 $this->assertDebuggingCalledCount(6);
1602 * Prepare environment for couple of tests related to permission checks in {@link get_extra_user_fields()}.
1605 * @deprecated since Moodle 3.11 MDL-45242
1607 protected function environment_for_get_extra_user_fields_tests() {
1610 $CFG->showuseridentity
= 'idnumber,country,city';
1611 $CFG->hiddenuserfields
= 'country,city';
1613 $env = new \
stdClass();
1615 $env->course
= $this->getDataGenerator()->create_course();
1616 $env->coursecontext
= \context_course
::instance($env->course
->id
);
1618 $env->teacherrole
= $DB->get_record('role', array('shortname' => 'teacher'));
1619 $env->studentrole
= $DB->get_record('role', array('shortname' => 'student'));
1620 $env->managerrole
= $DB->get_record('role', array('shortname' => 'manager'));
1622 $env->student
= $this->getDataGenerator()->create_user();
1623 $env->teacher
= $this->getDataGenerator()->create_user();
1624 $env->manager
= $this->getDataGenerator()->create_user();
1626 role_assign($env->studentrole
->id
, $env->student
->id
, $env->coursecontext
->id
);
1627 role_assign($env->teacherrole
->id
, $env->teacher
->id
, $env->coursecontext
->id
);
1628 role_assign($env->managerrole
->id
, $env->manager
->id
, SYSCONTEXTID
);
1634 * No identity fields shown to student user (no permission to view identity fields).
1636 * @deprecated since Moodle 3.11 MDL-45242
1638 public function test_get_extra_user_fields_no_access() {
1640 $this->resetAfterTest();
1641 $env = $this->environment_for_get_extra_user_fields_tests();
1642 $this->setUser($env->student
);
1644 $this->assertEquals(array(), get_extra_user_fields($env->coursecontext
));
1645 $this->assertEquals(array(), get_extra_user_fields(\context_system
::instance()));
1647 $this->assertDebuggingCalledCount(2);
1651 * Teacher can see students' identity fields only within the course.
1653 * @deprecated since Moodle 3.11 MDL-45242
1655 public function test_get_extra_user_fields_course_only_access() {
1657 $this->resetAfterTest();
1658 $env = $this->environment_for_get_extra_user_fields_tests();
1659 $this->setUser($env->teacher
);
1661 $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields($env->coursecontext
));
1662 $this->assertEquals(array(), get_extra_user_fields(\context_system
::instance()));
1664 $this->assertDebuggingCalledCount(2);
1668 * Teacher can be prevented from seeing students' identity fields even within the course.
1670 * @deprecated since Moodle 3.11 MDL-45242
1672 public function test_get_extra_user_fields_course_prevented_access() {
1674 $this->resetAfterTest();
1675 $env = $this->environment_for_get_extra_user_fields_tests();
1676 $this->setUser($env->teacher
);
1678 assign_capability('moodle/course:viewhiddenuserfields', CAP_PREVENT
, $env->teacherrole
->id
, $env->coursecontext
->id
);
1679 $this->assertEquals(array('idnumber'), get_extra_user_fields($env->coursecontext
));
1681 $this->assertDebuggingCalledCount(1);
1685 * Manager can see students' identity fields anywhere.
1687 * @deprecated since Moodle 3.11 MDL-45242
1689 public function test_get_extra_user_fields_anywhere_access() {
1691 $this->resetAfterTest();
1692 $env = $this->environment_for_get_extra_user_fields_tests();
1693 $this->setUser($env->manager
);
1695 $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields($env->coursecontext
));
1696 $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields(\context_system
::instance()));
1698 $this->assertDebuggingCalledCount(2);
1702 * Manager can be prevented from seeing hidden fields outside the course.
1704 * @deprecated since Moodle 3.11 MDL-45242
1706 public function test_get_extra_user_fields_schismatic_access() {
1708 $this->resetAfterTest();
1709 $env = $this->environment_for_get_extra_user_fields_tests();
1710 $this->setUser($env->manager
);
1712 assign_capability('moodle/user:viewhiddendetails', CAP_PREVENT
, $env->managerrole
->id
, SYSCONTEXTID
, true);
1713 $this->assertEquals(array('idnumber'), get_extra_user_fields(\context_system
::instance()));
1714 // Note that inside the course, the manager can still see the hidden identifiers as this is currently
1715 // controlled by a separate capability for legacy reasons.
1716 $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields($env->coursecontext
));
1718 $this->assertDebuggingCalledCount(2);
1722 * Two capabilities must be currently set to prevent manager from seeing hidden fields.
1724 * @deprecated since Moodle 3.11 MDL-45242
1726 public function test_get_extra_user_fields_hard_to_prevent_access() {
1728 $this->resetAfterTest();
1729 $env = $this->environment_for_get_extra_user_fields_tests();
1730 $this->setUser($env->manager
);
1732 assign_capability('moodle/user:viewhiddendetails', CAP_PREVENT
, $env->managerrole
->id
, SYSCONTEXTID
, true);
1733 assign_capability('moodle/course:viewhiddenuserfields', CAP_PREVENT
, $env->managerrole
->id
, SYSCONTEXTID
, true);
1735 $this->assertEquals(array('idnumber'), get_extra_user_fields(\context_system
::instance()));
1736 $this->assertEquals(array('idnumber'), get_extra_user_fields($env->coursecontext
));
1738 $this->assertDebuggingCalledCount(2);
1742 * Tests get_extra_user_fields_sql.
1744 * @deprecated since Moodle 3.11 MDL-45242
1746 public function test_get_extra_user_fields_sql() {
1747 global $CFG, $USER, $DB;
1748 $this->resetAfterTest();
1750 $this->setAdminUser();
1752 $context = \context_system
::instance();
1755 $CFG->showuseridentity
= '';
1756 $this->assertSame('', get_extra_user_fields_sql($context));
1759 $CFG->showuseridentity
= 'frog';
1760 $this->assertSame(', frog', get_extra_user_fields_sql($context));
1762 // Two fields with table prefix.
1763 $CFG->showuseridentity
= 'frog,zombie';
1764 $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1766 // Two fields with field prefix.
1767 $CFG->showuseridentity
= 'frog,zombie';
1768 $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
1769 get_extra_user_fields_sql($context, '', 'u_'));
1771 // One field excluded.
1772 $CFG->showuseridentity
= 'frog';
1773 $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
1775 // Two fields, one excluded, table+field prefix.
1776 $CFG->showuseridentity
= 'frog,zombie';
1777 $this->assertEquals(', u1.zombie AS u_zombie',
1778 get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1780 $this->assertDebuggingCalledCount(6);
1784 * Test some critical TZ/DST.
1786 * This method tests some special TZ/DST combinations that were fixed
1787 * by MDL-38999. The tests are done by comparing the results of the
1788 * output using Moodle TZ/DST support and PHP native one.
1790 * Note: If you don't trust PHP TZ/DST support, can verify the
1791 * harcoded expectations below with:
1792 * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
1794 public function test_some_moodle_special_dst() {
1795 $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
1797 // In Europe/Tallinn it was 2013/04/08 05:00:00.
1798 $expectation = '2013/04/08 05:00:00';
1799 $phpdt = \DateTime
::createFromFormat('U', $stamp, new \
DateTimeZone('UTC'));
1800 $phpdt->setTimezone(new \
DateTimeZone('Europe/Tallinn'));
1801 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1802 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1803 $this->assertSame($expectation, $phpres);
1804 $this->assertSame($expectation, $moodleres);
1806 // In St. Johns it was 2013/04/07 23:30:00.
1807 $expectation = '2013/04/07 23:30:00';
1808 $phpdt = \DateTime
::createFromFormat('U', $stamp, new \
DateTimeZone('UTC'));
1809 $phpdt->setTimezone(new \
DateTimeZone('America/St_Johns'));
1810 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1811 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1812 $this->assertSame($expectation, $phpres);
1813 $this->assertSame($expectation, $moodleres);
1815 $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1817 // In Europe/Tallinn it was 2013/11/08 04:00:00.
1818 $expectation = '2013/11/08 04:00:00';
1819 $phpdt = \DateTime
::createFromFormat('U', $stamp, new \
DateTimeZone('UTC'));
1820 $phpdt->setTimezone(new \
DateTimeZone('Europe/Tallinn'));
1821 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1822 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1823 $this->assertSame($expectation, $phpres);
1824 $this->assertSame($expectation, $moodleres);
1826 // In St. Johns it was 2013/11/07 22:30:00.
1827 $expectation = '2013/11/07 22:30:00';
1828 $phpdt = \DateTime
::createFromFormat('U', $stamp, new \
DateTimeZone('UTC'));
1829 $phpdt->setTimezone(new \
DateTimeZone('America/St_Johns'));
1830 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1831 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1832 $this->assertSame($expectation, $phpres);
1833 $this->assertSame($expectation, $moodleres);
1836 public function test_userdate() {
1837 global $USER, $CFG, $DB;
1838 $this->resetAfterTest();
1840 $this->setAdminUser();
1842 $testvalues = array(
1844 'time' => '1309514400',
1845 'usertimezone' => 'America/Moncton',
1846 'timezone' => '0.0', // No dst offset.
1847 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM',
1848 'expectedoutputhtml' => '<time datetime="2011-07-01T07:00:00-03:00">Friday, 1 July 2011, 10:00 AM</time>'
1851 'time' => '1309514400',
1852 'usertimezone' => 'America/Moncton',
1853 'timezone' => '99', // Dst offset and timezone offset.
1854 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM',
1855 'expectedoutputhtml' => '<time datetime="2011-07-01T07:00:00-03:00">Friday, 1 July 2011, 7:00 AM</time>'
1858 'time' => '1309514400',
1859 'usertimezone' => 'America/Moncton',
1860 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
1861 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM',
1862 'expectedoutputhtml' => '<time datetime="2011-07-01t07:00:00-03:00">Friday, 1 July 2011, 7:00 AM</time>'
1865 'time' => '1293876000 ',
1866 'usertimezone' => 'America/Moncton',
1867 'timezone' => '0.0', // No dst offset.
1868 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM',
1869 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 10:00 AM</time>'
1872 'time' => '1293876000 ',
1873 'usertimezone' => 'America/Moncton',
1874 'timezone' => '99', // No dst offset in jan, so just timezone offset.
1875 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM',
1876 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 6:00 AM</time>'
1879 'time' => '1293876000 ',
1880 'usertimezone' => 'America/Moncton',
1881 'timezone' => 'America/Moncton', // No dst offset in jan.
1882 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM',
1883 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 6:00 AM</time>'
1886 'time' => '1293876000 ',
1887 'usertimezone' => '2',
1888 'timezone' => '99', // Take user timezone.
1889 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM',
1890 'expectedoutputhtml' => '<time datetime="2011-01-01T12:00:00+02:00">Saturday, 1 January 2011, 12:00 PM</time>'
1893 'time' => '1293876000 ',
1894 'usertimezone' => '-2',
1895 'timezone' => '99', // Take user timezone.
1896 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM',
1897 'expectedoutputhtml' => '<time datetime="2011-01-01T08:00:00-02:00">Saturday, 1 January 2011, 8:00 AM</time>'
1900 'time' => '1293876000 ',
1901 'usertimezone' => '-10',
1902 'timezone' => '2', // Take this timezone.
1903 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM',
1904 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 12:00 PM</time>'
1907 'time' => '1293876000 ',
1908 'usertimezone' => '-10',
1909 'timezone' => '-2', // Take this timezone.
1910 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM',
1911 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 8:00 AM</time>'
1914 'time' => '1293876000 ',
1915 'usertimezone' => '-10',
1916 'timezone' => 'random/time', // This should show server time.
1917 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM',
1918 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 6:00 PM</time>'
1921 'time' => '1293876000 ',
1922 'usertimezone' => '20', // Fallback to server time zone.
1923 'timezone' => '99', // This should show user time.
1924 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM',
1925 'expectedoutputhtml' => '<time datetime="2011-01-01T18:00:00+08:00">Saturday, 1 January 2011, 6:00 PM</time>'
1929 // Set default timezone to Australia/Perth, else time calculated
1930 // will not match expected values.
1931 $this->setTimezone(99, 'Australia/Perth');
1933 foreach ($testvalues as $vals) {
1934 $USER->timezone
= $vals['usertimezone'];
1935 $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1936 $actualoutputhtml = userdate_htmltime($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1938 // On different systems case of AM PM changes so compare case insensitive.
1939 $vals['expectedoutput'] = \core_text
::strtolower($vals['expectedoutput']);
1940 $vals['expectedoutputhtml'] = \core_text
::strtolower($vals['expectedoutputhtml']);
1941 $actualoutput = \core_text
::strtolower($actualoutput);
1942 $actualoutputhtml = \core_text
::strtolower($actualoutputhtml);
1944 $this->assertSame($vals['expectedoutput'], $actualoutput,
1945 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput} \ndata: " . var_export($vals, true));
1946 $this->assertSame($vals['expectedoutputhtml'], $actualoutputhtml,
1947 "Expected: {$vals['expectedoutputhtml']} => Actual: {$actualoutputhtml} \ndata: " . var_export($vals, true));
1952 * Make sure the DST changes happen at the right time in Moodle.
1954 public function test_dst_changes() {
1955 // DST switching in Prague.
1956 // From 2AM to 3AM in 1989.
1957 $date = new \
DateTime('1989-03-26T01:59:00+01:00');
1958 $this->assertSame('Sunday, 26 March 1989, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1959 $date = new \
DateTime('1989-03-26T02:01:00+01:00');
1960 $this->assertSame('Sunday, 26 March 1989, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1961 // From 3AM to 2AM in 1989 - not the same as the west Europe.
1962 $date = new \
DateTime('1989-09-24T01:59:00+01:00');
1963 $this->assertSame('Sunday, 24 September 1989, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1964 $date = new \
DateTime('1989-09-24T02:01:00+01:00');
1965 $this->assertSame('Sunday, 24 September 1989, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1966 // From 2AM to 3AM in 2014.
1967 $date = new \
DateTime('2014-03-30T01:59:00+01:00');
1968 $this->assertSame('Sunday, 30 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1969 $date = new \
DateTime('2014-03-30T02:01:00+01:00');
1970 $this->assertSame('Sunday, 30 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1971 // From 3AM to 2AM in 2014.
1972 $date = new \
DateTime('2014-10-26T01:59:00+01:00');
1973 $this->assertSame('Sunday, 26 October 2014, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1974 $date = new \
DateTime('2014-10-26T02:01:00+01:00');
1975 $this->assertSame('Sunday, 26 October 2014, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1976 // From 2AM to 3AM in 2020.
1977 $date = new \
DateTime('2020-03-29T01:59:00+01:00');
1978 $this->assertSame('Sunday, 29 March 2020, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1979 $date = new \
DateTime('2020-03-29T02:01:00+01:00');
1980 $this->assertSame('Sunday, 29 March 2020, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1981 // From 3AM to 2AM in 2020.
1982 $date = new \
DateTime('2020-10-25T01:59:00+01:00');
1983 $this->assertSame('Sunday, 25 October 2020, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1984 $date = new \
DateTime('2020-10-25T02:01:00+01:00');
1985 $this->assertSame('Sunday, 25 October 2020, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1987 // DST switching in NZ.
1988 // From 3AM to 2AM in 2015.
1989 $date = new \
DateTime('2015-04-05T02:59:00+13:00');
1990 $this->assertSame('Sunday, 5 April 2015, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1991 $date = new \
DateTime('2015-04-05T03:01:00+13:00');
1992 $this->assertSame('Sunday, 5 April 2015, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1993 // From 2AM to 3AM in 2009.
1994 $date = new \
DateTime('2015-09-27T01:59:00+12:00');
1995 $this->assertSame('Sunday, 27 September 2015, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1996 $date = new \
DateTime('2015-09-27T02:01:00+12:00');
1997 $this->assertSame('Sunday, 27 September 2015, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1999 // DST switching in Perth.
2000 // From 3AM to 2AM in 2009.
2001 $date = new \
DateTime('2008-03-30T01:59:00+08:00');
2002 $this->assertSame('Sunday, 30 March 2008, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
2003 $date = new \
DateTime('2008-03-30T02:01:00+08:00');
2004 $this->assertSame('Sunday, 30 March 2008, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
2005 // From 2AM to 3AM in 2009.
2006 $date = new \
DateTime('2008-10-26T01:59:00+08:00');
2007 $this->assertSame('Sunday, 26 October 2008, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
2008 $date = new \
DateTime('2008-10-26T02:01:00+08:00');
2009 $this->assertSame('Sunday, 26 October 2008, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
2011 // DST switching in US.
2012 // From 2AM to 3AM in 2014.
2013 $date = new \
DateTime('2014-03-09T01:59:00-05:00');
2014 $this->assertSame('Sunday, 9 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
2015 $date = new \
DateTime('2014-03-09T02:01:00-05:00');
2016 $this->assertSame('Sunday, 9 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
2017 // From 3AM to 2AM in 2014.
2018 $date = new \
DateTime('2014-11-02T01:59:00-04:00');
2019 $this->assertSame('Sunday, 2 November 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
2020 $date = new \
DateTime('2014-11-02T02:01:00-04:00');
2021 $this->assertSame('Sunday, 2 November 2014, 01:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
2024 public function test_make_timestamp() {
2025 global $USER, $CFG, $DB;
2026 $this->resetAfterTest();
2028 $this->setAdminUser();
2030 $testvalues = array(
2032 'usertimezone' => 'America/Moncton',
2039 'timezone' => '0.0',
2040 'applydst' => false, // No dst offset.
2041 'expectedoutput' => '1309514400' // 6pm at UTC+0.
2044 'usertimezone' => 'America/Moncton',
2051 'timezone' => '99', // User default timezone.
2052 'applydst' => false, // Don't apply dst.
2053 'expectedoutput' => '1309528800'
2056 'usertimezone' => 'America/Moncton',
2063 'timezone' => '99', // User default timezone.
2064 'applydst' => true, // Apply dst.
2065 'expectedoutput' => '1309525200'
2068 'usertimezone' => 'America/Moncton',
2075 'timezone' => 'America/Moncton', // String timezone.
2076 'applydst' => true, // Apply dst.
2077 'expectedoutput' => '1309525200'
2080 'usertimezone' => '2', // No dst applyed.
2087 'timezone' => '99', // Take user timezone.
2088 'applydst' => true, // Apply dst.
2089 'expectedoutput' => '1309507200'
2092 'usertimezone' => '-2', // No dst applyed.
2099 'timezone' => '99', // Take usertimezone.
2100 'applydst' => true, // Apply dst.
2101 'expectedoutput' => '1309521600'
2104 'usertimezone' => '-10', // No dst applyed.
2111 'timezone' => '2', // Take this timezone.
2112 'applydst' => true, // Apply dst.
2113 'expectedoutput' => '1309507200'
2116 'usertimezone' => '-10', // No dst applyed.
2123 'timezone' => '-2', // Take this timezone.
2124 'applydst' => true, // Apply dst.
2125 'expectedoutput' => '1309521600'
2128 'usertimezone' => '-10', // No dst applyed.
2135 'timezone' => 'random/time', // This should show server time.
2136 'applydst' => true, // Apply dst.
2137 'expectedoutput' => '1309485600'
2140 'usertimezone' => '-14', // Server time.
2147 'timezone' => '99', // Get user time.
2148 'applydst' => true, // Apply dst.
2149 'expectedoutput' => '1309485600'
2153 // Set default timezone to Australia/Perth, else time calculated
2154 // will not match expected values.
2155 $this->setTimezone(99, 'Australia/Perth');
2157 // Test make_timestamp with all testvals and assert if anything wrong.
2158 foreach ($testvalues as $vals) {
2159 $USER->timezone
= $vals['usertimezone'];
2160 $actualoutput = make_timestamp(
2171 // On different systems case of AM PM changes so compare case insensitive.
2172 $vals['expectedoutput'] = \core_text
::strtolower($vals['expectedoutput']);
2173 $actualoutput = \core_text
::strtolower($actualoutput);
2175 $this->assertSame($vals['expectedoutput'], $actualoutput,
2176 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
2177 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
2182 * Test get_string and most importantly the implementation of the lang_string
2185 public function test_get_string() {
2188 // Make sure we are using English.
2189 $originallang = $COURSE->lang
;
2190 $COURSE->lang
= 'en';
2192 $yes = get_string('yes');
2193 $yesexpected = 'Yes';
2194 $this->assertIsString($yes);
2195 $this->assertSame($yesexpected, $yes);
2197 $yes = get_string('yes', 'moodle');
2198 $this->assertIsString($yes);
2199 $this->assertSame($yesexpected, $yes);
2201 $yes = get_string('yes', 'core');
2202 $this->assertIsString($yes);
2203 $this->assertSame($yesexpected, $yes);
2205 $yes = get_string('yes', '');
2206 $this->assertIsString($yes);
2207 $this->assertSame($yesexpected, $yes);
2209 $yes = get_string('yes', null);
2210 $this->assertIsString($yes);
2211 $this->assertSame($yesexpected, $yes);
2213 $yes = get_string('yes', null, 1);
2214 $this->assertIsString($yes);
2215 $this->assertSame($yesexpected, $yes);
2218 $numdays = get_string('numdays', 'core', '1');
2219 $numdaysexpected = $days.' days';
2220 $this->assertIsString($numdays);
2221 $this->assertSame($numdaysexpected, $numdays);
2223 $yes = get_string('yes', null, null, true);
2224 $this->assertInstanceOf('lang_string', $yes);
2225 $this->assertSame($yesexpected, (string)$yes);
2227 // Test lazy loading (returning lang_string) correctly interpolates 0 being used as args.
2228 $numdays = get_string('numdays', 'moodle', 0, true);
2229 $this->assertInstanceOf(lang_string
::class, $numdays);
2230 $this->assertSame('0 days', (string) $numdays);
2232 // Test using a lang_string object as the $a argument for a normal
2233 // get_string call (returning string).
2234 $test = new lang_string('yes', null, null, true);
2235 $testexpected = get_string('numdays', 'core', get_string('yes'));
2236 $testresult = get_string('numdays', null, $test);
2237 $this->assertIsString($testresult);
2238 $this->assertSame($testexpected, $testresult);
2240 // Test using a lang_string object as the $a argument for an object
2241 // get_string call (returning lang_string).
2242 $test = new lang_string('yes', null, null, true);
2243 $testexpected = get_string('numdays', 'core', get_string('yes'));
2244 $testresult = get_string('numdays', null, $test, true);
2245 $this->assertInstanceOf('lang_string', $testresult);
2246 $this->assertSame($testexpected, "$testresult");
2248 // Make sure that object properties that can't be converted don't cause
2250 // Level one: This is as deep as current language processing goes.
2251 $test = new \stdClass
;
2252 $test->one
= 'here';
2253 $string = get_string('yes', null, $test, true);
2254 $this->assertEquals($yesexpected, $string);
2256 // Make sure that object properties that can't be converted don't cause
2258 // Level two: Language processing doesn't currently reach this deep.
2259 // only immediate scalar properties are worked with.
2260 $test = new \stdClass
;
2261 $test->one
= new \stdClass
;
2262 $test->one
->two
= 'here';
2263 $string = get_string('yes', null, $test, true);
2264 $this->assertEquals($yesexpected, $string);
2266 // Make sure that object properties that can't be converted don't cause
2268 // Level three: It should never ever go this deep, but we're making sure
2269 // it doesn't cause any probs anyway.
2270 $test = new \stdClass
;
2271 $test->one
= new \stdClass
;
2272 $test->one
->two
= new \stdClass
;
2273 $test->one
->two
->three
= 'here';
2274 $string = get_string('yes', null, $test, true);
2275 $this->assertEquals($yesexpected, $string);
2277 // Make sure that object properties that can't be converted don't cause
2278 // errors and check lang_string properties.
2279 // Level one: This is as deep as current language processing goes.
2280 $test = new \stdClass
;
2281 $test->one
= new lang_string('yes');
2282 $string = get_string('yes', null, $test, true);
2283 $this->assertEquals($yesexpected, $string);
2285 // Make sure that object properties that can't be converted don't cause
2286 // errors and check lang_string properties.
2287 // Level two: Language processing doesn't currently reach this deep.
2288 // only immediate scalar properties are worked with.
2289 $test = new \stdClass
;
2290 $test->one
= new \stdClass
;
2291 $test->one
->two
= new lang_string('yes');
2292 $string = get_string('yes', null, $test, true);
2293 $this->assertEquals($yesexpected, $string);
2295 // Make sure that object properties that can't be converted don't cause
2296 // errors and check lang_string properties.
2297 // Level three: It should never ever go this deep, but we're making sure
2298 // it doesn't cause any probs anyway.
2299 $test = new \stdClass
;
2300 $test->one
= new \stdClass
;
2301 $test->one
->two
= new \stdClass
;
2302 $test->one
->two
->three
= new lang_string('yes');
2303 $string = get_string('yes', null, $test, true);
2304 $this->assertEquals($yesexpected, $string);
2306 // Make sure that array properties that can't be converted don't cause
2309 $test['one'] = new \stdClass
;
2310 $test['one']->two
= 'here';
2311 $string = get_string('yes', null, $test, true);
2312 $this->assertEquals($yesexpected, $string);
2314 // Same thing but as above except using an object... this is allowed :P.
2315 $string = get_string('yes', null, null, true);
2316 $object = new \stdClass
;
2317 $object->$string = 'Yes';
2318 $this->assertEquals($yesexpected, $string);
2319 $this->assertEquals($yesexpected, $object->$string);
2321 // Reset the language.
2322 $COURSE->lang
= $originallang;
2325 public function test_lang_string_var_export() {
2327 // Call var_export() on a newly generated lang_string.
2328 $str = new lang_string('no');
2330 // In PHP 8.2 exported class names are now fully qualified;
2331 // previously, the leading backslash was omitted.
2332 $leadingbackslash = (version_compare(PHP_VERSION
, '8.2.0', '>=')) ?
'\\' : '';
2335 {$leadingbackslash}lang_string::__set_state(array(
2336 'identifier' => 'no',
2337 'component' => 'moodle',
2341 'forcedstring' => false,
2345 $v = var_export($str, true);
2346 $this->assertEquals($expected1, $v);
2348 // Now execute the code that was returned - it should produce a correct string.
2349 $str = lang_string
::__set_state(array(
2350 'identifier' => 'no',
2351 'component' => 'moodle',
2355 'forcedstring' => false,
2358 $this->assertInstanceOf(lang_string
::class, $str);
2359 $this->assertEquals('No', $str);
2362 public function test_get_string_limitation() {
2363 // This is one of the limitations to the lang_string class. It can't be
2365 if (PHP_VERSION_ID
>= 80000) {
2366 $this->expectException(\TypeError
::class);
2368 $this->expectWarning();
2370 $array = array(get_string('yes', null, null, true) => 'yes');
2374 * Test localised float formatting.
2376 public function test_format_float() {
2378 // Special case for null.
2379 $this->assertEquals('', format_float(null));
2381 // Default 1 decimal place.
2382 $this->assertEquals('5.4', format_float(5.43));
2383 $this->assertEquals('5.0', format_float(5.001));
2385 // Custom number of decimal places.
2386 $this->assertEquals('5.43000', format_float(5.43, 5));
2388 // Auto detect the number of decimal places.
2389 $this->assertEquals('5.43', format_float(5.43, -1));
2390 $this->assertEquals('5.43', format_float(5.43000, -1));
2391 $this->assertEquals('5', format_float(5, -1));
2392 $this->assertEquals('5', format_float(5.0, -1));
2393 $this->assertEquals('0.543', format_float('5.43e-1', -1));
2394 $this->assertEquals('0.543', format_float('5.43000e-1', -1));
2396 // Option to strip ending zeros after rounding.
2397 $this->assertEquals('5.43', format_float(5.43, 5, true, true));
2398 $this->assertEquals('5', format_float(5.0001, 3, true, true));
2399 $this->assertEquals('100', format_float(100, 2, true, true));
2400 $this->assertEquals('100', format_float(100, 0, true, true));
2402 // Tests with a localised decimal separator.
2403 $this->define_local_decimal_separator();
2405 // Localisation on (default).
2406 $this->assertEquals('5X43000', format_float(5.43, 5));
2407 $this->assertEquals('5X43', format_float(5.43, 5, true, true));
2409 // Localisation off.
2410 $this->assertEquals('5.43000', format_float(5.43, 5, false));
2411 $this->assertEquals('5.43', format_float(5.43, 5, false, true));
2413 // Tests with tilde as localised decimal separator.
2414 $this->define_local_decimal_separator('~');
2416 // Must also work for '~' as decimal separator.
2417 $this->assertEquals('5', format_float(5.0001, 3, true, true));
2418 $this->assertEquals('5~43000', format_float(5.43, 5));
2419 $this->assertEquals('5~43', format_float(5.43, 5, true, true));
2423 * Test localised float unformatting.
2425 public function test_unformat_float() {
2427 // Tests without the localised decimal separator.
2429 // Special case for null, empty or white spaces only strings.
2430 $this->assertEquals(null, unformat_float(null));
2431 $this->assertEquals(null, unformat_float(''));
2432 $this->assertEquals(null, unformat_float(' '));
2435 $this->assertEquals(5.4, unformat_float('5.4'));
2436 $this->assertEquals(5.4, unformat_float('5.4', true));
2439 $this->assertEquals(5.0, unformat_float('5'));
2441 // Custom number of decimal.
2442 $this->assertEquals(5.43267, unformat_float('5.43267'));
2445 $this->assertEquals(100.0, unformat_float('100.00'));
2447 // With the thousand separator.
2448 $this->assertEquals(1000.0, unformat_float('1 000'));
2449 $this->assertEquals(1000.32, unformat_float('1 000.32'));
2452 $this->assertEquals(-100.0, unformat_float('-100'));
2455 $this->assertEquals(0.0, unformat_float('Wrong value'));
2456 // Wrong value in strict mode.
2457 $this->assertFalse(unformat_float('Wrong value', true));
2459 // Combining options.
2460 $this->assertEquals(-1023.862567, unformat_float(' -1 023.862567 '));
2462 // Bad decimal separator (should crop the decimal).
2463 $this->assertEquals(50.0, unformat_float('50,57'));
2464 // Bad decimal separator in strict mode (should return false).
2465 $this->assertFalse(unformat_float('50,57', true));
2467 // Tests with a localised decimal separator.
2468 $this->define_local_decimal_separator();
2470 // We repeat the tests above but with the current decimal separator.
2472 // Regular use without and with the localised separator.
2473 $this->assertEquals (5.4, unformat_float('5.4'));
2474 $this->assertEquals (5.4, unformat_float('5X4'));
2476 // Custom number of decimal.
2477 $this->assertEquals (5.43267, unformat_float('5X43267'));
2480 $this->assertEquals (100.0, unformat_float('100X00'));
2482 // With the thousand separator.
2483 $this->assertEquals (1000.32, unformat_float('1 000X32'));
2485 // Bad different separator (should crop the decimal).
2486 $this->assertEquals (50.0, unformat_float('50Y57'));
2487 // Bad different separator in strict mode (should return false).
2488 $this->assertFalse (unformat_float('50Y57', true));
2490 // Combining options.
2491 $this->assertEquals (-1023.862567, unformat_float(' -1 023X862567 '));
2492 // Combining options in strict mode.
2493 $this->assertEquals (-1023.862567, unformat_float(' -1 023X862567 ', true));
2497 * Test deleting of users.
2499 public function test_delete_user() {
2502 $this->resetAfterTest();
2504 $guest = $DB->get_record('user', array('id'=>$CFG->siteguest
), '*', MUST_EXIST
);
2505 $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins
), '*', MUST_EXIST
);
2506 $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
2508 $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
2509 $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
2510 $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
2511 $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
2512 $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => ''));
2513 $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => ''));
2515 // Delete user and capture event.
2516 $sink = $this->redirectEvents();
2517 $result = delete_user($user);
2518 $events = $sink->get_events();
2520 $event = array_pop($events);
2522 // Test user is deleted in DB.
2523 $this->assertTrue($result);
2524 $deluser = $DB->get_record('user', array('id'=>$user->id
), '*', MUST_EXIST
);
2525 $this->assertEquals(1, $deluser->deleted
);
2526 $this->assertEquals(0, $deluser->picture
);
2527 $this->assertSame('', $deluser->idnumber
);
2528 $this->assertSame(md5($user->username
), $deluser->email
);
2529 $this->assertMatchesRegularExpression('/^'.preg_quote($user->email
, '/').'\.\d*$/', $deluser->username
);
2531 $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
2534 $this->assertInstanceOf('\core\event\user_deleted', $event);
2535 $this->assertSame($user->id
, $event->objectid
);
2536 $eventdata = $event->get_data();
2537 $this->assertSame($eventdata['other']['username'], $user->username
);
2538 $this->assertSame($eventdata['other']['email'], $user->email
);
2539 $this->assertSame($eventdata['other']['idnumber'], $user->idnumber
);
2540 $this->assertSame($eventdata['other']['picture'], $user->picture
);
2541 $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid
);
2542 $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid
));
2543 $this->assertEventContextNotUsed($event);
2545 // Try invalid params.
2546 $record = new \
stdClass();
2549 delete_user($record);
2550 $this->fail('Expecting exception for invalid delete_user() $user parameter');
2551 } catch (\moodle_exception
$ex) {
2552 $this->assertInstanceOf('coding_exception', $ex);
2556 delete_user($record);
2557 $this->fail('Expecting exception for invalid delete_user() $user parameter');
2558 } catch (\moodle_exception
$ex) {
2559 $this->assertInstanceOf('coding_exception', $ex);
2562 $record = new \
stdClass();
2564 $record->username
= 'xx';
2565 $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
2566 $result = delete_user($record);
2567 $this->assertFalse($result);
2569 $result = delete_user($guest);
2570 $this->assertFalse($result);
2572 $result = delete_user($admin);
2573 $this->assertFalse($result);
2575 // Simultaneously deleting users with identical email addresses.
2576 $result1 = delete_user($usersharedemail1);
2577 $result2 = delete_user($usersharedemail2);
2579 $usersharedemail1after = $DB->get_record('user', array('id' => $usersharedemail1->id
));
2580 $usersharedemail2after = $DB->get_record('user', array('id' => $usersharedemail2->id
));
2581 $this->assertTrue($result1);
2582 $this->assertTrue($result2);
2583 $this->assertStringStartsWith($usersharedemail1->email
. '.', $usersharedemail1after->username
);
2584 $this->assertStringStartsWith($usersharedemail2->email
. '.', $usersharedemail2after->username
);
2586 // Simultaneously deleting users without email addresses.
2587 $result1 = delete_user($useremptyemail1);
2588 $result2 = delete_user($useremptyemail2);
2590 $useremptyemail1after = $DB->get_record('user', array('id' => $useremptyemail1->id
));
2591 $useremptyemail2after = $DB->get_record('user', array('id' => $useremptyemail2->id
));
2592 $this->assertTrue($result1);
2593 $this->assertTrue($result2);
2594 $this->assertStringStartsWith($useremptyemail1->username
. '.' . $useremptyemail1->id
. '@unknownemail.invalid.',
2595 $useremptyemail1after->username
);
2596 $this->assertStringStartsWith($useremptyemail2->username
. '.' . $useremptyemail2->id
. '@unknownemail.invalid.',
2597 $useremptyemail2after->username
);
2599 $this->resetDebugging();
2603 * Test deletion of user with long username
2605 public function test_delete_user_long_username() {
2608 $this->resetAfterTest();
2610 // For users without an e-mail, one will be created during deletion using {$username}.{$id}@unknownemail.invalid format.
2611 $user = $this->getDataGenerator()->create_user([
2612 'username' => str_repeat('a', 75),
2618 // The username for the deleted user shouldn't exceed 100 characters.
2619 $usernamedeleted = $DB->get_field('user', 'username', ['id' => $user->id
]);
2620 $this->assertEquals(100, \core_text
::strlen($usernamedeleted));
2622 $timestrlength = \core_text
::strlen((string) time());
2624 // It should start with the user name, and end with the current time.
2625 $this->assertStringStartsWith("{$user->username}.{$user->id}@", $usernamedeleted);
2626 $this->assertMatchesRegularExpression('/\.\d{' . $timestrlength . '}$/', $usernamedeleted);
2630 * Test deletion of user with long email address
2632 public function test_delete_user_long_email() {
2635 $this->resetAfterTest();
2637 // Create user with 90 character email address.
2638 $user = $this->getDataGenerator()->create_user([
2639 'email' => str_repeat('a', 78) . '@example.com',
2644 // The username for the deleted user shouldn't exceed 100 characters.
2645 $usernamedeleted = $DB->get_field('user', 'username', ['id' => $user->id
]);
2646 $this->assertEquals(100, \core_text
::strlen($usernamedeleted));
2648 $timestrlength = \core_text
::strlen((string) time());
2650 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
2651 $expectedemail = \core_text
::substr($user->email
, 0, 100 - ($timestrlength +
1));
2652 $this->assertMatchesRegularExpression('/^' . preg_quote($expectedemail) . '\.\d{' . $timestrlength . '}$/',
2657 * Test function convert_to_array()
2659 public function test_convert_to_array() {
2660 // Check that normal classes are converted to arrays the same way as (array) would do.
2661 $obj = new \
stdClass();
2662 $obj->prop1
= 'hello';
2663 $obj->prop2
= array('first', 'second', 13);
2665 $this->assertEquals(convert_to_array($obj), (array)$obj);
2667 // Check that context object (with iterator) is converted to array properly.
2668 $obj = \context_system
::instance();
2671 'contextlevel' => $obj->contextlevel
,
2672 'instanceid' => $obj->instanceid
,
2673 'path' => $obj->path
,
2674 'depth' => $obj->depth
,
2675 'locked' => $obj->locked
,
2677 $this->assertEquals(convert_to_array($obj), $ar);
2681 * Test the function date_format_string().
2683 public function test_date_format_string() {
2686 $this->resetAfterTest();
2687 $this->setTimezone(99, 'Australia/Perth');
2692 'str' => '%A, %d %B %Y, %I:%M %p',
2693 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
2697 'str' => '%A, %d %B %Y, %I:%M %p',
2698 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2701 // Note: this function expected the timestamp in weird format before,
2702 // since 2.9 it uses UTC.
2703 'tz' => 'Pacific/Auckland',
2704 'str' => '%A, %d %B %Y, %I:%M %p',
2705 'expected' => 'Saturday, 01 January 2011, 11:00 PM'
2707 // Following tests pass on Windows only because en lang pack does
2708 // not contain localewincharset, in real life lang pack maintainers
2709 // may use only characters that are present in localewincharset
2710 // in format strings!
2713 'str' => 'Žluťoučký koníček %A',
2714 'expected' => 'Žluťoučký koníček Saturday'
2718 'str' => '言語設定言語 %A',
2719 'expected' => '言語設定言語 Saturday'
2723 'str' => '简体中文简体 %A',
2724 'expected' => '简体中文简体 Saturday'
2728 // Note: date_format_string() uses the timezone only to differenciate
2729 // the server time from the UTC time. It does not modify the timestamp.
2730 // Hence similar results for timezones <= 13.
2731 // On different systems case of AM PM changes so compare case insensitive.
2732 foreach ($tests as $test) {
2733 $str = date_format_string(1293876000, $test['str'], $test['tz']);
2734 $this->assertSame(\core_text
::strtolower($test['expected']), \core_text
::strtolower($str));
2738 public function test_get_config() {
2741 $this->resetAfterTest();
2744 set_config('phpunit_test_get_config_1', 'test 1');
2745 set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2746 if (!is_array($CFG->config_php_settings
)) {
2747 $CFG->config_php_settings
= array();
2749 $CFG->config_php_settings
['phpunit_test_get_config_3'] = 'test 3';
2751 if (!is_array($CFG->forced_plugin_settings
)) {
2752 $CFG->forced_plugin_settings
= array();
2754 if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings
)) {
2755 $CFG->forced_plugin_settings
['mod_forum'] = array();
2757 $CFG->forced_plugin_settings
['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2758 $CFG->phpunit_test_get_config_5
= 'test 5';
2761 $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
2762 $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2763 $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
2764 $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2765 $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2766 $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2767 $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2769 // Test config we know to exist.
2770 $this->assertSame($CFG->dataroot
, get_config('core', 'dataroot'));
2771 $this->assertSame($CFG->phpunit_dataroot
, get_config('core', 'phpunit_dataroot'));
2772 $this->assertSame($CFG->dataroot
, get_config('core', 'phpunit_dataroot'));
2773 $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2775 // Test setting a config var that already exists.
2776 set_config('phpunit_test_get_config_1', 'test a');
2777 $this->assertSame('test a', $CFG->phpunit_test_get_config_1
);
2778 $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
2780 // Test cache invalidation.
2781 $cache = \cache
::make('core', 'config');
2782 $this->assertIsArray($cache->get('core'));
2783 $this->assertIsArray($cache->get('mod_forum'));
2784 set_config('phpunit_test_get_config_1', 'test b');
2785 $this->assertFalse($cache->get('core'));
2786 set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2787 $this->assertFalse($cache->get('mod_forum'));
2790 public function test_get_max_upload_sizes() {
2791 // Test with very low limits so we are not affected by php upload limits.
2792 // Test activity limit smallest.
2793 $sitebytes = 102400;
2794 $coursebytes = 51200;
2795 $modulebytes = 10240;
2796 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2799 $this->assertSame("Activity upload limit (10{$nbsp}KB)", $result['0']);
2800 $this->assertCount(2, $result);
2802 // Test course limit smallest.
2803 $sitebytes = 102400;
2804 $coursebytes = 10240;
2805 $modulebytes = 51200;
2806 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2808 $this->assertSame("Course upload limit (10{$nbsp}KB)", $result['0']);
2809 $this->assertCount(2, $result);
2811 // Test site limit smallest.
2813 $coursebytes = 102400;
2814 $modulebytes = 51200;
2815 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2817 $this->assertSame("Site upload limit (10{$nbsp}KB)", $result['0']);
2818 $this->assertCount(2, $result);
2820 // Test site limit not set.
2822 $coursebytes = 102400;
2823 $modulebytes = 51200;
2824 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2826 $this->assertSame("Activity upload limit (50{$nbsp}KB)", $result['0']);
2827 $this->assertCount(3, $result);
2830 $coursebytes = 51200;
2831 $modulebytes = 102400;
2832 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2834 $this->assertSame("Course upload limit (50{$nbsp}KB)", $result['0']);
2835 $this->assertCount(3, $result);
2837 // Test custom bytes in range.
2838 $sitebytes = 102400;
2839 $coursebytes = 51200;
2840 $modulebytes = 51200;
2841 $custombytes = 10240;
2842 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2844 $this->assertCount(3, $result);
2846 // Test custom bytes in range but non-standard.
2847 $sitebytes = 102400;
2848 $coursebytes = 51200;
2849 $modulebytes = 51200;
2850 $custombytes = 25600;
2851 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2853 $this->assertCount(4, $result);
2855 // Test custom bytes out of range.
2856 $sitebytes = 102400;
2857 $coursebytes = 51200;
2858 $modulebytes = 51200;
2859 $custombytes = 102400;
2860 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2862 $this->assertCount(3, $result);
2864 // Test custom bytes out of range and non-standard.
2865 $sitebytes = 102400;
2866 $coursebytes = 51200;
2867 $modulebytes = 51200;
2868 $custombytes = 256000;
2869 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2871 $this->assertCount(3, $result);
2873 // Test site limit only.
2875 $result = get_max_upload_sizes($sitebytes);
2877 $this->assertSame("Site upload limit (50{$nbsp}KB)", $result['0']);
2878 $this->assertSame("50{$nbsp}KB", $result['51200']);
2879 $this->assertSame("10{$nbsp}KB", $result['10240']);
2880 $this->assertCount(3, $result);
2883 $result = get_max_upload_sizes();
2884 $this->assertArrayHasKey('0', $result);
2885 $this->assertArrayHasKey(get_max_upload_file_size(), $result);
2889 * Test function password_is_legacy_hash().
2891 public function test_password_is_legacy_hash() {
2892 // Well formed md5s should be matched.
2893 foreach (array('some', 'strings', 'to_check!') as $string) {
2894 $md5 = md5($string);
2895 $this->assertTrue(password_is_legacy_hash($md5));
2897 // Strings that are not md5s should not be matched.
2898 foreach (array('', AUTH_PASSWORD_NOT_CACHED
, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
2899 $this->assertFalse(password_is_legacy_hash($notmd5));
2904 * Test function validate_internal_user_password().
2906 public function test_validate_internal_user_password() {
2907 // Test bcrypt hashes.
2908 $validhashes = array(
2909 'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2910 'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2911 'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2912 'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
2915 foreach ($validhashes as $password => $hash) {
2916 $user = new \
stdClass();
2917 $user->auth
= 'manual';
2918 $user->password
= $hash;
2919 // The correct password should be validated.
2920 $this->assertTrue(validate_internal_user_password($user, $password));
2921 // An incorrect password should not be validated.
2922 $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2927 * Test function hash_internal_user_password().
2929 public function test_hash_internal_user_password() {
2930 $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2932 // Check that some passwords that we convert to hashes can
2934 foreach ($passwords as $password) {
2935 $hash = hash_internal_user_password($password);
2936 $fasthash = hash_internal_user_password($password, true);
2937 $user = new \
stdClass();
2938 $user->auth
= 'manual';
2939 $user->password
= $hash;
2940 $this->assertTrue(validate_internal_user_password($user, $password));
2942 // They should not be in md5 format.
2943 $this->assertFalse(password_is_legacy_hash($hash));
2945 // Check that cost factor in hash is correctly set.
2946 $this->assertMatchesRegularExpression('/\$10\$/', $hash);
2947 $this->assertMatchesRegularExpression('/\$04\$/', $fasthash);
2952 * Test function update_internal_user_password().
2954 public function test_update_internal_user_password() {
2956 $this->resetAfterTest();
2957 $passwords = array('password', '1234', 'changeme', '****');
2958 foreach ($passwords as $password) {
2959 $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2960 update_internal_user_password($user, $password);
2961 // The user object should have been updated.
2962 $this->assertTrue(validate_internal_user_password($user, $password));
2963 // The database field for the user should also have been updated to the
2965 $this->assertSame($user->password
, $DB->get_field('user', 'password', array('id' => $user->id
)));
2968 $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2969 // Manually set the user's password to the md5 of the string 'password'.
2970 $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id
));
2972 $sink = $this->redirectEvents();
2973 // Update the password.
2974 update_internal_user_password($user, 'password');
2975 $events = $sink->get_events();
2977 $event = array_pop($events);
2979 // Password should have been updated to a bcrypt hash.
2980 $this->assertFalse(password_is_legacy_hash($user->password
));
2982 // Verify event information.
2983 $this->assertInstanceOf('\core\event\user_password_updated', $event);
2984 $this->assertSame($user->id
, $event->relateduserid
);
2985 $this->assertEquals(\context_user
::instance($user->id
), $event->get_context());
2986 $this->assertEventContextNotUsed($event);
2988 // Verify recovery of property 'auth'.
2990 update_internal_user_password($user, 'newpassword');
2991 $this->assertDebuggingCalled('User record in update_internal_user_password() must include field auth',
2993 $this->assertEquals('manual', $user->auth
);
2997 * Testing that if the password is not cached, that it does not update
2998 * the user table and fire event.
3000 public function test_update_internal_user_password_no_cache() {
3002 $this->resetAfterTest();
3004 $user = $this->getDataGenerator()->create_user(array('auth' => 'cas'));
3005 $DB->update_record('user', ['id' => $user->id
, 'password' => AUTH_PASSWORD_NOT_CACHED
]);
3006 $user->password
= AUTH_PASSWORD_NOT_CACHED
;
3008 $sink = $this->redirectEvents();
3009 update_internal_user_password($user, 'wonkawonka');
3010 $this->assertEquals(0, $sink->count(), 'User updated event should not fire');
3014 * Test if the user has a password hash, but now their auth method
3015 * says not to cache it. Then it should update.
3017 public function test_update_internal_user_password_update_no_cache() {
3018 $this->resetAfterTest();
3020 $user = $this->getDataGenerator()->create_user(array('password' => 'test'));
3021 $this->assertNotEquals(AUTH_PASSWORD_NOT_CACHED
, $user->password
);
3022 $user->auth
= 'cas'; // Change to a auth that does not store passwords.
3024 $sink = $this->redirectEvents();
3025 update_internal_user_password($user, 'wonkawonka');
3026 $this->assertGreaterThanOrEqual(1, $sink->count(), 'User updated event should fire');
3028 $this->assertEquals(AUTH_PASSWORD_NOT_CACHED
, $user->password
);
3031 public function test_fullname() {
3034 $this->resetAfterTest();
3036 // Create a user to test the name display on.
3038 $record['firstname'] = 'Scott';
3039 $record['lastname'] = 'Fletcher';
3040 $record['firstnamephonetic'] = 'スコット';
3041 $record['lastnamephonetic'] = 'フレチャー';
3042 $record['alternatename'] = 'No friends';
3043 $user = $this->getDataGenerator()->create_user($record);
3045 // Back up config settings for restore later.
3046 $originalcfg = new \
stdClass();
3047 $originalcfg->fullnamedisplay
= $CFG->fullnamedisplay
;
3048 $originalcfg->alternativefullnameformat
= $CFG->alternativefullnameformat
;
3050 // Testing existing fullnamedisplay settings.
3051 $CFG->fullnamedisplay
= 'firstname';
3052 $testname = fullname($user);
3053 $this->assertSame($user->firstname
, $testname);
3055 $CFG->fullnamedisplay
= 'firstname lastname';
3056 $expectedname = "$user->firstname $user->lastname";
3057 $testname = fullname($user);
3058 $this->assertSame($expectedname, $testname);
3060 $CFG->fullnamedisplay
= 'lastname firstname';
3061 $expectedname = "$user->lastname $user->firstname";
3062 $testname = fullname($user);
3063 $this->assertSame($expectedname, $testname);
3065 $expectedname = get_string('fullnamedisplay', null, $user);
3066 $CFG->fullnamedisplay
= 'language';
3067 $testname = fullname($user);
3068 $this->assertSame($expectedname, $testname);
3070 // Test override parameter.
3071 $CFG->fullnamedisplay
= 'firstname';
3072 $expectedname = "$user->firstname $user->lastname";
3073 $testname = fullname($user, true);
3074 $this->assertSame($expectedname, $testname);
3076 // Test alternativefullnameformat setting.
3077 // Test alternativefullnameformat that has been set to nothing.
3078 $CFG->alternativefullnameformat
= '';
3079 $expectedname = "$user->firstname $user->lastname";
3080 $testname = fullname($user, true);
3081 $this->assertSame($expectedname, $testname);
3083 // Test alternativefullnameformat that has been set to 'language'.
3084 $CFG->alternativefullnameformat
= 'language';
3085 $expectedname = "$user->firstname $user->lastname";
3086 $testname = fullname($user, true);
3087 $this->assertSame($expectedname, $testname);
3089 // Test customising the alternativefullnameformat setting with all additional name fields.
3090 $CFG->alternativefullnameformat
= 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename';
3091 $expectedname = "$user->firstname $user->lastname $user->firstnamephonetic $user->lastnamephonetic $user->middlename $user->alternatename";
3092 $testname = fullname($user, true);
3093 $this->assertSame($expectedname, $testname);
3095 // Test additional name fields.
3096 $CFG->fullnamedisplay
= 'lastname lastnamephonetic firstname firstnamephonetic';
3097 $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
3098 $testname = fullname($user);
3099 $this->assertSame($expectedname, $testname);
3101 // Test for handling missing data.
3102 $user->middlename
= null;
3103 // Parenthesis with no data.
3104 $CFG->fullnamedisplay
= 'firstname (middlename) lastname';
3105 $expectedname = "$user->firstname $user->lastname";
3106 $testname = fullname($user);
3107 $this->assertSame($expectedname, $testname);
3109 // Extra spaces due to no data.
3110 $CFG->fullnamedisplay
= 'firstname middlename lastname';
3111 $expectedname = "$user->firstname $user->lastname";
3112 $testname = fullname($user);
3113 $this->assertSame($expectedname, $testname);
3115 // Regular expression testing.
3116 // Remove some data from the user fields.
3117 $user->firstnamephonetic
= '';
3118 $user->lastnamephonetic
= '';
3120 // Removing empty brackets and excess whitespace.
3121 // All of these configurations should resolve to just firstname lastname.
3122 $configarray = array();
3123 $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
3124 $configarray[] = 'firstname lastname \'middlename\'';
3125 $configarray[] = 'firstname "firstnamephonetic" lastname';
3126 $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
3128 foreach ($configarray as $config) {
3129 $CFG->fullnamedisplay
= $config;
3130 $expectedname = "$user->firstname $user->lastname";
3131 $testname = fullname($user);
3132 $this->assertSame($expectedname, $testname);
3135 // Check to make sure that other characters are left in place.
3136 $configarray = array();
3137 $configarray['0'] = new \
stdClass();
3138 $configarray['0']->config
= 'lastname firstname, middlename';
3139 $configarray['0']->expectedname
= "$user->lastname $user->firstname,";
3140 $configarray['1'] = new \
stdClass();
3141 $configarray['1']->config
= 'lastname firstname + alternatename';
3142 $configarray['1']->expectedname
= "$user->lastname $user->firstname + $user->alternatename";
3143 $configarray['2'] = new \
stdClass();
3144 $configarray['2']->config
= 'firstname aka: alternatename';
3145 $configarray['2']->expectedname
= "$user->firstname aka: $user->alternatename";
3146 $configarray['3'] = new \
stdClass();
3147 $configarray['3']->config
= 'firstname (alternatename)';
3148 $configarray['3']->expectedname
= "$user->firstname ($user->alternatename)";
3149 $configarray['4'] = new \
stdClass();
3150 $configarray['4']->config
= 'firstname [alternatename]';
3151 $configarray['4']->expectedname
= "$user->firstname [$user->alternatename]";
3152 $configarray['5'] = new \
stdClass();
3153 $configarray['5']->config
= 'firstname "lastname"';
3154 $configarray['5']->expectedname
= "$user->firstname \"$user->lastname\"";
3156 foreach ($configarray as $config) {
3157 $CFG->fullnamedisplay
= $config->config
;
3158 $expectedname = $config->expectedname
;
3159 $testname = fullname($user);
3160 $this->assertSame($expectedname, $testname);
3163 // Test debugging message displays when
3164 // fullnamedisplay setting is "normal".
3165 $CFG->fullnamedisplay
= 'firstname lastname';
3167 $user = new \
stdClass();
3168 $user->firstname
= 'Stan';
3169 $user->lastname
= 'Lee';
3170 $namedisplay = fullname($user);
3171 $this->assertDebuggingCalled();
3173 // Tidy up after we finish testing.
3174 $CFG->fullnamedisplay
= $originalcfg->fullnamedisplay
;
3175 $CFG->alternativefullnameformat
= $originalcfg->alternativefullnameformat
;
3179 * Tests the get_all_user_name_fields() deprecated function.
3181 * @deprecated since Moodle 3.11 MDL-45242
3183 public function test_get_all_user_name_fields() {
3184 $this->resetAfterTest();
3186 // Additional names in an array.
3187 $testarray = array('firstnamephonetic' => 'firstnamephonetic',
3188 'lastnamephonetic' => 'lastnamephonetic',
3189 'middlename' => 'middlename',
3190 'alternatename' => 'alternatename',
3191 'firstname' => 'firstname',
3192 'lastname' => 'lastname');
3193 $this->assertEquals($testarray, get_all_user_name_fields());
3195 // Additional names as a string.
3196 $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
3197 $this->assertEquals($teststring, get_all_user_name_fields(true));
3199 // Additional names as a string with an alias.
3200 $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
3201 $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
3203 // Additional name fields with a prefix - object.
3204 $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
3205 'lastnamephonetic' => 'authorlastnamephonetic',
3206 'middlename' => 'authormiddlename',
3207 'alternatename' => 'authoralternatename',
3208 'firstname' => 'authorfirstname',
3209 'lastname' => 'authorlastname');
3210 $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
3212 // Additional name fields with an alias and a title - string.
3213 $teststring = 'u.firstnamephonetic AS authorfirstnamephonetic,u.lastnamephonetic AS authorlastnamephonetic,u.middlename AS authormiddlename,u.alternatename AS authoralternatename,u.firstname AS authorfirstname,u.lastname AS authorlastname';
3214 $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
3216 // Test the order parameter of the function.
3217 // Returning an array.
3218 $testarray = array('firstname' => 'firstname',
3219 'lastname' => 'lastname',
3220 'firstnamephonetic' => 'firstnamephonetic',
3221 'lastnamephonetic' => 'lastnamephonetic',
3222 'middlename' => 'middlename',
3223 'alternatename' => 'alternatename'
3225 $this->assertEquals($testarray, get_all_user_name_fields(false, null, null, null, true));
3227 // Returning a string.
3228 $teststring = 'firstname,lastname,firstnamephonetic,lastnamephonetic,middlename,alternatename';
3229 $this->assertEquals($teststring, get_all_user_name_fields(true, null, null, null, true));
3231 $this->assertDebuggingCalledCount(7);
3234 public function test_order_in_string() {
3235 $this->resetAfterTest();
3237 // Return an array in an order as they are encountered in a string.
3238 $valuearray = array('second', 'firsthalf', 'first');
3239 $formatstring = 'first firsthalf some other text (second)';
3240 $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
3241 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
3243 // Try again with a different order for the format.
3244 $valuearray = array('second', 'firsthalf', 'first');
3245 $formatstring = 'firsthalf first second';
3246 $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
3247 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
3249 // Try again with yet another different order for the format.
3250 $valuearray = array('second', 'firsthalf', 'first');
3251 $formatstring = 'start seconds away second firstquater first firsthalf';
3252 $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
3253 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
3256 public function test_complete_user_login() {
3259 $this->resetAfterTest();
3260 $user = $this->getDataGenerator()->create_user();
3263 $sink = $this->redirectEvents();
3264 $loginuser = clone($user);
3265 $this->setCurrentTimeStart();
3266 @complete_user_login
($loginuser); // Hide session header errors.
3267 $this->assertSame($loginuser, $USER);
3268 $this->assertEquals($user->id
, $USER->id
);
3269 $events = $sink->get_events();
3272 $this->assertCount(1, $events);
3273 $event = reset($events);
3274 $this->assertInstanceOf('\core\event\user_loggedin', $event);
3275 $this->assertEquals('user', $event->objecttable
);
3276 $this->assertEquals($user->id
, $event->objectid
);
3277 $this->assertEquals(\context_system
::instance()->id
, $event->contextid
);
3278 $this->assertEventContextNotUsed($event);
3280 $user = $DB->get_record('user', array('id'=>$user->id
));
3282 $this->assertTimeCurrent($user->firstaccess
);
3283 $this->assertTimeCurrent($user->lastaccess
);
3285 $this->assertTimeCurrent($USER->firstaccess
);
3286 $this->assertTimeCurrent($USER->lastaccess
);
3287 $this->assertTimeCurrent($USER->currentlogin
);
3288 $this->assertSame(sesskey(), $USER->sesskey
);
3289 $this->assertTimeCurrent($USER->preference
['_lastloaded']);
3290 $this->assertObjectNotHasAttribute('password', $USER);
3291 $this->assertObjectNotHasAttribute('description', $USER);
3295 * Test require_logout.
3297 public function test_require_logout() {
3298 $this->resetAfterTest();
3299 $user = $this->getDataGenerator()->create_user();
3300 $this->setUser($user);
3302 $this->assertTrue(isloggedin());
3304 // Logout user and capture event.
3305 $sink = $this->redirectEvents();
3307 $events = $sink->get_events();
3309 $event = array_pop($events);
3311 // Check if user is logged out.
3312 $this->assertFalse(isloggedin());
3315 $this->assertInstanceOf('\core\event\user_loggedout', $event);
3316 $this->assertSame($user->id
, $event->objectid
);
3317 $this->assertEventContextNotUsed($event);
3321 * A data provider for testing email messageid
3323 public function generate_email_messageid_provider() {
3326 'wwwroot' => 'http://www.example.com',
3328 'a-custom-id' => '<a-custom-id@www.example.com>',
3329 'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash@www.example.com>',
3333 'wwwroot' => 'http://www.example.com/path/subdir',
3335 'a-custom-id' => '<a-custom-id/path/subdir@www.example.com>',
3336 'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash/path/subdir@www.example.com>',
3343 * Test email message id generation
3345 * @dataProvider generate_email_messageid_provider
3347 * @param string $wwwroot The wwwroot
3348 * @param array $msgids An array of msgid local parts and the final result
3350 public function test_generate_email_messageid($wwwroot, $msgids) {
3353 $this->resetAfterTest();
3354 $CFG->wwwroot
= $wwwroot;
3356 foreach ($msgids as $local => $final) {
3357 $this->assertEquals($final, generate_email_messageid($local));
3362 * Test email with custom headers
3364 public function test_send_email_with_custom_header() {
3366 $this->preventResetByRollback();
3367 $this->resetAfterTest();
3369 $touser = $this->getDataGenerator()->create_user();
3370 $fromuser = $this->getDataGenerator()->create_user();
3371 $fromuser->customheaders
= 'X-Custom-Header: foo';
3373 set_config('allowedemaildomains', 'example.com');
3374 set_config('emailheaders', 'X-Fixed-Header: bar');
3376 $sink = $this->redirectEmails();
3377 email_to_user($touser, $fromuser, 'subject', 'message');
3379 $emails = $sink->get_messages();
3380 $this->assertCount(1, $emails);
3381 $email = reset($emails);
3382 $this->assertStringContainsString('X-Custom-Header: foo', $email->header
);
3383 $this->assertStringContainsString("X-Fixed-Header: bar", $email->header
);
3388 * A data provider for testing email diversion
3390 public function diverted_emails_provider() {
3392 'nodiverts' => array(
3393 'divertallemailsto' => null,
3394 'divertallemailsexcept' => null,
3398 'fred.jones@example.com',
3401 'fred+verp@example.com',
3405 'alldiverts' => array(
3406 'divertallemailsto' => 'somewhere@elsewhere.com',
3407 'divertallemailsexcept' => null,
3411 'fred.jones@example.com',
3414 'fred+verp@example.com',
3418 'alsodiverts' => array(
3419 'divertallemailsto' => 'somewhere@elsewhere.com',
3420 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
3424 'fred.jones@example.com',
3425 'Fred.Jones@Example.com',
3429 'divertsexceptions' => array(
3430 'divertallemailsto' => 'somewhere@elsewhere.com',
3431 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
3436 'fred+verp@example.com',
3440 'divertsexceptionsnewline' => array(
3441 'divertallemailsto' => 'somewhere@elsewhere.com',
3442 'divertallemailsexcept' => "@dev.com\nfred(\+.*)?@example.com",
3446 'fred+verp@example.com',
3450 'alsodivertsnewline' => array(
3451 'divertallemailsto' => 'somewhere@elsewhere.com',
3452 'divertallemailsexcept' => "@dev.com\nfred(\+.*)?@example.com",
3456 'fred.jones@example.com',
3460 'alsodivertsblankline' => array(
3461 'divertallemailsto' => 'somewhere@elsewhere.com',
3462 'divertallemailsexcept' => "@dev.com\n",
3464 'lionel@example.com',
3468 'divertsexceptionblankline' => array(
3469 'divertallemailsto' => 'somewhere@elsewhere.com',
3470 'divertallemailsexcept' => "@example.com\n",
3472 'lionel@example.com',
3480 * Test email diversion
3482 * @dataProvider diverted_emails_provider
3484 * @param string $divertallemailsto An optional email address
3485 * @param string $divertallemailsexcept An optional exclusion list
3486 * @param array $addresses An array of test addresses
3487 * @param boolean $expected Expected result
3489 public function test_email_should_be_diverted($divertallemailsto, $divertallemailsexcept, $addresses, $expected) {
3492 $this->resetAfterTest();
3493 $CFG->divertallemailsto
= $divertallemailsto;
3494 $CFG->divertallemailsexcept
= $divertallemailsexcept;
3496 foreach ($addresses as $address) {
3497 $this->assertEquals($expected, email_should_be_diverted($address));
3501 public function test_email_to_user() {
3504 $this->resetAfterTest();
3506 $user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1, 'mailformat' => 0));
3507 $user2 = $this->getDataGenerator()->create_user(array('maildisplay' => 1, 'mailformat' => 1));
3508 $user3 = $this->getDataGenerator()->create_user(array('maildisplay' => 0));
3509 set_config('allowedemaildomains', "example.com\r\nmoodle.org");
3511 $subject = 'subject';
3512 $messagetext = 'message text';
3513 $subject2 = 'subject 2';
3514 $messagetext2 = '<b>message text 2</b>';
3516 // Close the default email sink.
3517 $sink = $this->redirectEmails();
3520 $CFG->noemailever
= true;
3521 $this->assertNotEmpty($CFG->noemailever
);
3522 email_to_user($user1, $user2, $subject, $messagetext);
3523 $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
3525 unset_config('noemailever');
3527 email_to_user($user1, $user2, $subject, $messagetext);
3528 $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
3530 $sink = $this->redirectEmails();
3531 email_to_user($user1, $user2, $subject, $messagetext);
3532 email_to_user($user2, $user1, $subject2, $messagetext2);
3533 $this->assertSame(2, $sink->count());
3534 $result = $sink->get_messages();
3535 $this->assertCount(2, $result);
3538 $this->assertSame($subject, $result[0]->subject
);
3539 $this->assertSame($messagetext, trim($result[0]->body
));
3540 $this->assertSame($user1->email
, $result[0]->to
);
3541 $this->assertSame($user2->email
, $result[0]->from
);
3542 $this->assertStringContainsString('Content-Type: text/plain', $result[0]->header
);
3544 $this->assertSame($subject2, $result[1]->subject
);
3545 $this->assertStringContainsString($messagetext2, quoted_printable_decode($result[1]->body
));
3546 $this->assertSame($user2->email
, $result[1]->to
);
3547 $this->assertSame($user1->email
, $result[1]->from
);
3548 $this->assertStringNotContainsString('Content-Type: text/plain', $result[1]->header
);
3550 email_to_user($user1, $user2, $subject, $messagetext);
3551 $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
3553 // Test that an empty noreplyaddress will default to a no-reply address.
3554 $sink = $this->redirectEmails();
3555 email_to_user($user1, $user3, $subject, $messagetext);
3556 $result = $sink->get_messages();
3557 $this->assertEquals($CFG->noreplyaddress
, $result[0]->from
);
3559 set_config('noreplyaddress', '');
3560 $sink = $this->redirectEmails();
3561 email_to_user($user1, $user3, $subject, $messagetext);
3562 $result = $sink->get_messages();
3563 $this->assertEquals('noreply@www.example.com', $result[0]->from
);
3566 // Test $CFG->allowedemaildomains.
3567 set_config('noreplyaddress', 'noreply@www.example.com');
3568 $this->assertNotEmpty($CFG->allowedemaildomains
);
3569 $sink = $this->redirectEmails();
3570 email_to_user($user1, $user2, $subject, $messagetext);
3571 unset_config('allowedemaildomains');
3572 email_to_user($user1, $user2, $subject, $messagetext);
3573 $result = $sink->get_messages();
3574 $this->assertNotEquals($CFG->noreplyaddress
, $result[0]->from
);
3575 $this->assertEquals($CFG->noreplyaddress
, $result[1]->from
);
3578 // Try to send an unsafe attachment, we should see an error message in the eventual mail body.
3579 $attachment = '../test.txt';
3580 $attachname = 'txt';
3582 $sink = $this->redirectEmails();
3583 email_to_user($user1, $user2, $subject, $messagetext, '', $attachment, $attachname);
3584 $this->assertSame(1, $sink->count());
3585 $result = $sink->get_messages();
3586 $this->assertCount(1, $result);
3587 $this->assertStringContainsString('error.txt', $result[0]->body
);
3588 $this->assertStringContainsString('Error in attachment. User attempted to attach a filename with a unsafe name.', $result[0]->body
);
3593 * Data provider for {@see test_email_to_user_attachment}
3597 public function email_to_user_attachment_provider(): array {
3600 // Return all paths that can be used to send attachments from.
3602 'cachedir' => [$CFG->cachedir
],
3603 'dataroot' => [$CFG->dataroot
],
3604 'dirroot' => [$CFG->dirroot
],
3605 'localcachedir' => [$CFG->localcachedir
],
3606 'tempdir' => [$CFG->tempdir
],
3607 // Paths within $CFG->localrequestdir.
3608 'localrequestdir_request_directory' => [make_request_directory()],
3609 'localrequestdir_request_storage_directory' => [get_request_storage_directory()],
3610 // Pass null to indicate we want to test a path relative to $CFG->dataroot.
3611 'relative' => [null]
3616 * Test sending attachments with email_to_user
3618 * @param string|null $filedir
3620 * @dataProvider email_to_user_attachment_provider
3622 public function test_email_to_user_attachment(?
string $filedir): void
{
3625 // If $filedir is null, then write our test file to $CFG->dataroot.
3626 $filepath = ($filedir ?
: $CFG->dataroot
) . '/hello.txt';
3627 file_put_contents($filepath, 'Hello');
3629 $user = \core_user
::get_support_user();
3630 $message = 'Test attachment path';
3632 // Create sink to catch all sent e-mails.
3633 $sink = $this->redirectEmails();
3635 // Attachment path will be that of the test file if $filedir was passed, otherwise the relative path from $CFG->dataroot.
3636 $filename = basename($filepath);
3637 $attachmentpath = $filedir ?
$filepath : $filename;
3638 email_to_user($user, $user, $message, $message, $message, $attachmentpath, $filename);
3640 $messages = $sink->get_messages();
3643 $this->assertCount(1, $messages);
3645 // Verify attachment in message body (attachment is in MIME format, but we can detect some Content fields).
3646 $messagebody = reset($messages)->body
;
3647 $this->assertStringContainsString('Content-Type: text/plain; name=' . $filename, $messagebody);
3648 $this->assertStringContainsString('Content-Disposition: attachment; filename=' . $filename, $messagebody);
3655 * Test sending an attachment that doesn't exist to email_to_user
3657 public function test_email_to_user_attachment_missing(): void
{
3658 $user = \core_user
::get_support_user();
3659 $message = 'Test attachment path';
3661 // Create sink to catch all sent e-mails.
3662 $sink = $this->redirectEmails();
3664 $attachmentpath = '/hola/hello.txt';
3665 $filename = basename($attachmentpath);
3666 email_to_user($user, $user, $message, $message, $message, $attachmentpath, $filename);
3668 $messages = $sink->get_messages();
3671 $this->assertCount(1, $messages);
3673 // Verify attachment not in message body (attachment is in MIME format, but we can detect some Content fields).
3674 $messagebody = reset($messages)->body
;
3675 $this->assertStringNotContainsString('Content-Type: text/plain; name="' . $filename . '"', $messagebody);
3676 $this->assertStringNotContainsString('Content-Disposition: attachment; filename=' . $filename, $messagebody);
3680 * Test setnew_password_and_mail.
3682 public function test_setnew_password_and_mail() {
3685 $this->resetAfterTest();
3687 $user = $this->getDataGenerator()->create_user();
3689 // Update user password.
3690 $sink = $this->redirectEvents();
3691 $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
3692 setnew_password_and_mail($user);
3693 $events = $sink->get_events();
3696 $event = array_pop($events);
3698 // Test updated value.
3699 $dbuser = $DB->get_record('user', array('id' => $user->id
));
3700 $this->assertSame($user->firstname
, $dbuser->firstname
);
3701 $this->assertNotEmpty($dbuser->password
);
3704 $this->assertInstanceOf('\core\event\user_password_updated', $event);
3705 $this->assertSame($user->id
, $event->relateduserid
);
3706 $this->assertEquals(\context_user
::instance($user->id
), $event->get_context());
3707 $this->assertEventContextNotUsed($event);
3711 * Data provider for test_generate_confirmation_link
3712 * @return Array of confirmation urls and expected resultant confirmation links
3714 public function generate_confirmation_link_provider() {
3718 "username" => "simplename",
3719 "confirmationurl" => null,
3720 "expected" => $CFG->wwwroot
. "/login/confirm.php?data=/simplename"
3722 "Period in between words in username" => [
3723 "username" => "period.inbetween",
3724 "confirmationurl" => null,
3725 "expected" => $CFG->wwwroot
. "/login/confirm.php?data=/period%2Einbetween"
3727 "Trailing periods in username" => [
3728 "username" => "trailingperiods...",
3729 "confirmationurl" => null,
3730 "expected" => $CFG->wwwroot
. "/login/confirm.php?data=/trailingperiods%2E%2E%2E"
3732 "At symbol in username" => [
3733 "username" => "at@symbol",
3734 "confirmationurl" => null,
3735 "expected" => $CFG->wwwroot
. "/login/confirm.php?data=/at%40symbol"
3737 "Dash symbol in username" => [
3738 "username" => "has-dash",
3739 "confirmationurl" => null,
3740 "expected" => $CFG->wwwroot
. "/login/confirm.php?data=/has-dash"
3742 "Underscore in username" => [
3743 "username" => "under_score",
3744 "confirmationurl" => null,
3745 "expected" => $CFG->wwwroot
. "/login/confirm.php?data=/under_score"
3747 "Many different characters in username" => [
3748 "username" => "many_-.@characters@_@-..-..",
3749 "confirmationurl" => null,
3750 "expected" => $CFG->wwwroot
. "/login/confirm.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3752 "Custom relative confirmation url" => [
3753 "username" => "many_-.@characters@_@-..-..",
3754 "confirmationurl" => "/custom/local/url.php",
3755 "expected" => $CFG->wwwroot
. "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3757 "Custom relative confirmation url with parameters" => [
3758 "username" => "many_-.@characters@_@-..-..",
3759 "confirmationurl" => "/custom/local/url.php?with=param",
3760 "expected" => $CFG->wwwroot
. "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3762 "Custom local confirmation url" => [
3763 "username" => "many_-.@characters@_@-..-..",
3764 "confirmationurl" => $CFG->wwwroot
. "/custom/local/url.php",
3765 "expected" => $CFG->wwwroot
. "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3767 "Custom local confirmation url with parameters" => [
3768 "username" => "many_-.@characters@_@-..-..",
3769 "confirmationurl" => $CFG->wwwroot
. "/custom/local/url.php?with=param",
3770 "expected" => $CFG->wwwroot
. "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3772 "Custom external confirmation url" => [
3773 "username" => "many_-.@characters@_@-..-..",
3774 "confirmationurl" => "http://moodle.org/custom/external/url.php",
3775 "expected" => "http://moodle.org/custom/external/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3777 "Custom external confirmation url with parameters" => [
3778 "username" => "many_-.@characters@_@-..-..",
3779 "confirmationurl" => "http://moodle.org/ext.php?with=some¶m=eters",
3780 "expected" => "http://moodle.org/ext.php?with=some¶m=eters&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3782 "Custom external confirmation url with parameters" => [
3783 "username" => "many_-.@characters@_@-..-..",
3784 "confirmationurl" => "http://moodle.org/ext.php?with=some&data=test",
3785 "expected" => "http://moodle.org/ext.php?with=some&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3791 * Test generate_confirmation_link
3792 * @dataProvider generate_confirmation_link_provider
3793 * @param string $username The name of the user
3794 * @param string $confirmationurl The url the user should go to to confirm
3795 * @param string $expected The expected url of the confirmation link
3797 public function test_generate_confirmation_link($username, $confirmationurl, $expected) {
3798 $this->resetAfterTest();
3799 $sink = $this->redirectEmails();
3801 $user = $this->getDataGenerator()->create_user(
3803 "username" => $username,
3805 "email" => 'test@example.com',
3809 send_confirmation_email($user, $confirmationurl);
3811 $messages = $sink->get_messages();
3812 $message = array_shift($messages);
3813 $messagebody = quoted_printable_decode($message->body
);
3815 $this->assertStringContainsString($expected, $messagebody);
3819 * Test generate_confirmation_link with custom admin link
3821 public function test_generate_confirmation_link_with_custom_admin() {
3824 $this->resetAfterTest();
3825 $sink = $this->redirectEmails();
3827 $admin = $CFG->admin
;
3828 $CFG->admin
= 'custom/admin/path';
3830 $user = $this->getDataGenerator()->create_user(
3832 "username" => "many_-.@characters@_@-..-..",
3834 "email" => 'test@example.com',
3837 $confirmationurl = "/admin/test.php?with=params";
3838 $expected = $CFG->wwwroot
. "/" . $CFG->admin
. "/test.php?with=params&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E";
3840 send_confirmation_email($user, $confirmationurl);
3842 $messages = $sink->get_messages();
3843 $message = array_shift($messages);
3844 $messagebody = quoted_printable_decode($message->body
);
3847 $this->assertStringContainsString($expected, $messagebody);
3849 $CFG->admin
= $admin;
3854 * Test remove_course_content deletes course contents
3855 * TODO Add asserts to verify other data related to course is deleted as well.
3857 public function test_remove_course_contents() {
3859 $this->resetAfterTest();
3861 $course = $this->getDataGenerator()->create_course();
3862 $user = $this->getDataGenerator()->create_user();
3863 $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
3864 $note = $gen->create_instance(array('courseid' => $course->id
, 'userid' => $user->id
));
3866 $this->assertNotEquals(false, note_load($note->id
));
3867 remove_course_contents($course->id
, false);
3868 $this->assertFalse(note_load($note->id
));
3872 * Test function username_load_fields_from_object().
3874 public function test_username_load_fields_from_object() {
3875 $this->resetAfterTest();
3877 // This object represents the information returned from an sql query.
3878 $userinfo = new \
stdClass();
3879 $userinfo->userid
= 1;
3880 $userinfo->username
= 'loosebruce';
3881 $userinfo->firstname
= 'Bruce';
3882 $userinfo->lastname
= 'Campbell';
3883 $userinfo->firstnamephonetic
= 'ブルース';
3884 $userinfo->lastnamephonetic
= 'カンベッル';
3885 $userinfo->middlename
= '';
3886 $userinfo->alternatename
= '';
3887 $userinfo->email
= '';
3888 $userinfo->picture
= 23;
3889 $userinfo->imagealt
= 'Michael Jordan draining another basket.';
3890 $userinfo->idnumber
= 3982;
3892 // Just user name fields.
3893 $user = new \
stdClass();
3894 $user = username_load_fields_from_object($user, $userinfo);
3895 $expectedarray = new \
stdClass();
3896 $expectedarray->firstname
= 'Bruce';
3897 $expectedarray->lastname
= 'Campbell';
3898 $expectedarray->firstnamephonetic
= 'ブルース';
3899 $expectedarray->lastnamephonetic
= 'カンベッル';
3900 $expectedarray->middlename
= '';
3901 $expectedarray->alternatename
= '';
3902 $this->assertEquals($user, $expectedarray);
3904 // User information for showing a picture.
3905 $user = new \
stdClass();
3906 $additionalfields = explode(',', implode(',', \core_user\fields
::get_picture_fields()));
3907 $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
3908 $user->id
= $userinfo->userid
;
3909 $expectedarray = new \
stdClass();
3910 $expectedarray->id
= 1;
3911 $expectedarray->firstname
= 'Bruce';
3912 $expectedarray->lastname
= 'Campbell';
3913 $expectedarray->firstnamephonetic
= 'ブルース';
3914 $expectedarray->lastnamephonetic
= 'カンベッル';
3915 $expectedarray->middlename
= '';
3916 $expectedarray->alternatename
= '';
3917 $expectedarray->email
= '';
3918 $expectedarray->picture
= 23;
3919 $expectedarray->imagealt
= 'Michael Jordan draining another basket.';
3920 $this->assertEquals($user, $expectedarray);
3922 // Alter the userinfo object to have a prefix.
3923 $userinfo->authorfirstname
= 'Bruce';
3924 $userinfo->authorlastname
= 'Campbell';
3925 $userinfo->authorfirstnamephonetic
= 'ブルース';
3926 $userinfo->authorlastnamephonetic
= 'カンベッル';
3927 $userinfo->authormiddlename
= '';
3928 $userinfo->authorpicture
= 23;
3929 $userinfo->authorimagealt
= 'Michael Jordan draining another basket.';
3930 $userinfo->authoremail
= 'test@example.com';
3933 // Return an object with user picture information.
3934 $user = new \
stdClass();
3935 $additionalfields = explode(',', implode(',', \core_user\fields
::get_picture_fields()));
3936 $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
3937 $user->id
= $userinfo->userid
;
3938 $expectedarray = new \
stdClass();
3939 $expectedarray->id
= 1;
3940 $expectedarray->firstname
= 'Bruce';
3941 $expectedarray->lastname
= 'Campbell';
3942 $expectedarray->firstnamephonetic
= 'ブルース';
3943 $expectedarray->lastnamephonetic
= 'カンベッル';
3944 $expectedarray->middlename
= '';
3945 $expectedarray->alternatename
= '';
3946 $expectedarray->email
= 'test@example.com';
3947 $expectedarray->picture
= 23;
3948 $expectedarray->imagealt
= 'Michael Jordan draining another basket.';
3949 $this->assertEquals($user, $expectedarray);
3953 * Test function {@see count_words()}.
3955 * @dataProvider count_words_testcases
3956 * @param int $expectedcount number of words in $string.
3957 * @param string $string the test string to count the words of.
3958 * @param int|null $format
3960 public function test_count_words(int $expectedcount, string $string, $format = null): void
{
3961 $this->assertEquals($expectedcount, count_words($string, $format),
3962 "'$string' with format '$format' does not match count $expectedcount");
3966 * Data provider for {@see test_count_words}.
3968 * @return array of test cases.
3970 public function count_words_testcases(): array {
3971 // Copy-pasting example from MDL-64240.
3972 $copypasted = <<<EOT
3973 <p onclick="alert('boop');">Snoot is booped</p>
3974 <script>alert('Boop the snoot');</script>
3975 <img alt="Boop the Snoot." src="https://proxy.duckduckgo.com/iu/?u=http%3A%2F%2Fwww.geekfill.com%2Fwp-content%2Fuploads%2F2015%2F08%2FBoop-the-Snoot.jpg&f=1">
3978 // The counts here should match MS Word and Libre Office.
3981 [4, 'one two three four'],
3985 [2, 'one two'],
3986 [1, 'email@example.com'],
3987 [2, 'first\part second/part'],
3988 [4, '<p>one two<br></br>three four</p>'],
3989 [4, '<p>one two<br>three four</p>'],
3990 [4, '<p>one two<br />three four</p>'], // XHTML style.
3991 [3, ' one ... three '],
3993 [3, ' one & three '],
3997 [4, '1³ £2 €3.45 $6,789'],
3998 [2, 'ブルース カンベッル'], // MS word counts this as 11, but we don't handle that yet.
3999 [4, '<p>one two</p><p>three four</p>'],
4000 [4, '<p>one two</p><p><br/></p><p>three four</p>'],
4001 [4, '<p>one</p><ul><li>two</li><li>three</li></ul><p>four.</p>'],
4002 [1, '<p>em<b>phas</b>is.</p>'],
4003 [1, '<p>em<i>phas</i>is.</p>'],
4004 [1, '<p>em<strong>phas</strong>is.</p>'],
4005 [1, '<p>em<em>phas</em>is.</p>'],
4011 [1, "SO<sub>4</sub><sup>2-</sup>"],
4012 [6, '4+4=8 i.e. O(1) a,b,c,d I’m black&blue_really'],
4013 [1, '<span>a</span><span>b</span>'],
4014 [1, '<span>a</span><span>b</span>', FORMAT_PLAIN
],
4015 [1, '<span>a</span><span>b</span>', FORMAT_HTML
],
4016 [1, '<span>a</span><span>b</span>', FORMAT_MOODLE
],
4017 [1, '<span>a</span><span>b</span>', FORMAT_MARKDOWN
],
4018 [1, 'aa <argh <bleh>pokus</bleh>'],
4019 [2, 'aa <argh <bleh>pokus</bleh>', FORMAT_HTML
],
4021 [6, $copypasted, FORMAT_PLAIN
],
4022 [3, $copypasted, FORMAT_HTML
],
4023 [3, $copypasted, FORMAT_MOODLE
],
4028 * Test function {@see count_letters()}.
4030 * @dataProvider count_letters_testcases
4031 * @param int $expectedcount number of characters in $string.
4032 * @param string $string the test string to count the letters of.
4033 * @param int|null $format
4035 public function test_count_letters(int $expectedcount, string $string, $format = null): void
{
4036 $this->assertEquals($expectedcount, count_letters($string, $format),
4037 "'$string' with format '$format' does not match count $expectedcount");
4041 * Data provider for {@see count_letters_testcases}.
4043 * @return array of test cases.
4045 public function count_letters_testcases(): array {
4051 [4, '<p>frog</p>', FORMAT_PLAIN
],
4052 [4, '<p>frog</p>', FORMAT_MOODLE
],
4053 [4, '<p>frog</p>', FORMAT_HTML
],
4054 [4, '<p>frog</p>', FORMAT_MARKDOWN
],
4055 [2, 'aa <argh <bleh>pokus</bleh>'],
4056 [7, 'aa <argh <bleh>pokus</bleh>', FORMAT_HTML
],
4061 * Tests the getremoteaddr() function.
4063 public function test_getremoteaddr() {
4066 $this->resetAfterTest();
4068 $CFG->getremoteaddrconf
= null; // Use default value, GETREMOTEADDR_SKIP_DEFAULT.
4069 $noip = getremoteaddr('1.1.1.1');
4070 $this->assertEquals('1.1.1.1', $noip);
4072 $remoteaddr = isset($_SERVER['REMOTE_ADDR']) ?
$_SERVER['REMOTE_ADDR'] : null;
4073 $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
4074 $singleip = getremoteaddr();
4075 $this->assertEquals('127.0.0.1', $singleip);
4077 $_SERVER['REMOTE_ADDR'] = $remoteaddr; // Restore server value.
4079 $CFG->getremoteaddrconf
= 0; // Don't skip any source.
4080 $noip = getremoteaddr('1.1.1.1');
4081 $this->assertEquals('1.1.1.1', $noip);
4083 // Populate all $_SERVER values to review order.
4085 'HTTP_CLIENT_IP' => '2.2.2.2',
4086 'HTTP_X_FORWARDED_FOR' => '3.3.3.3',
4087 'REMOTE_ADDR' => '4.4.4.4',
4089 $originalvalues = [];
4090 foreach ($ipsources as $source => $ip) {
4091 $originalvalues[$source] = isset($_SERVER[$source]) ?
$_SERVER[$source] : null; // Saving data to restore later.
4092 $_SERVER[$source] = $ip;
4095 foreach ($ipsources as $source => $expectedip) {
4096 $ip = getremoteaddr();
4097 $this->assertEquals($expectedip, $ip);
4098 unset($_SERVER[$source]); // Removing the value so next time we get the following ip.
4101 // Restore server values.
4102 foreach ($originalvalues as $source => $ip) {
4103 $_SERVER[$source] = $ip;
4106 // All $_SERVER values have been removed, we should get the default again.
4107 $noip = getremoteaddr('1.1.1.1');
4108 $this->assertEquals('1.1.1.1', $noip);
4110 $CFG->getremoteaddrconf
= GETREMOTEADDR_SKIP_HTTP_CLIENT_IP
;
4111 $xforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ?
$_SERVER['HTTP_X_FORWARDED_FOR'] : null;
4113 $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
4114 $noip = getremoteaddr('1.1.1.1');
4115 $this->assertEquals('1.1.1.1', $noip);
4117 $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
4118 $noip = getremoteaddr();
4119 $this->assertEquals('0.0.0.0', $noip);
4121 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1';
4122 $singleip = getremoteaddr();
4123 $this->assertEquals('127.0.0.1', $singleip);
4125 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2';
4126 $twoip = getremoteaddr();
4127 $this->assertEquals('127.0.0.2', $twoip);
4129 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2,127.0.0.3';
4130 $threeip = getremoteaddr();
4131 $this->assertEquals('127.0.0.3', $threeip);
4133 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2:65535';
4134 $portip = getremoteaddr();
4135 $this->assertEquals('127.0.0.2', $portip);
4137 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,0:0:0:0:0:0:0:2';
4138 $portip = getremoteaddr();
4139 $this->assertEquals('0:0:0:0:0:0:0:2', $portip);
4141 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,0::2';
4142 $portip = getremoteaddr();
4143 $this->assertEquals('0:0:0:0:0:0:0:2', $portip);
4145 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,[0:0:0:0:0:0:0:2]:65535';
4146 $portip = getremoteaddr();
4147 $this->assertEquals('0:0:0:0:0:0:0:2', $portip);
4149 $_SERVER['HTTP_X_FORWARDED_FOR'] = $xforwardedfor;
4154 * Test emulation of random_bytes() function.
4156 public function test_random_bytes_emulate() {
4157 $result = random_bytes_emulate(10);
4158 $this->assertSame(10, strlen($result));
4159 $this->assertnotSame($result, random_bytes_emulate(10));
4161 $result = random_bytes_emulate(21);
4162 $this->assertSame(21, strlen($result));
4163 $this->assertnotSame($result, random_bytes_emulate(21));
4165 $result = random_bytes_emulate(666);
4166 $this->assertSame(666, strlen($result));
4168 $result = random_bytes_emulate(40);
4169 $this->assertSame(40, strlen($result));
4171 $this->assertDebuggingNotCalled();
4173 $result = random_bytes_emulate(0);
4174 $this->assertSame('', $result);
4175 $this->assertDebuggingCalled();
4177 $result = random_bytes_emulate(-1);
4178 $this->assertSame('', $result);
4179 $this->assertDebuggingCalled();
4183 * Test function for creation of random strings.
4185 public function test_random_string() {
4186 $pool = 'a-zA-Z0-9';
4188 $result = random_string(10);
4189 $this->assertSame(10, strlen($result));
4190 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4191 $this->assertNotSame($result, random_string(10));
4193 $result = random_string(21);
4194 $this->assertSame(21, strlen($result));
4195 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4196 $this->assertNotSame($result, random_string(21));
4198 $result = random_string(666);
4199 $this->assertSame(666, strlen($result));
4200 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4202 $result = random_string();
4203 $this->assertSame(15, strlen($result));
4204 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4206 $this->assertDebuggingNotCalled();
4208 $result = random_string(0);
4209 $this->assertSame('', $result);
4210 $this->assertDebuggingCalled();
4212 $result = random_string(-1);
4213 $this->assertSame('', $result);
4214 $this->assertDebuggingCalled();
4218 * Test function for creation of complex random strings.
4220 public function test_complex_random_string() {
4221 $pool = preg_quote('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#%^&*()_+-=[];,./<>?:{} ', '/');
4223 $result = complex_random_string(10);
4224 $this->assertSame(10, strlen($result));
4225 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4226 $this->assertNotSame($result, complex_random_string(10));
4228 $result = complex_random_string(21);
4229 $this->assertSame(21, strlen($result));
4230 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4231 $this->assertNotSame($result, complex_random_string(21));
4233 $result = complex_random_string(666);
4234 $this->assertSame(666, strlen($result));
4235 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4237 $result = complex_random_string();
4238 $this->assertEqualsWithDelta(28, strlen($result), 4); // Expected length is 24 - 32.
4239 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4241 $this->assertDebuggingNotCalled();
4243 $result = complex_random_string(0);
4244 $this->assertSame('', $result);
4245 $this->assertDebuggingCalled();
4247 $result = complex_random_string(-1);
4248 $this->assertSame('', $result);
4249 $this->assertDebuggingCalled();
4253 * Data provider for private ips.
4255 public function data_private_ips() {
4258 array('172.16.0.0'),
4259 array('192.168.1.0'),
4260 array('fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c'),
4261 array('fdc6:c46b:bb8f:7d4c:fdc6:c46b:bb8f:7d4c'),
4262 array('fdc6:c46b:bb8f:7d4c:0000:8a2e:0370:7334'),
4263 array('127.0.0.1'), // This has been buggy in past: https://bugs.php.net/bug.php?id=53150.
4268 * Checks ip_is_public returns false for private ips.
4270 * @param string $ip the ipaddress to test
4271 * @dataProvider data_private_ips
4273 public function test_ip_is_public_private_ips($ip) {
4274 $this->assertFalse(ip_is_public($ip));
4278 * Data provider for public ips.
4280 public function data_public_ips() {
4282 array('2400:cb00:2048:1::8d65:71b3'),
4283 array('2400:6180:0:d0::1b:2001'),
4284 array('141.101.113.179'),
4285 array('123.45.67.178'),
4290 * Checks ip_is_public returns true for public ips.
4292 * @param string $ip the ipaddress to test
4293 * @dataProvider data_public_ips
4295 public function test_ip_is_public_public_ips($ip) {
4296 $this->assertTrue(ip_is_public($ip));
4300 * Test the function can_send_from_real_email_address
4302 * @param string $email Email address for the from user.
4303 * @param int $display The user's email display preference.
4304 * @param bool $samecourse Are the users in the same course?
4305 * @param string $config The CFG->allowedemaildomains config values
4306 * @param bool $result The expected result.
4307 * @dataProvider data_can_send_from_real_email_address
4309 public function test_can_send_from_real_email_address($email, $display, $samecourse, $config, $result) {
4310 $this->resetAfterTest();
4312 $fromuser = $this->getDataGenerator()->create_user();
4313 $touser = $this->getDataGenerator()->create_user();
4314 $course = $this->getDataGenerator()->create_course();
4315 set_config('allowedemaildomains', $config);
4317 $fromuser->email
= $email;
4318 $fromuser->maildisplay
= $display;
4320 $this->getDataGenerator()->enrol_user($fromuser->id
, $course->id
, 'student');
4321 $this->getDataGenerator()->enrol_user($touser->id
, $course->id
, 'student');
4323 $this->getDataGenerator()->enrol_user($fromuser->id
, $course->id
, 'student');
4325 $this->assertEquals($result, can_send_from_real_email_address($fromuser, $touser));
4329 * Data provider for test_can_send_from_real_email_address.
4331 * @return array Returns an array of test data for the above function.
4333 public function data_can_send_from_real_email_address() {
4335 // Test from email is in allowed domain.
4336 // Test that from display is set to show no one.
4338 'email' => 'fromuser@example.com',
4339 'display' => \core_user
::MAILDISPLAY_HIDE
,
4340 'samecourse' => false,
4341 'config' => "example.com\r\ntest.com",
4344 // Test that from display is set to course members only (course member).
4346 'email' => 'fromuser@example.com',
4347 'display' => \core_user
::MAILDISPLAY_COURSE_MEMBERS_ONLY
,
4348 'samecourse' => true,
4349 'config' => "example.com\r\ntest.com",
4352 // Test that from display is set to course members only (Non course member).
4354 'email' => 'fromuser@example.com',
4355 'display' => \core_user
::MAILDISPLAY_COURSE_MEMBERS_ONLY
,
4356 'samecourse' => false,
4357 'config' => "example.com\r\ntest.com",
4360 // Test that from display is set to show everyone.
4362 'email' => 'fromuser@example.com',
4363 'display' => \core_user
::MAILDISPLAY_EVERYONE
,
4364 'samecourse' => false,
4365 'config' => "example.com\r\ntest.com",
4368 // Test a few different config value formats for parsing correctness.
4370 'email' => 'fromuser@example.com',
4371 'display' => \core_user
::MAILDISPLAY_EVERYONE
,
4372 'samecourse' => false,
4373 'config' => "\n test.com\nexample.com \n",
4377 'email' => 'fromuser@example.com',
4378 'display' => \core_user
::MAILDISPLAY_EVERYONE
,
4379 'samecourse' => false,
4380 'config' => "\r\n example.com \r\n test.com \r\n",
4384 'email' => 'fromuser@EXAMPLE.com',
4385 'display' => \core_user
::MAILDISPLAY_EVERYONE
,
4386 'samecourse' => false,
4387 'config' => "example.com\r\ntest.com",
4390 // Test from email is not in allowed domain.
4391 // Test that from display is set to show no one.
4392 [ 'email' => 'fromuser@moodle.com',
4393 'display' => \core_user
::MAILDISPLAY_HIDE
,
4394 'samecourse' => false,
4395 'config' => "example.com\r\ntest.com",
4398 // Test that from display is set to course members only (course member).
4399 [ 'email' => 'fromuser@moodle.com',
4400 'display' => \core_user
::MAILDISPLAY_COURSE_MEMBERS_ONLY
,
4401 'samecourse' => true,
4402 'config' => "example.com\r\ntest.com",
4405 // Test that from display is set to course members only (Non course member.
4406 [ 'email' => 'fromuser@moodle.com',
4407 'display' => \core_user
::MAILDISPLAY_COURSE_MEMBERS_ONLY
,
4408 'samecourse' => false,
4409 'config' => "example.com\r\ntest.com",
4412 // Test that from display is set to show everyone.
4413 [ 'email' => 'fromuser@moodle.com',
4414 'display' => \core_user
::MAILDISPLAY_EVERYONE
,
4415 'samecourse' => false,
4416 'config' => "example.com\r\ntest.com",
4419 // Test a few erroneous config value and confirm failure.
4420 [ 'email' => 'fromuser@moodle.com',
4421 'display' => \core_user
::MAILDISPLAY_EVERYONE
,
4422 'samecourse' => false,
4423 'config' => "\r\n \r\n",
4426 [ 'email' => 'fromuser@moodle.com',
4427 'display' => \core_user
::MAILDISPLAY_EVERYONE
,
4428 'samecourse' => false,
4429 'config' => " \n \n \n ",
4436 * Test that generate_email_processing_address() returns valid email address.
4438 public function test_generate_email_processing_address() {
4440 $this->resetAfterTest();
4444 'email' => 'my.email+from_moodle@example.com',
4447 $modargs = 'B'.base64_encode(pack('V', $data->id
)).substr(md5($data->email
), 0, 16);
4449 $CFG->maildomain
= 'example.com';
4450 $CFG->mailprefix
= 'mdl+';
4451 $this->assertTrue(validate_email(generate_email_processing_address(0, $modargs)));
4453 $CFG->maildomain
= 'mail.example.com';
4454 $CFG->mailprefix
= 'mdl-';
4455 $this->assertTrue(validate_email(generate_email_processing_address(23, $modargs)));
4459 * Test allowemailaddresses setting.
4461 * @param string $email Email address for the from user.
4462 * @param string $config The CFG->allowemailaddresses config values
4463 * @param false/string $result The expected result.
4465 * @dataProvider data_email_is_not_allowed_for_allowemailaddresses
4467 public function test_email_is_not_allowed_for_allowemailaddresses($email, $config, $result) {
4468 $this->resetAfterTest();
4470 set_config('allowemailaddresses', $config);
4471 $this->assertEquals($result, email_is_not_allowed($email));
4475 * Data provider for data_email_is_not_allowed_for_allowemailaddresses.
4477 * @return array Returns an array of test data for the above function.
4479 public function data_email_is_not_allowed_for_allowemailaddresses() {
4481 // Test allowed domain empty list.
4483 'email' => 'fromuser@example.com',
4487 // Test from email is in allowed domain.
4489 'email' => 'fromuser@example.com',
4490 'config' => 'example.com test.com',
4493 // Test from email is in allowed domain but uppercase config.
4495 'email' => 'fromuser@example.com',
4496 'config' => 'EXAMPLE.com test.com',
4499 // Test from email is in allowed domain but uppercase email.
4501 'email' => 'fromuser@EXAMPLE.com',
4502 'config' => 'example.com test.com',
4505 // Test from email is in allowed subdomain.
4507 'email' => 'fromuser@something.example.com',
4508 'config' => '.example.com test.com',
4511 // Test from email is in allowed subdomain but uppercase config.
4513 'email' => 'fromuser@something.example.com',
4514 'config' => '.EXAMPLE.com test.com',
4517 // Test from email is in allowed subdomain but uppercase email.
4519 'email' => 'fromuser@something.EXAMPLE.com',
4520 'config' => '.example.com test.com',
4523 // Test from email is not in allowed domain.
4524 [ 'email' => 'fromuser@moodle.com',
4525 'config' => 'example.com test.com',
4526 'result' => get_string('emailonlyallowed', '', 'example.com test.com')
4528 // Test from email is not in allowed subdomain.
4529 [ 'email' => 'fromuser@something.example.com',
4530 'config' => 'example.com test.com',
4531 'result' => get_string('emailonlyallowed', '', 'example.com test.com')
4537 * Test denyemailaddresses setting.
4539 * @param string $email Email address for the from user.
4540 * @param string $config The CFG->denyemailaddresses config values
4541 * @param false/string $result The expected result.
4543 * @dataProvider data_email_is_not_allowed_for_denyemailaddresses
4545 public function test_email_is_not_allowed_for_denyemailaddresses($email, $config, $result) {
4546 $this->resetAfterTest();
4548 set_config('denyemailaddresses', $config);
4549 $this->assertEquals($result, email_is_not_allowed($email));
4554 * Data provider for test_email_is_not_allowed_for_denyemailaddresses.
4556 * @return array Returns an array of test data for the above function.
4558 public function data_email_is_not_allowed_for_denyemailaddresses() {
4560 // Test denied domain empty list.
4562 'email' => 'fromuser@example.com',
4566 // Test from email is in denied domain.
4568 'email' => 'fromuser@example.com',
4569 'config' => 'example.com test.com',
4570 'result' => get_string('emailnotallowed', '', 'example.com test.com')
4572 // Test from email is in denied domain but uppercase config.
4574 'email' => 'fromuser@example.com',
4575 'config' => 'EXAMPLE.com test.com',
4576 'result' => get_string('emailnotallowed', '', 'EXAMPLE.com test.com')
4578 // Test from email is in denied domain but uppercase email.
4580 'email' => 'fromuser@EXAMPLE.com',
4581 'config' => 'example.com test.com',
4582 'result' => get_string('emailnotallowed', '', 'example.com test.com')
4584 // Test from email is in denied subdomain.
4586 'email' => 'fromuser@something.example.com',
4587 'config' => '.example.com test.com',
4588 'result' => get_string('emailnotallowed', '', '.example.com test.com')
4590 // Test from email is in denied subdomain but uppercase config.
4592 'email' => 'fromuser@something.example.com',
4593 'config' => '.EXAMPLE.com test.com',
4594 'result' => get_string('emailnotallowed', '', '.EXAMPLE.com test.com')
4596 // Test from email is in denied subdomain but uppercase email.
4598 'email' => 'fromuser@something.EXAMPLE.com',
4599 'config' => '.example.com test.com',
4600 'result' => get_string('emailnotallowed', '', '.example.com test.com')
4602 // Test from email is not in denied domain.
4603 [ 'email' => 'fromuser@moodle.com',
4604 'config' => 'example.com test.com',
4607 // Test from email is not in denied subdomain.
4608 [ 'email' => 'fromuser@something.example.com',
4609 'config' => 'example.com test.com',
4616 * Test safe method unserialize_array().
4618 public function test_unserialize_array() {
4620 $this->assertEquals($a, unserialize_array(serialize($a)));
4621 $this->assertEquals($a, unserialize_array(serialize($a)));
4622 $a = ['a' => 1, 2 => 2, 'b' => 'cde'];
4623 $this->assertEquals($a, unserialize_array(serialize($a)));
4624 $this->assertEquals($a, unserialize_array(serialize($a)));
4625 $a = ['a' => 1, 2 => 2, 'b' => 'c"d"e'];
4626 $this->assertEquals($a, unserialize_array(serialize($a)));
4627 $a = ['a' => 1, 2 => ['c' => 'd', 'e' => 'f'], 'b' => 'cde'];
4628 $this->assertEquals($a, unserialize_array(serialize($a)));
4630 // Can not unserialize if any string contains semicolons.
4631 $a = ['a' => 1, 2 => 2, 'b' => 'c"d";e'];
4632 $this->assertEquals(false, unserialize_array(serialize($a)));
4634 // Can not unserialize if there are any objects.
4635 $a = (object)['a' => 1, 2 => 2, 'b' => 'cde'];
4636 $this->assertEquals(false, unserialize_array(serialize($a)));
4637 $a = ['a' => 1, 2 => 2, 'b' => (object)['a' => 'cde']];
4638 $this->assertEquals(false, unserialize_array(serialize($a)));
4640 // Array used in the grader report.
4641 $a = array('aggregatesonly' => [51, 34], 'gradesonly' => [21, 45, 78]);
4642 $this->assertEquals($a, unserialize_array(serialize($a)));
4646 * Test method for safely unserializing a serialized object of type stdClass
4648 public function test_unserialize_object(): void
{
4649 $object = (object) [
4652 'innerobject' => (object) [
4657 // We should get back the same object we serialized.
4658 $serializedobject = serialize($object);
4659 $this->assertEquals($object, unserialize_object($serializedobject));
4661 // Try serializing a different class, not allowed.
4662 $langstr = new lang_string('no');
4663 $serializedlangstr = serialize($langstr);
4664 $unserializedlangstr = unserialize_object($serializedlangstr);
4665 $this->assertInstanceOf(\stdClass
::class, $unserializedlangstr);
4669 * Test that the component_class_callback returns the correct default value when the class was not found.
4671 * @dataProvider component_class_callback_default_provider
4674 public function test_component_class_callback_not_found($default) {
4675 $this->assertSame($default, component_class_callback('thisIsNotTheClassYouWereLookingFor', 'anymethod', [], $default));
4679 * Test that the component_class_callback returns the correct default value when the class was not found.
4681 * @dataProvider component_class_callback_default_provider
4684 public function test_component_class_callback_method_not_found($default) {
4685 require_once(__DIR__
. '/fixtures/component_class_callback_example.php');
4687 $this->assertSame($default, component_class_callback(test_component_class_callback_example
::class, 'this_is_not_the_method_you_were_looking_for', ['abc'], $default));
4691 * Test that the component_class_callback returns the default when the method returned null.
4693 * @dataProvider component_class_callback_default_provider
4696 public function test_component_class_callback_found_returns_null($default) {
4697 require_once(__DIR__
. '/fixtures/component_class_callback_example.php');
4699 $this->assertSame($default, component_class_callback(\test_component_class_callback_example
::class, 'method_returns_value', [null], $default));
4700 $this->assertSame($default, component_class_callback(\test_component_class_callback_child_example
::class, 'method_returns_value', [null], $default));
4704 * Test that the component_class_callback returns the expected value and not the default when there was a value.
4706 * @dataProvider component_class_callback_data_provider
4709 public function test_component_class_callback_found_returns_value($value) {
4710 require_once(__DIR__
. '/fixtures/component_class_callback_example.php');
4712 $this->assertSame($value, component_class_callback(\test_component_class_callback_example
::class, 'method_returns_value', [$value], 'This is not the value you were looking for'));
4713 $this->assertSame($value, component_class_callback(\test_component_class_callback_child_example
::class, 'method_returns_value', [$value], 'This is not the value you were looking for'));
4717 * Test that the component_class_callback handles multiple params correctly.
4719 * @dataProvider component_class_callback_multiple_params_provider
4722 public function test_component_class_callback_found_accepts_multiple($params, $count) {
4723 require_once(__DIR__
. '/fixtures/component_class_callback_example.php');
4725 $this->assertSame($count, component_class_callback(\test_component_class_callback_example
::class, 'method_returns_all_params', $params, 'This is not the value you were looking for'));
4726 $this->assertSame($count, component_class_callback(\test_component_class_callback_child_example
::class, 'method_returns_all_params', $params, 'This is not the value you were looking for'));
4730 * Data provider with list of default values for user in component_class_callback tests.
4734 public function component_class_callback_default_provider() {
4737 'empty string' => [''],
4738 'string' => ['This is a string'],
4740 'stdClass' => [(object) ['this is my content']],
4741 'array' => [['a' => 'b',]],
4746 * Data provider with list of default values for user in component_class_callback tests.
4750 public function component_class_callback_data_provider() {
4752 'empty string' => [''],
4753 'string' => ['This is a string'],
4755 'stdClass' => [(object) ['this is my content']],
4756 'array' => [['a' => 'b',]],
4761 * Data provider with list of default values for user in component_class_callback tests.
4765 public function component_class_callback_multiple_params_provider() {
4775 'string values' => [
4784 [null, null, null, null],
4788 ['a', 1, null, (object) [], []],
4795 * Test that {@link get_callable_name()} describes the callable as expected.
4797 * @dataProvider callable_names_provider
4798 * @param callable $callable
4799 * @param string $expectedname
4801 public function test_get_callable_name($callable, $expectedname) {
4802 $this->assertSame($expectedname, get_callable_name($callable));
4806 * Provides a set of callables and their human readable names.
4808 * @return array of (string)case => [(mixed)callable, (string|bool)expected description]
4810 public function callable_names_provider() {
4820 'static_method_as_literal' => [
4821 'my_foobar_class::my_foobar_method',
4822 'my_foobar_class::my_foobar_method',
4824 'static_method_of_literal_class' => [
4825 ['my_foobar_class', 'my_foobar_method'],
4826 'my_foobar_class::my_foobar_method',
4828 'static_method_of_object' => [
4829 [$this, 'my_foobar_method'],
4830 'core\moodlelib_test::my_foobar_method',
4832 'method_of_object' => [
4833 [new lang_string('parentlanguage', 'core_langconfig'), 'my_foobar_method'],
4834 'lang_string::my_foobar_method',
4836 'function_as_literal' => [
4837 'my_foobar_callback',
4838 'my_foobar_callback',
4840 'function_as_closure' => [
4841 function($a) { return $a; },
4842 'Closure::__invoke',
4848 * Data provider for \core_moodlelib_testcase::test_get_complete_user_data().
4852 public function user_data_provider() {
4854 'Fetch data using a valid username' => [
4855 'username', 's1', true
4857 'Fetch data using a valid username, different case' => [
4858 'username', 'S1', true
4860 'Fetch data using a valid username, different case for fieldname and value' => [
4861 'USERNAME', 'S1', true
4863 'Fetch data using an invalid username' => [
4864 'username', 's2', false
4866 'Fetch by email' => [
4867 'email', 's1@example.com', true
4869 'Fetch data using a non-existent email' => [
4870 'email', 's2@example.com', false
4872 'Fetch data using a non-existent email, throw exception' => [
4873 'email', 's2@example.com', false, \dml_missing_record_exception
::class
4875 'Multiple accounts with the same email' => [
4876 'email', 's1@example.com', false, 1
4878 'Multiple accounts with the same email, throw exception' => [
4879 'email', 's1@example.com', false, 1, \dml_multiple_records_exception
::class
4881 'Fetch data using a valid user ID' => [
4884 'Fetch data using a non-existent user ID' => [
4891 * Test for get_complete_user_data().
4893 * @dataProvider user_data_provider
4894 * @param string $field The field to use for the query.
4895 * @param string|boolean $value The field value. When fetching by ID, set true to fetch valid user ID, false otherwise.
4896 * @param boolean $success Whether we expect for the fetch to succeed or return false.
4897 * @param int $allowaccountssameemail Value for $CFG->allowaccountssameemail.
4898 * @param string $expectedexception The exception to be expected.
4900 public function test_get_complete_user_data($field, $value, $success, $allowaccountssameemail = 0, $expectedexception = '') {
4901 $this->resetAfterTest();
4903 // Set config settings we need for our environment.
4904 set_config('allowaccountssameemail', $allowaccountssameemail);
4906 // Generate the user data.
4907 $generator = $this->getDataGenerator();
4910 'email' => 's1@example.com',
4912 $user = $generator->create_user($userdata);
4914 if ($allowaccountssameemail) {
4915 // Create another user with the same email address.
4916 $generator->create_user(['email' => 's1@example.com']);
4919 // Since the data provider can't know what user ID to use, do a special handling for ID field tests.
4920 if ($field === 'id') {
4922 // Test for fetching data using a valid user ID. Use the generated user's ID.
4925 // Test for fetching data using a non-existent user ID.
4926 $value = $user->id +
1;
4930 // When an exception is expected.
4931 $throwexception = false;
4932 if ($expectedexception) {
4933 $this->expectException($expectedexception);
4934 $throwexception = true;
4937 $fetcheduser = get_complete_user_data($field, $value, null, $throwexception);
4939 $this->assertEquals($user->id
, $fetcheduser->id
);
4940 $this->assertEquals($user->username
, $fetcheduser->username
);
4941 $this->assertEquals($user->email
, $fetcheduser->email
);
4943 $this->assertFalse($fetcheduser);
4948 * Test for send_password_change_().
4950 public function test_send_password_change_info() {
4951 $this->resetAfterTest();
4953 $user = $this->getDataGenerator()->create_user();
4955 $sink = $this->redirectEmails(); // Make sure we are redirecting emails.
4956 send_password_change_info($user);
4957 $result = $sink->get_messages();
4960 $this->assertStringContainsString('passwords cannot be reset on this site', quoted_printable_decode($result[0]->body
));
4964 * Test the get_time_interval_string for a range of inputs.
4966 * @dataProvider get_time_interval_string_provider
4967 * @param int $time1 the time1 param.
4968 * @param int $time2 the time2 param.
4969 * @param string|null $format the format param.
4970 * @param string $expected the expected string.
4972 public function test_get_time_interval_string(int $time1, int $time2, ?
string $format, string $expected) {
4973 if (is_null($format)) {
4974 $this->assertEquals($expected, get_time_interval_string($time1, $time2));
4976 $this->assertEquals($expected, get_time_interval_string($time1, $time2, $format));
4981 * Data provider for the test_get_time_interval_string() method.
4983 public function get_time_interval_string_provider() {
4985 'Time is after the reference time by 1 minute, omitted format' => [
4986 'time1' => 12345660,
4987 'time2' => 12345600,
4989 'expected' => '0d 0h 1m'
4991 'Time is before the reference time by 1 minute, omitted format' => [
4992 'time1' => 12345540,
4993 'time2' => 12345600,
4995 'expected' => '0d 0h 1m'
4997 'Time is equal to the reference time, omitted format' => [
4998 'time1' => 12345600,
4999 'time2' => 12345600,
5001 'expected' => '0d 0h 0m'
5003 'Time is after the reference time by 1 minute, empty string format' => [
5004 'time1' => 12345660,
5005 'time2' => 12345600,
5007 'expected' => '0d 0h 1m'
5009 'Time is before the reference time by 1 minute, empty string format' => [
5010 'time1' => 12345540,
5011 'time2' => 12345600,
5013 'expected' => '0d 0h 1m'
5015 'Time is equal to the reference time, empty string format' => [
5016 'time1' => 12345600,
5017 'time2' => 12345600,
5019 'expected' => '0d 0h 0m'
5021 'Time is after the reference time by 1 minute, custom format' => [
5022 'time1' => 12345660,
5023 'time2' => 12345600,
5024 'format' => '%R%adays %hhours %imins',
5025 'expected' => '+0days 0hours 1mins'
5027 'Time is before the reference time by 1 minute, custom format' => [
5028 'time1' => 12345540,
5029 'time2' => 12345600,
5030 'format' => '%R%adays %hhours %imins',
5031 'expected' => '-0days 0hours 1mins'
5033 'Time is equal to the reference time, custom format' => [
5034 'time1' => 12345600,
5035 'time2' => 12345600,
5036 'format' => '%R%adays %hhours %imins',
5037 'expected' => '+0days 0hours 0mins'
5043 * Tests the rename_to_unused_name function with a file.
5045 public function test_rename_to_unused_name_file() {
5048 // Create a new file in dataroot.
5049 $file = $CFG->dataroot
. '/argh.txt';
5050 file_put_contents($file, 'Frogs');
5053 $newname = rename_to_unused_name($file);
5055 // Check new name has expected format.
5056 $this->assertMatchesRegularExpression('~/_temp_[a-f0-9]+$~', $newname);
5058 // Check it's still in the same folder.
5059 $this->assertEquals($CFG->dataroot
, dirname($newname));
5061 // Check file can be loaded.
5062 $this->assertEquals('Frogs', file_get_contents($newname));
5064 // OK, delete the file.
5069 * Tests the rename_to_unused_name function with a directory.
5071 public function test_rename_to_unused_name_dir() {
5074 // Create a new directory in dataroot.
5075 $file = $CFG->dataroot
. '/arghdir';
5079 $newname = rename_to_unused_name($file);
5081 // Check new name has expected format.
5082 $this->assertMatchesRegularExpression('~/_temp_[a-f0-9]+$~', $newname);
5084 // Check it's still in the same folder.
5085 $this->assertEquals($CFG->dataroot
, dirname($newname));
5087 // Check it's still a directory
5088 $this->assertTrue(is_dir($newname));
5090 // OK, delete the directory.
5095 * Tests the rename_to_unused_name function with error cases.
5097 public function test_rename_to_unused_name_failure() {
5100 // Rename a file that doesn't exist.
5101 $file = $CFG->dataroot
. '/argh.txt';
5102 $this->assertFalse(rename_to_unused_name($file));
5106 * Provider for display_size
5108 * @return array of ($size, $expected)
5110 public function display_size_provider() {
5115 [1023, '1023 bytes'],
5119 [444444, '434.0 KB'],
5120 [5555555, '5.3 MB'],
5121 [66666666, '63.6 MB'],
5122 [777777777, '741.7 MB'],
5123 [8888888888, '8.3 GB'],
5124 [99999999999, '93.1 GB'],
5125 [111111111111, '103.5 GB'],
5126 [2222222222222, '2.0 TB'],
5127 [33333333333333, '30.3 TB'],
5128 [444444444444444, '404.2 TB'],
5129 [5555555555555555, '4.9 PB'],
5130 [66666666666666666, '59.2 PB'],
5131 [777777777777777777, '690.8 PB'],
5137 * @dataProvider display_size_provider
5138 * @param int $size the size in bytes
5139 * @param string $expected the expected string.
5141 public function test_display_size($size, $expected) {
5142 $result = display_size($size);
5143 $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space.
5144 $this->assertEquals($expected, $result);
5148 * Provider for display_size using fixed units.
5150 * @return array of ($size, $units, $expected)
5152 public function display_size_fixed_provider(): array {
5154 [0, 'KB', '0.0 KB'],
5155 [1, 'MB', '0.0 MB'],
5156 [777777777, 'GB', '0.7 GB'],
5157 [8888888888, 'PB', '0.0 PB'],
5158 [99999999999, 'TB', '0.1 TB'],
5159 [99999999999, 'B', '99999999999 bytes'],
5164 * Test display_size using fixed units.
5166 * @dataProvider display_size_fixed_provider
5167 * @param int $size Size in bytes
5168 * @param string $units Fixed units
5169 * @param string $expected Expected string.
5171 public function test_display_size_fixed(int $size, string $units, string $expected): void
{
5172 $result = display_size($size, 1, $units);
5173 $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space.
5174 $this->assertEquals($expected, $result);
5178 * Provider for display_size using specified decimal places.
5180 * @return array of ($size, $decimalplaces, $units, $expected)
5182 public function display_size_dp_provider(): array {
5184 [0, 1, 'KB', '0.0 KB'],
5185 [1, 6, 'MB', '0.000001 MB'],
5186 [777777777, 0, 'GB', '1 GB'],
5187 [777777777, 0, '', '742 MB'],
5188 [42, 6, '', '42 bytes'],
5193 * Test display_size using specified decimal places.
5195 * @dataProvider display_size_dp_provider
5196 * @param int $size Size in bytes
5197 * @param int $places Number of decimal places
5198 * @param string $units Fixed units
5199 * @param string $expected Expected string.
5201 public function test_display_size_dp(int $size, int $places, string $units, string $expected): void
{
5202 $result = display_size($size, $places, $units);
5203 $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space.
5204 $this->assertEquals($expected, $result);
5208 * Test that the get_list_of_plugins function includes/excludes directories as appropriate.
5210 * @dataProvider get_list_of_plugins_provider
5211 * @param array $expectedlist The expected list of folders
5212 * @param array $content The list of file content to set up in the virtual file root
5213 * @param string $dir The base dir to look at in the virtual file root
5214 * @param string $exclude Any additional folder to exclude
5216 public function test_get_list_of_plugins(array $expectedlist, array $content, string $dir, string $exclude): void
{
5217 $vfileroot = \org\bovigo\vfs\vfsStream
::setup('root', null, $content);
5218 $base = \org\bovigo\vfs\vfsStream
::url('root');
5220 $this->assertEquals($expectedlist, get_list_of_plugins($dir, $exclude, $base));
5224 * Data provider for get_list_of_plugins checks.
5228 public function get_list_of_plugins_provider(): array {
5230 'Standard excludes' => [
5231 ['amdd', 'class', 'local', 'test'],
5247 'Standard excludes with addition' => [
5248 ['amdd', 'local', 'test'],
5264 'Files excluded' => [
5269 'abc' => 'File with filename abc',
5273 'example.txt' => 'In a directory called "def"',
5279 'Subdirectories only' => [
5302 * Test get_home_page() method.
5304 * @dataProvider get_home_page_provider
5305 * @param string $user Whether the user is logged, guest or not logged.
5306 * @param int $expected Expected value after calling the get_home_page method.
5307 * @param int $defaulthomepage The $CFG->defaulthomepage setting value.
5308 * @param int $enabledashboard Whether the dashboard should be enabled or not.
5309 * @param int $userpreference User preference for the home page setting.
5310 * @covers ::get_home_page
5312 public function test_get_home_page(string $user, int $expected, ?
int $defaulthomepage = null, ?
int $enabledashboard = null,
5313 ?
int $userpreference = null) {
5316 $this->resetAfterTest();
5318 if ($user == 'guest') {
5319 $this->setGuestUser();
5320 } else if ($user == 'logged') {
5321 $this->setUser($this->getDataGenerator()->create_user());
5324 if (isset($defaulthomepage)) {
5325 $CFG->defaulthomepage
= $defaulthomepage;
5327 if (isset($enabledashboard)) {
5328 $CFG->enabledashboard
= $enabledashboard;
5332 set_user_preferences(['user_home_page_preference' => $userpreference], $USER->id
);
5335 $homepage = get_home_page();
5336 $this->assertEquals($expected, $homepage);
5340 * Data provider for get_home_page checks.
5344 public function get_home_page_provider(): array {
5346 'No logged user' => [
5347 'user' => 'nologged',
5348 'expected' => HOMEPAGE_SITE
,
5352 'expected' => HOMEPAGE_SITE
,
5354 'Logged user. Dashboard set as default home page and enabled' => [
5356 'expected' => HOMEPAGE_MY
,
5357 'defaulthomepage' => HOMEPAGE_MY
,
5358 'enabledashboard' => 1,
5360 'Logged user. Dashboard set as default home page but disabled' => [
5362 'expected' => HOMEPAGE_MYCOURSES
,
5363 'defaulthomepage' => HOMEPAGE_MY
,
5364 'enabledashboard' => 0,
5366 'Logged user. My courses set as default home page with dashboard enabled' => [
5368 'expected' => HOMEPAGE_MYCOURSES
,
5369 'defaulthomepage' => HOMEPAGE_MYCOURSES
,
5370 'enabledashboard' => 1,
5372 'Logged user. My courses set as default home page with dashboard disabled' => [
5374 'expected' => HOMEPAGE_MYCOURSES
,
5375 'defaulthomepage' => HOMEPAGE_MYCOURSES
,
5376 'enabledashboard' => 0,
5378 'Logged user. Site set as default home page with dashboard enabled' => [
5380 'expected' => HOMEPAGE_SITE
,
5381 'defaulthomepage' => HOMEPAGE_SITE
,
5382 'enabledashboard' => 1,
5384 'Logged user. Site set as default home page with dashboard disabled' => [
5386 'expected' => HOMEPAGE_SITE
,
5387 'defaulthomepage' => HOMEPAGE_SITE
,
5388 'enabledashboard' => 0,
5390 'Logged user. User preference set as default page with dashboard enabled and user preference set to dashboard' => [
5392 'expected' => HOMEPAGE_MY
,
5393 'defaulthomepage' => HOMEPAGE_USER
,
5394 'enabledashboard' => 1,
5395 'userpreference' => HOMEPAGE_MY
,
5397 'Logged user. User preference set as default page with dashboard disabled and user preference set to dashboard' => [
5399 'expected' => HOMEPAGE_MYCOURSES
,
5400 'defaulthomepage' => HOMEPAGE_USER
,
5401 'enabledashboard' => 0,
5402 'userpreference' => HOMEPAGE_MY
,
5404 'Logged user. User preference set as default page with dashboard enabled and user preference set to my courses' => [
5406 'expected' => HOMEPAGE_MYCOURSES
,
5407 'defaulthomepage' => HOMEPAGE_USER
,
5408 'enabledashboard' => 1,
5409 'userpreference' => HOMEPAGE_MYCOURSES
,
5411 'Logged user. User preference set as default page with dashboard disabled and user preference set to my courses' => [
5413 'expected' => HOMEPAGE_MYCOURSES
,
5414 'defaulthomepage' => HOMEPAGE_USER
,
5415 'enabledashboard' => 0,
5416 'userpreference' => HOMEPAGE_MYCOURSES
,
5422 * Test get_default_home_page() method.
5424 * @covers ::get_default_home_page
5426 public function test_get_default_home_page() {
5429 $this->resetAfterTest();
5431 $CFG->enabledashboard
= 1;
5432 $default = get_default_home_page();
5433 $this->assertEquals(HOMEPAGE_MY
, $default);
5435 $CFG->enabledashboard
= 0;
5436 $default = get_default_home_page();
5437 $this->assertEquals(HOMEPAGE_MYCOURSES
, $default);
5441 * Tests the get_performance_info function with regard to locks.
5443 * @covers ::get_performance_info
5445 public function test_get_performance_info_locks(): void
{
5448 // Unset lock data just in case previous tests have set it.
5449 unset($PERF->locks
);
5451 // With no lock data, there should be no information about locks in the results.
5452 $result = get_performance_info();
5453 $this->assertStringNotContainsString('Lock', $result['html']);
5454 $this->assertStringNotContainsString('Lock', $result['txt']);
5456 // Rather than really do locks, just fill the array with fake data in the right format.
5459 'type' => 'phpunit',
5460 'resource' => 'lock1',
5465 'type' => 'phpunit',
5466 'resource' => 'lock2',
5471 $result = get_performance_info();
5473 // Extract HTML table rows.
5474 $this->assertEquals(1, preg_match('~<table class="locktimings.*?</table>~s',
5475 $result['html'], $matches));
5476 $this->assertEquals(3, preg_match_all('~<tr[> ].*?</tr>~s', $matches[0], $matches2));
5477 $rows = $matches2[0];
5480 $this->assertMatchesRegularExpression('~Lock.*Waited.*Obtained.*Held~s', $rows[0]);
5481 // Check both locks.
5482 $this->assertMatchesRegularExpression('~phpunit/lock1.*0\.6.*✓.*6\.0~s', $rows[1]);
5483 $this->assertMatchesRegularExpression('~phpunit/lock2.*0\.9.*❌.*-~s', $rows[2]);
5485 $this->assertStringContainsString('Locks (waited/obtained/held): ' .
5486 'phpunit/lock1 (0.6/y/6.0) phpunit/lock2 (0.9/n/-).', $result['txt']);
5490 * Tests the get_performance_info function with regard to session wait time.
5492 * @covers ::get_performance_info
5494 public function test_get_performance_info_session_wait(): void
{
5497 // With no session lock data, there should be no session wait information in the results.
5498 unset($PERF->sessionlock
);
5499 $result = get_performance_info();
5500 $this->assertStringNotContainsString('Session wait', $result['html']);
5501 $this->assertStringNotContainsString('sessionwait', $result['txt']);
5503 // With suitable data, it should be included in the result.
5504 $PERF->sessionlock
= ['wait' => 4.2];
5505 $result = get_performance_info();
5506 $this->assertStringContainsString('Session wait: 4.200 secs', $result['html']);
5507 $this->assertStringContainsString('sessionwait: 4.200 secs', $result['txt']);
5511 * Test the html_is_blank() function.
5513 * @covers ::html_is_blank
5515 public function test_html_is_blank() {
5516 $this->assertEquals(true, html_is_blank(null));
5517 $this->assertEquals(true, html_is_blank(''));
5518 $this->assertEquals(true, html_is_blank('<p> </p>'));
5519 $this->assertEquals(false, html_is_blank('<p>.</p>'));
5520 $this->assertEquals(false, html_is_blank('<img src="#">'));
5524 * Provider for is_proxybypass
5526 * @return array of test cases.
5528 public function is_proxybypass_provider(): array {
5531 'Proxybypass contains the same IP as the beginning of the URL' => [
5532 'http://192.168.5.5-fake-app-7f000101.nip.io',
5533 '192.168.5.5, 127.0.0.1',
5536 'Proxybypass contains the last part of the URL' => [
5537 'http://192.168.5.5-fake-app-7f000101.nip.io',
5538 'app-7f000101.nip.io',
5541 'Proxybypass contains the last part of the URL 2' => [
5542 'http://store.mydomain.com',
5546 'Proxybypass contains part of the url' => [
5551 'Different IPs used in proxybypass' => [
5552 'http://192.168.5.5',
5556 'Proxybypass and URL matchs' => [
5557 'http://store.mydomain.com',
5558 'store.mydomain.com',
5561 'IP used in proxybypass' => [
5562 'http://192.168.5.5',
5570 * Check if $url matches anything in proxybypass list
5572 * Test function {@see is_proxybypass()}.
5573 * @dataProvider is_proxybypass_provider
5574 * @param string $url url to check
5575 * @param string $proxybypass
5576 * @param bool $expected Expected value.
5578 public function test_is_proxybypass(string $url, string $proxybypass, bool $expected): void
{
5579 $this->resetAfterTest();
5582 $CFG->proxyhost
= '192.168.5.5'; // Test with a fake proxy.
5583 $CFG->proxybypass
= $proxybypass;
5585 $this->assertEquals($expected, is_proxybypass($url));