87f59e822333deed71faa2b11275b7d2f0c21097
[moodle.git] / lib / tests / moodlelib_test.php
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.
13 //
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.
19  *
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
25  */
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.
35      *
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.
42      */
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);
51     }
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));
70     }
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', ''));
155     }
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.');
177     }
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);
199         }
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());
208         }
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());
217         }
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);
223         }
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();
229     }
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);
251         }
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());
260         }
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());
269         }
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);
275         }
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);
284         }
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();
295     }
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);
311         }
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());
323         }
324         try {
325             required_param('username', '');
326             $this->fail('coding_exception expected');
327         } catch (moodle_exception $ex) {
328             $this->assertInstanceOf('coding_exception', $ex);
329         }
330         try {
331             required_param('', PARAM_RAW);
332             $this->fail('coding_exception expected');
333         } catch (moodle_exception $ex) {
334             $this->assertInstanceOf('coding_exception', $ex);
335         }
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();
341     }
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);
360         }
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());
369         }
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);
375         }
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);
384         }
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);
393         }
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();
399     }
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);
408         }
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);
416         }
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);
424         }
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());
433         }
434     }
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);
447         }
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());
456         }
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);
463         }
465         // Test recursive.
466     }
468     public function test_clean_param_raw() {
469         $this->assertSame(
470             '#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)',
471             clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_RAW));
472     }
474     public function test_clean_param_trim() {
475         $this->assertSame('Frog toad', clean_param("   Frog toad   \r\n  ", PARAM_RAW_TRIMMED));
476     }
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));
482     }
484     public function test_clean_param_alpha() {
485         $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHA));
486     }
488     public function test_clean_param_alphanum() {
489         $this->assertSame('978942897DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHANUM));
490     }
492     public function test_clean_param_alphaext() {
493         $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHAEXT));
494     }
496     public function test_clean_param_sequence() {
497         $this->assertSame(',9789,42897', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_SEQUENCE));
498     }
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));
526     }
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_'));
542     }
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));
559     }
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));
575     }
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));
596     }
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));
621     }
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));
661     }
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));
692     }
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));
712     }
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 {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýá\9e?\9eý??\9adoe ', 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;
746     }
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));
762     }
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);
801         }
802     }
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);
810         }
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);
820         }
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);
830         }
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);
836         }
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);
859         }
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);
865         }
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);
871         }
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);
877         }
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);
883         }
884     }
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));
890     }
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));
896     }
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));
903     }
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));
911     }
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));
919     }
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));
928     }
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));
940     }
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));
946     }
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));
973     }
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));
995     }
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));
1008     }
1010     public function test_shorten_filename() {
1011         // Test filename that contains more than 100 characters.
1012         $filename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium totam rem';
1013         $this->assertSame('sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot',
1014             shorten_filename($filename));
1015         // Filename contains extension.
1016         $this->assertSame('sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot.zip',
1017             shorten_filename($filename . '.zip'));
1018         // Limit filename to 50 chars.
1019         $this->assertSame('sed ut perspiciatis unde omnis iste natus error si',
1020             shorten_filename($filename, 50));
1021         $this->assertSame('sed ut perspiciatis unde omnis iste natus error si.zip',
1022             shorten_filename($filename . '.zip', 50));
1024         // Test filename that contains less than 100 characters.
1025         $filename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque';
1026         $this->assertSame('sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque',
1027             shorten_filename($filename));
1028         // Filename contains extension.
1029         $this->assertSame('sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque.zip',
1030             shorten_filename($filename . '.zip'));
1031     }
1033     public function test_usergetdate() {
1034         global $USER, $CFG, $DB;
1035         $this->resetAfterTest();
1037         $this->setAdminUser();
1039         $USER->timezone = 2;// Set the timezone to a known state.
1041         $ts = 1261540267; // The time this function was created.
1043         $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
1044         $arr = array_values($arr);
1046         list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1047         $this->assertSame(7, $seconds);
1048         $this->assertSame(51, $minutes);
1049         $this->assertSame(4, $hours);
1050         $this->assertSame(23, $mday);
1051         $this->assertSame(3, $wday);
1052         $this->assertSame(12, $mon);
1053         $this->assertSame(2009, $year);
1054         $this->assertSame(356, $yday);
1055         $this->assertSame('Wednesday', $weekday);
1056         $this->assertSame('December', $month);
1057         $arr = usergetdate($ts); // Gets the timezone from the $USER object.
1058         $arr = array_values($arr);
1060         list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1061         $this->assertSame(7, $seconds);
1062         $this->assertSame(51, $minutes);
1063         $this->assertSame(5, $hours);
1064         $this->assertSame(23, $mday);
1065         $this->assertSame(3, $wday);
1066         $this->assertSame(12, $mon);
1067         $this->assertSame(2009, $year);
1068         $this->assertSame(356, $yday);
1069         $this->assertSame('Wednesday', $weekday);
1070         $this->assertSame('December', $month);
1071     }
1073     public function test_mark_user_preferences_changed() {
1074         $this->resetAfterTest();
1075         $otheruser = $this->getDataGenerator()->create_user();
1076         $otheruserid = $otheruser->id;
1078         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1079         mark_user_preferences_changed($otheruserid);
1081         $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1082         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1083     }
1085     public function test_check_user_preferences_loaded() {
1086         global $DB;
1087         $this->resetAfterTest();
1089         $otheruser = $this->getDataGenerator()->create_user();
1090         $otheruserid = $otheruser->id;
1092         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1093         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1095         $user = new stdClass();
1096         $user->id = $otheruserid;
1098         // Load.
1099         check_user_preferences_loaded($user);
1100         $this->assertTrue(isset($user->preference));
1101         $this->assertTrue(is_array($user->preference));
1102         $this->assertArrayHasKey('_lastloaded', $user->preference);
1103         $this->assertCount(1, $user->preference);
1105         // Add preference via direct call.
1106         $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1108         // No cache reload yet.
1109         check_user_preferences_loaded($user);
1110         $this->assertCount(1, $user->preference);
1112         // Forced reloading of cache.
1113         unset($user->preference);
1114         check_user_preferences_loaded($user);
1115         $this->assertCount(2, $user->preference);
1116         $this->assertSame('yyy', $user->preference['xxx']);
1118         // Add preference via direct call.
1119         $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1121         // Test timeouts and modifications from different session.
1122         set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1123         $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1124         check_user_preferences_loaded($user);
1125         $this->assertCount(2, $user->preference);
1126         check_user_preferences_loaded($user, 10);
1127         $this->assertCount(3, $user->preference);
1128         $this->assertSame('bbb', $user->preference['aaa']);
1129         set_cache_flag('userpreferenceschanged', $user->id, null);
1130     }
1132     public function test_set_user_preference() {
1133         global $DB, $USER;
1134         $this->resetAfterTest();
1136         $this->setAdminUser();
1138         $otheruser = $this->getDataGenerator()->create_user();
1139         $otheruserid = $otheruser->id;
1141         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1142         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1144         $user = new stdClass();
1145         $user->id = $otheruserid;
1147         set_user_preference('aaa', 'bbb', $otheruserid);
1148         $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1149         $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
1151         set_user_preference('xxx', 'yyy', $user);
1152         $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1153         $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
1154         $this->assertTrue(is_array($user->preference));
1155         $this->assertSame('bbb', $user->preference['aaa']);
1156         $this->assertSame('yyy', $user->preference['xxx']);
1158         set_user_preference('xxx', null, $user);
1159         $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1160         $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
1162         set_user_preference('ooo', true, $user);
1163         $prefs = get_user_preferences(null, null, $otheruserid);
1164         $this->assertSame($user->preference['aaa'], $prefs['aaa']);
1165         $this->assertSame($user->preference['ooo'], $prefs['ooo']);
1166         $this->assertSame('1', $prefs['ooo']);
1168         set_user_preference('null', 0, $user);
1169         $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1171         $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1173         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1174         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1176         // Test $USER default.
1177         set_user_preference('_test_user_preferences_pref', 'ok');
1178         $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1179         unset_user_preference('_test_user_preferences_pref');
1180         $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1182         // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
1183         $longvalue = str_repeat('a', 1333);
1184         set_user_preference('_test_long_user_preference', $longvalue);
1185         $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1186         $this->assertEquals($longvalue,
1187             $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1189         // Test > 1333 char values, coding_exception expected.
1190         $longvalue = str_repeat('a', 1334);
1191         try {
1192             set_user_preference('_test_long_user_preference', $longvalue);
1193             $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1194         } catch (moodle_exception $ex) {
1195             $this->assertInstanceOf('coding_exception', $ex);
1196         }
1198         // Test invalid params.
1199         try {
1200             set_user_preference('_test_user_preferences_pref', array());
1201             $this->fail('Exception expected - array not valid preference value');
1202         } catch (moodle_exception $ex) {
1203             $this->assertInstanceOf('coding_exception', $ex);
1204         }
1205         try {
1206             set_user_preference('_test_user_preferences_pref', new stdClass);
1207             $this->fail('Exception expected - class not valid preference value');
1208         } catch (moodle_exception $ex) {
1209             $this->assertInstanceOf('coding_exception', $ex);
1210         }
1211         try {
1212             set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1213             $this->fail('Exception expected - user instance expected');
1214         } catch (moodle_exception $ex) {
1215             $this->assertInstanceOf('coding_exception', $ex);
1216         }
1217         try {
1218             set_user_preference('_test_user_preferences_pref', 1, 'abc');
1219             $this->fail('Exception expected - user instance expected');
1220         } catch (moodle_exception $ex) {
1221             $this->assertInstanceOf('coding_exception', $ex);
1222         }
1223         try {
1224             set_user_preference('', 1);
1225             $this->fail('Exception expected - invalid name accepted');
1226         } catch (moodle_exception $ex) {
1227             $this->assertInstanceOf('coding_exception', $ex);
1228         }
1229         try {
1230             set_user_preference('1', 1);
1231             $this->fail('Exception expected - invalid name accepted');
1232         } catch (moodle_exception $ex) {
1233             $this->assertInstanceOf('coding_exception', $ex);
1234         }
1235     }
1237     public function test_set_user_preference_for_current_user() {
1238         global $USER;
1239         $this->resetAfterTest();
1240         $this->setAdminUser();
1242         set_user_preference('test_pref', 2);
1243         set_user_preference('test_pref', 1, $USER->id);
1244         $this->assertEquals(1, get_user_preferences('test_pref'));
1245     }
1247     public function test_unset_user_preference_for_current_user() {
1248         global $USER;
1249         $this->resetAfterTest();
1250         $this->setAdminUser();
1252         set_user_preference('test_pref', 1);
1253         unset_user_preference('test_pref', $USER->id);
1254         $this->assertNull(get_user_preferences('test_pref'));
1255     }
1257     public function test_get_extra_user_fields() {
1258         global $CFG, $USER, $DB;
1259         $this->resetAfterTest();
1261         $this->setAdminUser();
1263         // It would be really nice if there were a way to 'mock' has_capability
1264         // checks (either to return true or false) but as there is not, this
1265         // test doesn't test the capability check. Presumably, anyone running
1266         // unit tests will have the capability.
1267         $context = context_system::instance();
1269         // No fields.
1270         $CFG->showuseridentity = '';
1271         $this->assertEquals(array(), get_extra_user_fields($context));
1273         // One field.
1274         $CFG->showuseridentity = 'frog';
1275         $this->assertEquals(array('frog'), get_extra_user_fields($context));
1277         // Two fields.
1278         $CFG->showuseridentity = 'frog,zombie';
1279         $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1281         // No fields, except.
1282         $CFG->showuseridentity = '';
1283         $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1285         // One field.
1286         $CFG->showuseridentity = 'frog';
1287         $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1289         // Two fields.
1290         $CFG->showuseridentity = 'frog,zombie';
1291         $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1292     }
1294     public function test_get_extra_user_fields_sql() {
1295         global $CFG, $USER, $DB;
1296         $this->resetAfterTest();
1298         $this->setAdminUser();
1300         $context = context_system::instance();
1302         // No fields.
1303         $CFG->showuseridentity = '';
1304         $this->assertSame('', get_extra_user_fields_sql($context));
1306         // One field.
1307         $CFG->showuseridentity = 'frog';
1308         $this->assertSame(', frog', get_extra_user_fields_sql($context));
1310         // Two fields with table prefix.
1311         $CFG->showuseridentity = 'frog,zombie';
1312         $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1314         // Two fields with field prefix.
1315         $CFG->showuseridentity = 'frog,zombie';
1316         $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
1317             get_extra_user_fields_sql($context, '', 'u_'));
1319         // One field excluded.
1320         $CFG->showuseridentity = 'frog';
1321         $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
1323         // Two fields, one excluded, table+field prefix.
1324         $CFG->showuseridentity = 'frog,zombie';
1325         $this->assertEquals(', u1.zombie AS u_zombie',
1326             get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1327     }
1329     /**
1330      * Test some critical TZ/DST.
1331      *
1332      * This method tests some special TZ/DST combinations that were fixed
1333      * by MDL-38999. The tests are done by comparing the results of the
1334      * output using Moodle TZ/DST support and PHP native one.
1335      *
1336      * Note: If you don't trust PHP TZ/DST support, can verify the
1337      * harcoded expectations below with:
1338      * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
1339      */
1340     public function test_some_moodle_special_dst() {
1341         $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
1343         // In Europe/Tallinn it was 2013/04/08 05:00:00.
1344         $expectation = '2013/04/08 05:00:00';
1345         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1346         $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1347         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1348         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1349         $this->assertSame($expectation, $phpres);
1350         $this->assertSame($expectation, $moodleres);
1352         // In St. Johns it was 2013/04/07 23:30:00.
1353         $expectation = '2013/04/07 23:30:00';
1354         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1355         $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1356         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1357         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1358         $this->assertSame($expectation, $phpres);
1359         $this->assertSame($expectation, $moodleres);
1361         $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1363         // In Europe/Tallinn it was 2013/11/08 04:00:00.
1364         $expectation = '2013/11/08 04:00:00';
1365         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1366         $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1367         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1368         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1369         $this->assertSame($expectation, $phpres);
1370         $this->assertSame($expectation, $moodleres);
1372         // In St. Johns it was 2013/11/07 22:30:00.
1373         $expectation = '2013/11/07 22:30:00';
1374         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1375         $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1376         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1377         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1378         $this->assertSame($expectation, $phpres);
1379         $this->assertSame($expectation, $moodleres);
1380     }
1382     public function test_userdate() {
1383         global $USER, $CFG, $DB;
1384         $this->resetAfterTest();
1386         $this->setAdminUser();
1388         $testvalues = array(
1389             array(
1390                 'time' => '1309514400',
1391                 'usertimezone' => 'America/Moncton',
1392                 'timezone' => '0.0', // No dst offset.
1393                 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1394             ),
1395             array(
1396                 'time' => '1309514400',
1397                 'usertimezone' => 'America/Moncton',
1398                 'timezone' => '99', // Dst offset and timezone offset.
1399                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1400             ),
1401             array(
1402                 'time' => '1309514400',
1403                 'usertimezone' => 'America/Moncton',
1404                 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
1405                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1406             ),
1407             array(
1408                 'time' => '1293876000 ',
1409                 'usertimezone' => 'America/Moncton',
1410                 'timezone' => '0.0', // No dst offset.
1411                 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1412             ),
1413             array(
1414                 'time' => '1293876000 ',
1415                 'usertimezone' => 'America/Moncton',
1416                 'timezone' => '99', // No dst offset in jan, so just timezone offset.
1417                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1418             ),
1419             array(
1420                 'time' => '1293876000 ',
1421                 'usertimezone' => 'America/Moncton',
1422                 'timezone' => 'America/Moncton', // No dst offset in jan.
1423                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1424             ),
1425             array(
1426                 'time' => '1293876000 ',
1427                 'usertimezone' => '2',
1428                 'timezone' => '99', // Take user timezone.
1429                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1430             ),
1431             array(
1432                 'time' => '1293876000 ',
1433                 'usertimezone' => '-2',
1434                 'timezone' => '99', // Take user timezone.
1435                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1436             ),
1437             array(
1438                 'time' => '1293876000 ',
1439                 'usertimezone' => '-10',
1440                 'timezone' => '2', // Take this timezone.
1441                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1442             ),
1443             array(
1444                 'time' => '1293876000 ',
1445                 'usertimezone' => '-10',
1446                 'timezone' => '-2', // Take this timezone.
1447                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1448             ),
1449             array(
1450                 'time' => '1293876000 ',
1451                 'usertimezone' => '-10',
1452                 'timezone' => 'random/time', // This should show server time.
1453                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1454             ),
1455             array(
1456                 'time' => '1293876000 ',
1457                 'usertimezone' => '20', // Fallback to server time zone.
1458                 'timezone' => '99',     // This should show user time.
1459                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1460             ),
1461         );
1463         // Set default timezone to Australia/Perth, else time calculated
1464         // will not match expected values.
1465         $this->setTimezone(99, 'Australia/Perth');
1467         foreach ($testvalues as $vals) {
1468             $USER->timezone = $vals['usertimezone'];
1469             $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1471             // On different systems case of AM PM changes so compare case insensitive.
1472             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1473             $actualoutput = core_text::strtolower($actualoutput);
1475             $this->assertSame($vals['expectedoutput'], $actualoutput,
1476                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput} \ndata: " . var_export($vals, true));
1477         }
1478     }
1480     /**
1481      * Make sure the DST changes happen at the right time in Moodle.
1482      */
1483     public function test_dst_changes() {
1484         // DST switching in Prague.
1485         // From 2AM to 3AM in 1989.
1486         $date = new DateTime('1989-03-26T01:59:00+01:00');
1487         $this->assertSame('Sunday, 26 March 1989, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1488         $date = new DateTime('1989-03-26T02:01:00+01:00');
1489         $this->assertSame('Sunday, 26 March 1989, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1490         // From 3AM to 2AM in 1989 - not the same as the west Europe.
1491         $date = new DateTime('1989-09-24T01:59:00+01:00');
1492         $this->assertSame('Sunday, 24 September 1989, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1493         $date = new DateTime('1989-09-24T02:01:00+01:00');
1494         $this->assertSame('Sunday, 24 September 1989, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1495         // From 2AM to 3AM in 2014.
1496         $date = new DateTime('2014-03-30T01:59:00+01:00');
1497         $this->assertSame('Sunday, 30 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1498         $date = new DateTime('2014-03-30T02:01:00+01:00');
1499         $this->assertSame('Sunday, 30 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1500         // From 3AM to 2AM in 2014.
1501         $date = new DateTime('2014-10-26T01:59:00+01:00');
1502         $this->assertSame('Sunday, 26 October 2014, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1503         $date = new DateTime('2014-10-26T02:01:00+01:00');
1504         $this->assertSame('Sunday, 26 October 2014, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1505         // From 2AM to 3AM in 2020.
1506         $date = new DateTime('2020-03-29T01:59:00+01:00');
1507         $this->assertSame('Sunday, 29 March 2020, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1508         $date = new DateTime('2020-03-29T02:01:00+01:00');
1509         $this->assertSame('Sunday, 29 March 2020, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1510         // From 3AM to 2AM in 2020.
1511         $date = new DateTime('2020-10-25T01:59:00+01:00');
1512         $this->assertSame('Sunday, 25 October 2020, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1513         $date = new DateTime('2020-10-25T02:01:00+01:00');
1514         $this->assertSame('Sunday, 25 October 2020, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1516         // DST switching in NZ.
1517         // From 3AM to 2AM in 2015.
1518         $date = new DateTime('2015-04-05T02:59:00+13:00');
1519         $this->assertSame('Sunday, 5 April 2015, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1520         $date = new DateTime('2015-04-05T03:01:00+13:00');
1521         $this->assertSame('Sunday, 5 April 2015, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1522         // From 2AM to 3AM in 2009.
1523         $date = new DateTime('2015-09-27T01:59:00+12:00');
1524         $this->assertSame('Sunday, 27 September 2015, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1525         $date = new DateTime('2015-09-27T02:01:00+12:00');
1526         $this->assertSame('Sunday, 27 September 2015, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1528         // DST switching in Perth.
1529         // From 3AM to 2AM in 2009.
1530         $date = new DateTime('2008-03-30T01:59:00+08:00');
1531         $this->assertSame('Sunday, 30 March 2008, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1532         $date = new DateTime('2008-03-30T02:01:00+08:00');
1533         $this->assertSame('Sunday, 30 March 2008, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1534         // From 2AM to 3AM in 2009.
1535         $date = new DateTime('2008-10-26T01:59:00+08:00');
1536         $this->assertSame('Sunday, 26 October 2008, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1537         $date = new DateTime('2008-10-26T02:01:00+08:00');
1538         $this->assertSame('Sunday, 26 October 2008, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1540         // DST switching in US.
1541         // From 2AM to 3AM in 2014.
1542         $date = new DateTime('2014-03-09T01:59:00-05:00');
1543         $this->assertSame('Sunday, 9 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1544         $date = new DateTime('2014-03-09T02:01:00-05:00');
1545         $this->assertSame('Sunday, 9 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1546         // From 3AM to 2AM in 2014.
1547         $date = new DateTime('2014-11-02T01:59:00-04:00');
1548         $this->assertSame('Sunday, 2 November 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1549         $date = new DateTime('2014-11-02T02:01:00-04:00');
1550         $this->assertSame('Sunday, 2 November 2014, 01:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1551     }
1553     public function test_make_timestamp() {
1554         global $USER, $CFG, $DB;
1555         $this->resetAfterTest();
1557         $this->setAdminUser();
1559         $testvalues = array(
1560             array(
1561                 'usertimezone' => 'America/Moncton',
1562                 'year' => '2011',
1563                 'month' => '7',
1564                 'day' => '1',
1565                 'hour' => '10',
1566                 'minutes' => '00',
1567                 'seconds' => '00',
1568                 'timezone' => '0.0',
1569                 'applydst' => false, // No dst offset.
1570                 'expectedoutput' => '1309514400' // 6pm at UTC+0.
1571             ),
1572             array(
1573                 'usertimezone' => 'America/Moncton',
1574                 'year' => '2011',
1575                 'month' => '7',
1576                 'day' => '1',
1577                 'hour' => '10',
1578                 'minutes' => '00',
1579                 'seconds' => '00',
1580                 'timezone' => '99',  // User default timezone.
1581                 'applydst' => false, // Don't apply dst.
1582                 'expectedoutput' => '1309528800'
1583             ),
1584             array(
1585                 'usertimezone' => 'America/Moncton',
1586                 'year' => '2011',
1587                 'month' => '7',
1588                 'day' => '1',
1589                 'hour' => '10',
1590                 'minutes' => '00',
1591                 'seconds' => '00',
1592                 'timezone' => '99', // User default timezone.
1593                 'applydst' => true, // Apply dst.
1594                 'expectedoutput' => '1309525200'
1595             ),
1596             array(
1597                 'usertimezone' => 'America/Moncton',
1598                 'year' => '2011',
1599                 'month' => '7',
1600                 'day' => '1',
1601                 'hour' => '10',
1602                 'minutes' => '00',
1603                 'seconds' => '00',
1604                 'timezone' => 'America/Moncton', // String timezone.
1605                 'applydst' => true, // Apply dst.
1606                 'expectedoutput' => '1309525200'
1607             ),
1608             array(
1609                 'usertimezone' => '2', // No dst applyed.
1610                 'year' => '2011',
1611                 'month' => '7',
1612                 'day' => '1',
1613                 'hour' => '10',
1614                 'minutes' => '00',
1615                 'seconds' => '00',
1616                 'timezone' => '99', // Take user timezone.
1617                 'applydst' => true, // Apply dst.
1618                 'expectedoutput' => '1309507200'
1619             ),
1620             array(
1621                 'usertimezone' => '-2', // No dst applyed.
1622                 'year' => '2011',
1623                 'month' => '7',
1624                 'day' => '1',
1625                 'hour' => '10',
1626                 'minutes' => '00',
1627                 'seconds' => '00',
1628                 'timezone' => '99', // Take usertimezone.
1629                 'applydst' => true, // Apply dst.
1630                 'expectedoutput' => '1309521600'
1631             ),
1632             array(
1633                 'usertimezone' => '-10', // No dst applyed.
1634                 'year' => '2011',
1635                 'month' => '7',
1636                 'day' => '1',
1637                 'hour' => '10',
1638                 'minutes' => '00',
1639                 'seconds' => '00',
1640                 'timezone' => '2',  // Take this timezone.
1641                 'applydst' => true, // Apply dst.
1642                 'expectedoutput' => '1309507200'
1643             ),
1644             array(
1645                 'usertimezone' => '-10', // No dst applyed.
1646                 'year' => '2011',
1647                 'month' => '7',
1648                 'day' => '1',
1649                 'hour' => '10',
1650                 'minutes' => '00',
1651                 'seconds' => '00',
1652                 'timezone' => '-2', // Take this timezone.
1653                 'applydst' => true, // Apply dst.
1654                 'expectedoutput' => '1309521600'
1655             ),
1656             array(
1657                 'usertimezone' => '-10', // No dst applyed.
1658                 'year' => '2011',
1659                 'month' => '7',
1660                 'day' => '1',
1661                 'hour' => '10',
1662                 'minutes' => '00',
1663                 'seconds' => '00',
1664                 'timezone' => 'random/time', // This should show server time.
1665                 'applydst' => true,          // Apply dst.
1666                 'expectedoutput' => '1309485600'
1667             ),
1668             array(
1669                 'usertimezone' => '-14', // Server time.
1670                 'year' => '2011',
1671                 'month' => '7',
1672                 'day' => '1',
1673                 'hour' => '10',
1674                 'minutes' => '00',
1675                 'seconds' => '00',
1676                 'timezone' => '99', // Get user time.
1677                 'applydst' => true, // Apply dst.
1678                 'expectedoutput' => '1309485600'
1679             )
1680         );
1682         // Set default timezone to Australia/Perth, else time calculated
1683         // will not match expected values.
1684         $this->setTimezone(99, 'Australia/Perth');
1686         // Test make_timestamp with all testvals and assert if anything wrong.
1687         foreach ($testvalues as $vals) {
1688             $USER->timezone = $vals['usertimezone'];
1689             $actualoutput = make_timestamp(
1690                 $vals['year'],
1691                 $vals['month'],
1692                 $vals['day'],
1693                 $vals['hour'],
1694                 $vals['minutes'],
1695                 $vals['seconds'],
1696                 $vals['timezone'],
1697                 $vals['applydst']
1698             );
1700             // On different systems case of AM PM changes so compare case insensitive.
1701             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1702             $actualoutput = core_text::strtolower($actualoutput);
1704             $this->assertSame($vals['expectedoutput'], $actualoutput,
1705                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1706                 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1707         }
1708     }
1710     /**
1711      * Test get_string and most importantly the implementation of the lang_string
1712      * object.
1713      */
1714     public function test_get_string() {
1715         global $COURSE;
1717         // Make sure we are using English.
1718         $originallang = $COURSE->lang;
1719         $COURSE->lang = 'en';
1721         $yes = get_string('yes');
1722         $yesexpected = 'Yes';
1723         $this->assertInternalType('string', $yes);
1724         $this->assertSame($yesexpected, $yes);
1726         $yes = get_string('yes', 'moodle');
1727         $this->assertInternalType('string', $yes);
1728         $this->assertSame($yesexpected, $yes);
1730         $yes = get_string('yes', 'core');
1731         $this->assertInternalType('string', $yes);
1732         $this->assertSame($yesexpected, $yes);
1734         $yes = get_string('yes', '');
1735         $this->assertInternalType('string', $yes);
1736         $this->assertSame($yesexpected, $yes);
1738         $yes = get_string('yes', null);
1739         $this->assertInternalType('string', $yes);
1740         $this->assertSame($yesexpected, $yes);
1742         $yes = get_string('yes', null, 1);
1743         $this->assertInternalType('string', $yes);
1744         $this->assertSame($yesexpected, $yes);
1746         $days = 1;
1747         $numdays = get_string('numdays', 'core', '1');
1748         $numdaysexpected = $days.' days';
1749         $this->assertInternalType('string', $numdays);
1750         $this->assertSame($numdaysexpected, $numdays);
1752         $yes = get_string('yes', null, null, true);
1753         $this->assertInstanceOf('lang_string', $yes);
1754         $this->assertSame($yesexpected, (string)$yes);
1756         // Test using a lang_string object as the $a argument for a normal
1757         // get_string call (returning string).
1758         $test = new lang_string('yes', null, null, true);
1759         $testexpected = get_string('numdays', 'core', get_string('yes'));
1760         $testresult = get_string('numdays', null, $test);
1761         $this->assertInternalType('string', $testresult);
1762         $this->assertSame($testexpected, $testresult);
1764         // Test using a lang_string object as the $a argument for an object
1765         // get_string call (returning lang_string).
1766         $test = new lang_string('yes', null, null, true);
1767         $testexpected = get_string('numdays', 'core', get_string('yes'));
1768         $testresult = get_string('numdays', null, $test, true);
1769         $this->assertInstanceOf('lang_string', $testresult);
1770         $this->assertSame($testexpected, "$testresult");
1772         // Make sure that object properties that can't be converted don't cause
1773         // errors.
1774         // Level one: This is as deep as current language processing goes.
1775         $test = new stdClass;
1776         $test->one = 'here';
1777         $string = get_string('yes', null, $test, true);
1778         $this->assertEquals($yesexpected, $string);
1780         // Make sure that object properties that can't be converted don't cause
1781         // errors.
1782         // Level two: Language processing doesn't currently reach this deep.
1783         // only immediate scalar properties are worked with.
1784         $test = new stdClass;
1785         $test->one = new stdClass;
1786         $test->one->two = 'here';
1787         $string = get_string('yes', null, $test, true);
1788         $this->assertEquals($yesexpected, $string);
1790         // Make sure that object properties that can't be converted don't cause
1791         // errors.
1792         // Level three: It should never ever go this deep, but we're making sure
1793         // it doesn't cause any probs anyway.
1794         $test = new stdClass;
1795         $test->one = new stdClass;
1796         $test->one->two = new stdClass;
1797         $test->one->two->three = 'here';
1798         $string = get_string('yes', null, $test, true);
1799         $this->assertEquals($yesexpected, $string);
1801         // Make sure that object properties that can't be converted don't cause
1802         // errors and check lang_string properties.
1803         // Level one: This is as deep as current language processing goes.
1804         $test = new stdClass;
1805         $test->one = new lang_string('yes');
1806         $string = get_string('yes', null, $test, true);
1807         $this->assertEquals($yesexpected, $string);
1809         // Make sure that object properties that can't be converted don't cause
1810         // errors and check lang_string properties.
1811         // Level two: Language processing doesn't currently reach this deep.
1812         // only immediate scalar properties are worked with.
1813         $test = new stdClass;
1814         $test->one = new stdClass;
1815         $test->one->two = new lang_string('yes');
1816         $string = get_string('yes', null, $test, true);
1817         $this->assertEquals($yesexpected, $string);
1819         // Make sure that object properties that can't be converted don't cause
1820         // errors and check lang_string properties.
1821         // Level three: It should never ever go this deep, but we're making sure
1822         // it doesn't cause any probs anyway.
1823         $test = new stdClass;
1824         $test->one = new stdClass;
1825         $test->one->two = new stdClass;
1826         $test->one->two->three = new lang_string('yes');
1827         $string = get_string('yes', null, $test, true);
1828         $this->assertEquals($yesexpected, $string);
1830         // Make sure that array properties that can't be converted don't cause
1831         // errors.
1832         $test = array();
1833         $test['one'] = new stdClass;
1834         $test['one']->two = 'here';
1835         $string = get_string('yes', null, $test, true);
1836         $this->assertEquals($yesexpected, $string);
1838         // Same thing but as above except using an object... this is allowed :P.
1839         $string = get_string('yes', null, null, true);
1840         $object = new stdClass;
1841         $object->$string = 'Yes';
1842         $this->assertEquals($yesexpected, $string);
1843         $this->assertEquals($yesexpected, $object->$string);
1845         // Reset the language.
1846         $COURSE->lang = $originallang;
1847     }
1849     /**
1850      * @expectedException PHPUnit\Framework\Error\Warning
1851      */
1852     public function test_get_string_limitation() {
1853         // This is one of the limitations to the lang_string class. It can't be
1854         // used as a key.
1855         $array = array(get_string('yes', null, null, true) => 'yes');
1856     }
1858     /**
1859      * Test localised float formatting.
1860      */
1861     public function test_format_float() {
1863         // Special case for null.
1864         $this->assertEquals('', format_float(null));
1866         // Default 1 decimal place.
1867         $this->assertEquals('5.4', format_float(5.43));
1868         $this->assertEquals('5.0', format_float(5.001));
1870         // Custom number of decimal places.
1871         $this->assertEquals('5.43000', format_float(5.43, 5));
1873         // Option to strip ending zeros after rounding.
1874         $this->assertEquals('5.43', format_float(5.43, 5, true, true));
1875         $this->assertEquals('5', format_float(5.0001, 3, true, true));
1877         // Tests with a localised decimal separator.
1878         $this->define_local_decimal_separator();
1880         // Localisation on (default).
1881         $this->assertEquals('5X43000', format_float(5.43, 5));
1882         $this->assertEquals('5X43', format_float(5.43, 5, true, true));
1884         // Localisation off.
1885         $this->assertEquals('5.43000', format_float(5.43, 5, false));
1886         $this->assertEquals('5.43', format_float(5.43, 5, false, true));
1887     }
1889     /**
1890      * Test localised float unformatting.
1891      */
1892     public function test_unformat_float() {
1894         // Tests without the localised decimal separator.
1896         // Special case for null, empty or white spaces only strings.
1897         $this->assertEquals(null, unformat_float(null));
1898         $this->assertEquals(null, unformat_float(''));
1899         $this->assertEquals(null, unformat_float('    '));
1901         // Regular use.
1902         $this->assertEquals(5.4, unformat_float('5.4'));
1903         $this->assertEquals(5.4, unformat_float('5.4', true));
1905         // No decimal.
1906         $this->assertEquals(5.0, unformat_float('5'));
1908         // Custom number of decimal.
1909         $this->assertEquals(5.43267, unformat_float('5.43267'));
1911         // Empty decimal.
1912         $this->assertEquals(100.0, unformat_float('100.00'));
1914         // With the thousand separator.
1915         $this->assertEquals(1000.0, unformat_float('1 000'));
1916         $this->assertEquals(1000.32, unformat_float('1 000.32'));
1918         // Negative number.
1919         $this->assertEquals(-100.0, unformat_float('-100'));
1921         // Wrong value.
1922         $this->assertEquals(0.0, unformat_float('Wrong value'));
1923         // Wrong value in strict mode.
1924         $this->assertFalse(unformat_float('Wrong value', true));
1926         // Combining options.
1927         $this->assertEquals(-1023.862567, unformat_float('   -1 023.862567     '));
1929         // Bad decimal separator (should crop the decimal).
1930         $this->assertEquals(50.0, unformat_float('50,57'));
1931         // Bad decimal separator in strict mode (should return false).
1932         $this->assertFalse(unformat_float('50,57', true));
1934         // Tests with a localised decimal separator.
1935         $this->define_local_decimal_separator();
1937         // We repeat the tests above but with the current decimal separator.
1939         // Regular use without and with the localised separator.
1940         $this->assertEquals (5.4, unformat_float('5.4'));
1941         $this->assertEquals (5.4, unformat_float('5X4'));
1943         // Custom number of decimal.
1944         $this->assertEquals (5.43267, unformat_float('5X43267'));
1946         // Empty decimal.
1947         $this->assertEquals (100.0, unformat_float('100X00'));
1949         // With the thousand separator.
1950         $this->assertEquals (1000.32, unformat_float('1 000X32'));
1952         // Bad different separator (should crop the decimal).
1953         $this->assertEquals (50.0, unformat_float('50Y57'));
1954         // Bad different separator in strict mode (should return false).
1955         $this->assertFalse (unformat_float('50Y57', true));
1957         // Combining options.
1958         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     '));
1959         // Combining options in strict mode.
1960         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     ', true));
1961     }
1963     /**
1964      * Test deleting of users.
1965      */
1966     public function test_delete_user() {
1967         global $DB, $CFG;
1969         $this->resetAfterTest();
1971         $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
1972         $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
1973         $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
1975         $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
1976         $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
1977         $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
1978         $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
1979         $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => ''));
1980         $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => ''));
1982         // Delete user and capture event.
1983         $sink = $this->redirectEvents();
1984         $result = delete_user($user);
1985         $events = $sink->get_events();
1986         $sink->close();
1987         $event = array_pop($events);
1989         // Test user is deleted in DB.
1990         $this->assertTrue($result);
1991         $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
1992         $this->assertEquals(1, $deluser->deleted);
1993         $this->assertEquals(0, $deluser->picture);
1994         $this->assertSame('', $deluser->idnumber);
1995         $this->assertSame(md5($user->username), $deluser->email);
1996         $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
1998         $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
2000         // Test Event.
2001         $this->assertInstanceOf('\core\event\user_deleted', $event);
2002         $this->assertSame($user->id, $event->objectid);
2003         $this->assertSame('user_deleted', $event->get_legacy_eventname());
2004         $this->assertEventLegacyData($user, $event);
2005         $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
2006         $this->assertEventLegacyLogData($expectedlogdata, $event);
2007         $eventdata = $event->get_data();
2008         $this->assertSame($eventdata['other']['username'], $user->username);
2009         $this->assertSame($eventdata['other']['email'], $user->email);
2010         $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
2011         $this->assertSame($eventdata['other']['picture'], $user->picture);
2012         $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
2013         $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
2014         $this->assertEventContextNotUsed($event);
2016         // Try invalid params.
2017         $record = new stdClass();
2018         $record->grrr = 1;
2019         try {
2020             delete_user($record);
2021             $this->fail('Expecting exception for invalid delete_user() $user parameter');
2022         } catch (moodle_exception $ex) {
2023             $this->assertInstanceOf('coding_exception', $ex);
2024         }
2025         $record->id = 1;
2026         try {
2027             delete_user($record);
2028             $this->fail('Expecting exception for invalid delete_user() $user parameter');
2029         } catch (moodle_exception $ex) {
2030             $this->assertInstanceOf('coding_exception', $ex);
2031         }
2033         $record = new stdClass();
2034         $record->id = 666;
2035         $record->username = 'xx';
2036         $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
2037         $result = delete_user($record);
2038         $this->assertFalse($result);
2040         $result = delete_user($guest);
2041         $this->assertFalse($result);
2043         $result = delete_user($admin);
2044         $this->assertFalse($result);
2046         // Simultaneously deleting users with identical email addresses.
2047         $result1 = delete_user($usersharedemail1);
2048         $result2 = delete_user($usersharedemail2);
2050         $usersharedemail1after = $DB->get_record('user', array('id' => $usersharedemail1->id));
2051         $usersharedemail2after = $DB->get_record('user', array('id' => $usersharedemail2->id));
2052         $this->assertTrue($result1);
2053         $this->assertTrue($result2);
2054         $this->assertStringStartsWith($usersharedemail1->email . '.', $usersharedemail1after->username);
2055         $this->assertStringStartsWith($usersharedemail2->email . '.', $usersharedemail2after->username);
2057         // Simultaneously deleting users without email addresses.
2058         $result1 = delete_user($useremptyemail1);
2059         $result2 = delete_user($useremptyemail2);
2061         $useremptyemail1after = $DB->get_record('user', array('id' => $useremptyemail1->id));
2062         $useremptyemail2after = $DB->get_record('user', array('id' => $useremptyemail2->id));
2063         $this->assertTrue($result1);
2064         $this->assertTrue($result2);
2065         $this->assertStringStartsWith($useremptyemail1->username . '.' . $useremptyemail1->id . '@unknownemail.invalid.',
2066             $useremptyemail1after->username);
2067         $this->assertStringStartsWith($useremptyemail2->username . '.' . $useremptyemail2->id . '@unknownemail.invalid.',
2068             $useremptyemail2after->username);
2070         $this->resetDebugging();
2071     }
2073     /**
2074      * Test function convert_to_array()
2075      */
2076     public function test_convert_to_array() {
2077         // Check that normal classes are converted to arrays the same way as (array) would do.
2078         $obj = new stdClass();
2079         $obj->prop1 = 'hello';
2080         $obj->prop2 = array('first', 'second', 13);
2081         $obj->prop3 = 15;
2082         $this->assertEquals(convert_to_array($obj), (array)$obj);
2084         // Check that context object (with iterator) is converted to array properly.
2085         $obj = context_system::instance();
2086         $ar = array(
2087             'id'           => $obj->id,
2088             'contextlevel' => $obj->contextlevel,
2089             'instanceid'   => $obj->instanceid,
2090             'path'         => $obj->path,
2091             'depth'        => $obj->depth
2092         );
2093         $this->assertEquals(convert_to_array($obj), $ar);
2094     }
2096     /**
2097      * Test the function date_format_string().
2098      */
2099     public function test_date_format_string() {
2100         global $CFG;
2102         $this->resetAfterTest();
2103         $this->setTimezone(99, 'Australia/Perth');
2105         $tests = array(
2106             array(
2107                 'tz' => 99,
2108                 'str' => '%A, %d %B %Y, %I:%M %p',
2109                 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
2110             ),
2111             array(
2112                 'tz' => 0,
2113                 'str' => '%A, %d %B %Y, %I:%M %p',
2114                 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2115             ),
2116             array(
2117                 // Note: this function expected the timestamp in weird format before,
2118                 // since 2.9 it uses UTC.
2119                 'tz' => 'Pacific/Auckland',
2120                 'str' => '%A, %d %B %Y, %I:%M %p',
2121                 'expected' => 'Saturday, 01 January 2011, 11:00 PM'
2122             ),
2123             // Following tests pass on Windows only because en lang pack does
2124             // not contain localewincharset, in real life lang pack maintainers
2125             // may use only characters that are present in localewincharset
2126             // in format strings!
2127             array(
2128                 'tz' => 99,
2129                 'str' => 'Žluťoučký koníček %A',
2130                 'expected' => 'Žluťoučký koníček Saturday'
2131             ),
2132             array(
2133                 'tz' => 99,
2134                 'str' => '言語設定言語 %A',
2135                 'expected' => '言語設定言語 Saturday'
2136             ),
2137             array(
2138                 'tz' => 99,
2139                 'str' => '简体中文简体 %A',
2140                 'expected' => '简体中文简体 Saturday'
2141             ),
2142         );
2144         // Note: date_format_string() uses the timezone only to differenciate
2145         // the server time from the UTC time. It does not modify the timestamp.
2146         // Hence similar results for timezones <= 13.
2147         // On different systems case of AM PM changes so compare case insensitive.
2148         foreach ($tests as $test) {
2149             $str = date_format_string(1293876000, $test['str'], $test['tz']);
2150             $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
2151         }
2152     }
2154     public function test_get_config() {
2155         global $CFG;
2157         $this->resetAfterTest();
2159         // Preparation.
2160         set_config('phpunit_test_get_config_1', 'test 1');
2161         set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2162         if (!is_array($CFG->config_php_settings)) {
2163             $CFG->config_php_settings = array();
2164         }
2165         $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
2167         if (!is_array($CFG->forced_plugin_settings)) {
2168             $CFG->forced_plugin_settings = array();
2169         }
2170         if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
2171             $CFG->forced_plugin_settings['mod_forum'] = array();
2172         }
2173         $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2174         $CFG->phpunit_test_get_config_5 = 'test 5';
2176         // Testing.
2177         $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
2178         $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2179         $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
2180         $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2181         $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2182         $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2183         $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2185         // Test config we know to exist.
2186         $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
2187         $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2188         $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2189         $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2191         // Test setting a config var that already exists.
2192         set_config('phpunit_test_get_config_1', 'test a');
2193         $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
2194         $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
2196         // Test cache invalidation.
2197         $cache = cache::make('core', 'config');
2198         $this->assertInternalType('array', $cache->get('core'));
2199         $this->assertInternalType('array', $cache->get('mod_forum'));
2200         set_config('phpunit_test_get_config_1', 'test b');
2201         $this->assertFalse($cache->get('core'));
2202         set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2203         $this->assertFalse($cache->get('mod_forum'));
2204     }
2206     public function test_get_max_upload_sizes() {
2207         // Test with very low limits so we are not affected by php upload limits.
2208         // Test activity limit smallest.
2209         $sitebytes = 102400;
2210         $coursebytes = 51200;
2211         $modulebytes = 10240;
2212         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2214         $this->assertSame('Activity upload limit (10KB)', $result['0']);
2215         $this->assertCount(2, $result);
2217         // Test course limit smallest.
2218         $sitebytes = 102400;
2219         $coursebytes = 10240;
2220         $modulebytes = 51200;
2221         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2223         $this->assertSame('Course upload limit (10KB)', $result['0']);
2224         $this->assertCount(2, $result);
2226         // Test site limit smallest.
2227         $sitebytes = 10240;
2228         $coursebytes = 102400;
2229         $modulebytes = 51200;
2230         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2232         $this->assertSame('Site upload limit (10KB)', $result['0']);
2233         $this->assertCount(2, $result);
2235         // Test site limit not set.
2236         $sitebytes = 0;
2237         $coursebytes = 102400;
2238         $modulebytes = 51200;
2239         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2241         $this->assertSame('Activity upload limit (50KB)', $result['0']);
2242         $this->assertCount(3, $result);
2244         $sitebytes = 0;
2245         $coursebytes = 51200;
2246         $modulebytes = 102400;
2247         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2249         $this->assertSame('Course upload limit (50KB)', $result['0']);
2250         $this->assertCount(3, $result);
2252         // Test custom bytes in range.
2253         $sitebytes = 102400;
2254         $coursebytes = 51200;
2255         $modulebytes = 51200;
2256         $custombytes = 10240;
2257         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2259         $this->assertCount(3, $result);
2261         // Test custom bytes in range but non-standard.
2262         $sitebytes = 102400;
2263         $coursebytes = 51200;
2264         $modulebytes = 51200;
2265         $custombytes = 25600;
2266         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2268         $this->assertCount(4, $result);
2270         // Test custom bytes out of range.
2271         $sitebytes = 102400;
2272         $coursebytes = 51200;
2273         $modulebytes = 51200;
2274         $custombytes = 102400;
2275         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2277         $this->assertCount(3, $result);
2279         // Test custom bytes out of range and non-standard.
2280         $sitebytes = 102400;
2281         $coursebytes = 51200;
2282         $modulebytes = 51200;
2283         $custombytes = 256000;
2284         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2286         $this->assertCount(3, $result);
2288         // Test site limit only.
2289         $sitebytes = 51200;
2290         $result = get_max_upload_sizes($sitebytes);
2292         $this->assertSame('Site upload limit (50KB)', $result['0']);
2293         $this->assertSame('50KB', $result['51200']);
2294         $this->assertSame('10KB', $result['10240']);
2295         $this->assertCount(3, $result);
2297         // Test no limit.
2298         $result = get_max_upload_sizes();
2299         $this->assertArrayHasKey('0', $result);
2300         $this->assertArrayHasKey(get_max_upload_file_size(), $result);
2301     }
2303     /**
2304      * Test function password_is_legacy_hash().
2305      */
2306     public function test_password_is_legacy_hash() {
2307         // Well formed md5s should be matched.
2308         foreach (array('some', 'strings', 'to_check!') as $string) {
2309             $md5 = md5($string);
2310             $this->assertTrue(password_is_legacy_hash($md5));
2311         }
2312         // Strings that are not md5s should not be matched.
2313         foreach (array('', AUTH_PASSWORD_NOT_CACHED, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
2314             $this->assertFalse(password_is_legacy_hash($notmd5));
2315         }
2316     }
2318     /**
2319      * Test function validate_internal_user_password().
2320      */
2321     public function test_validate_internal_user_password() {
2322         // Test bcrypt hashes.
2323         $validhashes = array(
2324             'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2325             'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2326             'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2327             'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
2328         );
2330         foreach ($validhashes as $password => $hash) {
2331             $user = new stdClass();
2332             $user->auth = 'manual';
2333             $user->password = $hash;
2334             // The correct password should be validated.
2335             $this->assertTrue(validate_internal_user_password($user, $password));
2336             // An incorrect password should not be validated.
2337             $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2338         }
2339     }
2341     /**
2342      * Test function hash_internal_user_password().
2343      */
2344     public function test_hash_internal_user_password() {
2345         $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2347         // Check that some passwords that we convert to hashes can
2348         // be validated.
2349         foreach ($passwords as $password) {
2350             $hash = hash_internal_user_password($password);
2351             $fasthash = hash_internal_user_password($password, true);
2352             $user = new stdClass();
2353             $user->auth = 'manual';
2354             $user->password = $hash;
2355             $this->assertTrue(validate_internal_user_password($user, $password));
2357             // They should not be in md5 format.
2358             $this->assertFalse(password_is_legacy_hash($hash));
2360             // Check that cost factor in hash is correctly set.
2361             $this->assertRegExp('/\$10\$/', $hash);
2362             $this->assertRegExp('/\$04\$/', $fasthash);
2363         }
2364     }
2366     /**
2367      * Test function update_internal_user_password().
2368      */
2369     public function test_update_internal_user_password() {
2370         global $DB;
2371         $this->resetAfterTest();
2372         $passwords = array('password', '1234', 'changeme', '****');
2373         foreach ($passwords as $password) {
2374             $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2375             update_internal_user_password($user, $password);
2376             // The user object should have been updated.
2377             $this->assertTrue(validate_internal_user_password($user, $password));
2378             // The database field for the user should also have been updated to the
2379             // same value.
2380             $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
2381         }
2383         $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2384         // Manually set the user's password to the md5 of the string 'password'.
2385         $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
2387         $sink = $this->redirectEvents();
2388         // Update the password.
2389         update_internal_user_password($user, 'password');
2390         $events = $sink->get_events();
2391         $sink->close();
2392         $event = array_pop($events);
2394         // Password should have been updated to a bcrypt hash.
2395         $this->assertFalse(password_is_legacy_hash($user->password));
2397         // Verify event information.
2398         $this->assertInstanceOf('\core\event\user_password_updated', $event);
2399         $this->assertSame($user->id, $event->relateduserid);
2400         $this->assertEquals(context_user::instance($user->id), $event->get_context());
2401         $this->assertEventContextNotUsed($event);
2403         // Verify recovery of property 'auth'.
2404         unset($user->auth);
2405         update_internal_user_password($user, 'newpassword');
2406         $this->assertDebuggingCalled('User record in update_internal_user_password() must include field auth',
2407                 DEBUG_DEVELOPER);
2408         $this->assertEquals('manual', $user->auth);
2409     }
2411     /**
2412      * Testing that if the password is not cached, that it does not update
2413      * the user table and fire event.
2414      */
2415     public function test_update_internal_user_password_no_cache() {
2416         $this->resetAfterTest();
2418         $user = $this->getDataGenerator()->create_user(array('auth' => 'cas'));
2419         $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2421         $sink = $this->redirectEvents();
2422         update_internal_user_password($user, 'wonkawonka');
2423         $this->assertEquals(0, $sink->count(), 'User updated event should not fire');
2424     }
2426     /**
2427      * Test if the user has a password hash, but now their auth method
2428      * says not to cache it.  Then it should update.
2429      */
2430     public function test_update_internal_user_password_update_no_cache() {
2431         $this->resetAfterTest();
2433         $user = $this->getDataGenerator()->create_user(array('password' => 'test'));
2434         $this->assertNotEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2435         $user->auth = 'cas'; // Change to a auth that does not store passwords.
2437         $sink = $this->redirectEvents();
2438         update_internal_user_password($user, 'wonkawonka');
2439         $this->assertGreaterThanOrEqual(1, $sink->count(), 'User updated event should fire');
2441         $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2442     }
2444     public function test_fullname() {
2445         global $CFG;
2447         $this->resetAfterTest();
2449         // Create a user to test the name display on.
2450         $record = array();
2451         $record['firstname'] = 'Scott';
2452         $record['lastname'] = 'Fletcher';
2453         $record['firstnamephonetic'] = 'スコット';
2454         $record['lastnamephonetic'] = 'フレチャー';
2455         $record['alternatename'] = 'No friends';
2456         $user = $this->getDataGenerator()->create_user($record);
2458         // Back up config settings for restore later.
2459         $originalcfg = new stdClass();
2460         $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
2461         $originalcfg->alternativefullnameformat = $CFG->alternativefullnameformat;
2463         // Testing existing fullnamedisplay settings.
2464         $CFG->fullnamedisplay = 'firstname';
2465         $testname = fullname($user);
2466         $this->assertSame($user->firstname, $testname);
2468         $CFG->fullnamedisplay = 'firstname lastname';
2469         $expectedname = "$user->firstname $user->lastname";
2470         $testname = fullname($user);
2471         $this->assertSame($expectedname, $testname);
2473         $CFG->fullnamedisplay = 'lastname firstname';
2474         $expectedname = "$user->lastname $user->firstname";
2475         $testname = fullname($user);
2476         $this->assertSame($expectedname, $testname);
2478         $expectedname = get_string('fullnamedisplay', null, $user);
2479         $CFG->fullnamedisplay = 'language';
2480         $testname = fullname($user);
2481         $this->assertSame($expectedname, $testname);
2483         // Test override parameter.
2484         $CFG->fullnamedisplay = 'firstname';
2485         $expectedname = "$user->firstname $user->lastname";
2486         $testname = fullname($user, true);
2487         $this->assertSame($expectedname, $testname);
2489         // Test alternativefullnameformat setting.
2490         // Test alternativefullnameformat that has been set to nothing.
2491         $CFG->alternativefullnameformat = '';
2492         $expectedname = "$user->firstname $user->lastname";
2493         $testname = fullname($user, true);
2494         $this->assertSame($expectedname, $testname);
2496         // Test alternativefullnameformat that has been set to 'language'.
2497         $CFG->alternativefullnameformat = 'language';
2498         $expectedname = "$user->firstname $user->lastname";
2499         $testname = fullname($user, true);
2500         $this->assertSame($expectedname, $testname);
2502         // Test customising the alternativefullnameformat setting with all additional name fields.
2503         $CFG->alternativefullnameformat = 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename';
2504         $expectedname = "$user->firstname $user->lastname $user->firstnamephonetic $user->lastnamephonetic $user->middlename $user->alternatename";
2505         $testname = fullname($user, true);
2506         $this->assertSame($expectedname, $testname);
2508         // Test additional name fields.
2509         $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
2510         $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
2511         $testname = fullname($user);
2512         $this->assertSame($expectedname, $testname);
2514         // Test for handling missing data.
2515         $user->middlename = null;
2516         // Parenthesis with no data.
2517         $CFG->fullnamedisplay = 'firstname (middlename) lastname';
2518         $expectedname = "$user->firstname $user->lastname";
2519         $testname = fullname($user);
2520         $this->assertSame($expectedname, $testname);
2522         // Extra spaces due to no data.
2523         $CFG->fullnamedisplay = 'firstname middlename lastname';
2524         $expectedname = "$user->firstname $user->lastname";
2525         $testname = fullname($user);
2526         $this->assertSame($expectedname, $testname);
2528         // Regular expression testing.
2529         // Remove some data from the user fields.
2530         $user->firstnamephonetic = '';
2531         $user->lastnamephonetic = '';
2533         // Removing empty brackets and excess whitespace.
2534         // All of these configurations should resolve to just firstname lastname.
2535         $configarray = array();
2536         $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
2537         $configarray[] = 'firstname lastname \'middlename\'';
2538         $configarray[] = 'firstname "firstnamephonetic" lastname';
2539         $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
2541         foreach ($configarray as $config) {
2542             $CFG->fullnamedisplay = $config;
2543             $expectedname = "$user->firstname $user->lastname";
2544             $testname = fullname($user);
2545             $this->assertSame($expectedname, $testname);
2546         }
2548         // Check to make sure that other characters are left in place.
2549         $configarray = array();
2550         $configarray['0'] = new stdClass();
2551         $configarray['0']->config = 'lastname firstname, middlename';
2552         $configarray['0']->expectedname = "$user->lastname $user->firstname,";
2553         $configarray['1'] = new stdClass();
2554         $configarray['1']->config = 'lastname firstname + alternatename';
2555         $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
2556         $configarray['2'] = new stdClass();
2557         $configarray['2']->config = 'firstname aka: alternatename';
2558         $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
2559         $configarray['3'] = new stdClass();
2560         $configarray['3']->config = 'firstname (alternatename)';
2561         $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
2562         $configarray['4'] = new stdClass();
2563         $configarray['4']->config = 'firstname [alternatename]';
2564         $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
2565         $configarray['5'] = new stdClass();
2566         $configarray['5']->config = 'firstname "lastname"';
2567         $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
2569         foreach ($configarray as $config) {
2570             $CFG->fullnamedisplay = $config->config;
2571             $expectedname = $config->expectedname;
2572             $testname = fullname($user);
2573             $this->assertSame($expectedname, $testname);
2574         }
2576         // Test debugging message displays when
2577         // fullnamedisplay setting is "normal".
2578         $CFG->fullnamedisplay = 'firstname lastname';
2579         unset($user);
2580         $user = new stdClass();
2581         $user->firstname = 'Stan';
2582         $user->lastname = 'Lee';
2583         $namedisplay = fullname($user);
2584         $this->assertDebuggingCalled();
2586         // Tidy up after we finish testing.
2587         $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
2588         $CFG->alternativefullnameformat = $originalcfg->alternativefullnameformat;
2589     }
2591     public function test_get_all_user_name_fields() {
2592         $this->resetAfterTest();
2594         // Additional names in an array.
2595         $testarray = array('firstnamephonetic' => 'firstnamephonetic',
2596                 'lastnamephonetic' => 'lastnamephonetic',
2597                 'middlename' => 'middlename',
2598                 'alternatename' => 'alternatename',
2599                 'firstname' => 'firstname',
2600                 'lastname' => 'lastname');
2601         $this->assertEquals($testarray, get_all_user_name_fields());
2603         // Additional names as a string.
2604         $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
2605         $this->assertEquals($teststring, get_all_user_name_fields(true));
2607         // Additional names as a string with an alias.
2608         $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
2609         $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
2611         // Additional name fields with a prefix - object.
2612         $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
2613                 'lastnamephonetic' => 'authorlastnamephonetic',
2614                 'middlename' => 'authormiddlename',
2615                 'alternatename' => 'authoralternatename',
2616                 'firstname' => 'authorfirstname',
2617                 'lastname' => 'authorlastname');
2618         $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
2620         // Additional name fields with an alias and a title - string.
2621         $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';
2622         $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
2624         // Test the order parameter of the function.
2625         // Returning an array.
2626         $testarray = array('firstname' => 'firstname',
2627                 'lastname' => 'lastname',
2628                 'firstnamephonetic' => 'firstnamephonetic',
2629                 'lastnamephonetic' => 'lastnamephonetic',
2630                 'middlename' => 'middlename',
2631                 'alternatename' => 'alternatename'
2632         );
2633         $this->assertEquals($testarray, get_all_user_name_fields(false, null, null, null, true));
2635         // Returning a string.
2636         $teststring = 'firstname,lastname,firstnamephonetic,lastnamephonetic,middlename,alternatename';
2637         $this->assertEquals($teststring, get_all_user_name_fields(true, null, null, null, true));
2638     }
2640     public function test_order_in_string() {
2641         $this->resetAfterTest();
2643         // Return an array in an order as they are encountered in a string.
2644         $valuearray = array('second', 'firsthalf', 'first');
2645         $formatstring = 'first firsthalf some other text (second)';
2646         $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
2647         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2649         // Try again with a different order for the format.
2650         $valuearray = array('second', 'firsthalf', 'first');
2651         $formatstring = 'firsthalf first second';
2652         $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
2653         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2655         // Try again with yet another different order for the format.
2656         $valuearray = array('second', 'firsthalf', 'first');
2657         $formatstring = 'start seconds away second firstquater first firsthalf';
2658         $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
2659         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2660     }
2662     public function test_complete_user_login() {
2663         global $USER, $DB;
2665         $this->resetAfterTest();
2666         $user = $this->getDataGenerator()->create_user();
2667         $this->setUser(0);
2669         $sink = $this->redirectEvents();
2670         $loginuser = clone($user);
2671         $this->setCurrentTimeStart();
2672         @complete_user_login($loginuser); // Hide session header errors.
2673         $this->assertSame($loginuser, $USER);
2674         $this->assertEquals($user->id, $USER->id);
2675         $events = $sink->get_events();
2676         $sink->close();
2678         $this->assertCount(1, $events);
2679         $event = reset($events);
2680         $this->assertInstanceOf('\core\event\user_loggedin', $event);
2681         $this->assertEquals('user', $event->objecttable);
2682         $this->assertEquals($user->id, $event->objectid);
2683         $this->assertEquals(context_system::instance()->id, $event->contextid);
2684         $this->assertEventContextNotUsed($event);
2686         $user = $DB->get_record('user', array('id'=>$user->id));
2688         $this->assertTimeCurrent($user->firstaccess);
2689         $this->assertTimeCurrent($user->lastaccess);
2691         $this->assertTimeCurrent($USER->firstaccess);
2692         $this->assertTimeCurrent($USER->lastaccess);
2693         $this->assertTimeCurrent($USER->currentlogin);
2694         $this->assertSame(sesskey(), $USER->sesskey);
2695         $this->assertTimeCurrent($USER->preference['_lastloaded']);
2696         $this->assertObjectNotHasAttribute('password', $USER);
2697         $this->assertObjectNotHasAttribute('description', $USER);
2698     }
2700     /**
2701      * Test require_logout.
2702      */
2703     public function test_require_logout() {
2704         $this->resetAfterTest();
2705         $user = $this->getDataGenerator()->create_user();
2706         $this->setUser($user);
2708         $this->assertTrue(isloggedin());
2710         // Logout user and capture event.
2711         $sink = $this->redirectEvents();
2712         require_logout();
2713         $events = $sink->get_events();
2714         $sink->close();
2715         $event = array_pop($events);
2717         // Check if user is logged out.
2718         $this->assertFalse(isloggedin());
2720         // Test Event.
2721         $this->assertInstanceOf('\core\event\user_loggedout', $event);
2722         $this->assertSame($user->id, $event->objectid);
2723         $this->assertSame('user_logout', $event->get_legacy_eventname());
2724         $this->assertEventLegacyData($user, $event);
2725         $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
2726             $event->objectid);
2727         $this->assertEventLegacyLogData($expectedlogdata, $event);
2728         $this->assertEventContextNotUsed($event);
2729     }
2731     /**
2732      * A data provider for testing email messageid
2733      */
2734     public function generate_email_messageid_provider() {
2735         return array(
2736             'nopath' => array(
2737                 'wwwroot' => 'http://www.example.com',
2738                 'ids' => array(
2739                     'a-custom-id' => '<a-custom-id@www.example.com>',
2740                     'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash@www.example.com>',
2741                 ),
2742             ),
2743             'path' => array(
2744                 'wwwroot' => 'http://www.example.com/path/subdir',
2745                 'ids' => array(
2746                     'a-custom-id' => '<a-custom-id/path/subdir@www.example.com>',
2747                     'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash/path/subdir@www.example.com>',
2748                 ),
2749             ),
2750         );
2751     }
2753     /**
2754      * Test email message id generation
2755      *
2756      * @dataProvider generate_email_messageid_provider
2757      *
2758      * @param string $wwwroot The wwwroot
2759      * @param array $msgids An array of msgid local parts and the final result
2760      */
2761     public function test_generate_email_messageid($wwwroot, $msgids) {
2762         global $CFG;
2764         $this->resetAfterTest();
2765         $CFG->wwwroot = $wwwroot;
2767         foreach ($msgids as $local => $final) {
2768             $this->assertEquals($final, generate_email_messageid($local));
2769         }
2770     }
2772     /**
2773      * A data provider for testing email diversion
2774      */
2775     public function diverted_emails_provider() {
2776         return array(
2777             'nodiverts' => array(
2778                 'divertallemailsto' => null,
2779                 'divertallemailsexcept' => null,
2780                 array(
2781                     'foo@example.com',
2782                     'test@real.com',
2783                     'fred.jones@example.com',
2784                     'dev1@dev.com',
2785                     'fred@example.com',
2786                     'fred+verp@example.com',
2787                 ),
2788                 false,
2789             ),
2790             'alldiverts' => array(
2791                 'divertallemailsto' => 'somewhere@elsewhere.com',
2792                 'divertallemailsexcept' => null,
2793                 array(
2794                     'foo@example.com',
2795                     'test@real.com',
2796                     'fred.jones@example.com',
2797                     'dev1@dev.com',
2798                     'fred@example.com',
2799                     'fred+verp@example.com',
2800                 ),
2801                 true,
2802             ),
2803             'alsodiverts' => array(
2804                 'divertallemailsto' => 'somewhere@elsewhere.com',
2805                 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
2806                 array(
2807                     'foo@example.com',
2808                     'test@real.com',
2809                     'fred.jones@example.com',
2810                 ),
2811                 true,
2812             ),
2813             'divertsexceptions' => array(
2814                 'divertallemailsto' => 'somewhere@elsewhere.com',
2815                 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
2816                 array(
2817                     'dev1@dev.com',
2818                     'fred@example.com',
2819                     'fred+verp@example.com',
2820                 ),
2821                 false,
2822             ),
2823         );
2824     }
2826     /**
2827      * Test email diversion
2828      *
2829      * @dataProvider diverted_emails_provider
2830      *
2831      * @param string $divertallemailsto An optional email address
2832      * @param string $divertallemailsexcept An optional exclusion list
2833      * @param array $addresses An array of test addresses
2834      * @param boolean $expected Expected result
2835      */
2836     public function test_email_should_be_diverted($divertallemailsto, $divertallemailsexcept, $addresses, $expected) {
2837         global $CFG;
2839         $this->resetAfterTest();
2840         $CFG->divertallemailsto = $divertallemailsto;
2841         $CFG->divertallemailsexcept = $divertallemailsexcept;
2843         foreach ($addresses as $address) {
2844             $this->assertEquals($expected, email_should_be_diverted($address));
2845         }
2846     }
2848     public function test_email_to_user() {
2849         global $CFG;
2851         $this->resetAfterTest();
2853         $user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
2854         $user2 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
2855         $user3 = $this->getDataGenerator()->create_user(array('maildisplay' => 0));
2856         set_config('allowedemaildomains', "example.com\r\nmoodle.org");
2858         $subject = 'subject';
2859         $messagetext = 'message text';
2860         $subject2 = 'subject 2';
2861         $messagetext2 = 'message text 2';
2863         // Close the default email sink.
2864         $sink = $this->redirectEmails();
2865         $sink->close();
2867         $CFG->noemailever = true;
2868         $this->assertNotEmpty($CFG->noemailever);
2869         email_to_user($user1, $user2, $subject, $messagetext);
2870         $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
2872         unset_config('noemailever');
2874         email_to_user($user1, $user2, $subject, $messagetext);
2875         $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2877         $sink = $this->redirectEmails();
2878         email_to_user($user1, $user2, $subject, $messagetext);
2879         email_to_user($user2, $user1, $subject2, $messagetext2);
2880         $this->assertSame(2, $sink->count());
2881         $result = $sink->get_messages();
2882         $this->assertCount(2, $result);
2883         $sink->close();
2885         $this->assertSame($subject, $result[0]->subject);
2886         $this->assertSame($messagetext, trim($result[0]->body));
2887         $this->assertSame($user1->email, $result[0]->to);
2888         $this->assertSame($user2->email, $result[0]->from);
2890         $this->assertSame($subject2, $result[1]->subject);
2891         $this->assertSame($messagetext2, trim($result[1]->body));
2892         $this->assertSame($user2->email, $result[1]->to);
2893         $this->assertSame($user1->email, $result[1]->from);
2895         email_to_user($user1, $user2, $subject, $messagetext);
2896         $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2898         // Test that an empty noreplyaddress will default to a no-reply address.
2899         $sink = $this->redirectEmails();
2900         email_to_user($user1, $user3, $subject, $messagetext);
2901         $result = $sink->get_messages();
2902         $this->assertEquals($CFG->noreplyaddress, $result[0]->from);
2903         $sink->close();
2904         set_config('noreplyaddress', '');
2905         $sink = $this->redirectEmails();
2906         email_to_user($user1, $user3, $subject, $messagetext);
2907         $result = $sink->get_messages();
2908         $this->assertEquals('noreply@www.example.com', $result[0]->from);
2909         $sink->close();
2911         // Test $CFG->allowedemaildomains.
2912         set_config('noreplyaddress', 'noreply@www.example.com');
2913         $this->assertNotEmpty($CFG->allowedemaildomains);
2914         $sink = $this->redirectEmails();
2915         email_to_user($user1, $user2, $subject, $messagetext);
2916         unset_config('allowedemaildomains');
2917         email_to_user($user1, $user2, $subject, $messagetext);
2918         $result = $sink->get_messages();
2919         $this->assertNotEquals($CFG->noreplyaddress, $result[0]->from);
2920         $this->assertEquals($CFG->noreplyaddress, $result[1]->from);
2921         $sink->close();
2923         // Try to send an unsafe attachment, we should see an error message in the eventual mail body.
2924         $attachment = '../test.txt';
2925         $attachname = 'txt';
2927         $sink = $this->redirectEmails();
2928         email_to_user($user1, $user2, $subject, $messagetext, '', $attachment, $attachname);
2929         $this->assertSame(1, $sink->count());
2930         $result = $sink->get_messages();
2931         $this->assertCount(1, $result);
2932         $this->assertContains('error.txt', $result[0]->body);
2933         $this->assertContains('Error in attachment.  User attempted to attach a filename with a unsafe name.', $result[0]->body);
2934         $sink->close();
2935     }
2937     /**
2938      * Test setnew_password_and_mail.
2939      */
2940     public function test_setnew_password_and_mail() {
2941         global $DB, $CFG;
2943         $this->resetAfterTest();
2945         $user = $this->getDataGenerator()->create_user();
2947         // Update user password.
2948         $sink = $this->redirectEvents();
2949         $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
2950         setnew_password_and_mail($user);
2951         $events = $sink->get_events();
2952         $sink->close();
2953         $sink2->close();
2954         $event = array_pop($events);
2956         // Test updated value.
2957         $dbuser = $DB->get_record('user', array('id' => $user->id));
2958         $this->assertSame($user->firstname, $dbuser->firstname);
2959         $this->assertNotEmpty($dbuser->password);
2961         // Test event.
2962         $this->assertInstanceOf('\core\event\user_password_updated', $event);
2963         $this->assertSame($user->id, $event->relateduserid);
2964         $this->assertEquals(context_user::instance($user->id), $event->get_context());
2965         $this->assertEventContextNotUsed($event);
2966     }
2968     /**
2969      * Data provider for test_generate_confirmation_link
2970      * @return Array of confirmation urls and expected resultant confirmation links
2971      */
2972     public function generate_confirmation_link_provider() {
2973         global $CFG;
2974         return [
2975             "Simple name" => [
2976                 "username" => "simplename",
2977                 "confirmationurl" => null,
2978                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/simplename"
2979             ],
2980             "Period in between words in username" => [
2981                 "username" => "period.inbetween",
2982                 "confirmationurl" => null,
2983                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/period%2Einbetween"
2984             ],
2985             "Trailing periods in username" => [
2986                 "username" => "trailingperiods...",
2987                 "confirmationurl" => null,
2988                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/trailingperiods%2E%2E%2E"
2989             ],
2990             "At symbol in username" => [
2991                 "username" => "at@symbol",
2992                 "confirmationurl" => null,
2993                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/at%40symbol"
2994             ],
2995             "Dash symbol in username" => [
2996                 "username" => "has-dash",
2997                 "confirmationurl" => null,
2998                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/has-dash"
2999             ],
3000             "Underscore in username" => [
3001                 "username" => "under_score",
3002                 "confirmationurl" => null,
3003                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/under_score"
3004             ],
3005             "Many different characters in username" => [
3006                 "username" => "many_-.@characters@_@-..-..",
3007                 "confirmationurl" => null,
3008                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3009             ],
3010             "Custom relative confirmation url" => [
3011                 "username" => "many_-.@characters@_@-..-..",
3012                 "confirmationurl" => "/custom/local/url.php",
3013                 "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3014             ],
3015             "Custom relative confirmation url with parameters" => [
3016                 "username" => "many_-.@characters@_@-..-..",
3017                 "confirmationurl" => "/custom/local/url.php?with=param",
3018                 "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3019             ],
3020             "Custom local confirmation url" => [
3021                 "username" => "many_-.@characters@_@-..-..",
3022                 "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php",
3023                 "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3024             ],
3025             "Custom local confirmation url with parameters" => [
3026                 "username" => "many_-.@characters@_@-..-..",
3027                 "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php?with=param",
3028                 "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3029             ],
3030             "Custom external confirmation url" => [
3031                 "username" => "many_-.@characters@_@-..-..",
3032                 "confirmationurl" => "http://moodle.org/custom/external/url.php",
3033                 "expected" => "http://moodle.org/custom/external/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3034             ],
3035             "Custom external confirmation url with parameters" => [
3036                 "username" => "many_-.@characters@_@-..-..",
3037                 "confirmationurl" => "http://moodle.org/ext.php?with=some&param=eters",
3038                 "expected" => "http://moodle.org/ext.php?with=some&param=eters&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3039             ],
3040             "Custom external confirmation url with parameters" => [
3041                 "username" => "many_-.@characters@_@-..-..",
3042                 "confirmationurl" => "http://moodle.org/ext.php?with=some&data=test",
3043                 "expected" => "http://moodle.org/ext.php?with=some&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3044             ],
3045         ];
3046     }
3048     /**
3049      * Test generate_confirmation_link
3050      * @dataProvider generate_confirmation_link_provider
3051      * @param string $username The name of the user
3052      * @param string $confirmationurl The url the user should go to to confirm
3053      * @param string $expected The expected url of the confirmation link
3054      */
3055     public function test_generate_confirmation_link($username, $confirmationurl, $expected) {
3056         $this->resetAfterTest();
3057         $sink = $this->redirectEmails();
3059         $user = $this->getDataGenerator()->create_user(
3060             [
3061                 "username" => $username,
3062                 "confirmed" => false,
3063                 "email" => 'test@example.com',
3064             ]
3065         );
3067         send_confirmation_email($user, $confirmationurl);
3068         $sink->close();
3069         $messages = $sink->get_messages();
3070         $message = array_shift($messages);
3071         $messagebody = quoted_printable_decode($message->body);
3073         $this->assertContains($expected, $messagebody);
3074     }
3076     /**
3077      * Test generate_confirmation_link with custom admin link
3078      */
3079     public function test_generate_confirmation_link_with_custom_admin() {
3080         global $CFG;
3082         $this->resetAfterTest();
3083         $sink = $this->redirectEmails();
3085         $admin = $CFG->admin;
3086         $CFG->admin = 'custom/admin/path';
3088         $user = $this->getDataGenerator()->create_user(
3089             [
3090                 "username" => "many_-.@characters@_@-..-..",
3091                 "confirmed" => false,
3092                 "email" => 'test@example.com',
3093             ]
3094         );
3095         $confirmationurl = "/admin/test.php?with=params";
3096         $expected = $CFG->wwwroot . "/" . $CFG->admin . "/test.php?with=params&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E";
3098         send_confirmation_email($user, $confirmationurl);
3099         $sink->close();
3100         $messages = $sink->get_messages();
3101         $message = array_shift($messages);
3102         $messagebody = quoted_printable_decode($message->body);
3104         $sink->close();
3105         $this->assertContains($expected, $messagebody);
3107         $CFG->admin = $admin;
3108     }
3111     /**
3112      * Test remove_course_content deletes course contents
3113      * TODO Add asserts to verify other data related to course is deleted as well.
3114      */
3115     public function test_remove_course_contents() {
3117         $this->resetAfterTest();
3119         $course = $this->getDataGenerator()->create_course();
3120         $user = $this->getDataGenerator()->create_user();
3121         $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
3122         $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id));
3124         $this->assertNotEquals(false, note_load($note->id));
3125         remove_course_contents($course->id, false);
3126         $this->assertFalse(note_load($note->id));
3127     }
3129     /**
3130      * Test function username_load_fields_from_object().
3131      */
3132     public function test_username_load_fields_from_object() {
3133         $this->resetAfterTest();
3135         // This object represents the information returned from an sql query.
3136         $userinfo = new stdClass();
3137         $userinfo->userid = 1;
3138         $userinfo->username = 'loosebruce';
3139         $userinfo->firstname = 'Bruce';
3140         $userinfo->lastname = 'Campbell';
3141         $userinfo->firstnamephonetic = 'ブルース';
3142         $userinfo->lastnamephonetic = 'カンベッル';
3143         $userinfo->middlename = '';
3144         $userinfo->alternatename = '';
3145         $userinfo->email = '';
3146         $userinfo->picture = 23;
3147         $userinfo->imagealt = 'Michael Jordan draining another basket.';
3148         $userinfo->idnumber = 3982;
3150         // Just user name fields.
3151         $user = new stdClass();
3152         $user = username_load_fields_from_object($user, $userinfo);
3153         $expectedarray = new stdClass();
3154         $expectedarray->firstname = 'Bruce';
3155         $expectedarray->lastname = 'Campbell';
3156         $expectedarray->firstnamephonetic = 'ブルース';
3157         $expectedarray->lastnamephonetic = 'カンベッル';
3158         $expectedarray->middlename = '';
3159         $expectedarray->alternatename = '';
3160         $this->assertEquals($user, $expectedarray);
3162         // User information for showing a picture.
3163         $user = new stdClass();
3164         $additionalfields = explode(',', user_picture::fields());
3165         $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
3166         $user->id = $userinfo->userid;
3167         $expectedarray = new stdClass();
3168         $expectedarray->id = 1;
3169         $expectedarray->firstname = 'Bruce';
3170         $expectedarray->lastname = 'Campbell';
3171         $expectedarray->firstnamephonetic = 'ブルース';
3172         $expectedarray->lastnamephonetic = 'カンベッル';
3173         $expectedarray->middlename = '';
3174         $expectedarray->alternatename = '';
3175         $expectedarray->email = '';
3176         $expectedarray->picture = 23;
3177         $expectedarray->imagealt = 'Michael Jordan draining another basket.';
3178         $this->assertEquals($user, $expectedarray);
3180         // Alter the userinfo object to have a prefix.
3181         $userinfo->authorfirstname = 'Bruce';
3182         $userinfo->authorlastname = 'Campbell';
3183         $userinfo->authorfirstnamephonetic = 'ブルース';
3184         $userinfo->authorlastnamephonetic = 'カンベッル';
3185         $userinfo->authormiddlename = '';
3186         $userinfo->authorpicture = 23;
3187         $userinfo->authorimagealt = 'Michael Jordan draining another basket.';
3188         $userinfo->authoremail = 'test@example.com';
3191         // Return an object with user picture information.
3192         $user = new stdClass();
3193         $additionalfields = explode(',', user_picture::fields());
3194         $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
3195         $user->id = $userinfo->userid;
3196         $expectedarray = new stdClass();
3197         $expectedarray->id = 1;
3198         $expectedarray->firstname = 'Bruce';
3199         $expectedarray->lastname = 'Campbell';
3200         $expectedarray->firstnamephonetic = 'ブルース';
3201         $expectedarray->lastnamephonetic = 'カンベッル';
3202         $expectedarray->middlename = '';
3203         $expectedarray->alternatename = '';
3204         $expectedarray->email = 'test@example.com';
3205         $expectedarray->picture = 23;
3206         $expectedarray->imagealt = 'Michael Jordan draining another basket.';
3207         $this->assertEquals($user, $expectedarray);
3208     }
3210     /**
3211      * Test function count_words().
3212      */
3213     public function test_count_words() {
3214         $count = count_words("one two three'four");
3215         $this->assertEquals(3, $count);
3217         $count = count_words('one+two three’four');
3218         $this->assertEquals(3, $count);
3220         $count = count_words('one"two three-four');
3221         $this->assertEquals(2, $count);
3223         $count = count_words('one@two three_four');
3224         $this->assertEquals(4, $count);
3226         $count = count_words('one\two three/four');
3227         $this->assertEquals(4, $count);
3229         $count = count_words(' one ... two &nbsp; three...four ');
3230         $this->assertEquals(4, $count);
3232         $count = count_words('one.2 3,four');
3233         $this->assertEquals(4, $count);
3235         $count = count_words('1³ £2 €3.45 $6,789');
3236         $this->assertEquals(4, $count);
3238         $count = count_words('one—two ブルース カンベッル');
3239         $this->assertEquals(4, $count);
3241         $count = count_words('one…two ブルース … カンベッル');
3242         $this->assertEquals(4, $count);
3243     }
3244     /**
3245      * Tests the getremoteaddr() function.
3246      */
3247     public function test_getremoteaddr() {
3248         $xforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null;
3250         $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
3251         $noip = getremoteaddr('1.1.1.1');
3252         $this->assertEquals('1.1.1.1', $noip);
3254         $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
3255         $noip = getremoteaddr();
3256         $this->assertEquals('0.0.0.0', $noip);
3258         $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1';
3259         $singleip = getremoteaddr();
3260         $this->assertEquals('127.0.0.1', $singleip);
3262         $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2';
3263         $twoip = getremoteaddr();
3264         $this->assertEquals('127.0.0.1', $twoip);
3266         $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2, 127.0.0.3';
3267         $threeip = getremoteaddr();
3268         $this->assertEquals('127.0.0.1', $threeip);
3270         $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1:65535,127.0.0.2';
3271         $portip = getremoteaddr();
3272         $this->assertEquals('127.0.0.1', $portip);
3274         $_SERVER['HTTP_X_FORWARDED_FOR'] = '0:0:0:0:0:0:0:1,127.0.0.2';
3275         $portip = getremoteaddr();
3276         $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3278         $_SERVER['HTTP_X_FORWARDED_FOR'] = '0::1,127.0.0.2';
3279         $portip = getremoteaddr();
3280         $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3282         $_SERVER['HTTP_X_FORWARDED_FOR'] = '[0:0:0:0:0:0:0:1]:65535,127.0.0.2';
3283         $portip = getremoteaddr();
3284         $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3286         $_SERVER['HTTP_X_FORWARDED_FOR'] = $xforwardedfor;
3288     }
3290     /*
3291      * Test emulation of random_bytes() function.
3292      */
3293     public function test_random_bytes_emulate() {
3294         $result = random_bytes_emulate(10);
3295         $this->assertSame(10, strlen($result));
3296         $this->assertnotSame($result, random_bytes_emulate(10));
3298         $result = random_bytes_emulate(21);
3299         $this->assertSame(21, strlen($result));
3300         $this->assertnotSame($result, random_bytes_emulate(21));
3302         $result = random_bytes_emulate(666);
3303         $this->assertSame(666, strlen($result));
3305         $result = random_bytes_emulate(40);
3306         $this->assertSame(40, strlen($result));
3308         $this->assertDebuggingNotCalled();
3310         $result = random_bytes_emulate(0);
3311         $this->assertSame('', $result);
3312         $this->assertDebuggingCalled();
3314         $result = random_bytes_emulate(-1);
3315         $this->assertSame('', $result);
3316         $this->assertDebuggingCalled();
3317     }
3319     /**
3320      * Test function for creation of random strings.
3321      */
3322     public function test_random_string() {
3323         $pool = 'a-zA-Z0-9';
3325         $result = random_string(10);
3326         $this->assertSame(10, strlen($result));
3327         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3328         $this->assertNotSame($result, random_string(10));
3330         $result = random_string(21);
3331         $this->assertSame(21, strlen($result));
3332         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3333         $this->assertNotSame($result, random_string(21));
3335         $result = random_string(666);
3336         $this->assertSame(666, strlen($result));
3337         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3339         $result = random_string();
3340         $this->assertSame(15, strlen($result));
3341         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3343         $this->assertDebuggingNotCalled();
3345         $result = random_string(0);
3346         $this->assertSame('', $result);
3347         $this->assertDebuggingCalled();
3349         $result = random_string(-1);
3350         $this->assertSame('', $result);
3351         $this->assertDebuggingCalled();
3352     }
3354     /**
3355      * Test function for creation of complex random strings.
3356      */
3357     public function test_complex_random_string() {
3358         $pool = preg_quote('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#%^&*()_+-=[];,./<>?:{} ', '/');
3360         $result = complex_random_string(10);
3361         $this->assertSame(10, strlen($result));
3362         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3363         $this->assertNotSame($result, complex_random_string(10));
3365         $result = complex_random_string(21);
3366         $this->assertSame(21, strlen($result));
3367         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3368         $this->assertNotSame($result, complex_random_string(21));
3370         $result = complex_random_string(666);
3371         $this->assertSame(666, strlen($result));
3372         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3374         $result = complex_random_string();
3375         $this->assertEquals(28, strlen($result), '', 4); // Expected length is 24 - 32.
3376         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3378         $this->assertDebuggingNotCalled();
3380         $result = complex_random_string(0);
3381         $this->assertSame('', $result);
3382         $this->assertDebuggingCalled();
3384         $result = complex_random_string(-1);
3385         $this->assertSame('', $result);
3386         $this->assertDebuggingCalled();
3387     }
3389     /**
3390      * Data provider for private ips.
3391      */
3392     public function data_private_ips() {
3393         return array(
3394             array('10.0.0.0'),
3395             array('172.16.0.0'),
3396             array('192.168.1.0'),
3397             array('fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c'),
3398             array('fdc6:c46b:bb8f:7d4c:fdc6:c46b:bb8f:7d4c'),
3399             array('fdc6:c46b:bb8f:7d4c:0000:8a2e:0370:7334'),
3400             array('127.0.0.1'), // This has been buggy in past: https://bugs.php.net/bug.php?id=53150.
3401         );
3402     }
3404     /**
3405      * Checks ip_is_public returns false for private ips.
3406      *
3407      * @param string $ip the ipaddress to test
3408      * @dataProvider data_private_ips
3409      */
3410     public function test_ip_is_public_private_ips($ip) {
3411         $this->assertFalse(ip_is_public($ip));
3412     }
3414     /**
3415      * Data provider for public ips.
3416      */
3417     public function data_public_ips() {
3418         return array(
3419             array('2400:cb00:2048:1::8d65:71b3'),
3420             array('2400:6180:0:d0::1b:2001'),
3421             array('141.101.113.179'),
3422             array('123.45.67.178'),
3423         );
3424     }
3426     /**
3427      * Checks ip_is_public returns true for public ips.
3428      *
3429      * @param string $ip the ipaddress to test
3430      * @dataProvider data_public_ips
3431      */
3432     public function test_ip_is_public_public_ips($ip) {
3433         $this->assertTrue(ip_is_public($ip));
3434     }
3436     /**
3437      * Test the function can_send_from_real_email_address
3438      *
3439      * @param string $email Email address for the from user.
3440      * @param int $display The user's email display preference.
3441      * @param bool $samecourse Are the users in the same course?
3442      * @param string $config The CFG->allowedemaildomains config values
3443      * @param bool $result The expected result.
3444      * @dataProvider data_can_send_from_real_email_address
3445      */
3446     public function test_can_send_from_real_email_address($email, $display, $samecourse, $config, $result) {
3447         $this->resetAfterTest();
3449         $fromuser = $this->getDataGenerator()->create_user();
3450         $touser = $this->getDataGenerator()->create_user();
3451         $course = $this->getDataGenerator()->create_course();
3452         set_config('allowedemaildomains', $config);
3454         $fromuser->email = $email;
3455         $fromuser->maildisplay = $display;
3456         if ($samecourse) {
3457             $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student');
3458             $this->getDataGenerator()->enrol_user($touser->id, $course->id, 'student');
3459         } else {
3460             $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student');
3461         }
3462         $this->assertEquals($result, can_send_from_real_email_address($fromuser, $touser));
3463     }
3465     /**
3466      * Data provider for test_can_send_from_real_email_address.
3467      *
3468      * @return array Returns an array of test data for the above function.
3469      */
3470     public function data_can_send_from_real_email_address() {
3471         return [
3472             // Test from email is in allowed domain.
3473             // Test that from display is set to show no one.
3474             [
3475                 'email' => 'fromuser@example.com',
3476                 'display' => core_user::MAILDISPLAY_HIDE,
3477                 'samecourse' => false,
3478                 'config' => "example.com\r\ntest.com",
3479                 'result' => false
3480             ],
3481             // Test that from display is set to course members only (course member).
3482             [
3483                 'email' => 'fromuser@example.com',
3484                 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
3485                 'samecourse' => true,
3486                 'config' => "example.com\r\ntest.com",
3487                 'result' => true
3488             ],
3489             // Test that from display is set to course members only (Non course member).
3490             [
3491                 'email' => 'fromuser@example.com',
3492                 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
3493                 'samecourse' => false,
3494                 'config' => "example.com\r\ntest.com",
3495                 'result' => false
3496             ],
3497             // Test that from display is set to show everyone.
3498             [
3499                 'email' => 'fromuser@example.com',
3500                 'display' => core_user::MAILDISPLAY_EVERYONE,
3501                 'samecourse' => false,
3502                 'config' => "example.com\r\ntest.com",
3503                 'result' => true
3504             ],
3505             // Test a few different config value formats for parsing correctness.
3506             [
3507                 'email' => 'fromuser@example.com',
3508                 'display' => core_user::MAILDISPLAY_EVERYONE,
3509                 'samecourse' => false,
3510                 'config' => "\n test.com\nexample.com \n",
3511                 'result' => true
3512             ],
3513             [
3514                 'email' => 'fromuser@example.com',
3515                 'display' => core_user::MAILDISPLAY_EVERYONE,
3516                 'samecourse' => false,
3517                 'config' => "\r\n example.com \r\n test.com \r\n",
3518                 'result' => true
3519             ],
3521             // Test from email is not in allowed domain.
3522             // Test that from display is set to show no one.
3523             [   'email' => 'fromuser@moodle.com',
3524                 'display' => core_user::MAILDISPLAY_HIDE,
3525                 'samecourse' => false,
3526                 'config' => "example.com\r\ntest.com",
3527                 'result' => false
3528             ],
3529             // Test that from display is set to course members only (course member).
3530             [   'email' => 'fromuser@moodle.com',
3531                 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
3532                 'samecourse' => true,
3533                 'config' => "example.com\r\ntest.com",
3534                 'result' => false
3535             ],
3536             // Test that from display is set to course members only (Non course member.
3537             [   'email' => 'fromuser@moodle.com',
3538                 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
3539                 'samecourse' => false,
3540                 'config' => "example.com\r\ntest.com",
3541                 'result' => false
3542             ],
3543             // Test that from display is set to show everyone.
3544             [   'email' => 'fromuser@moodle.com',
3545                 'display' => core_user::MAILDISPLAY_EVERYONE,
3546                 'samecourse' => false,
3547                 'config' => "example.com\r\ntest.com",
3548                 'result' => false
3549             ],
3550             // Test a few erroneous config value and confirm failure.
3551             [   'email' => 'fromuser@moodle.com',
3552                 'display' => core_user::MAILDISPLAY_EVERYONE,
3553                 'samecourse' => false,
3554                 'config' => "\r\n   \r\n",
3555                 'result' => false
3556             ],
3557             [   'email' => 'fromuser@moodle.com',
3558                 'display' => core_user::MAILDISPLAY_EVERYONE,
3559                 'samecourse' => false,
3560                 'config' => " \n   \n \n ",
3561                 'result' => false
3562             ],
3563         ];
3564     }
3566     /**
3567      * Test that generate_email_processing_address() returns valid email address.
3568      */
3569     public function test_generate_email_processing_address() {
3570         global $CFG;
3571         $this->resetAfterTest();
3573         $data = (object)[
3574             'id' => 42,
3575             'email' => 'my.email+from_moodle@example.com',
3576         ];
3578         $modargs = 'B'.base64_encode(pack('V', $data->id)).substr(md5($data->email), 0, 16);
3580         $CFG->maildomain = 'example.com';
3581         $CFG->mailprefix = 'mdl+';
3582         $this->assertTrue(validate_email(generate_email_processing_address(0, $modargs)));
3584         $CFG->maildomain = 'mail.example.com';
3585         $CFG->mailprefix = 'mdl-';
3586         $this->assertTrue(validate_email(generate_email_processing_address(23, $modargs)));
3587     }
3589     /**
3590      * Test safe method unserialize_array().
3591      */
3592     public function test_unserialize_array() {
3593         $a = [1, 2, 3];
3594         $this->assertEquals($a, unserialize_array(serialize($a)));
3595         $this->assertEquals($a, unserialize_array(serialize($a)));
3596         $a = ['a' => 1, 2 => 2, 'b' => 'cde'];
3597         $this->assertEquals($a, unserialize_array(serialize($a)));
3598         $this->assertEquals($a, unserialize_array(serialize($a)));
3599         $a = ['a' => 1, 2 => 2, 'b' => 'c"d"e'];
3600         $this->assertEquals($a, unserialize_array(serialize($a)));
3601         $a = ['a' => 1, 2 => ['c' => 'd', 'e' => 'f'], 'b' => 'cde'];
3602         $this->assertEquals($a, unserialize_array(serialize($a)));
3604         // Can not unserialize if any string contains semicolons.
3605         $a = ['a' => 1, 2 => 2, 'b' => 'c"d";e'];
3606         $this->assertEquals(false, unserialize_array(serialize($a)));
3608         // Can not unserialize if there are any objects.
3609         $a = (object)['a' => 1, 2 => 2, 'b' => 'cde'];
3610         $this->assertEquals(false, unserialize_array(serialize($a)));
3611         $a = ['a' => 1, 2 => 2, 'b' => (object)['a' => 'cde']];
3612         $this->assertEquals(false, unserialize_array(serialize($a)));
3614         // Array used in the grader report.
3615         $a = array('aggregatesonly' => [51, 34], 'gradesonly' => [21, 45, 78]);
3616         $this->assertEquals($a, unserialize_array(serialize($a)));
3617     }
3619     /**
3620      * Test that the component_class_callback returns the correct default value when the class was not found.
3621      *
3622      * @dataProvider component_class_callback_default_provider
3623      * @param $default
3624      */
3625     public function test_component_class_callback_not_found($default) {
3626         $this->assertSame($default, component_class_callback('thisIsNotTheClassYouWereLookingFor', 'anymethod', [], $default));
3627     }
3629     /**
3630      * Test that the component_class_callback returns the correct default value when the class was not found.
3631      *
3632      * @dataProvider component_class_callback_default_provider
3633      * @param $default
3634      */
3635     public function test_component_class_callback_method_not_found($default) {
3636         require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
3638         $this->assertSame($default, component_class_callback(test_component_class_callback_example::class, 'this_is_not_the_method_you_were_looking_for', ['abc'], $default));
3639     }
3641     /**
3642      * Test that the component_class_callback returns the default when the method returned null.
3643      *
3644      * @dataProvider component_class_callback_default_provider
3645      * @param $default
3646      */
3647     public function test_component_class_callback_found_returns_null($default) {
3648         require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
3650         $this->assertSame($default, component_class_callback(test_component_class_callback_example::class, 'method_returns_value', [null], $default));
3651         $this->assertSame($default, component_class_callback(test_component_class_callback_child_example::class, 'method_returns_value', [null], $default));
3652     }
3654     /**
3655      * Test that the component_class_callback returns the expected value and not the default when there was a value.
3656      *
3657      * @dataProvider component_class_callback_data_provider
3658      * @param $default
3659      */
3660     public function test_component_class_callback_found_returns_value($value) {
3661         require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
3663         $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'));
3664         $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'));
3665     }
3667     /**
3668      * Test that the component_class_callback handles multiple params correctly.
3669      *
3670      * @dataProvider component_class_callback_multiple_params_provider
3671      * @param $default
3672      */
3673     public function test_component_class_callback_found_accepts_multiple($params, $count) {
3674         require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
3676         $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'));
3677         $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'));
3678     }
3680     /**
3681      * Data provider with list of default values for user in component_class_callback tests.
3682      *
3683      * @return array
3684      */
3685     public function component_class_callback_default_provider() {
3686         return [
3687             'null' => [null],
3688             'empty string' => [''],
3689             'string' => ['This is a string'],
3690             'int' => [12345],
3691             'stdClass' => [(object) ['this is my content']],
3692             'array' => [['a' => 'b',]],
3693         ];
3694     }
3696     /**
3697      * Data provider with list of default values for user in component_class_callback tests.
3698      *
3699      * @return array
3700      */
3701     public function component_class_callback_data_provider() {
3702         return [
3703             'empty string' => [''],
3704             'string' => ['This is a string'],
3705             'int' => [12345],
3706             'stdClass' => [(object) ['this is my content']],
3707             'array' => [['a' => 'b',]],
3708         ];
3709     }
3711     /**
3712      * Data provider with list of default values for user in component_class_callback tests.
3713      *
3714      * @return array
3715      */
3716     public function component_class_callback_multiple_params_provider() {
3717         return [
3718             'empty array' => [
3719                 [],
3720                 0,
3721             ],
3722             'string value' => [
3723                 ['one'],
3724                 1,
3725             ],
3726             'string values' => [
3727                 ['one', 'two'],
3728                 2,
3729             ],
3730             'arrays' => [
3731                 [[], []],
3732                 2,
3733             ],
3734             'nulls' => [
3735                 [null, null, null, null],
3736                 4,
3737             ],
3738             'mixed' => [
3739                 ['a', 1, null, (object) [], []],
3740                 5,
3741             ],
3742         ];
3743     }