454d9cc1939b7ac30fe5f2f4fd6e045c58d53f74
[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));
685         // Test filename that contains more than 90 characters.
686         $filename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium totam rem';
687         $this->assertSame('sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laud',
688             clean_param($filename, PARAM_FILE));
689         // Filename contains extension.
690         $this->assertSame('sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laud.zip',
691             clean_param($filename . '.zip', PARAM_FILE));
693         // The following behaviours have been maintained although they seem a little odd.
694         $this->assertSame('funnything', clean_param('funny:thing', PARAM_FILE));
695         $this->assertSame('.currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_FILE));
696         $this->assertSame('ctempwindowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_FILE));
697         $this->assertSame('homeuserlinuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_FILE));
698         $this->assertSame('~myfile.txt', clean_param('~/myfile.txt', PARAM_FILE));
699     }
701     public function test_clean_param_path() {
702         $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_PATH));
703         $this->assertSame('bad/file.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH));
704         $this->assertSame('/parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_PATH));
705         $this->assertSame('/grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_PATH));
706         $this->assertSame('/winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_PATH));
707         $this->assertSame('/wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_PATH));
708         $this->assertSame('funnything', clean_param('funny:thing', PARAM_PATH));
709         $this->assertSame('./here', clean_param('./././here', PARAM_PATH));
710         $this->assertSame('./currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_PATH));
711         $this->assertSame('c/temp/windowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_PATH));
712         $this->assertSame('/home/user/linuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_PATH));
713         $this->assertSame('/home../user ./.linuxfile.txt', clean_param('/home../user ./.linuxfile.txt', PARAM_PATH));
714         $this->assertSame('~/myfile.txt', clean_param('~/myfile.txt', PARAM_PATH));
715         $this->assertSame('~/myfile.txt', clean_param('~/../myfile.txt', PARAM_PATH));
716         $this->assertSame('/..b../.../myfile.txt', clean_param('/..b../.../myfile.txt', PARAM_PATH));
717         $this->assertSame('..b../.../myfile.txt', clean_param('..b../.../myfile.txt', PARAM_PATH));
718         $this->assertSame('/super/slashes/', clean_param('/super//slashes///', PARAM_PATH));
719     }
721     public function test_clean_param_username() {
722         global $CFG;
723         $currentstatus =  $CFG->extendedusernamechars;
725         // Run tests with extended character == false;.
726         $CFG->extendedusernamechars = false;
727         $this->assertSame('johndoe123', clean_param('johndoe123', PARAM_USERNAME) );
728         $this->assertSame('john.doe', clean_param('john.doe', PARAM_USERNAME));
729         $this->assertSame('john-doe', clean_param('john-doe', PARAM_USERNAME));
730         $this->assertSame('john-doe', clean_param('john- doe', PARAM_USERNAME));
731         $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
732         $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
733         $this->assertSame('johndoe', clean_param('john~doe', PARAM_USERNAME));
734         $this->assertSame('johndoe', clean_param('john´doe', PARAM_USERNAME));
735         $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john_');
736         $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john_');
737         $this->assertSame(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
738         $this->assertSame('johnd', clean_param('JOHNdóé ', PARAM_USERNAME));
739         $this->assertSame(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýá\9e?\9eý??\9adoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
741         // Test success condition, if extendedusernamechars == ENABLE;.
742         $CFG->extendedusernamechars = true;
743         $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
744         $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
745         $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john# $%&()+_^');
746         $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john# $%&()+_^');
747         $this->assertSame('john~doe', clean_param('john~doe', PARAM_USERNAME));
748         $this->assertSame('john´doe', clean_param('joHN´doe', PARAM_USERNAME));
749         $this->assertSame('johndoe', clean_param('johnDOE', PARAM_USERNAME));
750         $this->assertSame('johndóé', clean_param('johndóé ', PARAM_USERNAME));
752         $CFG->extendedusernamechars = $currentstatus;
753     }
755     public function test_clean_param_stringid() {
756         // Test string identifiers validation.
757         // Valid strings.
758         $this->assertSame('validstring', clean_param('validstring', PARAM_STRINGID));
759         $this->assertSame('mod/foobar:valid_capability', clean_param('mod/foobar:valid_capability', PARAM_STRINGID));
760         $this->assertSame('CZ', clean_param('CZ', PARAM_STRINGID));
761         $this->assertSame('application/vnd.ms-powerpoint', clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID));
762         $this->assertSame('grade2', clean_param('grade2', PARAM_STRINGID));
763         // Invalid strings.
764         $this->assertSame('', clean_param('trailing ', PARAM_STRINGID));
765         $this->assertSame('', clean_param('space bar', PARAM_STRINGID));
766         $this->assertSame('', clean_param('0numeric', PARAM_STRINGID));
767         $this->assertSame('', clean_param('*', PARAM_STRINGID));
768         $this->assertSame('', clean_param(' ', PARAM_STRINGID));
769     }
771     public function test_clean_param_timezone() {
772         // Test timezone validation.
773         $testvalues = array (
774             'America/Jamaica'                => 'America/Jamaica',
775             'America/Argentina/Cordoba'      => 'America/Argentina/Cordoba',
776             'America/Port-au-Prince'         => 'America/Port-au-Prince',
777             'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
778             'PST8PDT'                        => 'PST8PDT',
779             'Wrong.Value'                    => '',
780             'Wrong/.Value'                   => '',
781             'Wrong(Value)'                   => '',
782             '0'                              => '0',
783             '0.0'                            => '0.0',
784             '0.5'                            => '0.5',
785             '9.0'                            => '9.0',
786             '-9.0'                           => '-9.0',
787             '+9.0'                           => '+9.0',
788             '9.5'                            => '9.5',
789             '-9.5'                           => '-9.5',
790             '+9.5'                           => '+9.5',
791             '12.0'                           => '12.0',
792             '-12.0'                          => '-12.0',
793             '+12.0'                          => '+12.0',
794             '12.5'                           => '12.5',
795             '-12.5'                          => '-12.5',
796             '+12.5'                          => '+12.5',
797             '13.0'                           => '13.0',
798             '-13.0'                          => '-13.0',
799             '+13.0'                          => '+13.0',
800             '13.5'                           => '',
801             '+13.5'                          => '',
802             '-13.5'                          => '',
803             '0.2'                            => '');
805         foreach ($testvalues as $testvalue => $expectedvalue) {
806             $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
807             $this->assertEquals($expectedvalue, $actualvalue);
808         }
809     }
811     public function test_validate_param() {
812         try {
813             $param = validate_param('11a', PARAM_INT);
814             $this->fail('invalid_parameter_exception expected');
815         } catch (moodle_exception $ex) {
816             $this->assertInstanceOf('invalid_parameter_exception', $ex);
817         }
819         $param = validate_param('11', PARAM_INT);
820         $this->assertSame(11, $param);
822         try {
823             $param = validate_param(null, PARAM_INT, false);
824             $this->fail('invalid_parameter_exception expected');
825         } catch (moodle_exception $ex) {
826             $this->assertInstanceOf('invalid_parameter_exception', $ex);
827         }
829         $param = validate_param(null, PARAM_INT, true);
830         $this->assertSame(null, $param);
832         try {
833             $param = validate_param(array(), PARAM_INT);
834             $this->fail('invalid_parameter_exception expected');
835         } catch (moodle_exception $ex) {
836             $this->assertInstanceOf('invalid_parameter_exception', $ex);
837         }
838         try {
839             $param = validate_param(new stdClass, PARAM_INT);
840             $this->fail('invalid_parameter_exception expected');
841         } catch (moodle_exception $ex) {
842             $this->assertInstanceOf('invalid_parameter_exception', $ex);
843         }
845         $param = validate_param('1.0', PARAM_FLOAT);
846         $this->assertSame(1.0, $param);
848         // Make sure valid floats do not cause exception.
849         validate_param(1.0, PARAM_FLOAT);
850         validate_param(10, PARAM_FLOAT);
851         validate_param('0', PARAM_FLOAT);
852         validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
853         validate_param('011.1', PARAM_FLOAT);
854         validate_param('11', PARAM_FLOAT);
855         validate_param('+.1', PARAM_FLOAT);
856         validate_param('-.1', PARAM_FLOAT);
857         validate_param('1e10', PARAM_FLOAT);
858         validate_param('.1e+10', PARAM_FLOAT);
859         validate_param('1E-1', PARAM_FLOAT);
861         try {
862             $param = validate_param('1,2', PARAM_FLOAT);
863             $this->fail('invalid_parameter_exception expected');
864         } catch (moodle_exception $ex) {
865             $this->assertInstanceOf('invalid_parameter_exception', $ex);
866         }
867         try {
868             $param = validate_param('', PARAM_FLOAT);
869             $this->fail('invalid_parameter_exception expected');
870         } catch (moodle_exception $ex) {
871             $this->assertInstanceOf('invalid_parameter_exception', $ex);
872         }
873         try {
874             $param = validate_param('.', PARAM_FLOAT);
875             $this->fail('invalid_parameter_exception expected');
876         } catch (moodle_exception $ex) {
877             $this->assertInstanceOf('invalid_parameter_exception', $ex);
878         }
879         try {
880             $param = validate_param('e10', PARAM_FLOAT);
881             $this->fail('invalid_parameter_exception expected');
882         } catch (moodle_exception $ex) {
883             $this->assertInstanceOf('invalid_parameter_exception', $ex);
884         }
885         try {
886             $param = validate_param('abc', PARAM_FLOAT);
887             $this->fail('invalid_parameter_exception expected');
888         } catch (moodle_exception $ex) {
889             $this->assertInstanceOf('invalid_parameter_exception', $ex);
890         }
891     }
893     public function test_shorten_text_no_tags_already_short_enough() {
894         // ......12345678901234567890123456.
895         $text = "short text already no tags";
896         $this->assertSame($text, shorten_text($text));
897     }
899     public function test_shorten_text_with_tags_already_short_enough() {
900         // .........123456...7890....12345678.......901234567.
901         $text = "<p>short <b>text</b> already</p><p>with tags</p>";
902         $this->assertSame($text, shorten_text($text));
903     }
905     public function test_shorten_text_no_tags_needs_shortening() {
906         // Default truncation is after 30 chars, but allowing 3 for the final '...'.
907         // ......12345678901234567890123456789023456789012345678901234.
908         $text = "long text without any tags blah de blah blah blah what";
909         $this->assertSame('long text without any tags ...', shorten_text($text));
910     }
912     public function test_shorten_text_with_tags_needs_shortening() {
913         // .......................................123456789012345678901234567890...
914         $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
915             "be chopped off but <b>should be added back again</b></blockquote></p></div>";
916         $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
917             "tags that ...</blockquote></p></div>", shorten_text($text));
918     }
920     public function test_shorten_text_with_tags_and_html_comment() {
921         $text = "<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with ".
922             "tags that will<!--<![endif]--> ".
923             "be chopped off but <b>should be added back again</b></blockquote></p></div>";
924         $this->assertEquals("<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with " .
925             "tags that ...<!--<![endif]--></blockquote></p></div>", shorten_text($text));
926     }
928     public function test_shorten_text_with_entities() {
929         // Remember to allow 3 chars for the final '...'.
930         // ......123456789012345678901234567_____890...
931         $text = "some text which shouldn't &nbsp; break there";
932         $this->assertSame("some text which shouldn't &nbsp; ...", shorten_text($text, 31));
933         $this->assertSame("some text which shouldn't &nbsp;...", shorten_text($text, 30));
934         $this->assertSame("some text which shouldn't ...", shorten_text($text, 29));
935     }
937     public function test_shorten_text_known_tricky_case() {
938         // This case caused a bug up to 1.9.5
939         // ..........123456789012345678901234567890123456789.....0_____1___2___...
940         $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
941         $this->assertSame("<h3>standard 'break-out' sub groups in ...</h3>",
942             shorten_text($text, 41));
943         $this->assertSame("<h3>standard 'break-out' sub groups in TGs?...</h3>",
944             shorten_text($text, 42));
945         $this->assertSame("<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;...",
946             shorten_text($text, 43));
947     }
949     public function test_shorten_text_no_spaces() {
950         // ..........123456789.
951         $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
952         $this->assertSame("<h1>12345...</h1>", shorten_text($text, 8));
953     }
955     public function test_shorten_text_utf8_european() {
956         // Text without tags.
957         // ......123456789012345678901234567.
958         $text = "Žluťoučký koníček přeskočil";
959         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
960         $this->assertSame("Žluťoučký koníče...", shorten_text($text, 19, true));
961         $this->assertSame("Žluťoučký ...", shorten_text($text, 19, false));
962         // And try it with 2-less (that are, in bytes, the middle of a sequence).
963         $this->assertSame("Žluťoučký koní...", shorten_text($text, 17, true));
964         $this->assertSame("Žluťoučký ...", shorten_text($text, 17, false));
966         // .........123456789012345678...901234567....89012345.
967         $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
968         $this->assertSame($text, shorten_text($text, 60));
969         $this->assertSame("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
970         $this->assertSame("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
971         $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
972         // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
973         $this->assertSame("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
974         $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
975         // And try over one tag (start/end), it does proper text len.
976         $this->assertSame("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
977         $this->assertSame("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
978         // And in the middle of one tag.
979         $this->assertSame("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
980     }
982     public function test_shorten_text_utf8_oriental() {
983         // Japanese
984         // text without tags
985         // ......123456789012345678901234.
986         $text = '言語設定言語設定abcdefghijkl';
987         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
988         $this->assertSame("言語設定言語...", shorten_text($text, 9, true));
989         $this->assertSame("言語設定言語...", shorten_text($text, 9, false));
990         $this->assertSame("言語設定言語設定ab...", shorten_text($text, 13, true));
991         $this->assertSame("言語設定言語設定...", shorten_text($text, 13, false));
993         // Chinese
994         // text without tags
995         // ......123456789012345678901234.
996         $text = '简体中文简体中文abcdefghijkl';
997         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
998         $this->assertSame("简体中文简体...", shorten_text($text, 9, true));
999         $this->assertSame("简体中文简体...", shorten_text($text, 9, false));
1000         $this->assertSame("简体中文简体中文ab...", shorten_text($text, 13, true));
1001         $this->assertSame("简体中文简体中文...", shorten_text($text, 13, false));
1002     }
1004     public function test_shorten_text_multilang() {
1005         // This is not necessaryily specific to multilang. The issue is really
1006         // tags with attributes, where before we were generating invalid HTML
1007         // output like shorten_text('<span id="x" class="y">A</span> B', 1)
1008         // returning '<span id="x" ...</span>'. It is just that multilang
1009         // requires the sort of HTML that is quite likely to trigger this.
1010         // ........................................1...
1011         $text = '<span lang="en" class="multilang">A</span>' .
1012                 '<span lang="fr" class="multilang">B</span>';
1013         $this->assertSame('<span lang="en" class="multilang">...</span>',
1014                 shorten_text($text, 1));
1015     }
1017     public function test_usergetdate() {
1018         global $USER, $CFG, $DB;
1019         $this->resetAfterTest();
1021         $this->setAdminUser();
1023         $USER->timezone = 2;// Set the timezone to a known state.
1025         $ts = 1261540267; // The time this function was created.
1027         $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
1028         $arr = array_values($arr);
1030         list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1031         $this->assertSame(7, $seconds);
1032         $this->assertSame(51, $minutes);
1033         $this->assertSame(4, $hours);
1034         $this->assertSame(23, $mday);
1035         $this->assertSame(3, $wday);
1036         $this->assertSame(12, $mon);
1037         $this->assertSame(2009, $year);
1038         $this->assertSame(356, $yday);
1039         $this->assertSame('Wednesday', $weekday);
1040         $this->assertSame('December', $month);
1041         $arr = usergetdate($ts); // Gets the timezone from the $USER object.
1042         $arr = array_values($arr);
1044         list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1045         $this->assertSame(7, $seconds);
1046         $this->assertSame(51, $minutes);
1047         $this->assertSame(5, $hours);
1048         $this->assertSame(23, $mday);
1049         $this->assertSame(3, $wday);
1050         $this->assertSame(12, $mon);
1051         $this->assertSame(2009, $year);
1052         $this->assertSame(356, $yday);
1053         $this->assertSame('Wednesday', $weekday);
1054         $this->assertSame('December', $month);
1055     }
1057     public function test_mark_user_preferences_changed() {
1058         $this->resetAfterTest();
1059         $otheruser = $this->getDataGenerator()->create_user();
1060         $otheruserid = $otheruser->id;
1062         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1063         mark_user_preferences_changed($otheruserid);
1065         $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1066         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1067     }
1069     public function test_check_user_preferences_loaded() {
1070         global $DB;
1071         $this->resetAfterTest();
1073         $otheruser = $this->getDataGenerator()->create_user();
1074         $otheruserid = $otheruser->id;
1076         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1077         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1079         $user = new stdClass();
1080         $user->id = $otheruserid;
1082         // Load.
1083         check_user_preferences_loaded($user);
1084         $this->assertTrue(isset($user->preference));
1085         $this->assertTrue(is_array($user->preference));
1086         $this->assertArrayHasKey('_lastloaded', $user->preference);
1087         $this->assertCount(1, $user->preference);
1089         // Add preference via direct call.
1090         $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1092         // No cache reload yet.
1093         check_user_preferences_loaded($user);
1094         $this->assertCount(1, $user->preference);
1096         // Forced reloading of cache.
1097         unset($user->preference);
1098         check_user_preferences_loaded($user);
1099         $this->assertCount(2, $user->preference);
1100         $this->assertSame('yyy', $user->preference['xxx']);
1102         // Add preference via direct call.
1103         $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1105         // Test timeouts and modifications from different session.
1106         set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1107         $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1108         check_user_preferences_loaded($user);
1109         $this->assertCount(2, $user->preference);
1110         check_user_preferences_loaded($user, 10);
1111         $this->assertCount(3, $user->preference);
1112         $this->assertSame('bbb', $user->preference['aaa']);
1113         set_cache_flag('userpreferenceschanged', $user->id, null);
1114     }
1116     public function test_set_user_preference() {
1117         global $DB, $USER;
1118         $this->resetAfterTest();
1120         $this->setAdminUser();
1122         $otheruser = $this->getDataGenerator()->create_user();
1123         $otheruserid = $otheruser->id;
1125         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1126         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1128         $user = new stdClass();
1129         $user->id = $otheruserid;
1131         set_user_preference('aaa', 'bbb', $otheruserid);
1132         $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1133         $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
1135         set_user_preference('xxx', 'yyy', $user);
1136         $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1137         $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
1138         $this->assertTrue(is_array($user->preference));
1139         $this->assertSame('bbb', $user->preference['aaa']);
1140         $this->assertSame('yyy', $user->preference['xxx']);
1142         set_user_preference('xxx', null, $user);
1143         $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1144         $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
1146         set_user_preference('ooo', true, $user);
1147         $prefs = get_user_preferences(null, null, $otheruserid);
1148         $this->assertSame($user->preference['aaa'], $prefs['aaa']);
1149         $this->assertSame($user->preference['ooo'], $prefs['ooo']);
1150         $this->assertSame('1', $prefs['ooo']);
1152         set_user_preference('null', 0, $user);
1153         $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1155         $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1157         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1158         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1160         // Test $USER default.
1161         set_user_preference('_test_user_preferences_pref', 'ok');
1162         $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1163         unset_user_preference('_test_user_preferences_pref');
1164         $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1166         // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
1167         $longvalue = str_repeat('a', 1333);
1168         set_user_preference('_test_long_user_preference', $longvalue);
1169         $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1170         $this->assertEquals($longvalue,
1171             $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1173         // Test > 1333 char values, coding_exception expected.
1174         $longvalue = str_repeat('a', 1334);
1175         try {
1176             set_user_preference('_test_long_user_preference', $longvalue);
1177             $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1178         } catch (moodle_exception $ex) {
1179             $this->assertInstanceOf('coding_exception', $ex);
1180         }
1182         // Test invalid params.
1183         try {
1184             set_user_preference('_test_user_preferences_pref', array());
1185             $this->fail('Exception expected - array not valid preference value');
1186         } catch (moodle_exception $ex) {
1187             $this->assertInstanceOf('coding_exception', $ex);
1188         }
1189         try {
1190             set_user_preference('_test_user_preferences_pref', new stdClass);
1191             $this->fail('Exception expected - class not valid preference value');
1192         } catch (moodle_exception $ex) {
1193             $this->assertInstanceOf('coding_exception', $ex);
1194         }
1195         try {
1196             set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1197             $this->fail('Exception expected - user instance expected');
1198         } catch (moodle_exception $ex) {
1199             $this->assertInstanceOf('coding_exception', $ex);
1200         }
1201         try {
1202             set_user_preference('_test_user_preferences_pref', 1, 'abc');
1203             $this->fail('Exception expected - user instance expected');
1204         } catch (moodle_exception $ex) {
1205             $this->assertInstanceOf('coding_exception', $ex);
1206         }
1207         try {
1208             set_user_preference('', 1);
1209             $this->fail('Exception expected - invalid name accepted');
1210         } catch (moodle_exception $ex) {
1211             $this->assertInstanceOf('coding_exception', $ex);
1212         }
1213         try {
1214             set_user_preference('1', 1);
1215             $this->fail('Exception expected - invalid name accepted');
1216         } catch (moodle_exception $ex) {
1217             $this->assertInstanceOf('coding_exception', $ex);
1218         }
1219     }
1221     public function test_set_user_preference_for_current_user() {
1222         global $USER;
1223         $this->resetAfterTest();
1224         $this->setAdminUser();
1226         set_user_preference('test_pref', 2);
1227         set_user_preference('test_pref', 1, $USER->id);
1228         $this->assertEquals(1, get_user_preferences('test_pref'));
1229     }
1231     public function test_unset_user_preference_for_current_user() {
1232         global $USER;
1233         $this->resetAfterTest();
1234         $this->setAdminUser();
1236         set_user_preference('test_pref', 1);
1237         unset_user_preference('test_pref', $USER->id);
1238         $this->assertNull(get_user_preferences('test_pref'));
1239     }
1241     public function test_get_extra_user_fields() {
1242         global $CFG, $USER, $DB;
1243         $this->resetAfterTest();
1245         $this->setAdminUser();
1247         // It would be really nice if there were a way to 'mock' has_capability
1248         // checks (either to return true or false) but as there is not, this
1249         // test doesn't test the capability check. Presumably, anyone running
1250         // unit tests will have the capability.
1251         $context = context_system::instance();
1253         // No fields.
1254         $CFG->showuseridentity = '';
1255         $this->assertEquals(array(), get_extra_user_fields($context));
1257         // One field.
1258         $CFG->showuseridentity = 'frog';
1259         $this->assertEquals(array('frog'), get_extra_user_fields($context));
1261         // Two fields.
1262         $CFG->showuseridentity = 'frog,zombie';
1263         $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1265         // No fields, except.
1266         $CFG->showuseridentity = '';
1267         $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1269         // One field.
1270         $CFG->showuseridentity = 'frog';
1271         $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1273         // Two fields.
1274         $CFG->showuseridentity = 'frog,zombie';
1275         $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1276     }
1278     public function test_get_extra_user_fields_sql() {
1279         global $CFG, $USER, $DB;
1280         $this->resetAfterTest();
1282         $this->setAdminUser();
1284         $context = context_system::instance();
1286         // No fields.
1287         $CFG->showuseridentity = '';
1288         $this->assertSame('', get_extra_user_fields_sql($context));
1290         // One field.
1291         $CFG->showuseridentity = 'frog';
1292         $this->assertSame(', frog', get_extra_user_fields_sql($context));
1294         // Two fields with table prefix.
1295         $CFG->showuseridentity = 'frog,zombie';
1296         $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1298         // Two fields with field prefix.
1299         $CFG->showuseridentity = 'frog,zombie';
1300         $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
1301             get_extra_user_fields_sql($context, '', 'u_'));
1303         // One field excluded.
1304         $CFG->showuseridentity = 'frog';
1305         $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
1307         // Two fields, one excluded, table+field prefix.
1308         $CFG->showuseridentity = 'frog,zombie';
1309         $this->assertEquals(', u1.zombie AS u_zombie',
1310             get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1311     }
1313     /**
1314      * Test some critical TZ/DST.
1315      *
1316      * This method tests some special TZ/DST combinations that were fixed
1317      * by MDL-38999. The tests are done by comparing the results of the
1318      * output using Moodle TZ/DST support and PHP native one.
1319      *
1320      * Note: If you don't trust PHP TZ/DST support, can verify the
1321      * harcoded expectations below with:
1322      * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
1323      */
1324     public function test_some_moodle_special_dst() {
1325         $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
1327         // In Europe/Tallinn it was 2013/04/08 05:00:00.
1328         $expectation = '2013/04/08 05:00:00';
1329         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1330         $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1331         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1332         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1333         $this->assertSame($expectation, $phpres);
1334         $this->assertSame($expectation, $moodleres);
1336         // In St. Johns it was 2013/04/07 23:30:00.
1337         $expectation = '2013/04/07 23:30:00';
1338         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1339         $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1340         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1341         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1342         $this->assertSame($expectation, $phpres);
1343         $this->assertSame($expectation, $moodleres);
1345         $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1347         // In Europe/Tallinn it was 2013/11/08 04:00:00.
1348         $expectation = '2013/11/08 04:00:00';
1349         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1350         $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1351         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1352         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1353         $this->assertSame($expectation, $phpres);
1354         $this->assertSame($expectation, $moodleres);
1356         // In St. Johns it was 2013/11/07 22:30:00.
1357         $expectation = '2013/11/07 22:30:00';
1358         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1359         $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1360         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1361         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1362         $this->assertSame($expectation, $phpres);
1363         $this->assertSame($expectation, $moodleres);
1364     }
1366     public function test_userdate() {
1367         global $USER, $CFG, $DB;
1368         $this->resetAfterTest();
1370         $this->setAdminUser();
1372         $testvalues = array(
1373             array(
1374                 'time' => '1309514400',
1375                 'usertimezone' => 'America/Moncton',
1376                 'timezone' => '0.0', // No dst offset.
1377                 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1378             ),
1379             array(
1380                 'time' => '1309514400',
1381                 'usertimezone' => 'America/Moncton',
1382                 'timezone' => '99', // Dst offset and timezone offset.
1383                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1384             ),
1385             array(
1386                 'time' => '1309514400',
1387                 'usertimezone' => 'America/Moncton',
1388                 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
1389                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1390             ),
1391             array(
1392                 'time' => '1293876000 ',
1393                 'usertimezone' => 'America/Moncton',
1394                 'timezone' => '0.0', // No dst offset.
1395                 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1396             ),
1397             array(
1398                 'time' => '1293876000 ',
1399                 'usertimezone' => 'America/Moncton',
1400                 'timezone' => '99', // No dst offset in jan, so just timezone offset.
1401                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1402             ),
1403             array(
1404                 'time' => '1293876000 ',
1405                 'usertimezone' => 'America/Moncton',
1406                 'timezone' => 'America/Moncton', // No dst offset in jan.
1407                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1408             ),
1409             array(
1410                 'time' => '1293876000 ',
1411                 'usertimezone' => '2',
1412                 'timezone' => '99', // Take user timezone.
1413                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1414             ),
1415             array(
1416                 'time' => '1293876000 ',
1417                 'usertimezone' => '-2',
1418                 'timezone' => '99', // Take user timezone.
1419                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1420             ),
1421             array(
1422                 'time' => '1293876000 ',
1423                 'usertimezone' => '-10',
1424                 'timezone' => '2', // Take this timezone.
1425                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1426             ),
1427             array(
1428                 'time' => '1293876000 ',
1429                 'usertimezone' => '-10',
1430                 'timezone' => '-2', // Take this timezone.
1431                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1432             ),
1433             array(
1434                 'time' => '1293876000 ',
1435                 'usertimezone' => '-10',
1436                 'timezone' => 'random/time', // This should show server time.
1437                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1438             ),
1439             array(
1440                 'time' => '1293876000 ',
1441                 'usertimezone' => '20', // Fallback to server time zone.
1442                 'timezone' => '99',     // This should show user time.
1443                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1444             ),
1445         );
1447         // Set default timezone to Australia/Perth, else time calculated
1448         // will not match expected values.
1449         $this->setTimezone(99, 'Australia/Perth');
1451         foreach ($testvalues as $vals) {
1452             $USER->timezone = $vals['usertimezone'];
1453             $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1455             // On different systems case of AM PM changes so compare case insensitive.
1456             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1457             $actualoutput = core_text::strtolower($actualoutput);
1459             $this->assertSame($vals['expectedoutput'], $actualoutput,
1460                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput} \ndata: " . var_export($vals, true));
1461         }
1462     }
1464     /**
1465      * Make sure the DST changes happen at the right time in Moodle.
1466      */
1467     public function test_dst_changes() {
1468         // DST switching in Prague.
1469         // From 2AM to 3AM in 1989.
1470         $date = new DateTime('1989-03-26T01:59:00+01:00');
1471         $this->assertSame('Sunday, 26 March 1989, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1472         $date = new DateTime('1989-03-26T02:01:00+01:00');
1473         $this->assertSame('Sunday, 26 March 1989, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1474         // From 3AM to 2AM in 1989 - not the same as the west Europe.
1475         $date = new DateTime('1989-09-24T01:59:00+01:00');
1476         $this->assertSame('Sunday, 24 September 1989, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1477         $date = new DateTime('1989-09-24T02:01:00+01:00');
1478         $this->assertSame('Sunday, 24 September 1989, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1479         // From 2AM to 3AM in 2014.
1480         $date = new DateTime('2014-03-30T01:59:00+01:00');
1481         $this->assertSame('Sunday, 30 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1482         $date = new DateTime('2014-03-30T02:01:00+01:00');
1483         $this->assertSame('Sunday, 30 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1484         // From 3AM to 2AM in 2014.
1485         $date = new DateTime('2014-10-26T01:59:00+01:00');
1486         $this->assertSame('Sunday, 26 October 2014, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1487         $date = new DateTime('2014-10-26T02:01:00+01:00');
1488         $this->assertSame('Sunday, 26 October 2014, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1489         // From 2AM to 3AM in 2020.
1490         $date = new DateTime('2020-03-29T01:59:00+01:00');
1491         $this->assertSame('Sunday, 29 March 2020, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1492         $date = new DateTime('2020-03-29T02:01:00+01:00');
1493         $this->assertSame('Sunday, 29 March 2020, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1494         // From 3AM to 2AM in 2020.
1495         $date = new DateTime('2020-10-25T01:59:00+01:00');
1496         $this->assertSame('Sunday, 25 October 2020, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1497         $date = new DateTime('2020-10-25T02:01:00+01:00');
1498         $this->assertSame('Sunday, 25 October 2020, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1500         // DST switching in NZ.
1501         // From 3AM to 2AM in 2015.
1502         $date = new DateTime('2015-04-05T02:59:00+13:00');
1503         $this->assertSame('Sunday, 5 April 2015, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1504         $date = new DateTime('2015-04-05T03:01:00+13:00');
1505         $this->assertSame('Sunday, 5 April 2015, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1506         // From 2AM to 3AM in 2009.
1507         $date = new DateTime('2015-09-27T01:59:00+12:00');
1508         $this->assertSame('Sunday, 27 September 2015, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1509         $date = new DateTime('2015-09-27T02:01:00+12:00');
1510         $this->assertSame('Sunday, 27 September 2015, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1512         // DST switching in Perth.
1513         // From 3AM to 2AM in 2009.
1514         $date = new DateTime('2008-03-30T01:59:00+08:00');
1515         $this->assertSame('Sunday, 30 March 2008, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1516         $date = new DateTime('2008-03-30T02:01:00+08:00');
1517         $this->assertSame('Sunday, 30 March 2008, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1518         // From 2AM to 3AM in 2009.
1519         $date = new DateTime('2008-10-26T01:59:00+08:00');
1520         $this->assertSame('Sunday, 26 October 2008, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1521         $date = new DateTime('2008-10-26T02:01:00+08:00');
1522         $this->assertSame('Sunday, 26 October 2008, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1524         // DST switching in US.
1525         // From 2AM to 3AM in 2014.
1526         $date = new DateTime('2014-03-09T01:59:00-05:00');
1527         $this->assertSame('Sunday, 9 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1528         $date = new DateTime('2014-03-09T02:01:00-05:00');
1529         $this->assertSame('Sunday, 9 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1530         // From 3AM to 2AM in 2014.
1531         $date = new DateTime('2014-11-02T01:59:00-04:00');
1532         $this->assertSame('Sunday, 2 November 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1533         $date = new DateTime('2014-11-02T02:01:00-04:00');
1534         $this->assertSame('Sunday, 2 November 2014, 01:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1535     }
1537     public function test_make_timestamp() {
1538         global $USER, $CFG, $DB;
1539         $this->resetAfterTest();
1541         $this->setAdminUser();
1543         $testvalues = array(
1544             array(
1545                 'usertimezone' => 'America/Moncton',
1546                 'year' => '2011',
1547                 'month' => '7',
1548                 'day' => '1',
1549                 'hour' => '10',
1550                 'minutes' => '00',
1551                 'seconds' => '00',
1552                 'timezone' => '0.0',
1553                 'applydst' => false, // No dst offset.
1554                 'expectedoutput' => '1309514400' // 6pm at UTC+0.
1555             ),
1556             array(
1557                 'usertimezone' => 'America/Moncton',
1558                 'year' => '2011',
1559                 'month' => '7',
1560                 'day' => '1',
1561                 'hour' => '10',
1562                 'minutes' => '00',
1563                 'seconds' => '00',
1564                 'timezone' => '99',  // User default timezone.
1565                 'applydst' => false, // Don't apply dst.
1566                 'expectedoutput' => '1309528800'
1567             ),
1568             array(
1569                 'usertimezone' => 'America/Moncton',
1570                 'year' => '2011',
1571                 'month' => '7',
1572                 'day' => '1',
1573                 'hour' => '10',
1574                 'minutes' => '00',
1575                 'seconds' => '00',
1576                 'timezone' => '99', // User default timezone.
1577                 'applydst' => true, // Apply dst.
1578                 'expectedoutput' => '1309525200'
1579             ),
1580             array(
1581                 'usertimezone' => 'America/Moncton',
1582                 'year' => '2011',
1583                 'month' => '7',
1584                 'day' => '1',
1585                 'hour' => '10',
1586                 'minutes' => '00',
1587                 'seconds' => '00',
1588                 'timezone' => 'America/Moncton', // String timezone.
1589                 'applydst' => true, // Apply dst.
1590                 'expectedoutput' => '1309525200'
1591             ),
1592             array(
1593                 'usertimezone' => '2', // No dst applyed.
1594                 'year' => '2011',
1595                 'month' => '7',
1596                 'day' => '1',
1597                 'hour' => '10',
1598                 'minutes' => '00',
1599                 'seconds' => '00',
1600                 'timezone' => '99', // Take user timezone.
1601                 'applydst' => true, // Apply dst.
1602                 'expectedoutput' => '1309507200'
1603             ),
1604             array(
1605                 'usertimezone' => '-2', // No dst applyed.
1606                 'year' => '2011',
1607                 'month' => '7',
1608                 'day' => '1',
1609                 'hour' => '10',
1610                 'minutes' => '00',
1611                 'seconds' => '00',
1612                 'timezone' => '99', // Take usertimezone.
1613                 'applydst' => true, // Apply dst.
1614                 'expectedoutput' => '1309521600'
1615             ),
1616             array(
1617                 'usertimezone' => '-10', // No dst applyed.
1618                 'year' => '2011',
1619                 'month' => '7',
1620                 'day' => '1',
1621                 'hour' => '10',
1622                 'minutes' => '00',
1623                 'seconds' => '00',
1624                 'timezone' => '2',  // Take this timezone.
1625                 'applydst' => true, // Apply dst.
1626                 'expectedoutput' => '1309507200'
1627             ),
1628             array(
1629                 'usertimezone' => '-10', // No dst applyed.
1630                 'year' => '2011',
1631                 'month' => '7',
1632                 'day' => '1',
1633                 'hour' => '10',
1634                 'minutes' => '00',
1635                 'seconds' => '00',
1636                 'timezone' => '-2', // Take this timezone.
1637                 'applydst' => true, // Apply dst.
1638                 'expectedoutput' => '1309521600'
1639             ),
1640             array(
1641                 'usertimezone' => '-10', // No dst applyed.
1642                 'year' => '2011',
1643                 'month' => '7',
1644                 'day' => '1',
1645                 'hour' => '10',
1646                 'minutes' => '00',
1647                 'seconds' => '00',
1648                 'timezone' => 'random/time', // This should show server time.
1649                 'applydst' => true,          // Apply dst.
1650                 'expectedoutput' => '1309485600'
1651             ),
1652             array(
1653                 'usertimezone' => '-14', // Server time.
1654                 'year' => '2011',
1655                 'month' => '7',
1656                 'day' => '1',
1657                 'hour' => '10',
1658                 'minutes' => '00',
1659                 'seconds' => '00',
1660                 'timezone' => '99', // Get user time.
1661                 'applydst' => true, // Apply dst.
1662                 'expectedoutput' => '1309485600'
1663             )
1664         );
1666         // Set default timezone to Australia/Perth, else time calculated
1667         // will not match expected values.
1668         $this->setTimezone(99, 'Australia/Perth');
1670         // Test make_timestamp with all testvals and assert if anything wrong.
1671         foreach ($testvalues as $vals) {
1672             $USER->timezone = $vals['usertimezone'];
1673             $actualoutput = make_timestamp(
1674                 $vals['year'],
1675                 $vals['month'],
1676                 $vals['day'],
1677                 $vals['hour'],
1678                 $vals['minutes'],
1679                 $vals['seconds'],
1680                 $vals['timezone'],
1681                 $vals['applydst']
1682             );
1684             // On different systems case of AM PM changes so compare case insensitive.
1685             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1686             $actualoutput = core_text::strtolower($actualoutput);
1688             $this->assertSame($vals['expectedoutput'], $actualoutput,
1689                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1690                 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1691         }
1692     }
1694     /**
1695      * Test get_string and most importantly the implementation of the lang_string
1696      * object.
1697      */
1698     public function test_get_string() {
1699         global $COURSE;
1701         // Make sure we are using English.
1702         $originallang = $COURSE->lang;
1703         $COURSE->lang = 'en';
1705         $yes = get_string('yes');
1706         $yesexpected = 'Yes';
1707         $this->assertInternalType('string', $yes);
1708         $this->assertSame($yesexpected, $yes);
1710         $yes = get_string('yes', 'moodle');
1711         $this->assertInternalType('string', $yes);
1712         $this->assertSame($yesexpected, $yes);
1714         $yes = get_string('yes', 'core');
1715         $this->assertInternalType('string', $yes);
1716         $this->assertSame($yesexpected, $yes);
1718         $yes = get_string('yes', '');
1719         $this->assertInternalType('string', $yes);
1720         $this->assertSame($yesexpected, $yes);
1722         $yes = get_string('yes', null);
1723         $this->assertInternalType('string', $yes);
1724         $this->assertSame($yesexpected, $yes);
1726         $yes = get_string('yes', null, 1);
1727         $this->assertInternalType('string', $yes);
1728         $this->assertSame($yesexpected, $yes);
1730         $days = 1;
1731         $numdays = get_string('numdays', 'core', '1');
1732         $numdaysexpected = $days.' days';
1733         $this->assertInternalType('string', $numdays);
1734         $this->assertSame($numdaysexpected, $numdays);
1736         $yes = get_string('yes', null, null, true);
1737         $this->assertInstanceOf('lang_string', $yes);
1738         $this->assertSame($yesexpected, (string)$yes);
1740         // Test using a lang_string object as the $a argument for a normal
1741         // get_string call (returning string).
1742         $test = new lang_string('yes', null, null, true);
1743         $testexpected = get_string('numdays', 'core', get_string('yes'));
1744         $testresult = get_string('numdays', null, $test);
1745         $this->assertInternalType('string', $testresult);
1746         $this->assertSame($testexpected, $testresult);
1748         // Test using a lang_string object as the $a argument for an object
1749         // get_string call (returning lang_string).
1750         $test = new lang_string('yes', null, null, true);
1751         $testexpected = get_string('numdays', 'core', get_string('yes'));
1752         $testresult = get_string('numdays', null, $test, true);
1753         $this->assertInstanceOf('lang_string', $testresult);
1754         $this->assertSame($testexpected, "$testresult");
1756         // Make sure that object properties that can't be converted don't cause
1757         // errors.
1758         // Level one: This is as deep as current language processing goes.
1759         $test = new stdClass;
1760         $test->one = 'here';
1761         $string = get_string('yes', null, $test, true);
1762         $this->assertEquals($yesexpected, $string);
1764         // Make sure that object properties that can't be converted don't cause
1765         // errors.
1766         // Level two: Language processing doesn't currently reach this deep.
1767         // only immediate scalar properties are worked with.
1768         $test = new stdClass;
1769         $test->one = new stdClass;
1770         $test->one->two = 'here';
1771         $string = get_string('yes', null, $test, true);
1772         $this->assertEquals($yesexpected, $string);
1774         // Make sure that object properties that can't be converted don't cause
1775         // errors.
1776         // Level three: It should never ever go this deep, but we're making sure
1777         // it doesn't cause any probs anyway.
1778         $test = new stdClass;
1779         $test->one = new stdClass;
1780         $test->one->two = new stdClass;
1781         $test->one->two->three = 'here';
1782         $string = get_string('yes', null, $test, true);
1783         $this->assertEquals($yesexpected, $string);
1785         // Make sure that object properties that can't be converted don't cause
1786         // errors and check lang_string properties.
1787         // Level one: This is as deep as current language processing goes.
1788         $test = new stdClass;
1789         $test->one = new lang_string('yes');
1790         $string = get_string('yes', null, $test, true);
1791         $this->assertEquals($yesexpected, $string);
1793         // Make sure that object properties that can't be converted don't cause
1794         // errors and check lang_string properties.
1795         // Level two: Language processing doesn't currently reach this deep.
1796         // only immediate scalar properties are worked with.
1797         $test = new stdClass;
1798         $test->one = new stdClass;
1799         $test->one->two = new lang_string('yes');
1800         $string = get_string('yes', null, $test, true);
1801         $this->assertEquals($yesexpected, $string);
1803         // Make sure that object properties that can't be converted don't cause
1804         // errors and check lang_string properties.
1805         // Level three: It should never ever go this deep, but we're making sure
1806         // it doesn't cause any probs anyway.
1807         $test = new stdClass;
1808         $test->one = new stdClass;
1809         $test->one->two = new stdClass;
1810         $test->one->two->three = new lang_string('yes');
1811         $string = get_string('yes', null, $test, true);
1812         $this->assertEquals($yesexpected, $string);
1814         // Make sure that array properties that can't be converted don't cause
1815         // errors.
1816         $test = array();
1817         $test['one'] = new stdClass;
1818         $test['one']->two = 'here';
1819         $string = get_string('yes', null, $test, true);
1820         $this->assertEquals($yesexpected, $string);
1822         // Same thing but as above except using an object... this is allowed :P.
1823         $string = get_string('yes', null, null, true);
1824         $object = new stdClass;
1825         $object->$string = 'Yes';
1826         $this->assertEquals($yesexpected, $string);
1827         $this->assertEquals($yesexpected, $object->$string);
1829         // Reset the language.
1830         $COURSE->lang = $originallang;
1831     }
1833     /**
1834      * @expectedException PHPUnit\Framework\Error\Warning
1835      */
1836     public function test_get_string_limitation() {
1837         // This is one of the limitations to the lang_string class. It can't be
1838         // used as a key.
1839         $array = array(get_string('yes', null, null, true) => 'yes');
1840     }
1842     /**
1843      * Test localised float formatting.
1844      */
1845     public function test_format_float() {
1847         // Special case for null.
1848         $this->assertEquals('', format_float(null));
1850         // Default 1 decimal place.
1851         $this->assertEquals('5.4', format_float(5.43));
1852         $this->assertEquals('5.0', format_float(5.001));
1854         // Custom number of decimal places.
1855         $this->assertEquals('5.43000', format_float(5.43, 5));
1857         // Option to strip ending zeros after rounding.
1858         $this->assertEquals('5.43', format_float(5.43, 5, true, true));
1859         $this->assertEquals('5', format_float(5.0001, 3, true, true));
1861         // Tests with a localised decimal separator.
1862         $this->define_local_decimal_separator();
1864         // Localisation on (default).
1865         $this->assertEquals('5X43000', format_float(5.43, 5));
1866         $this->assertEquals('5X43', format_float(5.43, 5, true, true));
1868         // Localisation off.
1869         $this->assertEquals('5.43000', format_float(5.43, 5, false));
1870         $this->assertEquals('5.43', format_float(5.43, 5, false, true));
1871     }
1873     /**
1874      * Test localised float unformatting.
1875      */
1876     public function test_unformat_float() {
1878         // Tests without the localised decimal separator.
1880         // Special case for null, empty or white spaces only strings.
1881         $this->assertEquals(null, unformat_float(null));
1882         $this->assertEquals(null, unformat_float(''));
1883         $this->assertEquals(null, unformat_float('    '));
1885         // Regular use.
1886         $this->assertEquals(5.4, unformat_float('5.4'));
1887         $this->assertEquals(5.4, unformat_float('5.4', true));
1889         // No decimal.
1890         $this->assertEquals(5.0, unformat_float('5'));
1892         // Custom number of decimal.
1893         $this->assertEquals(5.43267, unformat_float('5.43267'));
1895         // Empty decimal.
1896         $this->assertEquals(100.0, unformat_float('100.00'));
1898         // With the thousand separator.
1899         $this->assertEquals(1000.0, unformat_float('1 000'));
1900         $this->assertEquals(1000.32, unformat_float('1 000.32'));
1902         // Negative number.
1903         $this->assertEquals(-100.0, unformat_float('-100'));
1905         // Wrong value.
1906         $this->assertEquals(0.0, unformat_float('Wrong value'));
1907         // Wrong value in strict mode.
1908         $this->assertFalse(unformat_float('Wrong value', true));
1910         // Combining options.
1911         $this->assertEquals(-1023.862567, unformat_float('   -1 023.862567     '));
1913         // Bad decimal separator (should crop the decimal).
1914         $this->assertEquals(50.0, unformat_float('50,57'));
1915         // Bad decimal separator in strict mode (should return false).
1916         $this->assertFalse(unformat_float('50,57', true));
1918         // Tests with a localised decimal separator.
1919         $this->define_local_decimal_separator();
1921         // We repeat the tests above but with the current decimal separator.
1923         // Regular use without and with the localised separator.
1924         $this->assertEquals (5.4, unformat_float('5.4'));
1925         $this->assertEquals (5.4, unformat_float('5X4'));
1927         // Custom number of decimal.
1928         $this->assertEquals (5.43267, unformat_float('5X43267'));
1930         // Empty decimal.
1931         $this->assertEquals (100.0, unformat_float('100X00'));
1933         // With the thousand separator.
1934         $this->assertEquals (1000.32, unformat_float('1 000X32'));
1936         // Bad different separator (should crop the decimal).
1937         $this->assertEquals (50.0, unformat_float('50Y57'));
1938         // Bad different separator in strict mode (should return false).
1939         $this->assertFalse (unformat_float('50Y57', true));
1941         // Combining options.
1942         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     '));
1943         // Combining options in strict mode.
1944         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     ', true));
1945     }
1947     /**
1948      * Test deleting of users.
1949      */
1950     public function test_delete_user() {
1951         global $DB, $CFG;
1953         $this->resetAfterTest();
1955         $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
1956         $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
1957         $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
1959         $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
1960         $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
1961         $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
1962         $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
1963         $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => ''));
1964         $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => ''));
1966         // Delete user and capture event.
1967         $sink = $this->redirectEvents();
1968         $result = delete_user($user);
1969         $events = $sink->get_events();
1970         $sink->close();
1971         $event = array_pop($events);
1973         // Test user is deleted in DB.
1974         $this->assertTrue($result);
1975         $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
1976         $this->assertEquals(1, $deluser->deleted);
1977         $this->assertEquals(0, $deluser->picture);
1978         $this->assertSame('', $deluser->idnumber);
1979         $this->assertSame(md5($user->username), $deluser->email);
1980         $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
1982         $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
1984         // Test Event.
1985         $this->assertInstanceOf('\core\event\user_deleted', $event);
1986         $this->assertSame($user->id, $event->objectid);
1987         $this->assertSame('user_deleted', $event->get_legacy_eventname());
1988         $this->assertEventLegacyData($user, $event);
1989         $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
1990         $this->assertEventLegacyLogData($expectedlogdata, $event);
1991         $eventdata = $event->get_data();
1992         $this->assertSame($eventdata['other']['username'], $user->username);
1993         $this->assertSame($eventdata['other']['email'], $user->email);
1994         $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
1995         $this->assertSame($eventdata['other']['picture'], $user->picture);
1996         $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
1997         $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
1998         $this->assertEventContextNotUsed($event);
2000         // Try invalid params.
2001         $record = new stdClass();
2002         $record->grrr = 1;
2003         try {
2004             delete_user($record);
2005             $this->fail('Expecting exception for invalid delete_user() $user parameter');
2006         } catch (moodle_exception $ex) {
2007             $this->assertInstanceOf('coding_exception', $ex);
2008         }
2009         $record->id = 1;
2010         try {
2011             delete_user($record);
2012             $this->fail('Expecting exception for invalid delete_user() $user parameter');
2013         } catch (moodle_exception $ex) {
2014             $this->assertInstanceOf('coding_exception', $ex);
2015         }
2017         $record = new stdClass();
2018         $record->id = 666;
2019         $record->username = 'xx';
2020         $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
2021         $result = delete_user($record);
2022         $this->assertFalse($result);
2024         $result = delete_user($guest);
2025         $this->assertFalse($result);
2027         $result = delete_user($admin);
2028         $this->assertFalse($result);
2030         // Simultaneously deleting users with identical email addresses.
2031         $result1 = delete_user($usersharedemail1);
2032         $result2 = delete_user($usersharedemail2);
2034         $usersharedemail1after = $DB->get_record('user', array('id' => $usersharedemail1->id));
2035         $usersharedemail2after = $DB->get_record('user', array('id' => $usersharedemail2->id));
2036         $this->assertTrue($result1);
2037         $this->assertTrue($result2);
2038         $this->assertStringStartsWith($usersharedemail1->email . '.', $usersharedemail1after->username);
2039         $this->assertStringStartsWith($usersharedemail2->email . '.', $usersharedemail2after->username);
2041         // Simultaneously deleting users without email addresses.
2042         $result1 = delete_user($useremptyemail1);
2043         $result2 = delete_user($useremptyemail2);
2045         $useremptyemail1after = $DB->get_record('user', array('id' => $useremptyemail1->id));
2046         $useremptyemail2after = $DB->get_record('user', array('id' => $useremptyemail2->id));
2047         $this->assertTrue($result1);
2048         $this->assertTrue($result2);
2049         $this->assertStringStartsWith($useremptyemail1->username . '.' . $useremptyemail1->id . '@unknownemail.invalid.',
2050             $useremptyemail1after->username);
2051         $this->assertStringStartsWith($useremptyemail2->username . '.' . $useremptyemail2->id . '@unknownemail.invalid.',
2052             $useremptyemail2after->username);
2054         $this->resetDebugging();
2055     }
2057     /**
2058      * Test function convert_to_array()
2059      */
2060     public function test_convert_to_array() {
2061         // Check that normal classes are converted to arrays the same way as (array) would do.
2062         $obj = new stdClass();
2063         $obj->prop1 = 'hello';
2064         $obj->prop2 = array('first', 'second', 13);
2065         $obj->prop3 = 15;
2066         $this->assertEquals(convert_to_array($obj), (array)$obj);
2068         // Check that context object (with iterator) is converted to array properly.
2069         $obj = context_system::instance();
2070         $ar = array(
2071             'id'           => $obj->id,
2072             'contextlevel' => $obj->contextlevel,
2073             'instanceid'   => $obj->instanceid,
2074             'path'         => $obj->path,
2075             'depth'        => $obj->depth
2076         );
2077         $this->assertEquals(convert_to_array($obj), $ar);
2078     }
2080     /**
2081      * Test the function date_format_string().
2082      */
2083     public function test_date_format_string() {
2084         global $CFG;
2086         $this->resetAfterTest();
2087         $this->setTimezone(99, 'Australia/Perth');
2089         $tests = array(
2090             array(
2091                 'tz' => 99,
2092                 'str' => '%A, %d %B %Y, %I:%M %p',
2093                 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
2094             ),
2095             array(
2096                 'tz' => 0,
2097                 'str' => '%A, %d %B %Y, %I:%M %p',
2098                 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2099             ),
2100             array(
2101                 // Note: this function expected the timestamp in weird format before,
2102                 // since 2.9 it uses UTC.
2103                 'tz' => 'Pacific/Auckland',
2104                 'str' => '%A, %d %B %Y, %I:%M %p',
2105                 'expected' => 'Saturday, 01 January 2011, 11:00 PM'
2106             ),
2107             // Following tests pass on Windows only because en lang pack does
2108             // not contain localewincharset, in real life lang pack maintainers
2109             // may use only characters that are present in localewincharset
2110             // in format strings!
2111             array(
2112                 'tz' => 99,
2113                 'str' => 'Žluťoučký koníček %A',
2114                 'expected' => 'Žluťoučký koníček Saturday'
2115             ),
2116             array(
2117                 'tz' => 99,
2118                 'str' => '言語設定言語 %A',
2119                 'expected' => '言語設定言語 Saturday'
2120             ),
2121             array(
2122                 'tz' => 99,
2123                 'str' => '简体中文简体 %A',
2124                 'expected' => '简体中文简体 Saturday'
2125             ),
2126         );
2128         // Note: date_format_string() uses the timezone only to differenciate
2129         // the server time from the UTC time. It does not modify the timestamp.
2130         // Hence similar results for timezones <= 13.
2131         // On different systems case of AM PM changes so compare case insensitive.
2132         foreach ($tests as $test) {
2133             $str = date_format_string(1293876000, $test['str'], $test['tz']);
2134             $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
2135         }
2136     }
2138     public function test_get_config() {
2139         global $CFG;
2141         $this->resetAfterTest();
2143         // Preparation.
2144         set_config('phpunit_test_get_config_1', 'test 1');
2145         set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2146         if (!is_array($CFG->config_php_settings)) {
2147             $CFG->config_php_settings = array();
2148         }
2149         $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
2151         if (!is_array($CFG->forced_plugin_settings)) {
2152             $CFG->forced_plugin_settings = array();
2153         }
2154         if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
2155             $CFG->forced_plugin_settings['mod_forum'] = array();
2156         }
2157         $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2158         $CFG->phpunit_test_get_config_5 = 'test 5';
2160         // Testing.
2161         $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
2162         $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2163         $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
2164         $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2165         $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2166         $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2167         $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2169         // Test config we know to exist.
2170         $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
2171         $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2172         $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2173         $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2175         // Test setting a config var that already exists.
2176         set_config('phpunit_test_get_config_1', 'test a');
2177         $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
2178         $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
2180         // Test cache invalidation.
2181         $cache = cache::make('core', 'config');
2182         $this->assertInternalType('array', $cache->get('core'));
2183         $this->assertInternalType('array', $cache->get('mod_forum'));
2184         set_config('phpunit_test_get_config_1', 'test b');
2185         $this->assertFalse($cache->get('core'));
2186         set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2187         $this->assertFalse($cache->get('mod_forum'));
2188     }
2190     public function test_get_max_upload_sizes() {
2191         // Test with very low limits so we are not affected by php upload limits.
2192         // Test activity limit smallest.
2193         $sitebytes = 102400;
2194         $coursebytes = 51200;
2195         $modulebytes = 10240;
2196         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2198         $this->assertSame('Activity upload limit (10KB)', $result['0']);
2199         $this->assertCount(2, $result);
2201         // Test course limit smallest.
2202         $sitebytes = 102400;
2203         $coursebytes = 10240;
2204         $modulebytes = 51200;
2205         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2207         $this->assertSame('Course upload limit (10KB)', $result['0']);
2208         $this->assertCount(2, $result);
2210         // Test site limit smallest.
2211         $sitebytes = 10240;
2212         $coursebytes = 102400;
2213         $modulebytes = 51200;
2214         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2216         $this->assertSame('Site upload limit (10KB)', $result['0']);
2217         $this->assertCount(2, $result);
2219         // Test site limit not set.
2220         $sitebytes = 0;
2221         $coursebytes = 102400;
2222         $modulebytes = 51200;
2223         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2225         $this->assertSame('Activity upload limit (50KB)', $result['0']);
2226         $this->assertCount(3, $result);
2228         $sitebytes = 0;
2229         $coursebytes = 51200;
2230         $modulebytes = 102400;
2231         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2233         $this->assertSame('Course upload limit (50KB)', $result['0']);
2234         $this->assertCount(3, $result);
2236         // Test custom bytes in range.
2237         $sitebytes = 102400;
2238         $coursebytes = 51200;
2239         $modulebytes = 51200;
2240         $custombytes = 10240;
2241         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2243         $this->assertCount(3, $result);
2245         // Test custom bytes in range but non-standard.
2246         $sitebytes = 102400;
2247         $coursebytes = 51200;
2248         $modulebytes = 51200;
2249         $custombytes = 25600;
2250         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2252         $this->assertCount(4, $result);
2254         // Test custom bytes out of range.
2255         $sitebytes = 102400;
2256         $coursebytes = 51200;
2257         $modulebytes = 51200;
2258         $custombytes = 102400;
2259         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2261         $this->assertCount(3, $result);
2263         // Test custom bytes out of range and non-standard.
2264         $sitebytes = 102400;
2265         $coursebytes = 51200;
2266         $modulebytes = 51200;
2267         $custombytes = 256000;
2268         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2270         $this->assertCount(3, $result);
2272         // Test site limit only.
2273         $sitebytes = 51200;
2274         $result = get_max_upload_sizes($sitebytes);
2276         $this->assertSame('Site upload limit (50KB)', $result['0']);
2277         $this->assertSame('50KB', $result['51200']);
2278         $this->assertSame('10KB', $result['10240']);
2279         $this->assertCount(3, $result);
2281         // Test no limit.
2282         $result = get_max_upload_sizes();
2283         $this->assertArrayHasKey('0', $result);
2284         $this->assertArrayHasKey(get_max_upload_file_size(), $result);
2285     }
2287     /**
2288      * Test function password_is_legacy_hash().
2289      */
2290     public function test_password_is_legacy_hash() {
2291         // Well formed md5s should be matched.
2292         foreach (array('some', 'strings', 'to_check!') as $string) {
2293             $md5 = md5($string);
2294             $this->assertTrue(password_is_legacy_hash($md5));
2295         }
2296         // Strings that are not md5s should not be matched.
2297         foreach (array('', AUTH_PASSWORD_NOT_CACHED, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
2298             $this->assertFalse(password_is_legacy_hash($notmd5));
2299         }
2300     }
2302     /**
2303      * Test function validate_internal_user_password().
2304      */
2305     public function test_validate_internal_user_password() {
2306         // Test bcrypt hashes.
2307         $validhashes = array(
2308             'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2309             'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2310             'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2311             'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
2312         );
2314         foreach ($validhashes as $password => $hash) {
2315             $user = new stdClass();
2316             $user->auth = 'manual';
2317             $user->password = $hash;
2318             // The correct password should be validated.
2319             $this->assertTrue(validate_internal_user_password($user, $password));
2320             // An incorrect password should not be validated.
2321             $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2322         }
2323     }
2325     /**
2326      * Test function hash_internal_user_password().
2327      */
2328     public function test_hash_internal_user_password() {
2329         $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2331         // Check that some passwords that we convert to hashes can
2332         // be validated.
2333         foreach ($passwords as $password) {
2334             $hash = hash_internal_user_password($password);
2335             $fasthash = hash_internal_user_password($password, true);
2336             $user = new stdClass();
2337             $user->auth = 'manual';
2338             $user->password = $hash;
2339             $this->assertTrue(validate_internal_user_password($user, $password));
2341             // They should not be in md5 format.
2342             $this->assertFalse(password_is_legacy_hash($hash));
2344             // Check that cost factor in hash is correctly set.
2345             $this->assertRegExp('/\$10\$/', $hash);
2346             $this->assertRegExp('/\$04\$/', $fasthash);
2347         }
2348     }
2350     /**
2351      * Test function update_internal_user_password().
2352      */
2353     public function test_update_internal_user_password() {
2354         global $DB;
2355         $this->resetAfterTest();
2356         $passwords = array('password', '1234', 'changeme', '****');
2357         foreach ($passwords as $password) {
2358             $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2359             update_internal_user_password($user, $password);
2360             // The user object should have been updated.
2361             $this->assertTrue(validate_internal_user_password($user, $password));
2362             // The database field for the user should also have been updated to the
2363             // same value.
2364             $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
2365         }
2367         $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2368         // Manually set the user's password to the md5 of the string 'password'.
2369         $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
2371         $sink = $this->redirectEvents();
2372         // Update the password.
2373         update_internal_user_password($user, 'password');
2374         $events = $sink->get_events();
2375         $sink->close();
2376         $event = array_pop($events);
2378         // Password should have been updated to a bcrypt hash.
2379         $this->assertFalse(password_is_legacy_hash($user->password));
2381         // Verify event information.
2382         $this->assertInstanceOf('\core\event\user_password_updated', $event);
2383         $this->assertSame($user->id, $event->relateduserid);
2384         $this->assertEquals(context_user::instance($user->id), $event->get_context());
2385         $this->assertEventContextNotUsed($event);
2387         // Verify recovery of property 'auth'.
2388         unset($user->auth);
2389         update_internal_user_password($user, 'newpassword');
2390         $this->assertDebuggingCalled('User record in update_internal_user_password() must include field auth',
2391                 DEBUG_DEVELOPER);
2392         $this->assertEquals('manual', $user->auth);
2393     }
2395     /**
2396      * Testing that if the password is not cached, that it does not update
2397      * the user table and fire event.
2398      */
2399     public function test_update_internal_user_password_no_cache() {
2400         $this->resetAfterTest();
2402         $user = $this->getDataGenerator()->create_user(array('auth' => 'cas'));
2403         $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2405         $sink = $this->redirectEvents();
2406         update_internal_user_password($user, 'wonkawonka');
2407         $this->assertEquals(0, $sink->count(), 'User updated event should not fire');
2408     }
2410     /**
2411      * Test if the user has a password hash, but now their auth method
2412      * says not to cache it.  Then it should update.
2413      */
2414     public function test_update_internal_user_password_update_no_cache() {
2415         $this->resetAfterTest();
2417         $user = $this->getDataGenerator()->create_user(array('password' => 'test'));
2418         $this->assertNotEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2419         $user->auth = 'cas'; // Change to a auth that does not store passwords.
2421         $sink = $this->redirectEvents();
2422         update_internal_user_password($user, 'wonkawonka');
2423         $this->assertGreaterThanOrEqual(1, $sink->count(), 'User updated event should fire');
2425         $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2426     }
2428     public function test_fullname() {
2429         global $CFG;
2431         $this->resetAfterTest();
2433         // Create a user to test the name display on.
2434         $record = array();
2435         $record['firstname'] = 'Scott';
2436         $record['lastname'] = 'Fletcher';
2437         $record['firstnamephonetic'] = 'スコット';
2438         $record['lastnamephonetic'] = 'フレチャー';
2439         $record['alternatename'] = 'No friends';
2440         $user = $this->getDataGenerator()->create_user($record);
2442         // Back up config settings for restore later.
2443         $originalcfg = new stdClass();
2444         $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
2445         $originalcfg->alternativefullnameformat = $CFG->alternativefullnameformat;
2447         // Testing existing fullnamedisplay settings.
2448         $CFG->fullnamedisplay = 'firstname';
2449         $testname = fullname($user);
2450         $this->assertSame($user->firstname, $testname);
2452         $CFG->fullnamedisplay = 'firstname lastname';
2453         $expectedname = "$user->firstname $user->lastname";
2454         $testname = fullname($user);
2455         $this->assertSame($expectedname, $testname);
2457         $CFG->fullnamedisplay = 'lastname firstname';
2458         $expectedname = "$user->lastname $user->firstname";
2459         $testname = fullname($user);
2460         $this->assertSame($expectedname, $testname);
2462         $expectedname = get_string('fullnamedisplay', null, $user);
2463         $CFG->fullnamedisplay = 'language';
2464         $testname = fullname($user);
2465         $this->assertSame($expectedname, $testname);
2467         // Test override parameter.
2468         $CFG->fullnamedisplay = 'firstname';
2469         $expectedname = "$user->firstname $user->lastname";
2470         $testname = fullname($user, true);
2471         $this->assertSame($expectedname, $testname);
2473         // Test alternativefullnameformat setting.
2474         // Test alternativefullnameformat that has been set to nothing.
2475         $CFG->alternativefullnameformat = '';
2476         $expectedname = "$user->firstname $user->lastname";
2477         $testname = fullname($user, true);
2478         $this->assertSame($expectedname, $testname);
2480         // Test alternativefullnameformat that has been set to 'language'.
2481         $CFG->alternativefullnameformat = 'language';
2482         $expectedname = "$user->firstname $user->lastname";
2483         $testname = fullname($user, true);
2484         $this->assertSame($expectedname, $testname);
2486         // Test customising the alternativefullnameformat setting with all additional name fields.
2487         $CFG->alternativefullnameformat = 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename';
2488         $expectedname = "$user->firstname $user->lastname $user->firstnamephonetic $user->lastnamephonetic $user->middlename $user->alternatename";
2489         $testname = fullname($user, true);
2490         $this->assertSame($expectedname, $testname);
2492         // Test additional name fields.
2493         $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
2494         $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
2495         $testname = fullname($user);
2496         $this->assertSame($expectedname, $testname);
2498         // Test for handling missing data.
2499         $user->middlename = null;
2500         // Parenthesis with no data.
2501         $CFG->fullnamedisplay = 'firstname (middlename) lastname';
2502         $expectedname = "$user->firstname $user->lastname";
2503         $testname = fullname($user);
2504         $this->assertSame($expectedname, $testname);
2506         // Extra spaces due to no data.
2507         $CFG->fullnamedisplay = 'firstname middlename lastname';
2508         $expectedname = "$user->firstname $user->lastname";
2509         $testname = fullname($user);
2510         $this->assertSame($expectedname, $testname);
2512         // Regular expression testing.
2513         // Remove some data from the user fields.
2514         $user->firstnamephonetic = '';
2515         $user->lastnamephonetic = '';
2517         // Removing empty brackets and excess whitespace.
2518         // All of these configurations should resolve to just firstname lastname.
2519         $configarray = array();
2520         $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
2521         $configarray[] = 'firstname lastname \'middlename\'';
2522         $configarray[] = 'firstname "firstnamephonetic" lastname';
2523         $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
2525         foreach ($configarray as $config) {
2526             $CFG->fullnamedisplay = $config;
2527             $expectedname = "$user->firstname $user->lastname";
2528             $testname = fullname($user);
2529             $this->assertSame($expectedname, $testname);
2530         }
2532         // Check to make sure that other characters are left in place.
2533         $configarray = array();
2534         $configarray['0'] = new stdClass();
2535         $configarray['0']->config = 'lastname firstname, middlename';
2536         $configarray['0']->expectedname = "$user->lastname $user->firstname,";
2537         $configarray['1'] = new stdClass();
2538         $configarray['1']->config = 'lastname firstname + alternatename';
2539         $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
2540         $configarray['2'] = new stdClass();
2541         $configarray['2']->config = 'firstname aka: alternatename';
2542         $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
2543         $configarray['3'] = new stdClass();
2544         $configarray['3']->config = 'firstname (alternatename)';
2545         $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
2546         $configarray['4'] = new stdClass();
2547         $configarray['4']->config = 'firstname [alternatename]';
2548         $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
2549         $configarray['5'] = new stdClass();
2550         $configarray['5']->config = 'firstname "lastname"';
2551         $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
2553         foreach ($configarray as $config) {
2554             $CFG->fullnamedisplay = $config->config;
2555             $expectedname = $config->expectedname;
2556             $testname = fullname($user);
2557             $this->assertSame($expectedname, $testname);
2558         }
2560         // Test debugging message displays when
2561         // fullnamedisplay setting is "normal".
2562         $CFG->fullnamedisplay = 'firstname lastname';
2563         unset($user);
2564         $user = new stdClass();
2565         $user->firstname = 'Stan';
2566         $user->lastname = 'Lee';
2567         $namedisplay = fullname($user);
2568         $this->assertDebuggingCalled();
2570         // Tidy up after we finish testing.
2571         $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
2572         $CFG->alternativefullnameformat = $originalcfg->alternativefullnameformat;
2573     }
2575     public function test_get_all_user_name_fields() {
2576         $this->resetAfterTest();
2578         // Additional names in an array.
2579         $testarray = array('firstnamephonetic' => 'firstnamephonetic',
2580                 'lastnamephonetic' => 'lastnamephonetic',
2581                 'middlename' => 'middlename',
2582                 'alternatename' => 'alternatename',
2583                 'firstname' => 'firstname',
2584                 'lastname' => 'lastname');
2585         $this->assertEquals($testarray, get_all_user_name_fields());
2587         // Additional names as a string.
2588         $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
2589         $this->assertEquals($teststring, get_all_user_name_fields(true));
2591         // Additional names as a string with an alias.
2592         $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
2593         $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
2595         // Additional name fields with a prefix - object.
2596         $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
2597                 'lastnamephonetic' => 'authorlastnamephonetic',
2598                 'middlename' => 'authormiddlename',
2599                 'alternatename' => 'authoralternatename',
2600                 'firstname' => 'authorfirstname',
2601                 'lastname' => 'authorlastname');
2602         $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
2604         // Additional name fields with an alias and a title - string.
2605         $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';
2606         $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
2608         // Test the order parameter of the function.
2609         // Returning an array.
2610         $testarray = array('firstname' => 'firstname',
2611                 'lastname' => 'lastname',
2612                 'firstnamephonetic' => 'firstnamephonetic',
2613                 'lastnamephonetic' => 'lastnamephonetic',
2614                 'middlename' => 'middlename',
2615                 'alternatename' => 'alternatename'
2616         );
2617         $this->assertEquals($testarray, get_all_user_name_fields(false, null, null, null, true));
2619         // Returning a string.
2620         $teststring = 'firstname,lastname,firstnamephonetic,lastnamephonetic,middlename,alternatename';
2621         $this->assertEquals($teststring, get_all_user_name_fields(true, null, null, null, true));
2622     }
2624     public function test_order_in_string() {
2625         $this->resetAfterTest();
2627         // Return an array in an order as they are encountered in a string.
2628         $valuearray = array('second', 'firsthalf', 'first');
2629         $formatstring = 'first firsthalf some other text (second)';
2630         $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
2631         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2633         // Try again with a different order for the format.
2634         $valuearray = array('second', 'firsthalf', 'first');
2635         $formatstring = 'firsthalf first second';
2636         $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
2637         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2639         // Try again with yet another different order for the format.
2640         $valuearray = array('second', 'firsthalf', 'first');
2641         $formatstring = 'start seconds away second firstquater first firsthalf';
2642         $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
2643         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2644     }
2646     public function test_complete_user_login() {
2647         global $USER, $DB;
2649         $this->resetAfterTest();
2650         $user = $this->getDataGenerator()->create_user();
2651         $this->setUser(0);
2653         $sink = $this->redirectEvents();
2654         $loginuser = clone($user);
2655         $this->setCurrentTimeStart();
2656         @complete_user_login($loginuser); // Hide session header errors.
2657         $this->assertSame($loginuser, $USER);
2658         $this->assertEquals($user->id, $USER->id);
2659         $events = $sink->get_events();
2660         $sink->close();
2662         $this->assertCount(1, $events);
2663         $event = reset($events);
2664         $this->assertInstanceOf('\core\event\user_loggedin', $event);
2665         $this->assertEquals('user', $event->objecttable);
2666         $this->assertEquals($user->id, $event->objectid);
2667         $this->assertEquals(context_system::instance()->id, $event->contextid);
2668         $this->assertEventContextNotUsed($event);
2670         $user = $DB->get_record('user', array('id'=>$user->id));
2672         $this->assertTimeCurrent($user->firstaccess);
2673         $this->assertTimeCurrent($user->lastaccess);
2675         $this->assertTimeCurrent($USER->firstaccess);
2676         $this->assertTimeCurrent($USER->lastaccess);
2677         $this->assertTimeCurrent($USER->currentlogin);
2678         $this->assertSame(sesskey(), $USER->sesskey);
2679         $this->assertTimeCurrent($USER->preference['_lastloaded']);
2680         $this->assertObjectNotHasAttribute('password', $USER);
2681         $this->assertObjectNotHasAttribute('description', $USER);
2682     }
2684     /**
2685      * Test require_logout.
2686      */
2687     public function test_require_logout() {
2688         $this->resetAfterTest();
2689         $user = $this->getDataGenerator()->create_user();
2690         $this->setUser($user);
2692         $this->assertTrue(isloggedin());
2694         // Logout user and capture event.
2695         $sink = $this->redirectEvents();
2696         require_logout();
2697         $events = $sink->get_events();
2698         $sink->close();
2699         $event = array_pop($events);
2701         // Check if user is logged out.
2702         $this->assertFalse(isloggedin());
2704         // Test Event.
2705         $this->assertInstanceOf('\core\event\user_loggedout', $event);
2706         $this->assertSame($user->id, $event->objectid);
2707         $this->assertSame('user_logout', $event->get_legacy_eventname());
2708         $this->assertEventLegacyData($user, $event);
2709         $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
2710             $event->objectid);
2711         $this->assertEventLegacyLogData($expectedlogdata, $event);
2712         $this->assertEventContextNotUsed($event);
2713     }
2715     /**
2716      * A data provider for testing email messageid
2717      */
2718     public function generate_email_messageid_provider() {
2719         return array(
2720             'nopath' => array(
2721                 'wwwroot' => 'http://www.example.com',
2722                 'ids' => array(
2723                     'a-custom-id' => '<a-custom-id@www.example.com>',
2724                     'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash@www.example.com>',
2725                 ),
2726             ),
2727             'path' => array(
2728                 'wwwroot' => 'http://www.example.com/path/subdir',
2729                 'ids' => array(
2730                     'a-custom-id' => '<a-custom-id/path/subdir@www.example.com>',
2731                     'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash/path/subdir@www.example.com>',
2732                 ),
2733             ),
2734         );
2735     }
2737     /**
2738      * Test email message id generation
2739      *
2740      * @dataProvider generate_email_messageid_provider
2741      *
2742      * @param string $wwwroot The wwwroot
2743      * @param array $msgids An array of msgid local parts and the final result
2744      */
2745     public function test_generate_email_messageid($wwwroot, $msgids) {
2746         global $CFG;
2748         $this->resetAfterTest();
2749         $CFG->wwwroot = $wwwroot;
2751         foreach ($msgids as $local => $final) {
2752             $this->assertEquals($final, generate_email_messageid($local));
2753         }
2754     }
2756     /**
2757      * A data provider for testing email diversion
2758      */
2759     public function diverted_emails_provider() {
2760         return array(
2761             'nodiverts' => array(
2762                 'divertallemailsto' => null,
2763                 'divertallemailsexcept' => null,
2764                 array(
2765                     'foo@example.com',
2766                     'test@real.com',
2767                     'fred.jones@example.com',
2768                     'dev1@dev.com',
2769                     'fred@example.com',
2770                     'fred+verp@example.com',
2771                 ),
2772                 false,
2773             ),
2774             'alldiverts' => array(
2775                 'divertallemailsto' => 'somewhere@elsewhere.com',
2776                 'divertallemailsexcept' => null,
2777                 array(
2778                     'foo@example.com',
2779                     'test@real.com',
2780                     'fred.jones@example.com',
2781                     'dev1@dev.com',
2782                     'fred@example.com',
2783                     'fred+verp@example.com',
2784                 ),
2785                 true,
2786             ),
2787             'alsodiverts' => array(
2788                 'divertallemailsto' => 'somewhere@elsewhere.com',
2789                 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
2790                 array(
2791                     'foo@example.com',
2792                     'test@real.com',
2793                     'fred.jones@example.com',
2794                 ),
2795                 true,
2796             ),
2797             'divertsexceptions' => array(
2798                 'divertallemailsto' => 'somewhere@elsewhere.com',
2799                 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
2800                 array(
2801                     'dev1@dev.com',
2802                     'fred@example.com',
2803                     'fred+verp@example.com',
2804                 ),
2805                 false,
2806             ),
2807         );
2808     }
2810     /**
2811      * Test email diversion
2812      *
2813      * @dataProvider diverted_emails_provider
2814      *
2815      * @param string $divertallemailsto An optional email address
2816      * @param string $divertallemailsexcept An optional exclusion list
2817      * @param array $addresses An array of test addresses
2818      * @param boolean $expected Expected result
2819      */
2820     public function test_email_should_be_diverted($divertallemailsto, $divertallemailsexcept, $addresses, $expected) {
2821         global $CFG;
2823         $this->resetAfterTest();
2824         $CFG->divertallemailsto = $divertallemailsto;
2825         $CFG->divertallemailsexcept = $divertallemailsexcept;
2827         foreach ($addresses as $address) {
2828             $this->assertEquals($expected, email_should_be_diverted($address));
2829         }
2830     }
2832     public function test_email_to_user() {
2833         global $CFG;
2835         $this->resetAfterTest();
2837         $user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
2838         $user2 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
2839         $user3 = $this->getDataGenerator()->create_user(array('maildisplay' => 0));
2840         set_config('allowedemaildomains', "example.com\r\nmoodle.org");
2842         $subject = 'subject';
2843         $messagetext = 'message text';
2844         $subject2 = 'subject 2';
2845         $messagetext2 = 'message text 2';
2847         // Close the default email sink.
2848         $sink = $this->redirectEmails();
2849         $sink->close();
2851         $CFG->noemailever = true;
2852         $this->assertNotEmpty($CFG->noemailever);
2853         email_to_user($user1, $user2, $subject, $messagetext);
2854         $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
2856         unset_config('noemailever');
2858         email_to_user($user1, $user2, $subject, $messagetext);
2859         $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2861         $sink = $this->redirectEmails();
2862         email_to_user($user1, $user2, $subject, $messagetext);
2863         email_to_user($user2, $user1, $subject2, $messagetext2);
2864         $this->assertSame(2, $sink->count());
2865         $result = $sink->get_messages();
2866         $this->assertCount(2, $result);
2867         $sink->close();
2869         $this->assertSame($subject, $result[0]->subject);
2870         $this->assertSame($messagetext, trim($result[0]->body));
2871         $this->assertSame($user1->email, $result[0]->to);
2872         $this->assertSame($user2->email, $result[0]->from);
2874         $this->assertSame($subject2, $result[1]->subject);
2875         $this->assertSame($messagetext2, trim($result[1]->body));
2876         $this->assertSame($user2->email, $result[1]->to);
2877         $this->assertSame($user1->email, $result[1]->from);
2879         email_to_user($user1, $user2, $subject, $messagetext);
2880         $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2882         // Test that an empty noreplyaddress will default to a no-reply address.
2883         $sink = $this->redirectEmails();
2884         email_to_user($user1, $user3, $subject, $messagetext);
2885         $result = $sink->get_messages();
2886         $this->assertEquals($CFG->noreplyaddress, $result[0]->from);
2887         $sink->close();
2888         set_config('noreplyaddress', '');
2889         $sink = $this->redirectEmails();
2890         email_to_user($user1, $user3, $subject, $messagetext);
2891         $result = $sink->get_messages();
2892         $this->assertEquals('noreply@www.example.com', $result[0]->from);
2893         $sink->close();
2895         // Test $CFG->allowedemaildomains.
2896         set_config('noreplyaddress', 'noreply@www.example.com');
2897         $this->assertNotEmpty($CFG->allowedemaildomains);
2898         $sink = $this->redirectEmails();
2899         email_to_user($user1, $user2, $subject, $messagetext);
2900         unset_config('allowedemaildomains');
2901         email_to_user($user1, $user2, $subject, $messagetext);
2902         $result = $sink->get_messages();
2903         $this->assertNotEquals($CFG->noreplyaddress, $result[0]->from);
2904         $this->assertEquals($CFG->noreplyaddress, $result[1]->from);
2905         $sink->close();
2907         // Try to send an unsafe attachment, we should see an error message in the eventual mail body.
2908         $attachment = '../test.txt';
2909         $attachname = 'txt';
2911         $sink = $this->redirectEmails();
2912         email_to_user($user1, $user2, $subject, $messagetext, '', $attachment, $attachname);
2913         $this->assertSame(1, $sink->count());
2914         $result = $sink->get_messages();
2915         $this->assertCount(1, $result);
2916         $this->assertContains('error.txt', $result[0]->body);
2917         $this->assertContains('Error in attachment.  User attempted to attach a filename with a unsafe name.', $result[0]->body);
2918         $sink->close();
2919     }
2921     /**
2922      * Test setnew_password_and_mail.
2923      */
2924     public function test_setnew_password_and_mail() {
2925         global $DB, $CFG;
2927         $this->resetAfterTest();
2929         $user = $this->getDataGenerator()->create_user();
2931         // Update user password.
2932         $sink = $this->redirectEvents();
2933         $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
2934         setnew_password_and_mail($user);
2935         $events = $sink->get_events();
2936         $sink->close();
2937         $sink2->close();
2938         $event = array_pop($events);
2940         // Test updated value.
2941         $dbuser = $DB->get_record('user', array('id' => $user->id));
2942         $this->assertSame($user->firstname, $dbuser->firstname);
2943         $this->assertNotEmpty($dbuser->password);
2945         // Test event.
2946         $this->assertInstanceOf('\core\event\user_password_updated', $event);
2947         $this->assertSame($user->id, $event->relateduserid);
2948         $this->assertEquals(context_user::instance($user->id), $event->get_context());
2949         $this->assertEventContextNotUsed($event);
2950     }
2952     /**
2953      * Data provider for test_generate_confirmation_link
2954      * @return Array of confirmation urls and expected resultant confirmation links
2955      */
2956     public function generate_confirmation_link_provider() {
2957         global $CFG;
2958         return [
2959             "Simple name" => [
2960                 "username" => "simplename",
2961                 "confirmationurl" => null,
2962                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/simplename"
2963             ],
2964             "Period in between words in username" => [
2965                 "username" => "period.inbetween",
2966                 "confirmationurl" => null,
2967                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/period%2Einbetween"
2968             ],
2969             "Trailing periods in username" => [
2970                 "username" => "trailingperiods...",
2971                 "confirmationurl" => null,
2972                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/trailingperiods%2E%2E%2E"
2973             ],
2974             "At symbol in username" => [
2975                 "username" => "at@symbol",
2976                 "confirmationurl" => null,
2977                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/at%40symbol"
2978             ],
2979             "Dash symbol in username" => [
2980                 "username" => "has-dash",
2981                 "confirmationurl" => null,
2982                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/has-dash"
2983             ],
2984             "Underscore in username" => [
2985                 "username" => "under_score",
2986                 "confirmationurl" => null,
2987                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/under_score"
2988             ],
2989             "Many different characters in username" => [
2990                 "username" => "many_-.@characters@_@-..-..",
2991                 "confirmationurl" => null,
2992                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
2993             ],
2994             "Custom relative confirmation url" => [
2995                 "username" => "many_-.@characters@_@-..-..",
2996                 "confirmationurl" => "/custom/local/url.php",
2997                 "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
2998             ],
2999             "Custom relative confirmation url with parameters" => [
3000                 "username" => "many_-.@characters@_@-..-..",
3001                 "confirmationurl" => "/custom/local/url.php?with=param",
3002                 "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3003             ],
3004             "Custom local confirmation url" => [
3005                 "username" => "many_-.@characters@_@-..-..",
3006                 "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php",
3007                 "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3008             ],
3009             "Custom local confirmation url with parameters" => [
3010                 "username" => "many_-.@characters@_@-..-..",
3011                 "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php?with=param",
3012                 "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3013             ],
3014             "Custom external confirmation url" => [
3015                 "username" => "many_-.@characters@_@-..-..",
3016                 "confirmationurl" => "http://moodle.org/custom/external/url.php",
3017                 "expected" => "http://moodle.org/custom/external/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3018             ],
3019             "Custom external confirmation url with parameters" => [
3020                 "username" => "many_-.@characters@_@-..-..",
3021                 "confirmationurl" => "http://moodle.org/ext.php?with=some&param=eters",
3022                 "expected" => "http://moodle.org/ext.php?with=some&param=eters&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3023             ],
3024             "Custom external confirmation url with parameters" => [
3025                 "username" => "many_-.@characters@_@-..-..",
3026                 "confirmationurl" => "http://moodle.org/ext.php?with=some&data=test",
3027                 "expected" => "http://moodle.org/ext.php?with=some&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3028             ],
3029         ];
3030     }
3032     /**
3033      * Test generate_confirmation_link
3034      * @dataProvider generate_confirmation_link_provider
3035      * @param string $username The name of the user
3036      * @param string $confirmationurl The url the user should go to to confirm
3037      * @param string $expected The expected url of the confirmation link
3038      */
3039     public function test_generate_confirmation_link($username, $confirmationurl, $expected) {
3040         $this->resetAfterTest();
3041         $sink = $this->redirectEmails();
3043         $user = $this->getDataGenerator()->create_user(
3044             [
3045                 "username" => $username,
3046                 "confirmed" => false,
3047                 "email" => 'test@example.com',
3048             ]
3049         );
3051         send_confirmation_email($user, $confirmationurl);
3052         $sink->close();
3053         $messages = $sink->get_messages();
3054         $message = array_shift($messages);
3055         $messagebody = quoted_printable_decode($message->body);
3057         $this->assertContains($expected, $messagebody);
3058     }
3060     /**
3061      * Test generate_confirmation_link with custom admin link
3062      */
3063     public function test_generate_confirmation_link_with_custom_admin() {
3064         global $CFG;
3066         $this->resetAfterTest();
3067         $sink = $this->redirectEmails();
3069         $admin = $CFG->admin;
3070         $CFG->admin = 'custom/admin/path';
3072         $user = $this->getDataGenerator()->create_user(
3073             [
3074                 "username" => "many_-.@characters@_@-..-..",
3075                 "confirmed" => false,
3076                 "email" => 'test@example.com',
3077             ]
3078         );
3079         $confirmationurl = "/admin/test.php?with=params";
3080         $expected = $CFG->wwwroot . "/" . $CFG->admin . "/test.php?with=params&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E";
3082         send_confirmation_email($user, $confirmationurl);
3083         $sink->close();
3084         $messages = $sink->get_messages();
3085         $message = array_shift($messages);
3086         $messagebody = quoted_printable_decode($message->body);
3088         $sink->close();
3089         $this->assertContains($expected, $messagebody);
3091         $CFG->admin = $admin;
3092     }
3095     /**
3096      * Test remove_course_content deletes course contents
3097      * TODO Add asserts to verify other data related to course is deleted as well.
3098      */
3099     public function test_remove_course_contents() {
3101         $this->resetAfterTest();
3103         $course = $this->getDataGenerator()->create_course();
3104         $user = $this->getDataGenerator()->create_user();
3105         $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
3106         $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id));
3108         $this->assertNotEquals(false, note_load($note->id));
3109         remove_course_contents($course->id, false);
3110         $this->assertFalse(note_load($note->id));
3111     }
3113     /**
3114      * Test function username_load_fields_from_object().
3115      */
3116     public function test_username_load_fields_from_object() {
3117         $this->resetAfterTest();
3119         // This object represents the information returned from an sql query.
3120         $userinfo = new stdClass();
3121         $userinfo->userid = 1;
3122         $userinfo->username = 'loosebruce';
3123         $userinfo->firstname = 'Bruce';
3124         $userinfo->lastname = 'Campbell';
3125         $userinfo->firstnamephonetic = 'ブルース';
3126         $userinfo->lastnamephonetic = 'カンベッル';
3127         $userinfo->middlename = '';
3128         $userinfo->alternatename = '';
3129         $userinfo->email = '';
3130         $userinfo->picture = 23;
3131         $userinfo->imagealt = 'Michael Jordan draining another basket.';
3132         $userinfo->idnumber = 3982;
3134         // Just user name fields.
3135         $user = new stdClass();
3136         $user = username_load_fields_from_object($user, $userinfo);
3137         $expectedarray = new stdClass();
3138         $expectedarray->firstname = 'Bruce';
3139         $expectedarray->lastname = 'Campbell';
3140         $expectedarray->firstnamephonetic = 'ブルース';
3141         $expectedarray->lastnamephonetic = 'カンベッル';
3142         $expectedarray->middlename = '';
3143         $expectedarray->alternatename = '';
3144         $this->assertEquals($user, $expectedarray);
3146         // User information for showing a picture.
3147         $user = new stdClass();
3148         $additionalfields = explode(',', user_picture::fields());
3149         $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
3150         $user->id = $userinfo->userid;
3151         $expectedarray = new stdClass();
3152         $expectedarray->id = 1;
3153         $expectedarray->firstname = 'Bruce';
3154         $expectedarray->lastname = 'Campbell';
3155         $expectedarray->firstnamephonetic = 'ブルース';
3156         $expectedarray->lastnamephonetic = 'カンベッル';
3157         $expectedarray->middlename = '';
3158         $expectedarray->alternatename = '';
3159         $expectedarray->email = '';
3160         $expectedarray->picture = 23;
3161         $expectedarray->imagealt = 'Michael Jordan draining another basket.';
3162         $this->assertEquals($user, $expectedarray);
3164         // Alter the userinfo object to have a prefix.
3165         $userinfo->authorfirstname = 'Bruce';
3166         $userinfo->authorlastname = 'Campbell';
3167         $userinfo->authorfirstnamephonetic = 'ブルース';
3168         $userinfo->authorlastnamephonetic = 'カンベッル';
3169         $userinfo->authormiddlename = '';
3170         $userinfo->authorpicture = 23;
3171         $userinfo->authorimagealt = 'Michael Jordan draining another basket.';
3172         $userinfo->authoremail = 'test@example.com';
3175         // Return an object with user picture information.
3176         $user = new stdClass();
3177         $additionalfields = explode(',', user_picture::fields());
3178         $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
3179         $user->id = $userinfo->userid;
3180         $expectedarray = new stdClass();
3181         $expectedarray->id = 1;
3182         $expectedarray->firstname = 'Bruce';
3183         $expectedarray->lastname = 'Campbell';
3184         $expectedarray->firstnamephonetic = 'ブルース';
3185         $expectedarray->lastnamephonetic = 'カンベッル';
3186         $expectedarray->middlename = '';
3187         $expectedarray->alternatename = '';
3188         $expectedarray->email = 'test@example.com';
3189         $expectedarray->picture = 23;
3190         $expectedarray->imagealt = 'Michael Jordan draining another basket.';
3191         $this->assertEquals($user, $expectedarray);
3192     }
3194     /**
3195      * Test function count_words().
3196      */
3197     public function test_count_words() {
3198         $count = count_words("one two three'four");
3199         $this->assertEquals(3, $count);
3201         $count = count_words('one+two three’four');
3202         $this->assertEquals(3, $count);
3204         $count = count_words('one"two three-four');
3205         $this->assertEquals(2, $count);
3207         $count = count_words('one@two three_four');
3208         $this->assertEquals(4, $count);
3210         $count = count_words('one\two three/four');
3211         $this->assertEquals(4, $count);
3213         $count = count_words(' one ... two &nbsp; three...four ');
3214         $this->assertEquals(4, $count);
3216         $count = count_words('one.2 3,four');
3217         $this->assertEquals(4, $count);
3219         $count = count_words('1³ £2 €3.45 $6,789');
3220         $this->assertEquals(4, $count);
3222         $count = count_words('one—two ブルース カンベッル');
3223         $this->assertEquals(4, $count);
3225         $count = count_words('one…two ブルース … カンベッル');
3226         $this->assertEquals(4, $count);
3227     }
3228     /**
3229      * Tests the getremoteaddr() function.
3230      */
3231     public function test_getremoteaddr() {
3232         $xforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null;
3234         $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
3235         $noip = getremoteaddr('1.1.1.1');
3236         $this->assertEquals('1.1.1.1', $noip);
3238         $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
3239         $noip = getremoteaddr();
3240         $this->assertEquals('0.0.0.0', $noip);
3242         $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1';
3243         $singleip = getremoteaddr();
3244         $this->assertEquals('127.0.0.1', $singleip);
3246         $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2';
3247         $twoip = getremoteaddr();
3248         $this->assertEquals('127.0.0.1', $twoip);
3250         $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2, 127.0.0.3';
3251         $threeip = getremoteaddr();
3252         $this->assertEquals('127.0.0.1', $threeip);
3254         $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1:65535,127.0.0.2';
3255         $portip = getremoteaddr();
3256         $this->assertEquals('127.0.0.1', $portip);
3258         $_SERVER['HTTP_X_FORWARDED_FOR'] = '0:0:0:0:0:0:0:1,127.0.0.2';
3259         $portip = getremoteaddr();
3260         $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3262         $_SERVER['HTTP_X_FORWARDED_FOR'] = '0::1,127.0.0.2';
3263         $portip = getremoteaddr();
3264         $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3266         $_SERVER['HTTP_X_FORWARDED_FOR'] = '[0:0:0:0:0:0:0:1]:65535,127.0.0.2';
3267         $portip = getremoteaddr();
3268         $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3270         $_SERVER['HTTP_X_FORWARDED_FOR'] = $xforwardedfor;
3272     }
3274     /*
3275      * Test emulation of random_bytes() function.
3276      */
3277     public function test_random_bytes_emulate() {
3278         $result = random_bytes_emulate(10);
3279         $this->assertSame(10, strlen($result));
3280         $this->assertnotSame($result, random_bytes_emulate(10));
3282         $result = random_bytes_emulate(21);
3283         $this->assertSame(21, strlen($result));
3284         $this->assertnotSame($result, random_bytes_emulate(21));
3286         $result = random_bytes_emulate(666);
3287         $this->assertSame(666, strlen($result));
3289         $result = random_bytes_emulate(40);
3290         $this->assertSame(40, strlen($result));
3292         $this->assertDebuggingNotCalled();
3294         $result = random_bytes_emulate(0);
3295         $this->assertSame('', $result);
3296         $this->assertDebuggingCalled();
3298         $result = random_bytes_emulate(-1);
3299         $this->assertSame('', $result);
3300         $this->assertDebuggingCalled();
3301     }
3303     /**
3304      * Test function for creation of random strings.
3305      */
3306     public function test_random_string() {
3307         $pool = 'a-zA-Z0-9';
3309         $result = random_string(10);
3310         $this->assertSame(10, strlen($result));
3311         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3312         $this->assertNotSame($result, random_string(10));
3314         $result = random_string(21);
3315         $this->assertSame(21, strlen($result));
3316         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3317         $this->assertNotSame($result, random_string(21));
3319         $result = random_string(666);
3320         $this->assertSame(666, strlen($result));
3321         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3323         $result = random_string();
3324         $this->assertSame(15, strlen($result));
3325         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3327         $this->assertDebuggingNotCalled();
3329         $result = random_string(0);
3330         $this->assertSame('', $result);
3331         $this->assertDebuggingCalled();
3333         $result = random_string(-1);
3334         $this->assertSame('', $result);
3335         $this->assertDebuggingCalled();
3336     }
3338     /**
3339      * Test function for creation of complex random strings.
3340      */
3341     public function test_complex_random_string() {
3342         $pool = preg_quote('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#%^&*()_+-=[];,./<>?:{} ', '/');
3344         $result = complex_random_string(10);
3345         $this->assertSame(10, strlen($result));
3346         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3347         $this->assertNotSame($result, complex_random_string(10));
3349         $result = complex_random_string(21);
3350         $this->assertSame(21, strlen($result));
3351         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3352         $this->assertNotSame($result, complex_random_string(21));
3354         $result = complex_random_string(666);
3355         $this->assertSame(666, strlen($result));
3356         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3358         $result = complex_random_string();
3359         $this->assertEquals(28, strlen($result), '', 4); // Expected length is 24 - 32.
3360         $this->assertRegExp('/^[' . $pool . ']+$/', $result);
3362         $this->assertDebuggingNotCalled();
3364         $result = complex_random_string(0);
3365         $this->assertSame('', $result);
3366         $this->assertDebuggingCalled();
3368         $result = complex_random_string(-1);
3369         $this->assertSame('', $result);
3370         $this->assertDebuggingCalled();
3371     }
3373     /**
3374      * Data provider for private ips.
3375      */
3376     public function data_private_ips() {
3377         return array(
3378             array('10.0.0.0'),
3379             array('172.16.0.0'),
3380             array('192.168.1.0'),
3381             array('fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c'),
3382             array('fdc6:c46b:bb8f:7d4c:fdc6:c46b:bb8f:7d4c'),
3383             array('fdc6:c46b:bb8f:7d4c:0000:8a2e:0370:7334'),
3384             array('127.0.0.1'), // This has been buggy in past: https://bugs.php.net/bug.php?id=53150.
3385         );
3386     }
3388     /**
3389      * Checks ip_is_public returns false for private ips.
3390      *
3391      * @param string $ip the ipaddress to test
3392      * @dataProvider data_private_ips
3393      */
3394     public function test_ip_is_public_private_ips($ip) {
3395         $this->assertFalse(ip_is_public($ip));
3396     }
3398     /**
3399      * Data provider for public ips.
3400      */
3401     public function data_public_ips() {
3402         return array(
3403             array('2400:cb00:2048:1::8d65:71b3'),
3404             array('2400:6180:0:d0::1b:2001'),
3405             array('141.101.113.179'),
3406             array('123.45.67.178'),
3407         );
3408     }
3410     /**
3411      * Checks ip_is_public returns true for public ips.
3412      *
3413      * @param string $ip the ipaddress to test
3414      * @dataProvider data_public_ips
3415      */
3416     public function test_ip_is_public_public_ips($ip) {
3417         $this->assertTrue(ip_is_public($ip));
3418     }
3420     /**
3421      * Test the function can_send_from_real_email_address
3422      *
3423      * @param string $email Email address for the from user.
3424      * @param int $display The user's email display preference.
3425      * @param bool $samecourse Are the users in the same course?
3426      * @param string $config The CFG->allowedemaildomains config values
3427      * @param bool $result The expected result.
3428      * @dataProvider data_can_send_from_real_email_address
3429      */
3430     public function test_can_send_from_real_email_address($email, $display, $samecourse, $config, $result) {
3431         $this->resetAfterTest();
3433         $fromuser = $this->getDataGenerator()->create_user();
3434         $touser = $this->getDataGenerator()->create_user();
3435         $course = $this->getDataGenerator()->create_course();
3436         set_config('allowedemaildomains', $config);
3438         $fromuser->email = $email;
3439         $fromuser->maildisplay = $display;
3440         if ($samecourse) {
3441             $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student');
3442             $this->getDataGenerator()->enrol_user($touser->id, $course->id, 'student');
3443         } else {
3444             $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student');
3445         }
3446         $this->assertEquals($result, can_send_from_real_email_address($fromuser, $touser));
3447     }
3449     /**
3450      * Data provider for test_can_send_from_real_email_address.
3451      *
3452      * @return array Returns an array of test data for the above function.
3453      */
3454     public function data_can_send_from_real_email_address() {
3455         return [
3456             // Test from email is in allowed domain.
3457             // Test that from display is set to show no one.
3458             [
3459                 'email' => 'fromuser@example.com',
3460                 'display' => core_user::MAILDISPLAY_HIDE,
3461                 'samecourse' => false,
3462                 'config' => "example.com\r\ntest.com",
3463                 'result' => false
3464             ],
3465             // Test that from display is set to course members only (course member).
3466             [
3467                 'email' => 'fromuser@example.com',
3468                 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
3469                 'samecourse' => true,
3470                 'config' => "example.com\r\ntest.com",
3471                 'result' => true
3472             ],
3473             // Test that from display is set to course members only (Non course member).
3474             [
3475                 'email' => 'fromuser@example.com',
3476                 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
3477                 'samecourse' => false,
3478                 'config' => "example.com\r\ntest.com",
3479                 'result' => false
3480             ],
3481             // Test that from display is set to show everyone.
3482             [
3483                 'email' => 'fromuser@example.com',
3484                 'display' => core_user::MAILDISPLAY_EVERYONE,
3485                 'samecourse' => false,
3486                 'config' => "example.com\r\ntest.com",
3487                 'result' => true
3488             ],
3489             // Test a few different config value formats for parsing correctness.
3490             [
3491                 'email' => 'fromuser@example.com',
3492                 'display' => core_user::MAILDISPLAY_EVERYONE,
3493                 'samecourse' => false,
3494                 'config' => "\n test.com\nexample.com \n",
3495                 'result' => true
3496             ],
3497             [
3498                 'email' => 'fromuser@example.com',
3499                 'display' => core_user::MAILDISPLAY_EVERYONE,
3500                 'samecourse' => false,
3501                 'config' => "\r\n example.com \r\n test.com \r\n",
3502                 'result' => true
3503             ],
3505             // Test from email is not in allowed domain.
3506             // Test that from display is set to show no one.
3507             [   'email' => 'fromuser@moodle.com',
3508                 'display' => core_user::MAILDISPLAY_HIDE,
3509                 'samecourse' => false,
3510                 'config' => "example.com\r\ntest.com",
3511                 'result' => false
3512             ],
3513             // Test that from display is set to course members only (course member).
3514             [   'email' => 'fromuser@moodle.com',
3515                 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
3516                 'samecourse' => true,
3517                 'config' => "example.com\r\ntest.com",
3518                 'result' => false
3519             ],
3520             // Test that from display is set to course members only (Non course member.
3521             [   'email' => 'fromuser@moodle.com',
3522                 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
3523                 'samecourse' => false,
3524                 'config' => "example.com\r\ntest.com",
3525                 'result' => false
3526             ],
3527             // Test that from display is set to show everyone.
3528             [   'email' => 'fromuser@moodle.com',
3529                 'display' => core_user::MAILDISPLAY_EVERYONE,
3530                 'samecourse' => false,
3531                 'config' => "example.com\r\ntest.com",
3532                 'result' => false
3533             ],
3534             // Test a few erroneous config value and confirm failure.
3535             [   'email' => 'fromuser@moodle.com',
3536                 'display' => core_user::MAILDISPLAY_EVERYONE,
3537                 'samecourse' => false,
3538                 'config' => "\r\n   \r\n",
3539                 'result' => false
3540             ],
3541             [   'email' => 'fromuser@moodle.com',
3542                 'display' => core_user::MAILDISPLAY_EVERYONE,
3543                 'samecourse' => false,
3544                 'config' => " \n   \n \n ",
3545                 'result' => false
3546             ],
3547         ];
3548     }
3550     /**
3551      * Test that generate_email_processing_address() returns valid email address.
3552      */
3553     public function test_generate_email_processing_address() {
3554         global $CFG;
3555         $this->resetAfterTest();
3557         $data = (object)[
3558             'id' => 42,
3559             'email' => 'my.email+from_moodle@example.com',
3560         ];
3562         $modargs = 'B'.base64_encode(pack('V', $data->id)).substr(md5($data->email), 0, 16);
3564         $CFG->maildomain = 'example.com';
3565         $CFG->mailprefix = 'mdl+';
3566         $this->assertTrue(validate_email(generate_email_processing_address(0, $modargs)));
3568         $CFG->maildomain = 'mail.example.com';
3569         $CFG->mailprefix = 'mdl-';
3570         $this->assertTrue(validate_email(generate_email_processing_address(23, $modargs)));
3571     }
3573     /**
3574      * Test safe method unserialize_array().
3575      */
3576     public function test_unserialize_array() {
3577         $a = [1, 2, 3];
3578         $this->assertEquals($a, unserialize_array(serialize($a)));
3579         $this->assertEquals($a, unserialize_array(serialize($a)));
3580         $a = ['a' => 1, 2 => 2, 'b' => 'cde'];
3581         $this->assertEquals($a, unserialize_array(serialize($a)));
3582         $this->assertEquals($a, unserialize_array(serialize($a)));
3583         $a = ['a' => 1, 2 => 2, 'b' => 'c"d"e'];
3584         $this->assertEquals($a, unserialize_array(serialize($a)));
3585         $a = ['a' => 1, 2 => ['c' => 'd', 'e' => 'f'], 'b' => 'cde'];
3586         $this->assertEquals($a, unserialize_array(serialize($a)));
3588         // Can not unserialize if any string contains semicolons.
3589         $a = ['a' => 1, 2 => 2, 'b' => 'c"d";e'];
3590         $this->assertEquals(false, unserialize_array(serialize($a)));
3592         // Can not unserialize if there are any objects.
3593         $a = (object)['a' => 1, 2 => 2, 'b' => 'cde'];
3594         $this->assertEquals(false, unserialize_array(serialize($a)));
3595         $a = ['a' => 1, 2 => 2, 'b' => (object)['a' => 'cde']];
3596         $this->assertEquals(false, unserialize_array(serialize($a)));
3598         // Array used in the grader report.
3599         $a = array('aggregatesonly' => [51, 34], 'gradesonly' => [21, 45, 78]);
3600         $this->assertEquals($a, unserialize_array(serialize($a)));
3601     }
3603     /**
3604      * Test that the component_class_callback returns the correct default value when the class was not found.
3605      *
3606      * @dataProvider component_class_callback_default_provider
3607      * @param $default
3608      */
3609     public function test_component_class_callback_not_found($default) {
3610         $this->assertSame($default, component_class_callback('thisIsNotTheClassYouWereLookingFor', 'anymethod', [], $default));
3611     }
3613     /**
3614      * Test that the component_class_callback returns the correct default value when the class was not found.
3615      *
3616      * @dataProvider component_class_callback_default_provider
3617      * @param $default
3618      */
3619     public function test_component_class_callback_method_not_found($default) {
3620         require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
3622         $this->assertSame($default, component_class_callback(test_component_class_callback_example::class, 'this_is_not_the_method_you_were_looking_for', ['abc'], $default));
3623     }
3625     /**
3626      * Test that the component_class_callback returns the default when the method returned null.
3627      *
3628      * @dataProvider component_class_callback_default_provider
3629      * @param $default
3630      */
3631     public function test_component_class_callback_found_returns_null($default) {
3632         require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
3634         $this->assertSame($default, component_class_callback(test_component_class_callback_example::class, 'method_returns_value', [null], $default));
3635         $this->assertSame($default, component_class_callback(test_component_class_callback_child_example::class, 'method_returns_value', [null], $default));
3636     }
3638     /**
3639      * Test that the component_class_callback returns the expected value and not the default when there was a value.
3640      *
3641      * @dataProvider component_class_callback_data_provider
3642      * @param $default
3643      */
3644     public function test_component_class_callback_found_returns_value($value) {
3645         require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
3647         $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'));
3648         $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'));
3649     }
3651     /**
3652      * Test that the component_class_callback handles multiple params correctly.
3653      *
3654      * @dataProvider component_class_callback_multiple_params_provider
3655      * @param $default
3656      */
3657     public function test_component_class_callback_found_accepts_multiple($params, $count) {
3658         require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
3660         $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'));
3661         $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'));
3662     }
3664     /**
3665      * Data provider with list of default values for user in component_class_callback tests.
3666      *
3667      * @return array
3668      */
3669     public function component_class_callback_default_provider() {
3670         return [
3671             'null' => [null],
3672             'empty string' => [''],
3673             'string' => ['This is a string'],
3674             'int' => [12345],
3675             'stdClass' => [(object) ['this is my content']],
3676             'array' => [['a' => 'b',]],
3677         ];
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_data_provider() {
3686         return [
3687             'empty string' => [''],
3688             'string' => ['This is a string'],
3689             'int' => [12345],
3690             'stdClass' => [(object) ['this is my content']],
3691             'array' => [['a' => 'b',]],
3692         ];
3693     }
3695     /**
3696      * Data provider with list of default values for user in component_class_callback tests.
3697      *
3698      * @return array
3699      */
3700     public function component_class_callback_multiple_params_provider() {
3701         return [
3702             'empty array' => [
3703                 [],
3704                 0,
3705             ],
3706             'string value' => [
3707                 ['one'],
3708                 1,
3709             ],
3710             'string values' => [
3711                 ['one', 'two'],
3712                 2,
3713             ],
3714             'arrays' => [
3715                 [[], []],
3716                 2,
3717             ],
3718             'nulls' => [
3719                 [null, null, null, null],
3720                 4,
3721             ],
3722             'mixed' => [
3723                 ['a', 1, null, (object) [], []],
3724                 5,
3725             ],
3726         ];
3727     }