Merge branch 'MDL-62560-master'
[moodle.git] / lib / tests / moodlelib_test.php
bloba2287541e9de6e6b28a5835697ecb981a9814147
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
18 * Unit tests for (some of) ../moodlelib.php.
20 * @package core
21 * @category phpunit
22 * @copyright &copy; 2006 The Open University
23 * @author T.J.Hunt@open.ac.uk
24 * @author nicolas@moodle.com
27 defined('MOODLE_INTERNAL') || die();
29 class core_moodlelib_testcase extends advanced_testcase {
31 public static $includecoverage = array('lib/moodlelib.php');
33 /**
34 * Define a local decimal separator.
36 * It is not possible to directly change the result of get_string in
37 * a unit test. Instead, we create a language pack for language 'xx' in
38 * dataroot and make langconfig.php with the string we need to change.
39 * The example separator used here is 'X'; on PHP 5.3 and before this
40 * must be a single byte character due to PHP bug/limitation in
41 * number_format, so you can't use UTF-8 characters.
43 protected function define_local_decimal_separator() {
44 global $SESSION, $CFG;
46 $SESSION->lang = 'xx';
47 $langconfig = "<?php\n\$string['decsep'] = 'X';";
48 $langfolder = $CFG->dataroot . '/lang/xx';
49 check_dir_exists($langfolder);
50 file_put_contents($langfolder . '/langconfig.php', $langconfig);
53 public function test_cleanremoteaddr() {
54 // IPv4.
55 $this->assertNull(cleanremoteaddr('1023.121.234.1'));
56 $this->assertSame('123.121.234.1', cleanremoteaddr('123.121.234.01 '));
58 // IPv6.
59 $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:0:0'));
60 $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:abh'));
61 $this->assertNull(cleanremoteaddr('0:0:0:::0:0:1'));
62 $this->assertSame('::', cleanremoteaddr('0:0:0:0:0:0:0:0', true));
63 $this->assertSame('::1:1', cleanremoteaddr('0:0:0:0:0:0:1:1', true));
64 $this->assertSame('abcd:ef::', cleanremoteaddr('abcd:00ef:0:0:0:0:0:0', true));
65 $this->assertSame('1::1', cleanremoteaddr('1:0:0:0:0:0:0:1', true));
66 $this->assertSame('0:0:0:0:0:0:10:1', cleanremoteaddr('::10:1', false));
67 $this->assertSame('1:1:0:0:0:0:0:0', cleanremoteaddr('01:1::', false));
68 $this->assertSame('10:0:0:0:0:0:0:10', cleanremoteaddr('10::10', false));
69 $this->assertSame('::ffff:c0a8:11', cleanremoteaddr('::ffff:192.168.1.1', true));
72 public function test_address_in_subnet() {
73 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask).
74 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.1/32'));
75 $this->assertFalse(address_in_subnet('123.121.23.1', '123.121.23.0/32'));
76 $this->assertTrue(address_in_subnet('10.10.10.100', '123.121.23.45/0'));
77 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/24'));
78 $this->assertFalse(address_in_subnet('123.121.34.1', '123.121.234.0/24'));
79 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/30'));
80 $this->assertFalse(address_in_subnet('123.121.23.8', '123.121.23.0/30'));
81 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
82 $this->assertFalse(address_in_subnet('bab:baba::baba', 'bab:baba::cece/128'));
83 $this->assertTrue(address_in_subnet('baba:baba::baba', 'cece:cece::cece/0'));
84 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
85 $this->assertTrue(address_in_subnet('baba:baba::00ba', 'baba:baba::/120'));
86 $this->assertFalse(address_in_subnet('baba:baba::aba', 'baba:baba::/120'));
87 $this->assertTrue(address_in_subnet('baba::baba:00ba', 'baba::baba:0/112'));
88 $this->assertFalse(address_in_subnet('baba::aba:00ba', 'baba::baba:0/112'));
89 $this->assertFalse(address_in_subnet('aba::baba:0000', 'baba::baba:0/112'));
91 // Fixed input.
92 $this->assertTrue(address_in_subnet('123.121.23.1 ', ' 123.121.23.0 / 24'));
93 $this->assertTrue(address_in_subnet('::ffff:10.1.1.1', ' 0:0:0:000:0:ffff:a1:10 / 126'));
95 // Incorrect input.
96 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/-2'));
97 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/64'));
98 $this->assertFalse(address_in_subnet('123.121.234.x', '123.121.234.1/24'));
99 $this->assertFalse(address_in_subnet('123.121.234.0', '123.121.234.xx/24'));
100 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/xx0'));
101 $this->assertFalse(address_in_subnet('::1', '::aa:0/xx0'));
102 $this->assertFalse(address_in_subnet('::1', '::aa:0/-5'));
103 $this->assertFalse(address_in_subnet('::1', '::aa:0/130'));
104 $this->assertFalse(address_in_subnet('x:1', '::aa:0/130'));
105 $this->assertFalse(address_in_subnet('::1', '::ax:0/130'));
107 // 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).
108 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12-14'));
109 $this->assertTrue(address_in_subnet('123.121.234.13', '123.121.234.12-14'));
110 $this->assertTrue(address_in_subnet('123.121.234.14', '123.121.234.12-14'));
111 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.12-14'));
112 $this->assertFalse(address_in_subnet('123.121.234.20', '123.121.234.12-14'));
113 $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.234.12-14'));
114 $this->assertFalse(address_in_subnet('123.12.234.12', '123.121.234.12-14'));
115 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba-babe'));
116 $this->assertTrue(address_in_subnet('baba:baba::babc', 'baba:baba::baba-babe'));
117 $this->assertTrue(address_in_subnet('baba:baba::babe', 'baba:baba::baba-babe'));
118 $this->assertFalse(address_in_subnet('bab:baba::bab0', 'bab:baba::baba-babe'));
119 $this->assertFalse(address_in_subnet('bab:baba::babf', 'bab:baba::baba-babe'));
120 $this->assertFalse(address_in_subnet('bab:baba::bfbe', 'bab:baba::baba-babe'));
121 $this->assertFalse(address_in_subnet('bfb:baba::babe', 'bab:baba::baba-babe'));
123 // Fixed input.
124 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12 - 14 '));
125 $this->assertTrue(address_in_subnet('bab:baba::babe', 'bab:baba::baba - babe '));
127 // Incorrect input.
128 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-234.14'));
129 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-256'));
130 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12--256'));
132 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-).
133 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12'));
134 $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.23.13'));
135 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.'));
136 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234'));
137 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121'));
138 $this->assertTrue(address_in_subnet('123.121.234.12', '123'));
139 $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234.'));
140 $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234'));
141 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba::bab'));
142 $this->assertFalse(address_in_subnet('baba:baba::ba', 'baba:baba::bc'));
143 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba'));
144 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:'));
145 $this->assertFalse(address_in_subnet('bab:baba::bab', 'baba:'));
147 // Multiple subnets.
148 $this->assertTrue(address_in_subnet('123.121.234.12', '::1/64, 124., 123.121.234.10-30'));
149 $this->assertTrue(address_in_subnet('124.121.234.12', '::1/64, 124., 123.121.234.10-30'));
150 $this->assertTrue(address_in_subnet('::2', '::1/64, 124., 123.121.234.10-30'));
151 $this->assertFalse(address_in_subnet('12.121.234.12', '::1/64, 124., 123.121.234.10-30'));
153 // Other incorrect input.
154 $this->assertFalse(address_in_subnet('123.123.123.123', ''));
157 public function test_fix_utf8() {
158 // Make sure valid data including other types is not changed.
159 $this->assertSame(null, fix_utf8(null));
160 $this->assertSame(1, fix_utf8(1));
161 $this->assertSame(1.1, fix_utf8(1.1));
162 $this->assertSame(true, fix_utf8(true));
163 $this->assertSame('', fix_utf8(''));
164 $this->assertSame('abc', fix_utf8('abc'));
165 $array = array('do', 're', 'mi');
166 $this->assertSame($array, fix_utf8($array));
167 $object = new stdClass();
168 $object->a = 'aa';
169 $object->b = 'bb';
170 $this->assertEquals($object, fix_utf8($object));
172 // valid utf8 string
173 $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"));
175 // Invalid utf8 string.
176 $this->assertSame('aš', fix_utf8('a'.chr(130).'š'), 'This fails with buggy iconv() when mbstring extenstion is not available as fallback.');
179 public function test_optional_param() {
180 global $CFG;
182 $_POST['username'] = 'post_user';
183 $_GET['username'] = 'get_user';
184 $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
186 unset($_POST['username']);
187 $this->assertSame($_GET['username'], optional_param('username', 'default_user', PARAM_RAW));
189 unset($_GET['username']);
190 $this->assertSame('default_user', optional_param('username', 'default_user', PARAM_RAW));
192 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
193 $_POST['username'] = 'post_user';
194 try {
195 optional_param('username', 'default_user', null);
196 $this->fail('coding_exception expected');
197 } catch (moodle_exception $ex) {
198 $this->assertInstanceOf('coding_exception', $ex);
200 try {
201 @optional_param('username', 'default_user');
202 $this->fail('coding_exception expected');
203 } catch (moodle_exception $ex) {
204 $this->assertInstanceOf('coding_exception', $ex);
205 } catch (Error $error) {
206 // PHP 7.1 throws Error even earlier.
207 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
209 try {
210 @optional_param('username');
211 $this->fail('coding_exception expected');
212 } catch (moodle_exception $ex) {
213 $this->assertInstanceOf('coding_exception', $ex);
214 } catch (Error $error) {
215 // PHP 7.1 throws Error even earlier.
216 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
218 try {
219 optional_param('', 'default_user', PARAM_RAW);
220 $this->fail('coding_exception expected');
221 } catch (moodle_exception $ex) {
222 $this->assertInstanceOf('coding_exception', $ex);
225 // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
226 $_POST['username'] = array('a'=>'a');
227 $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
228 $this->assertDebuggingCalled();
231 public function test_optional_param_array() {
232 global $CFG;
234 $_POST['username'] = array('a'=>'post_user');
235 $_GET['username'] = array('a'=>'get_user');
236 $this->assertSame($_POST['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
238 unset($_POST['username']);
239 $this->assertSame($_GET['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
241 unset($_GET['username']);
242 $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
244 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
245 $_POST['username'] = array('a'=>'post_user');
246 try {
247 optional_param_array('username', array('a'=>'default_user'), null);
248 $this->fail('coding_exception expected');
249 } catch (moodle_exception $ex) {
250 $this->assertInstanceOf('coding_exception', $ex);
252 try {
253 @optional_param_array('username', array('a'=>'default_user'));
254 $this->fail('coding_exception expected');
255 } catch (moodle_exception $ex) {
256 $this->assertInstanceOf('coding_exception', $ex);
257 } catch (Error $error) {
258 // PHP 7.1 throws Error even earlier.
259 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
261 try {
262 @optional_param_array('username');
263 $this->fail('coding_exception expected');
264 } catch (moodle_exception $ex) {
265 $this->assertInstanceOf('coding_exception', $ex);
266 } catch (Error $error) {
267 // PHP 7.1 throws Error even earlier.
268 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
270 try {
271 optional_param_array('', array('a'=>'default_user'), PARAM_RAW);
272 $this->fail('coding_exception expected');
273 } catch (moodle_exception $ex) {
274 $this->assertInstanceOf('coding_exception', $ex);
277 // Do not allow nested arrays.
278 try {
279 $_POST['username'] = array('a'=>array('b'=>'post_user'));
280 optional_param_array('username', array('a'=>'default_user'), PARAM_RAW);
281 $this->fail('coding_exception expected');
282 } catch (coding_exception $ex) {
283 $this->assertTrue(true);
286 // Do not allow non-arrays.
287 $_POST['username'] = 'post_user';
288 $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
289 $this->assertDebuggingCalled();
291 // Make sure array keys are sanitised.
292 $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
293 $this->assertSame(array('a1_-'=>'post_user'), optional_param_array('username', array(), PARAM_RAW));
294 $this->assertDebuggingCalled();
297 public function test_required_param() {
298 $_POST['username'] = 'post_user';
299 $_GET['username'] = 'get_user';
300 $this->assertSame('post_user', required_param('username', PARAM_RAW));
302 unset($_POST['username']);
303 $this->assertSame('get_user', required_param('username', PARAM_RAW));
305 unset($_GET['username']);
306 try {
307 $this->assertSame('default_user', required_param('username', PARAM_RAW));
308 $this->fail('moodle_exception expected');
309 } catch (moodle_exception $ex) {
310 $this->assertInstanceOf('moodle_exception', $ex);
313 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
314 $_POST['username'] = 'post_user';
315 try {
316 @required_param('username');
317 $this->fail('coding_exception expected');
318 } catch (moodle_exception $ex) {
319 $this->assertInstanceOf('coding_exception', $ex);
320 } catch (Error $error) {
321 // PHP 7.1 throws Error even earlier.
322 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
324 try {
325 required_param('username', '');
326 $this->fail('coding_exception expected');
327 } catch (moodle_exception $ex) {
328 $this->assertInstanceOf('coding_exception', $ex);
330 try {
331 required_param('', PARAM_RAW);
332 $this->fail('coding_exception expected');
333 } catch (moodle_exception $ex) {
334 $this->assertInstanceOf('coding_exception', $ex);
337 // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
338 $_POST['username'] = array('a'=>'a');
339 $this->assertSame($_POST['username'], required_param('username', PARAM_RAW));
340 $this->assertDebuggingCalled();
343 public function test_required_param_array() {
344 global $CFG;
346 $_POST['username'] = array('a'=>'post_user');
347 $_GET['username'] = array('a'=>'get_user');
348 $this->assertSame($_POST['username'], required_param_array('username', PARAM_RAW));
350 unset($_POST['username']);
351 $this->assertSame($_GET['username'], required_param_array('username', PARAM_RAW));
353 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
354 $_POST['username'] = array('a'=>'post_user');
355 try {
356 required_param_array('username', null);
357 $this->fail('coding_exception expected');
358 } catch (moodle_exception $ex) {
359 $this->assertInstanceOf('coding_exception', $ex);
361 try {
362 @required_param_array('username');
363 $this->fail('coding_exception expected');
364 } catch (moodle_exception $ex) {
365 $this->assertInstanceOf('coding_exception', $ex);
366 } catch (Error $error) {
367 // PHP 7.1 throws Error.
368 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
370 try {
371 required_param_array('', PARAM_RAW);
372 $this->fail('coding_exception expected');
373 } catch (moodle_exception $ex) {
374 $this->assertInstanceOf('coding_exception', $ex);
377 // Do not allow nested arrays.
378 try {
379 $_POST['username'] = array('a'=>array('b'=>'post_user'));
380 required_param_array('username', PARAM_RAW);
381 $this->fail('coding_exception expected');
382 } catch (moodle_exception $ex) {
383 $this->assertInstanceOf('coding_exception', $ex);
386 // Do not allow non-arrays.
387 try {
388 $_POST['username'] = 'post_user';
389 required_param_array('username', PARAM_RAW);
390 $this->fail('moodle_exception expected');
391 } catch (moodle_exception $ex) {
392 $this->assertInstanceOf('moodle_exception', $ex);
395 // Make sure array keys are sanitised.
396 $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
397 $this->assertSame(array('a1_-'=>'post_user'), required_param_array('username', PARAM_RAW));
398 $this->assertDebuggingCalled();
401 public function test_clean_param() {
402 // Forbid objects and arrays.
403 try {
404 clean_param(array('x', 'y'), PARAM_RAW);
405 $this->fail('coding_exception expected');
406 } catch (moodle_exception $ex) {
407 $this->assertInstanceOf('coding_exception', $ex);
409 try {
410 $param = new stdClass();
411 $param->id = 1;
412 clean_param($param, PARAM_RAW);
413 $this->fail('coding_exception expected');
414 } catch (moodle_exception $ex) {
415 $this->assertInstanceOf('coding_exception', $ex);
418 // Require correct type.
419 try {
420 clean_param('x', 'xxxxxx');
421 $this->fail('moodle_exception expected');
422 } catch (moodle_exception $ex) {
423 $this->assertInstanceOf('moodle_exception', $ex);
425 try {
426 @clean_param('x');
427 $this->fail('moodle_exception expected');
428 } catch (moodle_exception $ex) {
429 $this->assertInstanceOf('moodle_exception', $ex);
430 } catch (Error $error) {
431 // PHP 7.1 throws Error even earlier.
432 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
436 public function test_clean_param_array() {
437 $this->assertSame(array(), clean_param_array(null, PARAM_RAW));
438 $this->assertSame(array('a', 'b'), clean_param_array(array('a', 'b'), PARAM_RAW));
439 $this->assertSame(array('a', array('b')), clean_param_array(array('a', array('b')), PARAM_RAW, true));
441 // Require correct type.
442 try {
443 clean_param_array(array('x'), 'xxxxxx');
444 $this->fail('moodle_exception expected');
445 } catch (moodle_exception $ex) {
446 $this->assertInstanceOf('moodle_exception', $ex);
448 try {
449 @clean_param_array(array('x'));
450 $this->fail('moodle_exception expected');
451 } catch (moodle_exception $ex) {
452 $this->assertInstanceOf('moodle_exception', $ex);
453 } catch (Error $error) {
454 // PHP 7.1 throws Error even earlier.
455 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
458 try {
459 clean_param_array(array('x', array('y')), PARAM_RAW);
460 $this->fail('coding_exception expected');
461 } catch (moodle_exception $ex) {
462 $this->assertInstanceOf('coding_exception', $ex);
465 // Test recursive.
468 public function test_clean_param_raw() {
469 $this->assertSame(
470 '#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)',
471 clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_RAW));
474 public function test_clean_param_trim() {
475 $this->assertSame('Frog toad', clean_param(" Frog toad \r\n ", PARAM_RAW_TRIMMED));
478 public function test_clean_param_clean() {
479 // PARAM_CLEAN is an ugly hack, do not use in new code (skodak),
480 // instead use more specific type, or submit sothing that can be verified properly.
481 $this->assertSame('xx', clean_param('xx<script>', PARAM_CLEAN));
484 public function test_clean_param_alpha() {
485 $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHA));
488 public function test_clean_param_alphanum() {
489 $this->assertSame('978942897DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHANUM));
492 public function test_clean_param_alphaext() {
493 $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHAEXT));
496 public function test_clean_param_sequence() {
497 $this->assertSame(',9789,42897', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_SEQUENCE));
500 public function test_clean_param_component() {
501 // Please note the cleaning of component names is very strict, no guessing here.
502 $this->assertSame('mod_forum', clean_param('mod_forum', PARAM_COMPONENT));
503 $this->assertSame('block_online_users', clean_param('block_online_users', PARAM_COMPONENT));
504 $this->assertSame('block_blond_online_users', clean_param('block_blond_online_users', PARAM_COMPONENT));
505 $this->assertSame('mod_something2', clean_param('mod_something2', PARAM_COMPONENT));
506 $this->assertSame('forum', clean_param('forum', PARAM_COMPONENT));
507 $this->assertSame('user', clean_param('user', PARAM_COMPONENT));
508 $this->assertSame('rating', clean_param('rating', PARAM_COMPONENT));
509 $this->assertSame('feedback360', clean_param('feedback360', PARAM_COMPONENT));
510 $this->assertSame('mod_feedback360', clean_param('mod_feedback360', PARAM_COMPONENT));
511 $this->assertSame('', clean_param('mod_2something', PARAM_COMPONENT));
512 $this->assertSame('', clean_param('2mod_something', PARAM_COMPONENT));
513 $this->assertSame('', clean_param('mod_something_xx', PARAM_COMPONENT));
514 $this->assertSame('', clean_param('auth_something__xx', PARAM_COMPONENT));
515 $this->assertSame('', clean_param('mod_Something', PARAM_COMPONENT));
516 $this->assertSame('', clean_param('mod_somethíng', PARAM_COMPONENT));
517 $this->assertSame('', clean_param('mod__something', PARAM_COMPONENT));
518 $this->assertSame('', clean_param('auth_xx-yy', PARAM_COMPONENT));
519 $this->assertSame('', clean_param('_auth_xx', PARAM_COMPONENT));
520 $this->assertSame('', clean_param('a2uth_xx', PARAM_COMPONENT));
521 $this->assertSame('', clean_param('auth_xx_', PARAM_COMPONENT));
522 $this->assertSame('', clean_param('auth_xx.old', PARAM_COMPONENT));
523 $this->assertSame('', clean_param('_user', PARAM_COMPONENT));
524 $this->assertSame('', clean_param('2rating', PARAM_COMPONENT));
525 $this->assertSame('', clean_param('user_', PARAM_COMPONENT));
528 public function test_is_valid_plugin_name() {
529 $this->assertTrue(is_valid_plugin_name('forum'));
530 $this->assertTrue(is_valid_plugin_name('forum2'));
531 $this->assertTrue(is_valid_plugin_name('feedback360'));
532 $this->assertTrue(is_valid_plugin_name('online_users'));
533 $this->assertTrue(is_valid_plugin_name('blond_online_users'));
534 $this->assertFalse(is_valid_plugin_name('online__users'));
535 $this->assertFalse(is_valid_plugin_name('forum '));
536 $this->assertFalse(is_valid_plugin_name('forum.old'));
537 $this->assertFalse(is_valid_plugin_name('xx-yy'));
538 $this->assertFalse(is_valid_plugin_name('2xx'));
539 $this->assertFalse(is_valid_plugin_name('Xx'));
540 $this->assertFalse(is_valid_plugin_name('_xx'));
541 $this->assertFalse(is_valid_plugin_name('xx_'));
544 public function test_clean_param_plugin() {
545 // Please note the cleaning of plugin names is very strict, no guessing here.
546 $this->assertSame('forum', clean_param('forum', PARAM_PLUGIN));
547 $this->assertSame('forum2', clean_param('forum2', PARAM_PLUGIN));
548 $this->assertSame('feedback360', clean_param('feedback360', PARAM_PLUGIN));
549 $this->assertSame('online_users', clean_param('online_users', PARAM_PLUGIN));
550 $this->assertSame('blond_online_users', clean_param('blond_online_users', PARAM_PLUGIN));
551 $this->assertSame('', clean_param('online__users', PARAM_PLUGIN));
552 $this->assertSame('', clean_param('forum ', PARAM_PLUGIN));
553 $this->assertSame('', clean_param('forum.old', PARAM_PLUGIN));
554 $this->assertSame('', clean_param('xx-yy', PARAM_PLUGIN));
555 $this->assertSame('', clean_param('2xx', PARAM_PLUGIN));
556 $this->assertSame('', clean_param('Xx', PARAM_PLUGIN));
557 $this->assertSame('', clean_param('_xx', PARAM_PLUGIN));
558 $this->assertSame('', clean_param('xx_', PARAM_PLUGIN));
561 public function test_clean_param_area() {
562 // Please note the cleaning of area names is very strict, no guessing here.
563 $this->assertSame('something', clean_param('something', PARAM_AREA));
564 $this->assertSame('something2', clean_param('something2', PARAM_AREA));
565 $this->assertSame('some_thing', clean_param('some_thing', PARAM_AREA));
566 $this->assertSame('some_thing_xx', clean_param('some_thing_xx', PARAM_AREA));
567 $this->assertSame('feedback360', clean_param('feedback360', PARAM_AREA));
568 $this->assertSame('', clean_param('_something', PARAM_AREA));
569 $this->assertSame('', clean_param('something_', PARAM_AREA));
570 $this->assertSame('', clean_param('2something', PARAM_AREA));
571 $this->assertSame('', clean_param('Something', PARAM_AREA));
572 $this->assertSame('', clean_param('some-thing', PARAM_AREA));
573 $this->assertSame('', clean_param('somethííng', PARAM_AREA));
574 $this->assertSame('', clean_param('something.x', PARAM_AREA));
577 public function test_clean_param_text() {
578 $this->assertSame(PARAM_TEXT, PARAM_MULTILANG);
579 // Standard.
580 $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));
581 $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));
582 $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));
583 // Malformed.
584 $this->assertSame('<span lang="en" class="multilang">aa</span>', clean_param('<span lang="en" class="multilang">aa</span>', PARAM_TEXT));
585 $this->assertSame('aa', clean_param('<span lang="en" class="nothing" class="multilang">aa</span>', PARAM_TEXT));
586 $this->assertSame('aa', clean_param('<lang lang="en" class="multilang">aa</lang>', PARAM_TEXT));
587 $this->assertSame('aa', clean_param('<lang lang="en!!">aa</lang>', PARAM_TEXT));
588 $this->assertSame('aa', clean_param('<span lang="en==" class="multilang">aa</span>', PARAM_TEXT));
589 $this->assertSame('abc', clean_param('a<em>b</em>c', PARAM_TEXT));
590 $this->assertSame('a>c>', clean_param('a><xx >c>', PARAM_TEXT)); // Standard strip_tags() behaviour.
591 $this->assertSame('a', clean_param('a<b', PARAM_TEXT));
592 $this->assertSame('a>b', clean_param('a>b', PARAM_TEXT));
593 $this->assertSame('<lang lang="en">a>a</lang>', clean_param('<lang lang="en">a>a</lang>', PARAM_TEXT)); // Standard strip_tags() behaviour.
594 $this->assertSame('a', clean_param('<lang lang="en">a<a</lang>', PARAM_TEXT));
595 $this->assertSame('<lang lang="en">aa</lang>', clean_param('<lang lang="en">a<br>a</lang>', PARAM_TEXT));
598 public function test_clean_param_url() {
599 // Test PARAM_URL and PARAM_LOCALURL a bit.
600 // Valid URLs.
601 $this->assertSame('http://google.com/', clean_param('http://google.com/', PARAM_URL));
602 $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));
603 $this->assertSame('http://localhost/', clean_param('http://localhost/', PARAM_URL));
604 $this->assertSame('http://0.255.1.1/numericip.php', clean_param('http://0.255.1.1/numericip.php', PARAM_URL));
605 $this->assertSame('https://google.com/', clean_param('https://google.com/', PARAM_URL));
606 $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));
607 $this->assertSame('https://localhost/', clean_param('https://localhost/', PARAM_URL));
608 $this->assertSame('https://0.255.1.1/numericip.php', clean_param('https://0.255.1.1/numericip.php', PARAM_URL));
609 $this->assertSame('ftp://ftp.debian.org/debian/', clean_param('ftp://ftp.debian.org/debian/', PARAM_URL));
610 $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_URL));
611 // Invalid URLs.
612 $this->assertSame('', clean_param('funny:thing', PARAM_URL));
613 $this->assertSame('', clean_param('http://example.ee/sdsf"f', PARAM_URL));
614 $this->assertSame('', clean_param('javascript://comment%0Aalert(1)', PARAM_URL));
615 $this->assertSame('', clean_param('rtmp://example.com/livestream', PARAM_URL));
616 $this->assertSame('', clean_param('rtmp://example.com/live&foo', PARAM_URL));
617 $this->assertSame('', clean_param('rtmp://example.com/fms&mp4:path/to/file.mp4', PARAM_URL));
618 $this->assertSame('', clean_param('mailto:support@moodle.org', PARAM_URL));
619 $this->assertSame('', clean_param('mailto:support@moodle.org?subject=Hello%20Moodle', PARAM_URL));
620 $this->assertSame('', clean_param('mailto:support@moodle.org?subject=Hello%20Moodle&cc=feedback@moodle.org', PARAM_URL));
623 public function test_clean_param_localurl() {
624 global $CFG;
626 $this->resetAfterTest();
628 // External, invalid.
629 $this->assertSame('', clean_param('funny:thing', PARAM_LOCALURL));
630 $this->assertSame('', clean_param('http://google.com/', PARAM_LOCALURL));
631 $this->assertSame('', clean_param('https://google.com/?test=true', PARAM_LOCALURL));
632 $this->assertSame('', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL));
634 // Local absolute.
635 $this->assertSame(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
636 $this->assertSame($CFG->wwwroot . '/with/something?else=true',
637 clean_param($CFG->wwwroot . '/with/something?else=true', PARAM_LOCALURL));
639 // Local relative.
640 $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_LOCALURL));
641 $this->assertSame('course/view.php?id=3', clean_param('course/view.php?id=3', PARAM_LOCALURL));
643 // Local absolute HTTPS in a non HTTPS site.
644 $CFG->wwwroot = str_replace('https:', 'http:', $CFG->wwwroot); // Need to simulate non-https site.
645 $httpsroot = str_replace('http:', 'https:', $CFG->wwwroot);
646 $this->assertSame('', clean_param($httpsroot, PARAM_LOCALURL));
647 $this->assertSame('', clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL));
649 // Local absolute HTTPS in a HTTPS site.
650 $CFG->wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
651 $httpsroot = $CFG->wwwroot;
652 $this->assertSame($httpsroot, clean_param($httpsroot, PARAM_LOCALURL));
653 $this->assertSame($httpsroot . '/with/something?else=true',
654 clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL));
656 // Test open redirects are not possible.
657 $CFG->wwwroot = 'http://www.example.com';
658 $this->assertSame('', clean_param('http://www.example.com.evil.net/hack.php', PARAM_LOCALURL));
659 $CFG->wwwroot = 'https://www.example.com';
660 $this->assertSame('', clean_param('https://www.example.com.evil.net/hack.php', PARAM_LOCALURL));
663 public function test_clean_param_file() {
664 $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_FILE));
665 $this->assertSame('badfile.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE));
666 $this->assertSame('..parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_FILE));
667 $this->assertSame('....grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_FILE));
668 $this->assertSame('..winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_FILE));
669 $this->assertSame('....wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_FILE));
670 $this->assertSame('myfile.a.b.txt', clean_param('myfile.a.b.txt', PARAM_FILE));
671 $this->assertSame('myfile..a..b.txt', clean_param('myfile..a..b.txt', PARAM_FILE));
672 $this->assertSame('myfile.a..b...txt', clean_param('myfile.a..b...txt', PARAM_FILE));
673 $this->assertSame('myfile.a.txt', clean_param('myfile.a.txt', PARAM_FILE));
674 $this->assertSame('myfile...txt', clean_param('myfile...txt', PARAM_FILE));
675 $this->assertSame('...jpg', clean_param('...jpg', PARAM_FILE));
676 $this->assertSame('.a.b.', clean_param('.a.b.', PARAM_FILE));
677 $this->assertSame('', clean_param('.', PARAM_FILE));
678 $this->assertSame('', clean_param('..', PARAM_FILE));
679 $this->assertSame('...', clean_param('...', PARAM_FILE));
680 $this->assertSame('. . . .', clean_param('. . . .', PARAM_FILE));
681 $this->assertSame('dontrtrim.me. .. .. . ', clean_param('dontrtrim.me. .. .. . ', PARAM_FILE));
682 $this->assertSame(' . .dontltrim.me', clean_param(' . .dontltrim.me', PARAM_FILE));
683 $this->assertSame('here is a tab.txt', clean_param("here is a tab\t.txt", PARAM_FILE));
684 $this->assertSame('here is a linebreak.txt', clean_param("here is a line\r\nbreak.txt", PARAM_FILE));
686 // The following behaviours have been maintained although they seem a little odd.
687 $this->assertSame('funnything', clean_param('funny:thing', PARAM_FILE));
688 $this->assertSame('.currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_FILE));
689 $this->assertSame('ctempwindowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_FILE));
690 $this->assertSame('homeuserlinuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_FILE));
691 $this->assertSame('~myfile.txt', clean_param('~/myfile.txt', PARAM_FILE));
694 public function test_clean_param_path() {
695 $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_PATH));
696 $this->assertSame('bad/file.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH));
697 $this->assertSame('/parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_PATH));
698 $this->assertSame('/grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_PATH));
699 $this->assertSame('/winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_PATH));
700 $this->assertSame('/wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_PATH));
701 $this->assertSame('funnything', clean_param('funny:thing', PARAM_PATH));
702 $this->assertSame('./here', clean_param('./././here', PARAM_PATH));
703 $this->assertSame('./currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_PATH));
704 $this->assertSame('c/temp/windowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_PATH));
705 $this->assertSame('/home/user/linuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_PATH));
706 $this->assertSame('/home../user ./.linuxfile.txt', clean_param('/home../user ./.linuxfile.txt', PARAM_PATH));
707 $this->assertSame('~/myfile.txt', clean_param('~/myfile.txt', PARAM_PATH));
708 $this->assertSame('~/myfile.txt', clean_param('~/../myfile.txt', PARAM_PATH));
709 $this->assertSame('/..b../.../myfile.txt', clean_param('/..b../.../myfile.txt', PARAM_PATH));
710 $this->assertSame('..b../.../myfile.txt', clean_param('..b../.../myfile.txt', PARAM_PATH));
711 $this->assertSame('/super/slashes/', clean_param('/super//slashes///', PARAM_PATH));
714 public function test_clean_param_username() {
715 global $CFG;
716 $currentstatus = $CFG->extendedusernamechars;
718 // Run tests with extended character == false;.
719 $CFG->extendedusernamechars = false;
720 $this->assertSame('johndoe123', clean_param('johndoe123', PARAM_USERNAME) );
721 $this->assertSame('john.doe', clean_param('john.doe', PARAM_USERNAME));
722 $this->assertSame('john-doe', clean_param('john-doe', PARAM_USERNAME));
723 $this->assertSame('john-doe', clean_param('john- doe', PARAM_USERNAME));
724 $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
725 $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
726 $this->assertSame('johndoe', clean_param('john~doe', PARAM_USERNAME));
727 $this->assertSame('johndoe', clean_param('john´doe', PARAM_USERNAME));
728 $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john_');
729 $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john_');
730 $this->assertSame(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
731 $this->assertSame('johnd', clean_param('JOHNdóé ', PARAM_USERNAME));
732 $this->assertSame(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýáž?žý??šdoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
734 // Test success condition, if extendedusernamechars == ENABLE;.
735 $CFG->extendedusernamechars = true;
736 $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
737 $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
738 $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john# $%&()+_^');
739 $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john# $%&()+_^');
740 $this->assertSame('john~doe', clean_param('john~doe', PARAM_USERNAME));
741 $this->assertSame('john´doe', clean_param('joHN´doe', PARAM_USERNAME));
742 $this->assertSame('johndoe', clean_param('johnDOE', PARAM_USERNAME));
743 $this->assertSame('johndóé', clean_param('johndóé ', PARAM_USERNAME));
745 $CFG->extendedusernamechars = $currentstatus;
748 public function test_clean_param_stringid() {
749 // Test string identifiers validation.
750 // Valid strings.
751 $this->assertSame('validstring', clean_param('validstring', PARAM_STRINGID));
752 $this->assertSame('mod/foobar:valid_capability', clean_param('mod/foobar:valid_capability', PARAM_STRINGID));
753 $this->assertSame('CZ', clean_param('CZ', PARAM_STRINGID));
754 $this->assertSame('application/vnd.ms-powerpoint', clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID));
755 $this->assertSame('grade2', clean_param('grade2', PARAM_STRINGID));
756 // Invalid strings.
757 $this->assertSame('', clean_param('trailing ', PARAM_STRINGID));
758 $this->assertSame('', clean_param('space bar', PARAM_STRINGID));
759 $this->assertSame('', clean_param('0numeric', PARAM_STRINGID));
760 $this->assertSame('', clean_param('*', PARAM_STRINGID));
761 $this->assertSame('', clean_param(' ', PARAM_STRINGID));
764 public function test_clean_param_timezone() {
765 // Test timezone validation.
766 $testvalues = array (
767 'America/Jamaica' => 'America/Jamaica',
768 'America/Argentina/Cordoba' => 'America/Argentina/Cordoba',
769 'America/Port-au-Prince' => 'America/Port-au-Prince',
770 'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
771 'PST8PDT' => 'PST8PDT',
772 'Wrong.Value' => '',
773 'Wrong/.Value' => '',
774 'Wrong(Value)' => '',
775 '0' => '0',
776 '0.0' => '0.0',
777 '0.5' => '0.5',
778 '9.0' => '9.0',
779 '-9.0' => '-9.0',
780 '+9.0' => '+9.0',
781 '9.5' => '9.5',
782 '-9.5' => '-9.5',
783 '+9.5' => '+9.5',
784 '12.0' => '12.0',
785 '-12.0' => '-12.0',
786 '+12.0' => '+12.0',
787 '12.5' => '12.5',
788 '-12.5' => '-12.5',
789 '+12.5' => '+12.5',
790 '13.0' => '13.0',
791 '-13.0' => '-13.0',
792 '+13.0' => '+13.0',
793 '13.5' => '',
794 '+13.5' => '',
795 '-13.5' => '',
796 '0.2' => '');
798 foreach ($testvalues as $testvalue => $expectedvalue) {
799 $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
800 $this->assertEquals($expectedvalue, $actualvalue);
804 public function test_validate_param() {
805 try {
806 $param = validate_param('11a', PARAM_INT);
807 $this->fail('invalid_parameter_exception expected');
808 } catch (moodle_exception $ex) {
809 $this->assertInstanceOf('invalid_parameter_exception', $ex);
812 $param = validate_param('11', PARAM_INT);
813 $this->assertSame(11, $param);
815 try {
816 $param = validate_param(null, PARAM_INT, false);
817 $this->fail('invalid_parameter_exception expected');
818 } catch (moodle_exception $ex) {
819 $this->assertInstanceOf('invalid_parameter_exception', $ex);
822 $param = validate_param(null, PARAM_INT, true);
823 $this->assertSame(null, $param);
825 try {
826 $param = validate_param(array(), PARAM_INT);
827 $this->fail('invalid_parameter_exception expected');
828 } catch (moodle_exception $ex) {
829 $this->assertInstanceOf('invalid_parameter_exception', $ex);
831 try {
832 $param = validate_param(new stdClass, PARAM_INT);
833 $this->fail('invalid_parameter_exception expected');
834 } catch (moodle_exception $ex) {
835 $this->assertInstanceOf('invalid_parameter_exception', $ex);
838 $param = validate_param('1.0', PARAM_FLOAT);
839 $this->assertSame(1.0, $param);
841 // Make sure valid floats do not cause exception.
842 validate_param(1.0, PARAM_FLOAT);
843 validate_param(10, PARAM_FLOAT);
844 validate_param('0', PARAM_FLOAT);
845 validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
846 validate_param('011.1', PARAM_FLOAT);
847 validate_param('11', PARAM_FLOAT);
848 validate_param('+.1', PARAM_FLOAT);
849 validate_param('-.1', PARAM_FLOAT);
850 validate_param('1e10', PARAM_FLOAT);
851 validate_param('.1e+10', PARAM_FLOAT);
852 validate_param('1E-1', PARAM_FLOAT);
854 try {
855 $param = validate_param('1,2', PARAM_FLOAT);
856 $this->fail('invalid_parameter_exception expected');
857 } catch (moodle_exception $ex) {
858 $this->assertInstanceOf('invalid_parameter_exception', $ex);
860 try {
861 $param = validate_param('', PARAM_FLOAT);
862 $this->fail('invalid_parameter_exception expected');
863 } catch (moodle_exception $ex) {
864 $this->assertInstanceOf('invalid_parameter_exception', $ex);
866 try {
867 $param = validate_param('.', PARAM_FLOAT);
868 $this->fail('invalid_parameter_exception expected');
869 } catch (moodle_exception $ex) {
870 $this->assertInstanceOf('invalid_parameter_exception', $ex);
872 try {
873 $param = validate_param('e10', PARAM_FLOAT);
874 $this->fail('invalid_parameter_exception expected');
875 } catch (moodle_exception $ex) {
876 $this->assertInstanceOf('invalid_parameter_exception', $ex);
878 try {
879 $param = validate_param('abc', PARAM_FLOAT);
880 $this->fail('invalid_parameter_exception expected');
881 } catch (moodle_exception $ex) {
882 $this->assertInstanceOf('invalid_parameter_exception', $ex);
886 public function test_shorten_text_no_tags_already_short_enough() {
887 // ......12345678901234567890123456.
888 $text = "short text already no tags";
889 $this->assertSame($text, shorten_text($text));
892 public function test_shorten_text_with_tags_already_short_enough() {
893 // .........123456...7890....12345678.......901234567.
894 $text = "<p>short <b>text</b> already</p><p>with tags</p>";
895 $this->assertSame($text, shorten_text($text));
898 public function test_shorten_text_no_tags_needs_shortening() {
899 // Default truncation is after 30 chars, but allowing 3 for the final '...'.
900 // ......12345678901234567890123456789023456789012345678901234.
901 $text = "long text without any tags blah de blah blah blah what";
902 $this->assertSame('long text without any tags ...', shorten_text($text));
905 public function test_shorten_text_with_tags_needs_shortening() {
906 // .......................................123456789012345678901234567890...
907 $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
908 "be chopped off but <b>should be added back again</b></blockquote></p></div>";
909 $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
910 "tags that ...</blockquote></p></div>", shorten_text($text));
913 public function test_shorten_text_with_tags_and_html_comment() {
914 $text = "<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with ".
915 "tags that will<!--<![endif]--> ".
916 "be chopped off but <b>should be added back again</b></blockquote></p></div>";
917 $this->assertEquals("<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with " .
918 "tags that ...<!--<![endif]--></blockquote></p></div>", shorten_text($text));
921 public function test_shorten_text_with_entities() {
922 // Remember to allow 3 chars for the final '...'.
923 // ......123456789012345678901234567_____890...
924 $text = "some text which shouldn't &nbsp; break there";
925 $this->assertSame("some text which shouldn't &nbsp; ...", shorten_text($text, 31));
926 $this->assertSame("some text which shouldn't &nbsp;...", shorten_text($text, 30));
927 $this->assertSame("some text which shouldn't ...", shorten_text($text, 29));
930 public function test_shorten_text_known_tricky_case() {
931 // This case caused a bug up to 1.9.5
932 // ..........123456789012345678901234567890123456789.....0_____1___2___...
933 $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
934 $this->assertSame("<h3>standard 'break-out' sub groups in ...</h3>",
935 shorten_text($text, 41));
936 $this->assertSame("<h3>standard 'break-out' sub groups in TGs?...</h3>",
937 shorten_text($text, 42));
938 $this->assertSame("<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;...",
939 shorten_text($text, 43));
942 public function test_shorten_text_no_spaces() {
943 // ..........123456789.
944 $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
945 $this->assertSame("<h1>12345...</h1>", shorten_text($text, 8));
948 public function test_shorten_text_utf8_european() {
949 // Text without tags.
950 // ......123456789012345678901234567.
951 $text = "Žluťoučký koníček přeskočil";
952 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
953 $this->assertSame("Žluťoučký koníče...", shorten_text($text, 19, true));
954 $this->assertSame("Žluťoučký ...", shorten_text($text, 19, false));
955 // And try it with 2-less (that are, in bytes, the middle of a sequence).
956 $this->assertSame("Žluťoučký koní...", shorten_text($text, 17, true));
957 $this->assertSame("Žluťoučký ...", shorten_text($text, 17, false));
959 // .........123456789012345678...901234567....89012345.
960 $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
961 $this->assertSame($text, shorten_text($text, 60));
962 $this->assertSame("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
963 $this->assertSame("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
964 $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
965 // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
966 $this->assertSame("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
967 $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
968 // And try over one tag (start/end), it does proper text len.
969 $this->assertSame("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
970 $this->assertSame("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
971 // And in the middle of one tag.
972 $this->assertSame("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
975 public function test_shorten_text_utf8_oriental() {
976 // Japanese
977 // text without tags
978 // ......123456789012345678901234.
979 $text = '言語設定言語設定abcdefghijkl';
980 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
981 $this->assertSame("言語設定言語...", shorten_text($text, 9, true));
982 $this->assertSame("言語設定言語...", shorten_text($text, 9, false));
983 $this->assertSame("言語設定言語設定ab...", shorten_text($text, 13, true));
984 $this->assertSame("言語設定言語設定...", shorten_text($text, 13, false));
986 // Chinese
987 // text without tags
988 // ......123456789012345678901234.
989 $text = '简体中文简体中文abcdefghijkl';
990 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
991 $this->assertSame("简体中文简体...", shorten_text($text, 9, true));
992 $this->assertSame("简体中文简体...", shorten_text($text, 9, false));
993 $this->assertSame("简体中文简体中文ab...", shorten_text($text, 13, true));
994 $this->assertSame("简体中文简体中文...", shorten_text($text, 13, false));
997 public function test_shorten_text_multilang() {
998 // This is not necessaryily specific to multilang. The issue is really
999 // tags with attributes, where before we were generating invalid HTML
1000 // output like shorten_text('<span id="x" class="y">A</span> B', 1)
1001 // returning '<span id="x" ...</span>'. It is just that multilang
1002 // requires the sort of HTML that is quite likely to trigger this.
1003 // ........................................1...
1004 $text = '<span lang="en" class="multilang">A</span>' .
1005 '<span lang="fr" class="multilang">B</span>';
1006 $this->assertSame('<span lang="en" class="multilang">...</span>',
1007 shorten_text($text, 1));
1011 * Provider for long filenames and its expected result, with and without hash.
1013 * @return array of ($filename, $length, $expected, $includehash)
1015 public function shorten_filename_provider() {
1016 $filename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium totam rem';
1017 $shortfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque';
1019 return [
1020 'More than 100 characters' => [
1021 $filename,
1022 null,
1023 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot',
1024 false,
1026 'More than 100 characters with hash' => [
1027 $filename,
1028 null,
1029 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8',
1030 true,
1032 'More than 100 characters with extension' => [
1033 "{$filename}.zip",
1034 null,
1035 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot.zip',
1036 false,
1038 'More than 100 characters with extension and hash' => [
1039 "{$filename}.zip",
1040 null,
1041 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8.zip',
1042 true,
1044 'Limit filename to 50 chars' => [
1045 $filename,
1047 'sed ut perspiciatis unde omnis iste natus error si',
1048 false,
1050 'Limit filename to 50 chars with hash' => [
1051 $filename,
1053 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8',
1054 true,
1056 'Limit filename to 50 chars with extension' => [
1057 "{$filename}.zip",
1059 'sed ut perspiciatis unde omnis iste natus error si.zip',
1060 false,
1062 'Limit filename to 50 chars with extension and hash' => [
1063 "{$filename}.zip",
1065 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8.zip',
1066 true,
1068 'Test filename that contains less than 100 characters' => [
1069 $shortfilename,
1070 null,
1071 $shortfilename,
1072 false,
1074 'Test filename that contains less than 100 characters and hash' => [
1075 $shortfilename,
1076 null,
1077 $shortfilename,
1078 true,
1080 'Test filename that contains less than 100 characters with extension' => [
1081 "{$shortfilename}.zip",
1082 null,
1083 "{$shortfilename}.zip",
1084 false,
1086 'Test filename that contains less than 100 characters with extension and hash' => [
1087 "{$shortfilename}.zip",
1088 null,
1089 "{$shortfilename}.zip",
1090 true,
1096 * Test the {@link shorten_filename()} method.
1098 * @dataProvider shorten_filename_provider
1100 * @param string $filename
1101 * @param int $length
1102 * @param string $expected
1103 * @param boolean $includehash
1105 public function test_shorten_filename($filename, $length, $expected, $includehash) {
1106 if (null === $length) {
1107 $length = MAX_FILENAME_SIZE;
1110 $this->assertSame($expected, shorten_filename($filename, $length, $includehash));
1114 * Provider for long filenames and its expected result, with and without hash.
1116 * @return array of ($filename, $length, $expected, $includehash)
1118 public function shorten_filenames_provider() {
1119 $shortfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque';
1120 $longfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium totam rem';
1121 $extfilename = $longfilename.'.zip';
1122 $expected = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot';
1123 $expectedwithhash = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8';
1124 $expectedext = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot.zip';
1125 $expectedextwithhash = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8.zip';
1126 $expected50 = 'sed ut perspiciatis unde omnis iste natus error si';
1127 $expected50withhash = 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8';
1128 $expected50ext = 'sed ut perspiciatis unde omnis iste natus error si.zip';
1129 $expected50extwithhash = 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8.zip';
1130 $expected50short = 'sed ut perspiciatis unde omnis iste n - 5fb6543490';
1132 return [
1133 'Empty array without hash' => [
1135 null,
1137 false,
1139 'Empty array with hash' => [
1141 null,
1143 true,
1145 'Array with less than 100 characters' => [
1146 [$shortfilename, $shortfilename, $shortfilename],
1147 null,
1148 [$shortfilename, $shortfilename, $shortfilename],
1149 false,
1151 'Array with more than 100 characters without hash' => [
1152 [$longfilename, $longfilename, $longfilename],
1153 null,
1154 [$expected, $expected, $expected],
1155 false,
1157 'Array with more than 100 characters with hash' => [
1158 [$longfilename, $longfilename, $longfilename],
1159 null,
1160 [$expectedwithhash, $expectedwithhash, $expectedwithhash],
1161 true,
1163 'Array with more than 100 characters with extension' => [
1164 [$extfilename, $extfilename, $extfilename],
1165 null,
1166 [$expectedext, $expectedext, $expectedext],
1167 false,
1169 'Array with more than 100 characters with extension and hash' => [
1170 [$extfilename, $extfilename, $extfilename],
1171 null,
1172 [$expectedextwithhash, $expectedextwithhash, $expectedextwithhash],
1173 true,
1175 'Array with more than 100 characters mix (short, long, with extension) without hash' => [
1176 [$shortfilename, $longfilename, $extfilename],
1177 null,
1178 [$shortfilename, $expected, $expectedext],
1179 false,
1181 'Array with more than 100 characters mix (short, long, with extension) with hash' => [
1182 [$shortfilename, $longfilename, $extfilename],
1183 null,
1184 [$shortfilename, $expectedwithhash, $expectedextwithhash],
1185 true,
1187 'Array with less than 50 characters without hash' => [
1188 [$longfilename, $longfilename, $longfilename],
1190 [$expected50, $expected50, $expected50],
1191 false,
1193 'Array with less than 50 characters with hash' => [
1194 [$longfilename, $longfilename, $longfilename],
1196 [$expected50withhash, $expected50withhash, $expected50withhash],
1197 true,
1199 'Array with less than 50 characters with extension' => [
1200 [$extfilename, $extfilename, $extfilename],
1202 [$expected50ext, $expected50ext, $expected50ext],
1203 false,
1205 'Array with less than 50 characters with extension and hash' => [
1206 [$extfilename, $extfilename, $extfilename],
1208 [$expected50extwithhash, $expected50extwithhash, $expected50extwithhash],
1209 true,
1211 'Array with less than 50 characters mix (short, long, with extension) without hash' => [
1212 [$shortfilename, $longfilename, $extfilename],
1214 [$expected50, $expected50, $expected50ext],
1215 false,
1217 'Array with less than 50 characters mix (short, long, with extension) with hash' => [
1218 [$shortfilename, $longfilename, $extfilename],
1220 [$expected50short, $expected50withhash, $expected50extwithhash],
1221 true,
1227 * Test the {@link shorten_filenames()} method.
1229 * @dataProvider shorten_filenames_provider
1231 * @param string $filenames
1232 * @param int $length
1233 * @param string $expected
1234 * @param boolean $includehash
1236 public function test_shorten_filenames($filenames, $length, $expected, $includehash) {
1237 if (null === $length) {
1238 $length = MAX_FILENAME_SIZE;
1241 $this->assertSame($expected, shorten_filenames($filenames, $length, $includehash));
1244 public function test_usergetdate() {
1245 global $USER, $CFG, $DB;
1246 $this->resetAfterTest();
1248 $this->setAdminUser();
1250 $USER->timezone = 2;// Set the timezone to a known state.
1252 $ts = 1261540267; // The time this function was created.
1254 $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
1255 $arr = array_values($arr);
1257 list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1258 $this->assertSame(7, $seconds);
1259 $this->assertSame(51, $minutes);
1260 $this->assertSame(4, $hours);
1261 $this->assertSame(23, $mday);
1262 $this->assertSame(3, $wday);
1263 $this->assertSame(12, $mon);
1264 $this->assertSame(2009, $year);
1265 $this->assertSame(356, $yday);
1266 $this->assertSame('Wednesday', $weekday);
1267 $this->assertSame('December', $month);
1268 $arr = usergetdate($ts); // Gets the timezone from the $USER object.
1269 $arr = array_values($arr);
1271 list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1272 $this->assertSame(7, $seconds);
1273 $this->assertSame(51, $minutes);
1274 $this->assertSame(5, $hours);
1275 $this->assertSame(23, $mday);
1276 $this->assertSame(3, $wday);
1277 $this->assertSame(12, $mon);
1278 $this->assertSame(2009, $year);
1279 $this->assertSame(356, $yday);
1280 $this->assertSame('Wednesday', $weekday);
1281 $this->assertSame('December', $month);
1284 public function test_mark_user_preferences_changed() {
1285 $this->resetAfterTest();
1286 $otheruser = $this->getDataGenerator()->create_user();
1287 $otheruserid = $otheruser->id;
1289 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1290 mark_user_preferences_changed($otheruserid);
1292 $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1293 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1296 public function test_check_user_preferences_loaded() {
1297 global $DB;
1298 $this->resetAfterTest();
1300 $otheruser = $this->getDataGenerator()->create_user();
1301 $otheruserid = $otheruser->id;
1303 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1304 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1306 $user = new stdClass();
1307 $user->id = $otheruserid;
1309 // Load.
1310 check_user_preferences_loaded($user);
1311 $this->assertTrue(isset($user->preference));
1312 $this->assertTrue(is_array($user->preference));
1313 $this->assertArrayHasKey('_lastloaded', $user->preference);
1314 $this->assertCount(1, $user->preference);
1316 // Add preference via direct call.
1317 $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1319 // No cache reload yet.
1320 check_user_preferences_loaded($user);
1321 $this->assertCount(1, $user->preference);
1323 // Forced reloading of cache.
1324 unset($user->preference);
1325 check_user_preferences_loaded($user);
1326 $this->assertCount(2, $user->preference);
1327 $this->assertSame('yyy', $user->preference['xxx']);
1329 // Add preference via direct call.
1330 $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1332 // Test timeouts and modifications from different session.
1333 set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1334 $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1335 check_user_preferences_loaded($user);
1336 $this->assertCount(2, $user->preference);
1337 check_user_preferences_loaded($user, 10);
1338 $this->assertCount(3, $user->preference);
1339 $this->assertSame('bbb', $user->preference['aaa']);
1340 set_cache_flag('userpreferenceschanged', $user->id, null);
1343 public function test_set_user_preference() {
1344 global $DB, $USER;
1345 $this->resetAfterTest();
1347 $this->setAdminUser();
1349 $otheruser = $this->getDataGenerator()->create_user();
1350 $otheruserid = $otheruser->id;
1352 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1353 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1355 $user = new stdClass();
1356 $user->id = $otheruserid;
1358 set_user_preference('aaa', 'bbb', $otheruserid);
1359 $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1360 $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
1362 set_user_preference('xxx', 'yyy', $user);
1363 $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1364 $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
1365 $this->assertTrue(is_array($user->preference));
1366 $this->assertSame('bbb', $user->preference['aaa']);
1367 $this->assertSame('yyy', $user->preference['xxx']);
1369 set_user_preference('xxx', null, $user);
1370 $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1371 $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
1373 set_user_preference('ooo', true, $user);
1374 $prefs = get_user_preferences(null, null, $otheruserid);
1375 $this->assertSame($user->preference['aaa'], $prefs['aaa']);
1376 $this->assertSame($user->preference['ooo'], $prefs['ooo']);
1377 $this->assertSame('1', $prefs['ooo']);
1379 set_user_preference('null', 0, $user);
1380 $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1382 $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1384 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1385 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1387 // Test $USER default.
1388 set_user_preference('_test_user_preferences_pref', 'ok');
1389 $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1390 unset_user_preference('_test_user_preferences_pref');
1391 $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1393 // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
1394 $longvalue = str_repeat('a', 1333);
1395 set_user_preference('_test_long_user_preference', $longvalue);
1396 $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1397 $this->assertEquals($longvalue,
1398 $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1400 // Test > 1333 char values, coding_exception expected.
1401 $longvalue = str_repeat('a', 1334);
1402 try {
1403 set_user_preference('_test_long_user_preference', $longvalue);
1404 $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1405 } catch (moodle_exception $ex) {
1406 $this->assertInstanceOf('coding_exception', $ex);
1409 // Test invalid params.
1410 try {
1411 set_user_preference('_test_user_preferences_pref', array());
1412 $this->fail('Exception expected - array not valid preference value');
1413 } catch (moodle_exception $ex) {
1414 $this->assertInstanceOf('coding_exception', $ex);
1416 try {
1417 set_user_preference('_test_user_preferences_pref', new stdClass);
1418 $this->fail('Exception expected - class not valid preference value');
1419 } catch (moodle_exception $ex) {
1420 $this->assertInstanceOf('coding_exception', $ex);
1422 try {
1423 set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1424 $this->fail('Exception expected - user instance expected');
1425 } catch (moodle_exception $ex) {
1426 $this->assertInstanceOf('coding_exception', $ex);
1428 try {
1429 set_user_preference('_test_user_preferences_pref', 1, 'abc');
1430 $this->fail('Exception expected - user instance expected');
1431 } catch (moodle_exception $ex) {
1432 $this->assertInstanceOf('coding_exception', $ex);
1434 try {
1435 set_user_preference('', 1);
1436 $this->fail('Exception expected - invalid name accepted');
1437 } catch (moodle_exception $ex) {
1438 $this->assertInstanceOf('coding_exception', $ex);
1440 try {
1441 set_user_preference('1', 1);
1442 $this->fail('Exception expected - invalid name accepted');
1443 } catch (moodle_exception $ex) {
1444 $this->assertInstanceOf('coding_exception', $ex);
1448 public function test_set_user_preference_for_current_user() {
1449 global $USER;
1450 $this->resetAfterTest();
1451 $this->setAdminUser();
1453 set_user_preference('test_pref', 2);
1454 set_user_preference('test_pref', 1, $USER->id);
1455 $this->assertEquals(1, get_user_preferences('test_pref'));
1458 public function test_unset_user_preference_for_current_user() {
1459 global $USER;
1460 $this->resetAfterTest();
1461 $this->setAdminUser();
1463 set_user_preference('test_pref', 1);
1464 unset_user_preference('test_pref', $USER->id);
1465 $this->assertNull(get_user_preferences('test_pref'));
1469 * Test essential features implementation of {@link get_extra_user_fields()} as the admin user with all capabilities.
1471 public function test_get_extra_user_fields_essentials() {
1472 global $CFG, $USER, $DB;
1473 $this->resetAfterTest();
1475 $this->setAdminUser();
1476 $context = context_system::instance();
1478 // No fields.
1479 $CFG->showuseridentity = '';
1480 $this->assertEquals(array(), get_extra_user_fields($context));
1482 // One field.
1483 $CFG->showuseridentity = 'frog';
1484 $this->assertEquals(array('frog'), get_extra_user_fields($context));
1486 // Two fields.
1487 $CFG->showuseridentity = 'frog,zombie';
1488 $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1490 // No fields, except.
1491 $CFG->showuseridentity = '';
1492 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1494 // One field.
1495 $CFG->showuseridentity = 'frog';
1496 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1498 // Two fields.
1499 $CFG->showuseridentity = 'frog,zombie';
1500 $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1504 * Prepare environment for couple of tests related to permission checks in {@link get_extra_user_fields()}.
1506 * @return stdClass
1508 protected function environment_for_get_extra_user_fields_tests() {
1509 global $CFG, $DB;
1511 $CFG->showuseridentity = 'idnumber,country,city';
1512 $CFG->hiddenuserfields = 'country,city';
1514 $env = new stdClass();
1516 $env->course = $this->getDataGenerator()->create_course();
1517 $env->coursecontext = context_course::instance($env->course->id);
1519 $env->teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
1520 $env->studentrole = $DB->get_record('role', array('shortname' => 'student'));
1521 $env->managerrole = $DB->get_record('role', array('shortname' => 'manager'));
1523 $env->student = $this->getDataGenerator()->create_user();
1524 $env->teacher = $this->getDataGenerator()->create_user();
1525 $env->manager = $this->getDataGenerator()->create_user();
1527 role_assign($env->studentrole->id, $env->student->id, $env->coursecontext->id);
1528 role_assign($env->teacherrole->id, $env->teacher->id, $env->coursecontext->id);
1529 role_assign($env->managerrole->id, $env->manager->id, SYSCONTEXTID);
1531 return $env;
1535 * No identity fields shown to student user (no permission to view identity fields).
1537 public function test_get_extra_user_fields_no_access() {
1539 $this->resetAfterTest();
1540 $env = $this->environment_for_get_extra_user_fields_tests();
1541 $this->setUser($env->student);
1543 $this->assertEquals(array(), get_extra_user_fields($env->coursecontext));
1544 $this->assertEquals(array(), get_extra_user_fields(context_system::instance()));
1548 * Teacher can see students' identity fields only within the course.
1550 public function test_get_extra_user_fields_course_only_access() {
1552 $this->resetAfterTest();
1553 $env = $this->environment_for_get_extra_user_fields_tests();
1554 $this->setUser($env->teacher);
1556 $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields($env->coursecontext));
1557 $this->assertEquals(array(), get_extra_user_fields(context_system::instance()));
1561 * Teacher can be prevented from seeing students' identity fields even within the course.
1563 public function test_get_extra_user_fields_course_prevented_access() {
1565 $this->resetAfterTest();
1566 $env = $this->environment_for_get_extra_user_fields_tests();
1567 $this->setUser($env->teacher);
1569 assign_capability('moodle/course:viewhiddenuserfields', CAP_PREVENT, $env->teacherrole->id, $env->coursecontext->id);
1570 $this->assertEquals(array('idnumber'), get_extra_user_fields($env->coursecontext));
1574 * Manager can see students' identity fields anywhere.
1576 public function test_get_extra_user_fields_anywhere_access() {
1578 $this->resetAfterTest();
1579 $env = $this->environment_for_get_extra_user_fields_tests();
1580 $this->setUser($env->manager);
1582 $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields($env->coursecontext));
1583 $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields(context_system::instance()));
1587 * Manager can be prevented from seeing hidden fields outside the course.
1589 public function test_get_extra_user_fields_schismatic_access() {
1591 $this->resetAfterTest();
1592 $env = $this->environment_for_get_extra_user_fields_tests();
1593 $this->setUser($env->manager);
1595 assign_capability('moodle/user:viewhiddendetails', CAP_PREVENT, $env->managerrole->id, SYSCONTEXTID, true);
1596 $this->assertEquals(array('idnumber'), get_extra_user_fields(context_system::instance()));
1597 // Note that inside the course, the manager can still see the hidden identifiers as this is currently
1598 // controlled by a separate capability for legacy reasons.
1599 $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields($env->coursecontext));
1603 * Two capabilities must be currently set to prevent manager from seeing hidden fields.
1605 public function test_get_extra_user_fields_hard_to_prevent_access() {
1607 $this->resetAfterTest();
1608 $env = $this->environment_for_get_extra_user_fields_tests();
1609 $this->setUser($env->manager);
1611 assign_capability('moodle/user:viewhiddendetails', CAP_PREVENT, $env->managerrole->id, SYSCONTEXTID, true);
1612 assign_capability('moodle/course:viewhiddenuserfields', CAP_PREVENT, $env->managerrole->id, SYSCONTEXTID, true);
1614 $this->assertEquals(array('idnumber'), get_extra_user_fields(context_system::instance()));
1615 $this->assertEquals(array('idnumber'), get_extra_user_fields($env->coursecontext));
1618 public function test_get_extra_user_fields_sql() {
1619 global $CFG, $USER, $DB;
1620 $this->resetAfterTest();
1622 $this->setAdminUser();
1624 $context = context_system::instance();
1626 // No fields.
1627 $CFG->showuseridentity = '';
1628 $this->assertSame('', get_extra_user_fields_sql($context));
1630 // One field.
1631 $CFG->showuseridentity = 'frog';
1632 $this->assertSame(', frog', get_extra_user_fields_sql($context));
1634 // Two fields with table prefix.
1635 $CFG->showuseridentity = 'frog,zombie';
1636 $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1638 // Two fields with field prefix.
1639 $CFG->showuseridentity = 'frog,zombie';
1640 $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
1641 get_extra_user_fields_sql($context, '', 'u_'));
1643 // One field excluded.
1644 $CFG->showuseridentity = 'frog';
1645 $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
1647 // Two fields, one excluded, table+field prefix.
1648 $CFG->showuseridentity = 'frog,zombie';
1649 $this->assertEquals(', u1.zombie AS u_zombie',
1650 get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1654 * Test some critical TZ/DST.
1656 * This method tests some special TZ/DST combinations that were fixed
1657 * by MDL-38999. The tests are done by comparing the results of the
1658 * output using Moodle TZ/DST support and PHP native one.
1660 * Note: If you don't trust PHP TZ/DST support, can verify the
1661 * harcoded expectations below with:
1662 * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
1664 public function test_some_moodle_special_dst() {
1665 $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
1667 // In Europe/Tallinn it was 2013/04/08 05:00:00.
1668 $expectation = '2013/04/08 05:00:00';
1669 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1670 $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1671 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1672 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1673 $this->assertSame($expectation, $phpres);
1674 $this->assertSame($expectation, $moodleres);
1676 // In St. Johns it was 2013/04/07 23:30:00.
1677 $expectation = '2013/04/07 23:30:00';
1678 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1679 $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1680 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1681 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1682 $this->assertSame($expectation, $phpres);
1683 $this->assertSame($expectation, $moodleres);
1685 $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1687 // In Europe/Tallinn it was 2013/11/08 04:00:00.
1688 $expectation = '2013/11/08 04:00:00';
1689 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1690 $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1691 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1692 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1693 $this->assertSame($expectation, $phpres);
1694 $this->assertSame($expectation, $moodleres);
1696 // In St. Johns it was 2013/11/07 22:30:00.
1697 $expectation = '2013/11/07 22:30:00';
1698 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1699 $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1700 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1701 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1702 $this->assertSame($expectation, $phpres);
1703 $this->assertSame($expectation, $moodleres);
1706 public function test_userdate() {
1707 global $USER, $CFG, $DB;
1708 $this->resetAfterTest();
1710 $this->setAdminUser();
1712 $testvalues = array(
1713 array(
1714 'time' => '1309514400',
1715 'usertimezone' => 'America/Moncton',
1716 'timezone' => '0.0', // No dst offset.
1717 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM',
1718 'expectedoutputhtml' => '<time datetime="2011-07-01T07:00:00-03:00">Friday, 1 July 2011, 10:00 AM</time>'
1720 array(
1721 'time' => '1309514400',
1722 'usertimezone' => 'America/Moncton',
1723 'timezone' => '99', // Dst offset and timezone offset.
1724 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM',
1725 'expectedoutputhtml' => '<time datetime="2011-07-01T07:00:00-03:00">Friday, 1 July 2011, 7:00 AM</time>'
1727 array(
1728 'time' => '1309514400',
1729 'usertimezone' => 'America/Moncton',
1730 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
1731 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM',
1732 'expectedoutputhtml' => '<time datetime="2011-07-01t07:00:00-03:00">Friday, 1 July 2011, 7:00 AM</time>'
1734 array(
1735 'time' => '1293876000 ',
1736 'usertimezone' => 'America/Moncton',
1737 'timezone' => '0.0', // No dst offset.
1738 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM',
1739 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 10:00 AM</time>'
1741 array(
1742 'time' => '1293876000 ',
1743 'usertimezone' => 'America/Moncton',
1744 'timezone' => '99', // No dst offset in jan, so just timezone offset.
1745 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM',
1746 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 6:00 AM</time>'
1748 array(
1749 'time' => '1293876000 ',
1750 'usertimezone' => 'America/Moncton',
1751 'timezone' => 'America/Moncton', // No dst offset in jan.
1752 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM',
1753 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 6:00 AM</time>'
1755 array(
1756 'time' => '1293876000 ',
1757 'usertimezone' => '2',
1758 'timezone' => '99', // Take user timezone.
1759 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM',
1760 'expectedoutputhtml' => '<time datetime="2011-01-01T12:00:00+02:00">Saturday, 1 January 2011, 12:00 PM</time>'
1762 array(
1763 'time' => '1293876000 ',
1764 'usertimezone' => '-2',
1765 'timezone' => '99', // Take user timezone.
1766 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM',
1767 'expectedoutputhtml' => '<time datetime="2011-01-01T08:00:00-02:00">Saturday, 1 January 2011, 8:00 AM</time>'
1769 array(
1770 'time' => '1293876000 ',
1771 'usertimezone' => '-10',
1772 'timezone' => '2', // Take this timezone.
1773 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM',
1774 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 12:00 PM</time>'
1776 array(
1777 'time' => '1293876000 ',
1778 'usertimezone' => '-10',
1779 'timezone' => '-2', // Take this timezone.
1780 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM',
1781 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 8:00 AM</time>'
1783 array(
1784 'time' => '1293876000 ',
1785 'usertimezone' => '-10',
1786 'timezone' => 'random/time', // This should show server time.
1787 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM',
1788 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 6:00 PM</time>'
1790 array(
1791 'time' => '1293876000 ',
1792 'usertimezone' => '20', // Fallback to server time zone.
1793 'timezone' => '99', // This should show user time.
1794 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM',
1795 'expectedoutputhtml' => '<time datetime="2011-01-01T18:00:00+08:00">Saturday, 1 January 2011, 6:00 PM</time>'
1799 // Set default timezone to Australia/Perth, else time calculated
1800 // will not match expected values.
1801 $this->setTimezone(99, 'Australia/Perth');
1803 foreach ($testvalues as $vals) {
1804 $USER->timezone = $vals['usertimezone'];
1805 $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1806 $actualoutputhtml = userdate_htmltime($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1808 // On different systems case of AM PM changes so compare case insensitive.
1809 $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1810 $vals['expectedoutputhtml'] = core_text::strtolower($vals['expectedoutputhtml']);
1811 $actualoutput = core_text::strtolower($actualoutput);
1812 $actualoutputhtml = core_text::strtolower($actualoutputhtml);
1814 $this->assertSame($vals['expectedoutput'], $actualoutput,
1815 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput} \ndata: " . var_export($vals, true));
1816 $this->assertSame($vals['expectedoutputhtml'], $actualoutputhtml,
1817 "Expected: {$vals['expectedoutputhtml']} => Actual: {$actualoutputhtml} \ndata: " . var_export($vals, true));
1822 * Make sure the DST changes happen at the right time in Moodle.
1824 public function test_dst_changes() {
1825 // DST switching in Prague.
1826 // From 2AM to 3AM in 1989.
1827 $date = new DateTime('1989-03-26T01:59:00+01:00');
1828 $this->assertSame('Sunday, 26 March 1989, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1829 $date = new DateTime('1989-03-26T02:01:00+01:00');
1830 $this->assertSame('Sunday, 26 March 1989, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1831 // From 3AM to 2AM in 1989 - not the same as the west Europe.
1832 $date = new DateTime('1989-09-24T01:59:00+01:00');
1833 $this->assertSame('Sunday, 24 September 1989, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1834 $date = new DateTime('1989-09-24T02:01:00+01:00');
1835 $this->assertSame('Sunday, 24 September 1989, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1836 // From 2AM to 3AM in 2014.
1837 $date = new DateTime('2014-03-30T01:59:00+01:00');
1838 $this->assertSame('Sunday, 30 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1839 $date = new DateTime('2014-03-30T02:01:00+01:00');
1840 $this->assertSame('Sunday, 30 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1841 // From 3AM to 2AM in 2014.
1842 $date = new DateTime('2014-10-26T01:59:00+01:00');
1843 $this->assertSame('Sunday, 26 October 2014, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1844 $date = new DateTime('2014-10-26T02:01:00+01:00');
1845 $this->assertSame('Sunday, 26 October 2014, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1846 // From 2AM to 3AM in 2020.
1847 $date = new DateTime('2020-03-29T01:59:00+01:00');
1848 $this->assertSame('Sunday, 29 March 2020, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1849 $date = new DateTime('2020-03-29T02:01:00+01:00');
1850 $this->assertSame('Sunday, 29 March 2020, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1851 // From 3AM to 2AM in 2020.
1852 $date = new DateTime('2020-10-25T01:59:00+01:00');
1853 $this->assertSame('Sunday, 25 October 2020, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1854 $date = new DateTime('2020-10-25T02:01:00+01:00');
1855 $this->assertSame('Sunday, 25 October 2020, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1857 // DST switching in NZ.
1858 // From 3AM to 2AM in 2015.
1859 $date = new DateTime('2015-04-05T02:59:00+13:00');
1860 $this->assertSame('Sunday, 5 April 2015, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1861 $date = new DateTime('2015-04-05T03:01:00+13:00');
1862 $this->assertSame('Sunday, 5 April 2015, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1863 // From 2AM to 3AM in 2009.
1864 $date = new DateTime('2015-09-27T01:59:00+12:00');
1865 $this->assertSame('Sunday, 27 September 2015, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1866 $date = new DateTime('2015-09-27T02:01:00+12:00');
1867 $this->assertSame('Sunday, 27 September 2015, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1869 // DST switching in Perth.
1870 // From 3AM to 2AM in 2009.
1871 $date = new DateTime('2008-03-30T01:59:00+08:00');
1872 $this->assertSame('Sunday, 30 March 2008, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1873 $date = new DateTime('2008-03-30T02:01:00+08:00');
1874 $this->assertSame('Sunday, 30 March 2008, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1875 // From 2AM to 3AM in 2009.
1876 $date = new DateTime('2008-10-26T01:59:00+08:00');
1877 $this->assertSame('Sunday, 26 October 2008, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1878 $date = new DateTime('2008-10-26T02:01:00+08:00');
1879 $this->assertSame('Sunday, 26 October 2008, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1881 // DST switching in US.
1882 // From 2AM to 3AM in 2014.
1883 $date = new DateTime('2014-03-09T01:59:00-05:00');
1884 $this->assertSame('Sunday, 9 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1885 $date = new DateTime('2014-03-09T02:01:00-05:00');
1886 $this->assertSame('Sunday, 9 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1887 // From 3AM to 2AM in 2014.
1888 $date = new DateTime('2014-11-02T01:59:00-04:00');
1889 $this->assertSame('Sunday, 2 November 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1890 $date = new DateTime('2014-11-02T02:01:00-04:00');
1891 $this->assertSame('Sunday, 2 November 2014, 01:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1894 public function test_make_timestamp() {
1895 global $USER, $CFG, $DB;
1896 $this->resetAfterTest();
1898 $this->setAdminUser();
1900 $testvalues = array(
1901 array(
1902 'usertimezone' => 'America/Moncton',
1903 'year' => '2011',
1904 'month' => '7',
1905 'day' => '1',
1906 'hour' => '10',
1907 'minutes' => '00',
1908 'seconds' => '00',
1909 'timezone' => '0.0',
1910 'applydst' => false, // No dst offset.
1911 'expectedoutput' => '1309514400' // 6pm at UTC+0.
1913 array(
1914 'usertimezone' => 'America/Moncton',
1915 'year' => '2011',
1916 'month' => '7',
1917 'day' => '1',
1918 'hour' => '10',
1919 'minutes' => '00',
1920 'seconds' => '00',
1921 'timezone' => '99', // User default timezone.
1922 'applydst' => false, // Don't apply dst.
1923 'expectedoutput' => '1309528800'
1925 array(
1926 'usertimezone' => 'America/Moncton',
1927 'year' => '2011',
1928 'month' => '7',
1929 'day' => '1',
1930 'hour' => '10',
1931 'minutes' => '00',
1932 'seconds' => '00',
1933 'timezone' => '99', // User default timezone.
1934 'applydst' => true, // Apply dst.
1935 'expectedoutput' => '1309525200'
1937 array(
1938 'usertimezone' => 'America/Moncton',
1939 'year' => '2011',
1940 'month' => '7',
1941 'day' => '1',
1942 'hour' => '10',
1943 'minutes' => '00',
1944 'seconds' => '00',
1945 'timezone' => 'America/Moncton', // String timezone.
1946 'applydst' => true, // Apply dst.
1947 'expectedoutput' => '1309525200'
1949 array(
1950 'usertimezone' => '2', // No dst applyed.
1951 'year' => '2011',
1952 'month' => '7',
1953 'day' => '1',
1954 'hour' => '10',
1955 'minutes' => '00',
1956 'seconds' => '00',
1957 'timezone' => '99', // Take user timezone.
1958 'applydst' => true, // Apply dst.
1959 'expectedoutput' => '1309507200'
1961 array(
1962 'usertimezone' => '-2', // No dst applyed.
1963 'year' => '2011',
1964 'month' => '7',
1965 'day' => '1',
1966 'hour' => '10',
1967 'minutes' => '00',
1968 'seconds' => '00',
1969 'timezone' => '99', // Take usertimezone.
1970 'applydst' => true, // Apply dst.
1971 'expectedoutput' => '1309521600'
1973 array(
1974 'usertimezone' => '-10', // No dst applyed.
1975 'year' => '2011',
1976 'month' => '7',
1977 'day' => '1',
1978 'hour' => '10',
1979 'minutes' => '00',
1980 'seconds' => '00',
1981 'timezone' => '2', // Take this timezone.
1982 'applydst' => true, // Apply dst.
1983 'expectedoutput' => '1309507200'
1985 array(
1986 'usertimezone' => '-10', // No dst applyed.
1987 'year' => '2011',
1988 'month' => '7',
1989 'day' => '1',
1990 'hour' => '10',
1991 'minutes' => '00',
1992 'seconds' => '00',
1993 'timezone' => '-2', // Take this timezone.
1994 'applydst' => true, // Apply dst.
1995 'expectedoutput' => '1309521600'
1997 array(
1998 'usertimezone' => '-10', // No dst applyed.
1999 'year' => '2011',
2000 'month' => '7',
2001 'day' => '1',
2002 'hour' => '10',
2003 'minutes' => '00',
2004 'seconds' => '00',
2005 'timezone' => 'random/time', // This should show server time.
2006 'applydst' => true, // Apply dst.
2007 'expectedoutput' => '1309485600'
2009 array(
2010 'usertimezone' => '-14', // Server time.
2011 'year' => '2011',
2012 'month' => '7',
2013 'day' => '1',
2014 'hour' => '10',
2015 'minutes' => '00',
2016 'seconds' => '00',
2017 'timezone' => '99', // Get user time.
2018 'applydst' => true, // Apply dst.
2019 'expectedoutput' => '1309485600'
2023 // Set default timezone to Australia/Perth, else time calculated
2024 // will not match expected values.
2025 $this->setTimezone(99, 'Australia/Perth');
2027 // Test make_timestamp with all testvals and assert if anything wrong.
2028 foreach ($testvalues as $vals) {
2029 $USER->timezone = $vals['usertimezone'];
2030 $actualoutput = make_timestamp(
2031 $vals['year'],
2032 $vals['month'],
2033 $vals['day'],
2034 $vals['hour'],
2035 $vals['minutes'],
2036 $vals['seconds'],
2037 $vals['timezone'],
2038 $vals['applydst']
2041 // On different systems case of AM PM changes so compare case insensitive.
2042 $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
2043 $actualoutput = core_text::strtolower($actualoutput);
2045 $this->assertSame($vals['expectedoutput'], $actualoutput,
2046 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
2047 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
2052 * Test get_string and most importantly the implementation of the lang_string
2053 * object.
2055 public function test_get_string() {
2056 global $COURSE;
2058 // Make sure we are using English.
2059 $originallang = $COURSE->lang;
2060 $COURSE->lang = 'en';
2062 $yes = get_string('yes');
2063 $yesexpected = 'Yes';
2064 $this->assertInternalType('string', $yes);
2065 $this->assertSame($yesexpected, $yes);
2067 $yes = get_string('yes', 'moodle');
2068 $this->assertInternalType('string', $yes);
2069 $this->assertSame($yesexpected, $yes);
2071 $yes = get_string('yes', 'core');
2072 $this->assertInternalType('string', $yes);
2073 $this->assertSame($yesexpected, $yes);
2075 $yes = get_string('yes', '');
2076 $this->assertInternalType('string', $yes);
2077 $this->assertSame($yesexpected, $yes);
2079 $yes = get_string('yes', null);
2080 $this->assertInternalType('string', $yes);
2081 $this->assertSame($yesexpected, $yes);
2083 $yes = get_string('yes', null, 1);
2084 $this->assertInternalType('string', $yes);
2085 $this->assertSame($yesexpected, $yes);
2087 $days = 1;
2088 $numdays = get_string('numdays', 'core', '1');
2089 $numdaysexpected = $days.' days';
2090 $this->assertInternalType('string', $numdays);
2091 $this->assertSame($numdaysexpected, $numdays);
2093 $yes = get_string('yes', null, null, true);
2094 $this->assertInstanceOf('lang_string', $yes);
2095 $this->assertSame($yesexpected, (string)$yes);
2097 // Test using a lang_string object as the $a argument for a normal
2098 // get_string call (returning string).
2099 $test = new lang_string('yes', null, null, true);
2100 $testexpected = get_string('numdays', 'core', get_string('yes'));
2101 $testresult = get_string('numdays', null, $test);
2102 $this->assertInternalType('string', $testresult);
2103 $this->assertSame($testexpected, $testresult);
2105 // Test using a lang_string object as the $a argument for an object
2106 // get_string call (returning lang_string).
2107 $test = new lang_string('yes', null, null, true);
2108 $testexpected = get_string('numdays', 'core', get_string('yes'));
2109 $testresult = get_string('numdays', null, $test, true);
2110 $this->assertInstanceOf('lang_string', $testresult);
2111 $this->assertSame($testexpected, "$testresult");
2113 // Make sure that object properties that can't be converted don't cause
2114 // errors.
2115 // Level one: This is as deep as current language processing goes.
2116 $test = new stdClass;
2117 $test->one = 'here';
2118 $string = get_string('yes', null, $test, true);
2119 $this->assertEquals($yesexpected, $string);
2121 // Make sure that object properties that can't be converted don't cause
2122 // errors.
2123 // Level two: Language processing doesn't currently reach this deep.
2124 // only immediate scalar properties are worked with.
2125 $test = new stdClass;
2126 $test->one = new stdClass;
2127 $test->one->two = 'here';
2128 $string = get_string('yes', null, $test, true);
2129 $this->assertEquals($yesexpected, $string);
2131 // Make sure that object properties that can't be converted don't cause
2132 // errors.
2133 // Level three: It should never ever go this deep, but we're making sure
2134 // it doesn't cause any probs anyway.
2135 $test = new stdClass;
2136 $test->one = new stdClass;
2137 $test->one->two = new stdClass;
2138 $test->one->two->three = 'here';
2139 $string = get_string('yes', null, $test, true);
2140 $this->assertEquals($yesexpected, $string);
2142 // Make sure that object properties that can't be converted don't cause
2143 // errors and check lang_string properties.
2144 // Level one: This is as deep as current language processing goes.
2145 $test = new stdClass;
2146 $test->one = new lang_string('yes');
2147 $string = get_string('yes', null, $test, true);
2148 $this->assertEquals($yesexpected, $string);
2150 // Make sure that object properties that can't be converted don't cause
2151 // errors and check lang_string properties.
2152 // Level two: Language processing doesn't currently reach this deep.
2153 // only immediate scalar properties are worked with.
2154 $test = new stdClass;
2155 $test->one = new stdClass;
2156 $test->one->two = new lang_string('yes');
2157 $string = get_string('yes', null, $test, true);
2158 $this->assertEquals($yesexpected, $string);
2160 // Make sure that object properties that can't be converted don't cause
2161 // errors and check lang_string properties.
2162 // Level three: It should never ever go this deep, but we're making sure
2163 // it doesn't cause any probs anyway.
2164 $test = new stdClass;
2165 $test->one = new stdClass;
2166 $test->one->two = new stdClass;
2167 $test->one->two->three = new lang_string('yes');
2168 $string = get_string('yes', null, $test, true);
2169 $this->assertEquals($yesexpected, $string);
2171 // Make sure that array properties that can't be converted don't cause
2172 // errors.
2173 $test = array();
2174 $test['one'] = new stdClass;
2175 $test['one']->two = 'here';
2176 $string = get_string('yes', null, $test, true);
2177 $this->assertEquals($yesexpected, $string);
2179 // Same thing but as above except using an object... this is allowed :P.
2180 $string = get_string('yes', null, null, true);
2181 $object = new stdClass;
2182 $object->$string = 'Yes';
2183 $this->assertEquals($yesexpected, $string);
2184 $this->assertEquals($yesexpected, $object->$string);
2186 // Reset the language.
2187 $COURSE->lang = $originallang;
2191 * @expectedException PHPUnit\Framework\Error\Warning
2193 public function test_get_string_limitation() {
2194 // This is one of the limitations to the lang_string class. It can't be
2195 // used as a key.
2196 $array = array(get_string('yes', null, null, true) => 'yes');
2200 * Test localised float formatting.
2202 public function test_format_float() {
2204 // Special case for null.
2205 $this->assertEquals('', format_float(null));
2207 // Default 1 decimal place.
2208 $this->assertEquals('5.4', format_float(5.43));
2209 $this->assertEquals('5.0', format_float(5.001));
2211 // Custom number of decimal places.
2212 $this->assertEquals('5.43000', format_float(5.43, 5));
2214 // Option to strip ending zeros after rounding.
2215 $this->assertEquals('5.43', format_float(5.43, 5, true, true));
2216 $this->assertEquals('5', format_float(5.0001, 3, true, true));
2218 // Tests with a localised decimal separator.
2219 $this->define_local_decimal_separator();
2221 // Localisation on (default).
2222 $this->assertEquals('5X43000', format_float(5.43, 5));
2223 $this->assertEquals('5X43', format_float(5.43, 5, true, true));
2225 // Localisation off.
2226 $this->assertEquals('5.43000', format_float(5.43, 5, false));
2227 $this->assertEquals('5.43', format_float(5.43, 5, false, true));
2231 * Test localised float unformatting.
2233 public function test_unformat_float() {
2235 // Tests without the localised decimal separator.
2237 // Special case for null, empty or white spaces only strings.
2238 $this->assertEquals(null, unformat_float(null));
2239 $this->assertEquals(null, unformat_float(''));
2240 $this->assertEquals(null, unformat_float(' '));
2242 // Regular use.
2243 $this->assertEquals(5.4, unformat_float('5.4'));
2244 $this->assertEquals(5.4, unformat_float('5.4', true));
2246 // No decimal.
2247 $this->assertEquals(5.0, unformat_float('5'));
2249 // Custom number of decimal.
2250 $this->assertEquals(5.43267, unformat_float('5.43267'));
2252 // Empty decimal.
2253 $this->assertEquals(100.0, unformat_float('100.00'));
2255 // With the thousand separator.
2256 $this->assertEquals(1000.0, unformat_float('1 000'));
2257 $this->assertEquals(1000.32, unformat_float('1 000.32'));
2259 // Negative number.
2260 $this->assertEquals(-100.0, unformat_float('-100'));
2262 // Wrong value.
2263 $this->assertEquals(0.0, unformat_float('Wrong value'));
2264 // Wrong value in strict mode.
2265 $this->assertFalse(unformat_float('Wrong value', true));
2267 // Combining options.
2268 $this->assertEquals(-1023.862567, unformat_float(' -1 023.862567 '));
2270 // Bad decimal separator (should crop the decimal).
2271 $this->assertEquals(50.0, unformat_float('50,57'));
2272 // Bad decimal separator in strict mode (should return false).
2273 $this->assertFalse(unformat_float('50,57', true));
2275 // Tests with a localised decimal separator.
2276 $this->define_local_decimal_separator();
2278 // We repeat the tests above but with the current decimal separator.
2280 // Regular use without and with the localised separator.
2281 $this->assertEquals (5.4, unformat_float('5.4'));
2282 $this->assertEquals (5.4, unformat_float('5X4'));
2284 // Custom number of decimal.
2285 $this->assertEquals (5.43267, unformat_float('5X43267'));
2287 // Empty decimal.
2288 $this->assertEquals (100.0, unformat_float('100X00'));
2290 // With the thousand separator.
2291 $this->assertEquals (1000.32, unformat_float('1 000X32'));
2293 // Bad different separator (should crop the decimal).
2294 $this->assertEquals (50.0, unformat_float('50Y57'));
2295 // Bad different separator in strict mode (should return false).
2296 $this->assertFalse (unformat_float('50Y57', true));
2298 // Combining options.
2299 $this->assertEquals (-1023.862567, unformat_float(' -1 023X862567 '));
2300 // Combining options in strict mode.
2301 $this->assertEquals (-1023.862567, unformat_float(' -1 023X862567 ', true));
2305 * Test deleting of users.
2307 public function test_delete_user() {
2308 global $DB, $CFG;
2310 $this->resetAfterTest();
2312 $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
2313 $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
2314 $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
2316 $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
2317 $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
2318 $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
2319 $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
2320 $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => ''));
2321 $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => ''));
2323 // Delete user and capture event.
2324 $sink = $this->redirectEvents();
2325 $result = delete_user($user);
2326 $events = $sink->get_events();
2327 $sink->close();
2328 $event = array_pop($events);
2330 // Test user is deleted in DB.
2331 $this->assertTrue($result);
2332 $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
2333 $this->assertEquals(1, $deluser->deleted);
2334 $this->assertEquals(0, $deluser->picture);
2335 $this->assertSame('', $deluser->idnumber);
2336 $this->assertSame(md5($user->username), $deluser->email);
2337 $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
2339 $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
2341 // Test Event.
2342 $this->assertInstanceOf('\core\event\user_deleted', $event);
2343 $this->assertSame($user->id, $event->objectid);
2344 $this->assertSame('user_deleted', $event->get_legacy_eventname());
2345 $this->assertEventLegacyData($user, $event);
2346 $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
2347 $this->assertEventLegacyLogData($expectedlogdata, $event);
2348 $eventdata = $event->get_data();
2349 $this->assertSame($eventdata['other']['username'], $user->username);
2350 $this->assertSame($eventdata['other']['email'], $user->email);
2351 $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
2352 $this->assertSame($eventdata['other']['picture'], $user->picture);
2353 $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
2354 $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
2355 $this->assertEventContextNotUsed($event);
2357 // Try invalid params.
2358 $record = new stdClass();
2359 $record->grrr = 1;
2360 try {
2361 delete_user($record);
2362 $this->fail('Expecting exception for invalid delete_user() $user parameter');
2363 } catch (moodle_exception $ex) {
2364 $this->assertInstanceOf('coding_exception', $ex);
2366 $record->id = 1;
2367 try {
2368 delete_user($record);
2369 $this->fail('Expecting exception for invalid delete_user() $user parameter');
2370 } catch (moodle_exception $ex) {
2371 $this->assertInstanceOf('coding_exception', $ex);
2374 $record = new stdClass();
2375 $record->id = 666;
2376 $record->username = 'xx';
2377 $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
2378 $result = delete_user($record);
2379 $this->assertFalse($result);
2381 $result = delete_user($guest);
2382 $this->assertFalse($result);
2384 $result = delete_user($admin);
2385 $this->assertFalse($result);
2387 // Simultaneously deleting users with identical email addresses.
2388 $result1 = delete_user($usersharedemail1);
2389 $result2 = delete_user($usersharedemail2);
2391 $usersharedemail1after = $DB->get_record('user', array('id' => $usersharedemail1->id));
2392 $usersharedemail2after = $DB->get_record('user', array('id' => $usersharedemail2->id));
2393 $this->assertTrue($result1);
2394 $this->assertTrue($result2);
2395 $this->assertStringStartsWith($usersharedemail1->email . '.', $usersharedemail1after->username);
2396 $this->assertStringStartsWith($usersharedemail2->email . '.', $usersharedemail2after->username);
2398 // Simultaneously deleting users without email addresses.
2399 $result1 = delete_user($useremptyemail1);
2400 $result2 = delete_user($useremptyemail2);
2402 $useremptyemail1after = $DB->get_record('user', array('id' => $useremptyemail1->id));
2403 $useremptyemail2after = $DB->get_record('user', array('id' => $useremptyemail2->id));
2404 $this->assertTrue($result1);
2405 $this->assertTrue($result2);
2406 $this->assertStringStartsWith($useremptyemail1->username . '.' . $useremptyemail1->id . '@unknownemail.invalid.',
2407 $useremptyemail1after->username);
2408 $this->assertStringStartsWith($useremptyemail2->username . '.' . $useremptyemail2->id . '@unknownemail.invalid.',
2409 $useremptyemail2after->username);
2411 $this->resetDebugging();
2415 * Test function convert_to_array()
2417 public function test_convert_to_array() {
2418 // Check that normal classes are converted to arrays the same way as (array) would do.
2419 $obj = new stdClass();
2420 $obj->prop1 = 'hello';
2421 $obj->prop2 = array('first', 'second', 13);
2422 $obj->prop3 = 15;
2423 $this->assertEquals(convert_to_array($obj), (array)$obj);
2425 // Check that context object (with iterator) is converted to array properly.
2426 $obj = context_system::instance();
2427 $ar = array(
2428 'id' => $obj->id,
2429 'contextlevel' => $obj->contextlevel,
2430 'instanceid' => $obj->instanceid,
2431 'path' => $obj->path,
2432 'depth' => $obj->depth
2434 $this->assertEquals(convert_to_array($obj), $ar);
2438 * Test the function date_format_string().
2440 public function test_date_format_string() {
2441 global $CFG;
2443 $this->resetAfterTest();
2444 $this->setTimezone(99, 'Australia/Perth');
2446 $tests = array(
2447 array(
2448 'tz' => 99,
2449 'str' => '%A, %d %B %Y, %I:%M %p',
2450 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
2452 array(
2453 'tz' => 0,
2454 'str' => '%A, %d %B %Y, %I:%M %p',
2455 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2457 array(
2458 // Note: this function expected the timestamp in weird format before,
2459 // since 2.9 it uses UTC.
2460 'tz' => 'Pacific/Auckland',
2461 'str' => '%A, %d %B %Y, %I:%M %p',
2462 'expected' => 'Saturday, 01 January 2011, 11:00 PM'
2464 // Following tests pass on Windows only because en lang pack does
2465 // not contain localewincharset, in real life lang pack maintainers
2466 // may use only characters that are present in localewincharset
2467 // in format strings!
2468 array(
2469 'tz' => 99,
2470 'str' => 'Žluťoučký koníček %A',
2471 'expected' => 'Žluťoučký koníček Saturday'
2473 array(
2474 'tz' => 99,
2475 'str' => '言語設定言語 %A',
2476 'expected' => '言語設定言語 Saturday'
2478 array(
2479 'tz' => 99,
2480 'str' => '简体中文简体 %A',
2481 'expected' => '简体中文简体 Saturday'
2485 // Note: date_format_string() uses the timezone only to differenciate
2486 // the server time from the UTC time. It does not modify the timestamp.
2487 // Hence similar results for timezones <= 13.
2488 // On different systems case of AM PM changes so compare case insensitive.
2489 foreach ($tests as $test) {
2490 $str = date_format_string(1293876000, $test['str'], $test['tz']);
2491 $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
2495 public function test_get_config() {
2496 global $CFG;
2498 $this->resetAfterTest();
2500 // Preparation.
2501 set_config('phpunit_test_get_config_1', 'test 1');
2502 set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2503 if (!is_array($CFG->config_php_settings)) {
2504 $CFG->config_php_settings = array();
2506 $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
2508 if (!is_array($CFG->forced_plugin_settings)) {
2509 $CFG->forced_plugin_settings = array();
2511 if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
2512 $CFG->forced_plugin_settings['mod_forum'] = array();
2514 $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2515 $CFG->phpunit_test_get_config_5 = 'test 5';
2517 // Testing.
2518 $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
2519 $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2520 $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
2521 $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2522 $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2523 $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2524 $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2526 // Test config we know to exist.
2527 $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
2528 $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2529 $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2530 $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2532 // Test setting a config var that already exists.
2533 set_config('phpunit_test_get_config_1', 'test a');
2534 $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
2535 $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
2537 // Test cache invalidation.
2538 $cache = cache::make('core', 'config');
2539 $this->assertInternalType('array', $cache->get('core'));
2540 $this->assertInternalType('array', $cache->get('mod_forum'));
2541 set_config('phpunit_test_get_config_1', 'test b');
2542 $this->assertFalse($cache->get('core'));
2543 set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2544 $this->assertFalse($cache->get('mod_forum'));
2547 public function test_get_max_upload_sizes() {
2548 // Test with very low limits so we are not affected by php upload limits.
2549 // Test activity limit smallest.
2550 $sitebytes = 102400;
2551 $coursebytes = 51200;
2552 $modulebytes = 10240;
2553 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2555 $this->assertSame('Activity upload limit (10KB)', $result['0']);
2556 $this->assertCount(2, $result);
2558 // Test course limit smallest.
2559 $sitebytes = 102400;
2560 $coursebytes = 10240;
2561 $modulebytes = 51200;
2562 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2564 $this->assertSame('Course upload limit (10KB)', $result['0']);
2565 $this->assertCount(2, $result);
2567 // Test site limit smallest.
2568 $sitebytes = 10240;
2569 $coursebytes = 102400;
2570 $modulebytes = 51200;
2571 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2573 $this->assertSame('Site upload limit (10KB)', $result['0']);
2574 $this->assertCount(2, $result);
2576 // Test site limit not set.
2577 $sitebytes = 0;
2578 $coursebytes = 102400;
2579 $modulebytes = 51200;
2580 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2582 $this->assertSame('Activity upload limit (50KB)', $result['0']);
2583 $this->assertCount(3, $result);
2585 $sitebytes = 0;
2586 $coursebytes = 51200;
2587 $modulebytes = 102400;
2588 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2590 $this->assertSame('Course upload limit (50KB)', $result['0']);
2591 $this->assertCount(3, $result);
2593 // Test custom bytes in range.
2594 $sitebytes = 102400;
2595 $coursebytes = 51200;
2596 $modulebytes = 51200;
2597 $custombytes = 10240;
2598 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2600 $this->assertCount(3, $result);
2602 // Test custom bytes in range but non-standard.
2603 $sitebytes = 102400;
2604 $coursebytes = 51200;
2605 $modulebytes = 51200;
2606 $custombytes = 25600;
2607 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2609 $this->assertCount(4, $result);
2611 // Test custom bytes out of range.
2612 $sitebytes = 102400;
2613 $coursebytes = 51200;
2614 $modulebytes = 51200;
2615 $custombytes = 102400;
2616 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2618 $this->assertCount(3, $result);
2620 // Test custom bytes out of range and non-standard.
2621 $sitebytes = 102400;
2622 $coursebytes = 51200;
2623 $modulebytes = 51200;
2624 $custombytes = 256000;
2625 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2627 $this->assertCount(3, $result);
2629 // Test site limit only.
2630 $sitebytes = 51200;
2631 $result = get_max_upload_sizes($sitebytes);
2633 $this->assertSame('Site upload limit (50KB)', $result['0']);
2634 $this->assertSame('50KB', $result['51200']);
2635 $this->assertSame('10KB', $result['10240']);
2636 $this->assertCount(3, $result);
2638 // Test no limit.
2639 $result = get_max_upload_sizes();
2640 $this->assertArrayHasKey('0', $result);
2641 $this->assertArrayHasKey(get_max_upload_file_size(), $result);
2645 * Test function password_is_legacy_hash().
2647 public function test_password_is_legacy_hash() {
2648 // Well formed md5s should be matched.
2649 foreach (array('some', 'strings', 'to_check!') as $string) {
2650 $md5 = md5($string);
2651 $this->assertTrue(password_is_legacy_hash($md5));
2653 // Strings that are not md5s should not be matched.
2654 foreach (array('', AUTH_PASSWORD_NOT_CACHED, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
2655 $this->assertFalse(password_is_legacy_hash($notmd5));
2660 * Test function validate_internal_user_password().
2662 public function test_validate_internal_user_password() {
2663 // Test bcrypt hashes.
2664 $validhashes = array(
2665 'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2666 'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2667 'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2668 'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
2671 foreach ($validhashes as $password => $hash) {
2672 $user = new stdClass();
2673 $user->auth = 'manual';
2674 $user->password = $hash;
2675 // The correct password should be validated.
2676 $this->assertTrue(validate_internal_user_password($user, $password));
2677 // An incorrect password should not be validated.
2678 $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2683 * Test function hash_internal_user_password().
2685 public function test_hash_internal_user_password() {
2686 $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2688 // Check that some passwords that we convert to hashes can
2689 // be validated.
2690 foreach ($passwords as $password) {
2691 $hash = hash_internal_user_password($password);
2692 $fasthash = hash_internal_user_password($password, true);
2693 $user = new stdClass();
2694 $user->auth = 'manual';
2695 $user->password = $hash;
2696 $this->assertTrue(validate_internal_user_password($user, $password));
2698 // They should not be in md5 format.
2699 $this->assertFalse(password_is_legacy_hash($hash));
2701 // Check that cost factor in hash is correctly set.
2702 $this->assertRegExp('/\$10\$/', $hash);
2703 $this->assertRegExp('/\$04\$/', $fasthash);
2708 * Test function update_internal_user_password().
2710 public function test_update_internal_user_password() {
2711 global $DB;
2712 $this->resetAfterTest();
2713 $passwords = array('password', '1234', 'changeme', '****');
2714 foreach ($passwords as $password) {
2715 $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2716 update_internal_user_password($user, $password);
2717 // The user object should have been updated.
2718 $this->assertTrue(validate_internal_user_password($user, $password));
2719 // The database field for the user should also have been updated to the
2720 // same value.
2721 $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
2724 $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2725 // Manually set the user's password to the md5 of the string 'password'.
2726 $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
2728 $sink = $this->redirectEvents();
2729 // Update the password.
2730 update_internal_user_password($user, 'password');
2731 $events = $sink->get_events();
2732 $sink->close();
2733 $event = array_pop($events);
2735 // Password should have been updated to a bcrypt hash.
2736 $this->assertFalse(password_is_legacy_hash($user->password));
2738 // Verify event information.
2739 $this->assertInstanceOf('\core\event\user_password_updated', $event);
2740 $this->assertSame($user->id, $event->relateduserid);
2741 $this->assertEquals(context_user::instance($user->id), $event->get_context());
2742 $this->assertEventContextNotUsed($event);
2744 // Verify recovery of property 'auth'.
2745 unset($user->auth);
2746 update_internal_user_password($user, 'newpassword');
2747 $this->assertDebuggingCalled('User record in update_internal_user_password() must include field auth',
2748 DEBUG_DEVELOPER);
2749 $this->assertEquals('manual', $user->auth);
2753 * Testing that if the password is not cached, that it does not update
2754 * the user table and fire event.
2756 public function test_update_internal_user_password_no_cache() {
2757 $this->resetAfterTest();
2759 $user = $this->getDataGenerator()->create_user(array('auth' => 'cas'));
2760 $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2762 $sink = $this->redirectEvents();
2763 update_internal_user_password($user, 'wonkawonka');
2764 $this->assertEquals(0, $sink->count(), 'User updated event should not fire');
2768 * Test if the user has a password hash, but now their auth method
2769 * says not to cache it. Then it should update.
2771 public function test_update_internal_user_password_update_no_cache() {
2772 $this->resetAfterTest();
2774 $user = $this->getDataGenerator()->create_user(array('password' => 'test'));
2775 $this->assertNotEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2776 $user->auth = 'cas'; // Change to a auth that does not store passwords.
2778 $sink = $this->redirectEvents();
2779 update_internal_user_password($user, 'wonkawonka');
2780 $this->assertGreaterThanOrEqual(1, $sink->count(), 'User updated event should fire');
2782 $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2785 public function test_fullname() {
2786 global $CFG;
2788 $this->resetAfterTest();
2790 // Create a user to test the name display on.
2791 $record = array();
2792 $record['firstname'] = 'Scott';
2793 $record['lastname'] = 'Fletcher';
2794 $record['firstnamephonetic'] = 'スコット';
2795 $record['lastnamephonetic'] = 'フレチャー';
2796 $record['alternatename'] = 'No friends';
2797 $user = $this->getDataGenerator()->create_user($record);
2799 // Back up config settings for restore later.
2800 $originalcfg = new stdClass();
2801 $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
2802 $originalcfg->alternativefullnameformat = $CFG->alternativefullnameformat;
2804 // Testing existing fullnamedisplay settings.
2805 $CFG->fullnamedisplay = 'firstname';
2806 $testname = fullname($user);
2807 $this->assertSame($user->firstname, $testname);
2809 $CFG->fullnamedisplay = 'firstname lastname';
2810 $expectedname = "$user->firstname $user->lastname";
2811 $testname = fullname($user);
2812 $this->assertSame($expectedname, $testname);
2814 $CFG->fullnamedisplay = 'lastname firstname';
2815 $expectedname = "$user->lastname $user->firstname";
2816 $testname = fullname($user);
2817 $this->assertSame($expectedname, $testname);
2819 $expectedname = get_string('fullnamedisplay', null, $user);
2820 $CFG->fullnamedisplay = 'language';
2821 $testname = fullname($user);
2822 $this->assertSame($expectedname, $testname);
2824 // Test override parameter.
2825 $CFG->fullnamedisplay = 'firstname';
2826 $expectedname = "$user->firstname $user->lastname";
2827 $testname = fullname($user, true);
2828 $this->assertSame($expectedname, $testname);
2830 // Test alternativefullnameformat setting.
2831 // Test alternativefullnameformat that has been set to nothing.
2832 $CFG->alternativefullnameformat = '';
2833 $expectedname = "$user->firstname $user->lastname";
2834 $testname = fullname($user, true);
2835 $this->assertSame($expectedname, $testname);
2837 // Test alternativefullnameformat that has been set to 'language'.
2838 $CFG->alternativefullnameformat = 'language';
2839 $expectedname = "$user->firstname $user->lastname";
2840 $testname = fullname($user, true);
2841 $this->assertSame($expectedname, $testname);
2843 // Test customising the alternativefullnameformat setting with all additional name fields.
2844 $CFG->alternativefullnameformat = 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename';
2845 $expectedname = "$user->firstname $user->lastname $user->firstnamephonetic $user->lastnamephonetic $user->middlename $user->alternatename";
2846 $testname = fullname($user, true);
2847 $this->assertSame($expectedname, $testname);
2849 // Test additional name fields.
2850 $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
2851 $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
2852 $testname = fullname($user);
2853 $this->assertSame($expectedname, $testname);
2855 // Test for handling missing data.
2856 $user->middlename = null;
2857 // Parenthesis with no data.
2858 $CFG->fullnamedisplay = 'firstname (middlename) lastname';
2859 $expectedname = "$user->firstname $user->lastname";
2860 $testname = fullname($user);
2861 $this->assertSame($expectedname, $testname);
2863 // Extra spaces due to no data.
2864 $CFG->fullnamedisplay = 'firstname middlename lastname';
2865 $expectedname = "$user->firstname $user->lastname";
2866 $testname = fullname($user);
2867 $this->assertSame($expectedname, $testname);
2869 // Regular expression testing.
2870 // Remove some data from the user fields.
2871 $user->firstnamephonetic = '';
2872 $user->lastnamephonetic = '';
2874 // Removing empty brackets and excess whitespace.
2875 // All of these configurations should resolve to just firstname lastname.
2876 $configarray = array();
2877 $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
2878 $configarray[] = 'firstname lastname \'middlename\'';
2879 $configarray[] = 'firstname "firstnamephonetic" lastname';
2880 $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
2882 foreach ($configarray as $config) {
2883 $CFG->fullnamedisplay = $config;
2884 $expectedname = "$user->firstname $user->lastname";
2885 $testname = fullname($user);
2886 $this->assertSame($expectedname, $testname);
2889 // Check to make sure that other characters are left in place.
2890 $configarray = array();
2891 $configarray['0'] = new stdClass();
2892 $configarray['0']->config = 'lastname firstname, middlename';
2893 $configarray['0']->expectedname = "$user->lastname $user->firstname,";
2894 $configarray['1'] = new stdClass();
2895 $configarray['1']->config = 'lastname firstname + alternatename';
2896 $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
2897 $configarray['2'] = new stdClass();
2898 $configarray['2']->config = 'firstname aka: alternatename';
2899 $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
2900 $configarray['3'] = new stdClass();
2901 $configarray['3']->config = 'firstname (alternatename)';
2902 $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
2903 $configarray['4'] = new stdClass();
2904 $configarray['4']->config = 'firstname [alternatename]';
2905 $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
2906 $configarray['5'] = new stdClass();
2907 $configarray['5']->config = 'firstname "lastname"';
2908 $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
2910 foreach ($configarray as $config) {
2911 $CFG->fullnamedisplay = $config->config;
2912 $expectedname = $config->expectedname;
2913 $testname = fullname($user);
2914 $this->assertSame($expectedname, $testname);
2917 // Test debugging message displays when
2918 // fullnamedisplay setting is "normal".
2919 $CFG->fullnamedisplay = 'firstname lastname';
2920 unset($user);
2921 $user = new stdClass();
2922 $user->firstname = 'Stan';
2923 $user->lastname = 'Lee';
2924 $namedisplay = fullname($user);
2925 $this->assertDebuggingCalled();
2927 // Tidy up after we finish testing.
2928 $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
2929 $CFG->alternativefullnameformat = $originalcfg->alternativefullnameformat;
2932 public function test_get_all_user_name_fields() {
2933 $this->resetAfterTest();
2935 // Additional names in an array.
2936 $testarray = array('firstnamephonetic' => 'firstnamephonetic',
2937 'lastnamephonetic' => 'lastnamephonetic',
2938 'middlename' => 'middlename',
2939 'alternatename' => 'alternatename',
2940 'firstname' => 'firstname',
2941 'lastname' => 'lastname');
2942 $this->assertEquals($testarray, get_all_user_name_fields());
2944 // Additional names as a string.
2945 $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
2946 $this->assertEquals($teststring, get_all_user_name_fields(true));
2948 // Additional names as a string with an alias.
2949 $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
2950 $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
2952 // Additional name fields with a prefix - object.
2953 $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
2954 'lastnamephonetic' => 'authorlastnamephonetic',
2955 'middlename' => 'authormiddlename',
2956 'alternatename' => 'authoralternatename',
2957 'firstname' => 'authorfirstname',
2958 'lastname' => 'authorlastname');
2959 $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
2961 // Additional name fields with an alias and a title - string.
2962 $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';
2963 $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
2965 // Test the order parameter of the function.
2966 // Returning an array.
2967 $testarray = array('firstname' => 'firstname',
2968 'lastname' => 'lastname',
2969 'firstnamephonetic' => 'firstnamephonetic',
2970 'lastnamephonetic' => 'lastnamephonetic',
2971 'middlename' => 'middlename',
2972 'alternatename' => 'alternatename'
2974 $this->assertEquals($testarray, get_all_user_name_fields(false, null, null, null, true));
2976 // Returning a string.
2977 $teststring = 'firstname,lastname,firstnamephonetic,lastnamephonetic,middlename,alternatename';
2978 $this->assertEquals($teststring, get_all_user_name_fields(true, null, null, null, true));
2981 public function test_order_in_string() {
2982 $this->resetAfterTest();
2984 // Return an array in an order as they are encountered in a string.
2985 $valuearray = array('second', 'firsthalf', 'first');
2986 $formatstring = 'first firsthalf some other text (second)';
2987 $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
2988 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2990 // Try again with a different order for the format.
2991 $valuearray = array('second', 'firsthalf', 'first');
2992 $formatstring = 'firsthalf first second';
2993 $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
2994 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2996 // Try again with yet another different order for the format.
2997 $valuearray = array('second', 'firsthalf', 'first');
2998 $formatstring = 'start seconds away second firstquater first firsthalf';
2999 $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
3000 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
3003 public function test_complete_user_login() {
3004 global $USER, $DB;
3006 $this->resetAfterTest();
3007 $user = $this->getDataGenerator()->create_user();
3008 $this->setUser(0);
3010 $sink = $this->redirectEvents();
3011 $loginuser = clone($user);
3012 $this->setCurrentTimeStart();
3013 @complete_user_login($loginuser); // Hide session header errors.
3014 $this->assertSame($loginuser, $USER);
3015 $this->assertEquals($user->id, $USER->id);
3016 $events = $sink->get_events();
3017 $sink->close();
3019 $this->assertCount(1, $events);
3020 $event = reset($events);
3021 $this->assertInstanceOf('\core\event\user_loggedin', $event);
3022 $this->assertEquals('user', $event->objecttable);
3023 $this->assertEquals($user->id, $event->objectid);
3024 $this->assertEquals(context_system::instance()->id, $event->contextid);
3025 $this->assertEventContextNotUsed($event);
3027 $user = $DB->get_record('user', array('id'=>$user->id));
3029 $this->assertTimeCurrent($user->firstaccess);
3030 $this->assertTimeCurrent($user->lastaccess);
3032 $this->assertTimeCurrent($USER->firstaccess);
3033 $this->assertTimeCurrent($USER->lastaccess);
3034 $this->assertTimeCurrent($USER->currentlogin);
3035 $this->assertSame(sesskey(), $USER->sesskey);
3036 $this->assertTimeCurrent($USER->preference['_lastloaded']);
3037 $this->assertObjectNotHasAttribute('password', $USER);
3038 $this->assertObjectNotHasAttribute('description', $USER);
3042 * Test require_logout.
3044 public function test_require_logout() {
3045 $this->resetAfterTest();
3046 $user = $this->getDataGenerator()->create_user();
3047 $this->setUser($user);
3049 $this->assertTrue(isloggedin());
3051 // Logout user and capture event.
3052 $sink = $this->redirectEvents();
3053 require_logout();
3054 $events = $sink->get_events();
3055 $sink->close();
3056 $event = array_pop($events);
3058 // Check if user is logged out.
3059 $this->assertFalse(isloggedin());
3061 // Test Event.
3062 $this->assertInstanceOf('\core\event\user_loggedout', $event);
3063 $this->assertSame($user->id, $event->objectid);
3064 $this->assertSame('user_logout', $event->get_legacy_eventname());
3065 $this->assertEventLegacyData($user, $event);
3066 $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
3067 $event->objectid);
3068 $this->assertEventLegacyLogData($expectedlogdata, $event);
3069 $this->assertEventContextNotUsed($event);
3073 * A data provider for testing email messageid
3075 public function generate_email_messageid_provider() {
3076 return array(
3077 'nopath' => array(
3078 'wwwroot' => 'http://www.example.com',
3079 'ids' => array(
3080 'a-custom-id' => '<a-custom-id@www.example.com>',
3081 'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash@www.example.com>',
3084 'path' => array(
3085 'wwwroot' => 'http://www.example.com/path/subdir',
3086 'ids' => array(
3087 'a-custom-id' => '<a-custom-id/path/subdir@www.example.com>',
3088 'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash/path/subdir@www.example.com>',
3095 * Test email message id generation
3097 * @dataProvider generate_email_messageid_provider
3099 * @param string $wwwroot The wwwroot
3100 * @param array $msgids An array of msgid local parts and the final result
3102 public function test_generate_email_messageid($wwwroot, $msgids) {
3103 global $CFG;
3105 $this->resetAfterTest();
3106 $CFG->wwwroot = $wwwroot;
3108 foreach ($msgids as $local => $final) {
3109 $this->assertEquals($final, generate_email_messageid($local));
3114 * A data provider for testing email diversion
3116 public function diverted_emails_provider() {
3117 return array(
3118 'nodiverts' => array(
3119 'divertallemailsto' => null,
3120 'divertallemailsexcept' => null,
3121 array(
3122 'foo@example.com',
3123 'test@real.com',
3124 'fred.jones@example.com',
3125 'dev1@dev.com',
3126 'fred@example.com',
3127 'fred+verp@example.com',
3129 false,
3131 'alldiverts' => array(
3132 'divertallemailsto' => 'somewhere@elsewhere.com',
3133 'divertallemailsexcept' => null,
3134 array(
3135 'foo@example.com',
3136 'test@real.com',
3137 'fred.jones@example.com',
3138 'dev1@dev.com',
3139 'fred@example.com',
3140 'fred+verp@example.com',
3142 true,
3144 'alsodiverts' => array(
3145 'divertallemailsto' => 'somewhere@elsewhere.com',
3146 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
3147 array(
3148 'foo@example.com',
3149 'test@real.com',
3150 'fred.jones@example.com',
3152 true,
3154 'divertsexceptions' => array(
3155 'divertallemailsto' => 'somewhere@elsewhere.com',
3156 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
3157 array(
3158 'dev1@dev.com',
3159 'fred@example.com',
3160 'fred+verp@example.com',
3162 false,
3168 * Test email diversion
3170 * @dataProvider diverted_emails_provider
3172 * @param string $divertallemailsto An optional email address
3173 * @param string $divertallemailsexcept An optional exclusion list
3174 * @param array $addresses An array of test addresses
3175 * @param boolean $expected Expected result
3177 public function test_email_should_be_diverted($divertallemailsto, $divertallemailsexcept, $addresses, $expected) {
3178 global $CFG;
3180 $this->resetAfterTest();
3181 $CFG->divertallemailsto = $divertallemailsto;
3182 $CFG->divertallemailsexcept = $divertallemailsexcept;
3184 foreach ($addresses as $address) {
3185 $this->assertEquals($expected, email_should_be_diverted($address));
3189 public function test_email_to_user() {
3190 global $CFG;
3192 $this->resetAfterTest();
3194 $user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
3195 $user2 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
3196 $user3 = $this->getDataGenerator()->create_user(array('maildisplay' => 0));
3197 set_config('allowedemaildomains', "example.com\r\nmoodle.org");
3199 $subject = 'subject';
3200 $messagetext = 'message text';
3201 $subject2 = 'subject 2';
3202 $messagetext2 = 'message text 2';
3204 // Close the default email sink.
3205 $sink = $this->redirectEmails();
3206 $sink->close();
3208 $CFG->noemailever = true;
3209 $this->assertNotEmpty($CFG->noemailever);
3210 email_to_user($user1, $user2, $subject, $messagetext);
3211 $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
3213 unset_config('noemailever');
3215 email_to_user($user1, $user2, $subject, $messagetext);
3216 $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
3218 $sink = $this->redirectEmails();
3219 email_to_user($user1, $user2, $subject, $messagetext);
3220 email_to_user($user2, $user1, $subject2, $messagetext2);
3221 $this->assertSame(2, $sink->count());
3222 $result = $sink->get_messages();
3223 $this->assertCount(2, $result);
3224 $sink->close();
3226 $this->assertSame($subject, $result[0]->subject);
3227 $this->assertSame($messagetext, trim($result[0]->body));
3228 $this->assertSame($user1->email, $result[0]->to);
3229 $this->assertSame($user2->email, $result[0]->from);
3231 $this->assertSame($subject2, $result[1]->subject);
3232 $this->assertSame($messagetext2, trim($result[1]->body));
3233 $this->assertSame($user2->email, $result[1]->to);
3234 $this->assertSame($user1->email, $result[1]->from);
3236 email_to_user($user1, $user2, $subject, $messagetext);
3237 $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
3239 // Test that an empty noreplyaddress will default to a no-reply address.
3240 $sink = $this->redirectEmails();
3241 email_to_user($user1, $user3, $subject, $messagetext);
3242 $result = $sink->get_messages();
3243 $this->assertEquals($CFG->noreplyaddress, $result[0]->from);
3244 $sink->close();
3245 set_config('noreplyaddress', '');
3246 $sink = $this->redirectEmails();
3247 email_to_user($user1, $user3, $subject, $messagetext);
3248 $result = $sink->get_messages();
3249 $this->assertEquals('noreply@www.example.com', $result[0]->from);
3250 $sink->close();
3252 // Test $CFG->allowedemaildomains.
3253 set_config('noreplyaddress', 'noreply@www.example.com');
3254 $this->assertNotEmpty($CFG->allowedemaildomains);
3255 $sink = $this->redirectEmails();
3256 email_to_user($user1, $user2, $subject, $messagetext);
3257 unset_config('allowedemaildomains');
3258 email_to_user($user1, $user2, $subject, $messagetext);
3259 $result = $sink->get_messages();
3260 $this->assertNotEquals($CFG->noreplyaddress, $result[0]->from);
3261 $this->assertEquals($CFG->noreplyaddress, $result[1]->from);
3262 $sink->close();
3264 // Try to send an unsafe attachment, we should see an error message in the eventual mail body.
3265 $attachment = '../test.txt';
3266 $attachname = 'txt';
3268 $sink = $this->redirectEmails();
3269 email_to_user($user1, $user2, $subject, $messagetext, '', $attachment, $attachname);
3270 $this->assertSame(1, $sink->count());
3271 $result = $sink->get_messages();
3272 $this->assertCount(1, $result);
3273 $this->assertContains('error.txt', $result[0]->body);
3274 $this->assertContains('Error in attachment. User attempted to attach a filename with a unsafe name.', $result[0]->body);
3275 $sink->close();
3279 * Test setnew_password_and_mail.
3281 public function test_setnew_password_and_mail() {
3282 global $DB, $CFG;
3284 $this->resetAfterTest();
3286 $user = $this->getDataGenerator()->create_user();
3288 // Update user password.
3289 $sink = $this->redirectEvents();
3290 $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
3291 setnew_password_and_mail($user);
3292 $events = $sink->get_events();
3293 $sink->close();
3294 $sink2->close();
3295 $event = array_pop($events);
3297 // Test updated value.
3298 $dbuser = $DB->get_record('user', array('id' => $user->id));
3299 $this->assertSame($user->firstname, $dbuser->firstname);
3300 $this->assertNotEmpty($dbuser->password);
3302 // Test event.
3303 $this->assertInstanceOf('\core\event\user_password_updated', $event);
3304 $this->assertSame($user->id, $event->relateduserid);
3305 $this->assertEquals(context_user::instance($user->id), $event->get_context());
3306 $this->assertEventContextNotUsed($event);
3310 * Data provider for test_generate_confirmation_link
3311 * @return Array of confirmation urls and expected resultant confirmation links
3313 public function generate_confirmation_link_provider() {
3314 global $CFG;
3315 return [
3316 "Simple name" => [
3317 "username" => "simplename",
3318 "confirmationurl" => null,
3319 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/simplename"
3321 "Period in between words in username" => [
3322 "username" => "period.inbetween",
3323 "confirmationurl" => null,
3324 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/period%2Einbetween"
3326 "Trailing periods in username" => [
3327 "username" => "trailingperiods...",
3328 "confirmationurl" => null,
3329 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/trailingperiods%2E%2E%2E"
3331 "At symbol in username" => [
3332 "username" => "at@symbol",
3333 "confirmationurl" => null,
3334 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/at%40symbol"
3336 "Dash symbol in username" => [
3337 "username" => "has-dash",
3338 "confirmationurl" => null,
3339 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/has-dash"
3341 "Underscore in username" => [
3342 "username" => "under_score",
3343 "confirmationurl" => null,
3344 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/under_score"
3346 "Many different characters in username" => [
3347 "username" => "many_-.@characters@_@-..-..",
3348 "confirmationurl" => null,
3349 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3351 "Custom relative confirmation url" => [
3352 "username" => "many_-.@characters@_@-..-..",
3353 "confirmationurl" => "/custom/local/url.php",
3354 "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3356 "Custom relative confirmation url with parameters" => [
3357 "username" => "many_-.@characters@_@-..-..",
3358 "confirmationurl" => "/custom/local/url.php?with=param",
3359 "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3361 "Custom local confirmation url" => [
3362 "username" => "many_-.@characters@_@-..-..",
3363 "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php",
3364 "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3366 "Custom local confirmation url with parameters" => [
3367 "username" => "many_-.@characters@_@-..-..",
3368 "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php?with=param",
3369 "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3371 "Custom external confirmation url" => [
3372 "username" => "many_-.@characters@_@-..-..",
3373 "confirmationurl" => "http://moodle.org/custom/external/url.php",
3374 "expected" => "http://moodle.org/custom/external/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3376 "Custom external confirmation url with parameters" => [
3377 "username" => "many_-.@characters@_@-..-..",
3378 "confirmationurl" => "http://moodle.org/ext.php?with=some&param=eters",
3379 "expected" => "http://moodle.org/ext.php?with=some&param=eters&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3381 "Custom external confirmation url with parameters" => [
3382 "username" => "many_-.@characters@_@-..-..",
3383 "confirmationurl" => "http://moodle.org/ext.php?with=some&data=test",
3384 "expected" => "http://moodle.org/ext.php?with=some&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3390 * Test generate_confirmation_link
3391 * @dataProvider generate_confirmation_link_provider
3392 * @param string $username The name of the user
3393 * @param string $confirmationurl The url the user should go to to confirm
3394 * @param string $expected The expected url of the confirmation link
3396 public function test_generate_confirmation_link($username, $confirmationurl, $expected) {
3397 $this->resetAfterTest();
3398 $sink = $this->redirectEmails();
3400 $user = $this->getDataGenerator()->create_user(
3402 "username" => $username,
3403 "confirmed" => false,
3404 "email" => 'test@example.com',
3408 send_confirmation_email($user, $confirmationurl);
3409 $sink->close();
3410 $messages = $sink->get_messages();
3411 $message = array_shift($messages);
3412 $messagebody = quoted_printable_decode($message->body);
3414 $this->assertContains($expected, $messagebody);
3418 * Test generate_confirmation_link with custom admin link
3420 public function test_generate_confirmation_link_with_custom_admin() {
3421 global $CFG;
3423 $this->resetAfterTest();
3424 $sink = $this->redirectEmails();
3426 $admin = $CFG->admin;
3427 $CFG->admin = 'custom/admin/path';
3429 $user = $this->getDataGenerator()->create_user(
3431 "username" => "many_-.@characters@_@-..-..",
3432 "confirmed" => false,
3433 "email" => 'test@example.com',
3436 $confirmationurl = "/admin/test.php?with=params";
3437 $expected = $CFG->wwwroot . "/" . $CFG->admin . "/test.php?with=params&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E";
3439 send_confirmation_email($user, $confirmationurl);
3440 $sink->close();
3441 $messages = $sink->get_messages();
3442 $message = array_shift($messages);
3443 $messagebody = quoted_printable_decode($message->body);
3445 $sink->close();
3446 $this->assertContains($expected, $messagebody);
3448 $CFG->admin = $admin;
3453 * Test remove_course_content deletes course contents
3454 * TODO Add asserts to verify other data related to course is deleted as well.
3456 public function test_remove_course_contents() {
3458 $this->resetAfterTest();
3460 $course = $this->getDataGenerator()->create_course();
3461 $user = $this->getDataGenerator()->create_user();
3462 $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
3463 $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id));
3465 $this->assertNotEquals(false, note_load($note->id));
3466 remove_course_contents($course->id, false);
3467 $this->assertFalse(note_load($note->id));
3471 * Test function username_load_fields_from_object().
3473 public function test_username_load_fields_from_object() {
3474 $this->resetAfterTest();
3476 // This object represents the information returned from an sql query.
3477 $userinfo = new stdClass();
3478 $userinfo->userid = 1;
3479 $userinfo->username = 'loosebruce';
3480 $userinfo->firstname = 'Bruce';
3481 $userinfo->lastname = 'Campbell';
3482 $userinfo->firstnamephonetic = 'ブルース';
3483 $userinfo->lastnamephonetic = 'カンベッル';
3484 $userinfo->middlename = '';
3485 $userinfo->alternatename = '';
3486 $userinfo->email = '';
3487 $userinfo->picture = 23;
3488 $userinfo->imagealt = 'Michael Jordan draining another basket.';
3489 $userinfo->idnumber = 3982;
3491 // Just user name fields.
3492 $user = new stdClass();
3493 $user = username_load_fields_from_object($user, $userinfo);
3494 $expectedarray = new stdClass();
3495 $expectedarray->firstname = 'Bruce';
3496 $expectedarray->lastname = 'Campbell';
3497 $expectedarray->firstnamephonetic = 'ブルース';
3498 $expectedarray->lastnamephonetic = 'カンベッル';
3499 $expectedarray->middlename = '';
3500 $expectedarray->alternatename = '';
3501 $this->assertEquals($user, $expectedarray);
3503 // User information for showing a picture.
3504 $user = new stdClass();
3505 $additionalfields = explode(',', user_picture::fields());
3506 $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
3507 $user->id = $userinfo->userid;
3508 $expectedarray = new stdClass();
3509 $expectedarray->id = 1;
3510 $expectedarray->firstname = 'Bruce';
3511 $expectedarray->lastname = 'Campbell';
3512 $expectedarray->firstnamephonetic = 'ブルース';
3513 $expectedarray->lastnamephonetic = 'カンベッル';
3514 $expectedarray->middlename = '';
3515 $expectedarray->alternatename = '';
3516 $expectedarray->email = '';
3517 $expectedarray->picture = 23;
3518 $expectedarray->imagealt = 'Michael Jordan draining another basket.';
3519 $this->assertEquals($user, $expectedarray);
3521 // Alter the userinfo object to have a prefix.
3522 $userinfo->authorfirstname = 'Bruce';
3523 $userinfo->authorlastname = 'Campbell';
3524 $userinfo->authorfirstnamephonetic = 'ブルース';
3525 $userinfo->authorlastnamephonetic = 'カンベッル';
3526 $userinfo->authormiddlename = '';
3527 $userinfo->authorpicture = 23;
3528 $userinfo->authorimagealt = 'Michael Jordan draining another basket.';
3529 $userinfo->authoremail = 'test@example.com';
3532 // Return an object with user picture information.
3533 $user = new stdClass();
3534 $additionalfields = explode(',', user_picture::fields());
3535 $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
3536 $user->id = $userinfo->userid;
3537 $expectedarray = new stdClass();
3538 $expectedarray->id = 1;
3539 $expectedarray->firstname = 'Bruce';
3540 $expectedarray->lastname = 'Campbell';
3541 $expectedarray->firstnamephonetic = 'ブルース';
3542 $expectedarray->lastnamephonetic = 'カンベッル';
3543 $expectedarray->middlename = '';
3544 $expectedarray->alternatename = '';
3545 $expectedarray->email = 'test@example.com';
3546 $expectedarray->picture = 23;
3547 $expectedarray->imagealt = 'Michael Jordan draining another basket.';
3548 $this->assertEquals($user, $expectedarray);
3552 * Test function count_words().
3554 public function test_count_words() {
3555 $count = count_words("one two three'four");
3556 $this->assertEquals(3, $count);
3558 $count = count_words('one+two three’four');
3559 $this->assertEquals(3, $count);
3561 $count = count_words('one"two three-four');
3562 $this->assertEquals(2, $count);
3564 $count = count_words('one@two three_four');
3565 $this->assertEquals(4, $count);
3567 $count = count_words('one\two three/four');
3568 $this->assertEquals(4, $count);
3570 $count = count_words(' one ... two &nbsp; three...four ');
3571 $this->assertEquals(4, $count);
3573 $count = count_words('one.2 3,four');
3574 $this->assertEquals(4, $count);
3576 $count = count_words('1³ £2 €3.45 $6,789');
3577 $this->assertEquals(4, $count);
3579 $count = count_words('one—two ブルース カンベッル');
3580 $this->assertEquals(4, $count);
3582 $count = count_words('one…two ブルース … カンベッル');
3583 $this->assertEquals(4, $count);
3586 * Tests the getremoteaddr() function.
3588 public function test_getremoteaddr() {
3589 $xforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null;
3591 $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
3592 $noip = getremoteaddr('1.1.1.1');
3593 $this->assertEquals('1.1.1.1', $noip);
3595 $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
3596 $noip = getremoteaddr();
3597 $this->assertEquals('0.0.0.0', $noip);
3599 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1';
3600 $singleip = getremoteaddr();
3601 $this->assertEquals('127.0.0.1', $singleip);
3603 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2';
3604 $twoip = getremoteaddr();
3605 $this->assertEquals('127.0.0.1', $twoip);
3607 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2, 127.0.0.3';
3608 $threeip = getremoteaddr();
3609 $this->assertEquals('127.0.0.1', $threeip);
3611 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1:65535,127.0.0.2';
3612 $portip = getremoteaddr();
3613 $this->assertEquals('127.0.0.1', $portip);
3615 $_SERVER['HTTP_X_FORWARDED_FOR'] = '0:0:0:0:0:0:0:1,127.0.0.2';
3616 $portip = getremoteaddr();
3617 $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3619 $_SERVER['HTTP_X_FORWARDED_FOR'] = '0::1,127.0.0.2';
3620 $portip = getremoteaddr();
3621 $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3623 $_SERVER['HTTP_X_FORWARDED_FOR'] = '[0:0:0:0:0:0:0:1]:65535,127.0.0.2';
3624 $portip = getremoteaddr();
3625 $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3627 $_SERVER['HTTP_X_FORWARDED_FOR'] = $xforwardedfor;
3632 * Test emulation of random_bytes() function.
3634 public function test_random_bytes_emulate() {
3635 $result = random_bytes_emulate(10);
3636 $this->assertSame(10, strlen($result));
3637 $this->assertnotSame($result, random_bytes_emulate(10));
3639 $result = random_bytes_emulate(21);
3640 $this->assertSame(21, strlen($result));
3641 $this->assertnotSame($result, random_bytes_emulate(21));
3643 $result = random_bytes_emulate(666);
3644 $this->assertSame(666, strlen($result));
3646 $result = random_bytes_emulate(40);
3647 $this->assertSame(40, strlen($result));
3649 $this->assertDebuggingNotCalled();
3651 $result = random_bytes_emulate(0);
3652 $this->assertSame('', $result);
3653 $this->assertDebuggingCalled();
3655 $result = random_bytes_emulate(-1);
3656 $this->assertSame('', $result);
3657 $this->assertDebuggingCalled();
3661 * Test function for creation of random strings.
3663 public function test_random_string() {
3664 $pool = 'a-zA-Z0-9';
3666 $result = random_string(10);
3667 $this->assertSame(10, strlen($result));
3668 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3669 $this->assertNotSame($result, random_string(10));
3671 $result = random_string(21);
3672 $this->assertSame(21, strlen($result));
3673 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3674 $this->assertNotSame($result, random_string(21));
3676 $result = random_string(666);
3677 $this->assertSame(666, strlen($result));
3678 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3680 $result = random_string();
3681 $this->assertSame(15, strlen($result));
3682 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3684 $this->assertDebuggingNotCalled();
3686 $result = random_string(0);
3687 $this->assertSame('', $result);
3688 $this->assertDebuggingCalled();
3690 $result = random_string(-1);
3691 $this->assertSame('', $result);
3692 $this->assertDebuggingCalled();
3696 * Test function for creation of complex random strings.
3698 public function test_complex_random_string() {
3699 $pool = preg_quote('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#%^&*()_+-=[];,./<>?:{} ', '/');
3701 $result = complex_random_string(10);
3702 $this->assertSame(10, strlen($result));
3703 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3704 $this->assertNotSame($result, complex_random_string(10));
3706 $result = complex_random_string(21);
3707 $this->assertSame(21, strlen($result));
3708 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3709 $this->assertNotSame($result, complex_random_string(21));
3711 $result = complex_random_string(666);
3712 $this->assertSame(666, strlen($result));
3713 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3715 $result = complex_random_string();
3716 $this->assertEquals(28, strlen($result), '', 4); // Expected length is 24 - 32.
3717 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3719 $this->assertDebuggingNotCalled();
3721 $result = complex_random_string(0);
3722 $this->assertSame('', $result);
3723 $this->assertDebuggingCalled();
3725 $result = complex_random_string(-1);
3726 $this->assertSame('', $result);
3727 $this->assertDebuggingCalled();
3731 * Data provider for private ips.
3733 public function data_private_ips() {
3734 return array(
3735 array('10.0.0.0'),
3736 array('172.16.0.0'),
3737 array('192.168.1.0'),
3738 array('fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c'),
3739 array('fdc6:c46b:bb8f:7d4c:fdc6:c46b:bb8f:7d4c'),
3740 array('fdc6:c46b:bb8f:7d4c:0000:8a2e:0370:7334'),
3741 array('127.0.0.1'), // This has been buggy in past: https://bugs.php.net/bug.php?id=53150.
3746 * Checks ip_is_public returns false for private ips.
3748 * @param string $ip the ipaddress to test
3749 * @dataProvider data_private_ips
3751 public function test_ip_is_public_private_ips($ip) {
3752 $this->assertFalse(ip_is_public($ip));
3756 * Data provider for public ips.
3758 public function data_public_ips() {
3759 return array(
3760 array('2400:cb00:2048:1::8d65:71b3'),
3761 array('2400:6180:0:d0::1b:2001'),
3762 array('141.101.113.179'),
3763 array('123.45.67.178'),
3768 * Checks ip_is_public returns true for public ips.
3770 * @param string $ip the ipaddress to test
3771 * @dataProvider data_public_ips
3773 public function test_ip_is_public_public_ips($ip) {
3774 $this->assertTrue(ip_is_public($ip));
3778 * Test the function can_send_from_real_email_address
3780 * @param string $email Email address for the from user.
3781 * @param int $display The user's email display preference.
3782 * @param bool $samecourse Are the users in the same course?
3783 * @param string $config The CFG->allowedemaildomains config values
3784 * @param bool $result The expected result.
3785 * @dataProvider data_can_send_from_real_email_address
3787 public function test_can_send_from_real_email_address($email, $display, $samecourse, $config, $result) {
3788 $this->resetAfterTest();
3790 $fromuser = $this->getDataGenerator()->create_user();
3791 $touser = $this->getDataGenerator()->create_user();
3792 $course = $this->getDataGenerator()->create_course();
3793 set_config('allowedemaildomains', $config);
3795 $fromuser->email = $email;
3796 $fromuser->maildisplay = $display;
3797 if ($samecourse) {
3798 $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student');
3799 $this->getDataGenerator()->enrol_user($touser->id, $course->id, 'student');
3800 } else {
3801 $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student');
3803 $this->assertEquals($result, can_send_from_real_email_address($fromuser, $touser));
3807 * Data provider for test_can_send_from_real_email_address.
3809 * @return array Returns an array of test data for the above function.
3811 public function data_can_send_from_real_email_address() {
3812 return [
3813 // Test from email is in allowed domain.
3814 // Test that from display is set to show no one.
3816 'email' => 'fromuser@example.com',
3817 'display' => core_user::MAILDISPLAY_HIDE,
3818 'samecourse' => false,
3819 'config' => "example.com\r\ntest.com",
3820 'result' => false
3822 // Test that from display is set to course members only (course member).
3824 'email' => 'fromuser@example.com',
3825 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
3826 'samecourse' => true,
3827 'config' => "example.com\r\ntest.com",
3828 'result' => true
3830 // Test that from display is set to course members only (Non course member).
3832 'email' => 'fromuser@example.com',
3833 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
3834 'samecourse' => false,
3835 'config' => "example.com\r\ntest.com",
3836 'result' => false
3838 // Test that from display is set to show everyone.
3840 'email' => 'fromuser@example.com',
3841 'display' => core_user::MAILDISPLAY_EVERYONE,
3842 'samecourse' => false,
3843 'config' => "example.com\r\ntest.com",
3844 'result' => true
3846 // Test a few different config value formats for parsing correctness.
3848 'email' => 'fromuser@example.com',
3849 'display' => core_user::MAILDISPLAY_EVERYONE,
3850 'samecourse' => false,
3851 'config' => "\n test.com\nexample.com \n",
3852 'result' => true
3855 'email' => 'fromuser@example.com',
3856 'display' => core_user::MAILDISPLAY_EVERYONE,
3857 'samecourse' => false,
3858 'config' => "\r\n example.com \r\n test.com \r\n",
3859 'result' => true
3862 // Test from email is not in allowed domain.
3863 // Test that from display is set to show no one.
3864 [ 'email' => 'fromuser@moodle.com',
3865 'display' => core_user::MAILDISPLAY_HIDE,
3866 'samecourse' => false,
3867 'config' => "example.com\r\ntest.com",
3868 'result' => false
3870 // Test that from display is set to course members only (course member).
3871 [ 'email' => 'fromuser@moodle.com',
3872 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
3873 'samecourse' => true,
3874 'config' => "example.com\r\ntest.com",
3875 'result' => false
3877 // Test that from display is set to course members only (Non course member.
3878 [ 'email' => 'fromuser@moodle.com',
3879 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
3880 'samecourse' => false,
3881 'config' => "example.com\r\ntest.com",
3882 'result' => false
3884 // Test that from display is set to show everyone.
3885 [ 'email' => 'fromuser@moodle.com',
3886 'display' => core_user::MAILDISPLAY_EVERYONE,
3887 'samecourse' => false,
3888 'config' => "example.com\r\ntest.com",
3889 'result' => false
3891 // Test a few erroneous config value and confirm failure.
3892 [ 'email' => 'fromuser@moodle.com',
3893 'display' => core_user::MAILDISPLAY_EVERYONE,
3894 'samecourse' => false,
3895 'config' => "\r\n \r\n",
3896 'result' => false
3898 [ 'email' => 'fromuser@moodle.com',
3899 'display' => core_user::MAILDISPLAY_EVERYONE,
3900 'samecourse' => false,
3901 'config' => " \n \n \n ",
3902 'result' => false
3908 * Test that generate_email_processing_address() returns valid email address.
3910 public function test_generate_email_processing_address() {
3911 global $CFG;
3912 $this->resetAfterTest();
3914 $data = (object)[
3915 'id' => 42,
3916 'email' => 'my.email+from_moodle@example.com',
3919 $modargs = 'B'.base64_encode(pack('V', $data->id)).substr(md5($data->email), 0, 16);
3921 $CFG->maildomain = 'example.com';
3922 $CFG->mailprefix = 'mdl+';
3923 $this->assertTrue(validate_email(generate_email_processing_address(0, $modargs)));
3925 $CFG->maildomain = 'mail.example.com';
3926 $CFG->mailprefix = 'mdl-';
3927 $this->assertTrue(validate_email(generate_email_processing_address(23, $modargs)));
3931 * Test safe method unserialize_array().
3933 public function test_unserialize_array() {
3934 $a = [1, 2, 3];
3935 $this->assertEquals($a, unserialize_array(serialize($a)));
3936 $this->assertEquals($a, unserialize_array(serialize($a)));
3937 $a = ['a' => 1, 2 => 2, 'b' => 'cde'];
3938 $this->assertEquals($a, unserialize_array(serialize($a)));
3939 $this->assertEquals($a, unserialize_array(serialize($a)));
3940 $a = ['a' => 1, 2 => 2, 'b' => 'c"d"e'];
3941 $this->assertEquals($a, unserialize_array(serialize($a)));
3942 $a = ['a' => 1, 2 => ['c' => 'd', 'e' => 'f'], 'b' => 'cde'];
3943 $this->assertEquals($a, unserialize_array(serialize($a)));
3945 // Can not unserialize if any string contains semicolons.
3946 $a = ['a' => 1, 2 => 2, 'b' => 'c"d";e'];
3947 $this->assertEquals(false, unserialize_array(serialize($a)));
3949 // Can not unserialize if there are any objects.
3950 $a = (object)['a' => 1, 2 => 2, 'b' => 'cde'];
3951 $this->assertEquals(false, unserialize_array(serialize($a)));
3952 $a = ['a' => 1, 2 => 2, 'b' => (object)['a' => 'cde']];
3953 $this->assertEquals(false, unserialize_array(serialize($a)));
3955 // Array used in the grader report.
3956 $a = array('aggregatesonly' => [51, 34], 'gradesonly' => [21, 45, 78]);
3957 $this->assertEquals($a, unserialize_array(serialize($a)));
3961 * Test that the component_class_callback returns the correct default value when the class was not found.
3963 * @dataProvider component_class_callback_default_provider
3964 * @param $default
3966 public function test_component_class_callback_not_found($default) {
3967 $this->assertSame($default, component_class_callback('thisIsNotTheClassYouWereLookingFor', 'anymethod', [], $default));
3971 * Test that the component_class_callback returns the correct default value when the class was not found.
3973 * @dataProvider component_class_callback_default_provider
3974 * @param $default
3976 public function test_component_class_callback_method_not_found($default) {
3977 require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
3979 $this->assertSame($default, component_class_callback(test_component_class_callback_example::class, 'this_is_not_the_method_you_were_looking_for', ['abc'], $default));
3983 * Test that the component_class_callback returns the default when the method returned null.
3985 * @dataProvider component_class_callback_default_provider
3986 * @param $default
3988 public function test_component_class_callback_found_returns_null($default) {
3989 require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
3991 $this->assertSame($default, component_class_callback(test_component_class_callback_example::class, 'method_returns_value', [null], $default));
3992 $this->assertSame($default, component_class_callback(test_component_class_callback_child_example::class, 'method_returns_value', [null], $default));
3996 * Test that the component_class_callback returns the expected value and not the default when there was a value.
3998 * @dataProvider component_class_callback_data_provider
3999 * @param $default
4001 public function test_component_class_callback_found_returns_value($value) {
4002 require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
4004 $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'));
4005 $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'));
4009 * Test that the component_class_callback handles multiple params correctly.
4011 * @dataProvider component_class_callback_multiple_params_provider
4012 * @param $default
4014 public function test_component_class_callback_found_accepts_multiple($params, $count) {
4015 require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
4017 $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'));
4018 $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'));
4022 * Data provider with list of default values for user in component_class_callback tests.
4024 * @return array
4026 public function component_class_callback_default_provider() {
4027 return [
4028 'null' => [null],
4029 'empty string' => [''],
4030 'string' => ['This is a string'],
4031 'int' => [12345],
4032 'stdClass' => [(object) ['this is my content']],
4033 'array' => [['a' => 'b',]],
4038 * Data provider with list of default values for user in component_class_callback tests.
4040 * @return array
4042 public function component_class_callback_data_provider() {
4043 return [
4044 'empty string' => [''],
4045 'string' => ['This is a string'],
4046 'int' => [12345],
4047 'stdClass' => [(object) ['this is my content']],
4048 'array' => [['a' => 'b',]],
4053 * Data provider with list of default values for user in component_class_callback tests.
4055 * @return array
4057 public function component_class_callback_multiple_params_provider() {
4058 return [
4059 'empty array' => [
4063 'string value' => [
4064 ['one'],
4067 'string values' => [
4068 ['one', 'two'],
4071 'arrays' => [
4072 [[], []],
4075 'nulls' => [
4076 [null, null, null, null],
4079 'mixed' => [
4080 ['a', 1, null, (object) [], []],
4087 * Test that {@link get_callable_name()} describes the callable as expected.
4089 * @dataProvider callable_names_provider
4090 * @param callable $callable
4091 * @param string $expectedname
4093 public function test_get_callable_name($callable, $expectedname) {
4094 $this->assertSame($expectedname, get_callable_name($callable));
4098 * Provides a set of callables and their human readable names.
4100 * @return array of (string)case => [(mixed)callable, (string|bool)expected description]
4102 public function callable_names_provider() {
4103 return [
4104 'integer' => [
4105 386,
4106 false,
4108 'boolean' => [
4109 true,
4110 false,
4112 'static_method_as_literal' => [
4113 'my_foobar_class::my_foobar_method',
4114 'my_foobar_class::my_foobar_method',
4116 'static_method_of_literal_class' => [
4117 ['my_foobar_class', 'my_foobar_method'],
4118 'my_foobar_class::my_foobar_method',
4120 'static_method_of_object' => [
4121 [$this, 'my_foobar_method'],
4122 'core_moodlelib_testcase::my_foobar_method',
4124 'method_of_object' => [
4125 [new lang_string('parentlanguage', 'core_langconfig'), 'my_foobar_method'],
4126 'lang_string::my_foobar_method',
4128 'function_as_literal' => [
4129 'my_foobar_callback',
4130 'my_foobar_callback',
4132 'function_as_closure' => [
4133 function($a) { return $a; },
4134 'Closure::__invoke',