508608269d96f64b3fb05c95055939d86210e231
[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         $this->assertSame('http://google.com/', clean_param('http://google.com/', PARAM_URL));
601         $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));
602         $this->assertSame('http://localhost/', clean_param('http://localhost/', PARAM_URL));
603         $this->assertSame('http://0.255.1.1/numericip.php', clean_param('http://0.255.1.1/numericip.php', PARAM_URL));
604         $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_URL));
605         $this->assertSame('', clean_param('funny:thing', PARAM_URL));
606     }
608     public function test_clean_param_localurl() {
609         global $CFG;
611         $this->resetAfterTest();
613         // External, invalid.
614         $this->assertSame('', clean_param('funny:thing', PARAM_LOCALURL));
615         $this->assertSame('', clean_param('http://google.com/', PARAM_LOCALURL));
616         $this->assertSame('', clean_param('https://google.com/?test=true', PARAM_LOCALURL));
617         $this->assertSame('', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL));
619         // Local absolute.
620         $this->assertSame(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
621         $this->assertSame($CFG->wwwroot . '/with/something?else=true',
622             clean_param($CFG->wwwroot . '/with/something?else=true', PARAM_LOCALURL));
624         // Local relative.
625         $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_LOCALURL));
626         $this->assertSame('course/view.php?id=3', clean_param('course/view.php?id=3', PARAM_LOCALURL));
628         // Local absolute HTTPS.
629         $httpsroot = str_replace('http:', 'https:', $CFG->wwwroot);
630         $CFG->loginhttps = false;
631         $this->assertSame('', clean_param($httpsroot, PARAM_LOCALURL));
632         $this->assertSame('', clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL));
633         $CFG->loginhttps = true;
634         $this->assertSame($httpsroot, clean_param($httpsroot, PARAM_LOCALURL));
635         $this->assertSame($httpsroot . '/with/something?else=true',
636             clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL));
638         // Test open redirects are not possible.
639         $CFG->loginhttps = false;
640         $CFG->wwwroot = 'http://www.example.com';
641         $this->assertSame('', clean_param('http://www.example.com.evil.net/hack.php', PARAM_LOCALURL));
642         $CFG->loginhttps = true;
643         $this->assertSame('', clean_param('https://www.example.com.evil.net/hack.php', PARAM_LOCALURL));
644     }
646     public function test_clean_param_file() {
647         $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_FILE));
648         $this->assertSame('badfile.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE));
649         $this->assertSame('..parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_FILE));
650         $this->assertSame('....grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_FILE));
651         $this->assertSame('..winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_FILE));
652         $this->assertSame('....wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_FILE));
653         $this->assertSame('myfile.a.b.txt', clean_param('myfile.a.b.txt', PARAM_FILE));
654         $this->assertSame('myfile..a..b.txt', clean_param('myfile..a..b.txt', PARAM_FILE));
655         $this->assertSame('myfile.a..b...txt', clean_param('myfile.a..b...txt', PARAM_FILE));
656         $this->assertSame('myfile.a.txt', clean_param('myfile.a.txt', PARAM_FILE));
657         $this->assertSame('myfile...txt', clean_param('myfile...txt', PARAM_FILE));
658         $this->assertSame('...jpg', clean_param('...jpg', PARAM_FILE));
659         $this->assertSame('.a.b.', clean_param('.a.b.', PARAM_FILE));
660         $this->assertSame('', clean_param('.', PARAM_FILE));
661         $this->assertSame('', clean_param('..', PARAM_FILE));
662         $this->assertSame('...', clean_param('...', PARAM_FILE));
663         $this->assertSame('. . . .', clean_param('. . . .', PARAM_FILE));
664         $this->assertSame('dontrtrim.me. .. .. . ', clean_param('dontrtrim.me. .. .. . ', PARAM_FILE));
665         $this->assertSame(' . .dontltrim.me', clean_param(' . .dontltrim.me', PARAM_FILE));
666         $this->assertSame('here is a tab.txt', clean_param("here is a tab\t.txt", PARAM_FILE));
667         $this->assertSame('here is a linebreak.txt', clean_param("here is a line\r\nbreak.txt", PARAM_FILE));
669         // The following behaviours have been maintained although they seem a little odd.
670         $this->assertSame('funnything', clean_param('funny:thing', PARAM_FILE));
671         $this->assertSame('.currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_FILE));
672         $this->assertSame('ctempwindowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_FILE));
673         $this->assertSame('homeuserlinuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_FILE));
674         $this->assertSame('~myfile.txt', clean_param('~/myfile.txt', PARAM_FILE));
675     }
677     public function test_clean_param_path() {
678         $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_PATH));
679         $this->assertSame('bad/file.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH));
680         $this->assertSame('/parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_PATH));
681         $this->assertSame('/grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_PATH));
682         $this->assertSame('/winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_PATH));
683         $this->assertSame('/wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_PATH));
684         $this->assertSame('funnything', clean_param('funny:thing', PARAM_PATH));
685         $this->assertSame('./here', clean_param('./././here', PARAM_PATH));
686         $this->assertSame('./currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_PATH));
687         $this->assertSame('c/temp/windowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_PATH));
688         $this->assertSame('/home/user/linuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_PATH));
689         $this->assertSame('/home../user ./.linuxfile.txt', clean_param('/home../user ./.linuxfile.txt', PARAM_PATH));
690         $this->assertSame('~/myfile.txt', clean_param('~/myfile.txt', PARAM_PATH));
691         $this->assertSame('~/myfile.txt', clean_param('~/../myfile.txt', PARAM_PATH));
692         $this->assertSame('/..b../.../myfile.txt', clean_param('/..b../.../myfile.txt', PARAM_PATH));
693         $this->assertSame('..b../.../myfile.txt', clean_param('..b../.../myfile.txt', PARAM_PATH));
694         $this->assertSame('/super/slashes/', clean_param('/super//slashes///', PARAM_PATH));
695     }
697     public function test_clean_param_username() {
698         global $CFG;
699         $currentstatus =  $CFG->extendedusernamechars;
701         // Run tests with extended character == false;.
702         $CFG->extendedusernamechars = false;
703         $this->assertSame('johndoe123', clean_param('johndoe123', PARAM_USERNAME) );
704         $this->assertSame('john.doe', clean_param('john.doe', PARAM_USERNAME));
705         $this->assertSame('john-doe', clean_param('john-doe', PARAM_USERNAME));
706         $this->assertSame('john-doe', clean_param('john- doe', PARAM_USERNAME));
707         $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
708         $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
709         $this->assertSame('johndoe', clean_param('john~doe', PARAM_USERNAME));
710         $this->assertSame('johndoe', clean_param('john´doe', PARAM_USERNAME));
711         $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john_');
712         $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john_');
713         $this->assertSame(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
714         $this->assertSame('johnd', clean_param('JOHNdóé ', PARAM_USERNAME));
715         $this->assertSame(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýá\9e?\9eý??\9adoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
717         // Test success condition, if extendedusernamechars == ENABLE;.
718         $CFG->extendedusernamechars = true;
719         $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
720         $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
721         $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john# $%&()+_^');
722         $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john# $%&()+_^');
723         $this->assertSame('john~doe', clean_param('john~doe', PARAM_USERNAME));
724         $this->assertSame('john´doe', clean_param('joHN´doe', PARAM_USERNAME));
725         $this->assertSame('johndoe', clean_param('johnDOE', PARAM_USERNAME));
726         $this->assertSame('johndóé', clean_param('johndóé ', PARAM_USERNAME));
728         $CFG->extendedusernamechars = $currentstatus;
729     }
731     public function test_clean_param_stringid() {
732         // Test string identifiers validation.
733         // Valid strings.
734         $this->assertSame('validstring', clean_param('validstring', PARAM_STRINGID));
735         $this->assertSame('mod/foobar:valid_capability', clean_param('mod/foobar:valid_capability', PARAM_STRINGID));
736         $this->assertSame('CZ', clean_param('CZ', PARAM_STRINGID));
737         $this->assertSame('application/vnd.ms-powerpoint', clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID));
738         $this->assertSame('grade2', clean_param('grade2', PARAM_STRINGID));
739         // Invalid strings.
740         $this->assertSame('', clean_param('trailing ', PARAM_STRINGID));
741         $this->assertSame('', clean_param('space bar', PARAM_STRINGID));
742         $this->assertSame('', clean_param('0numeric', PARAM_STRINGID));
743         $this->assertSame('', clean_param('*', PARAM_STRINGID));
744         $this->assertSame('', clean_param(' ', PARAM_STRINGID));
745     }
747     public function test_clean_param_timezone() {
748         // Test timezone validation.
749         $testvalues = array (
750             'America/Jamaica'                => 'America/Jamaica',
751             'America/Argentina/Cordoba'      => 'America/Argentina/Cordoba',
752             'America/Port-au-Prince'         => 'America/Port-au-Prince',
753             'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
754             'PST8PDT'                        => 'PST8PDT',
755             'Wrong.Value'                    => '',
756             'Wrong/.Value'                   => '',
757             'Wrong(Value)'                   => '',
758             '0'                              => '0',
759             '0.0'                            => '0.0',
760             '0.5'                            => '0.5',
761             '9.0'                            => '9.0',
762             '-9.0'                           => '-9.0',
763             '+9.0'                           => '+9.0',
764             '9.5'                            => '9.5',
765             '-9.5'                           => '-9.5',
766             '+9.5'                           => '+9.5',
767             '12.0'                           => '12.0',
768             '-12.0'                          => '-12.0',
769             '+12.0'                          => '+12.0',
770             '12.5'                           => '12.5',
771             '-12.5'                          => '-12.5',
772             '+12.5'                          => '+12.5',
773             '13.0'                           => '13.0',
774             '-13.0'                          => '-13.0',
775             '+13.0'                          => '+13.0',
776             '13.5'                           => '',
777             '+13.5'                          => '',
778             '-13.5'                          => '',
779             '0.2'                            => '');
781         foreach ($testvalues as $testvalue => $expectedvalue) {
782             $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
783             $this->assertEquals($expectedvalue, $actualvalue);
784         }
785     }
787     public function test_validate_param() {
788         try {
789             $param = validate_param('11a', PARAM_INT);
790             $this->fail('invalid_parameter_exception expected');
791         } catch (moodle_exception $ex) {
792             $this->assertInstanceOf('invalid_parameter_exception', $ex);
793         }
795         $param = validate_param('11', PARAM_INT);
796         $this->assertSame(11, $param);
798         try {
799             $param = validate_param(null, PARAM_INT, false);
800             $this->fail('invalid_parameter_exception expected');
801         } catch (moodle_exception $ex) {
802             $this->assertInstanceOf('invalid_parameter_exception', $ex);
803         }
805         $param = validate_param(null, PARAM_INT, true);
806         $this->assertSame(null, $param);
808         try {
809             $param = validate_param(array(), PARAM_INT);
810             $this->fail('invalid_parameter_exception expected');
811         } catch (moodle_exception $ex) {
812             $this->assertInstanceOf('invalid_parameter_exception', $ex);
813         }
814         try {
815             $param = validate_param(new stdClass, PARAM_INT);
816             $this->fail('invalid_parameter_exception expected');
817         } catch (moodle_exception $ex) {
818             $this->assertInstanceOf('invalid_parameter_exception', $ex);
819         }
821         $param = validate_param('1.0', PARAM_FLOAT);
822         $this->assertSame(1.0, $param);
824         // Make sure valid floats do not cause exception.
825         validate_param(1.0, PARAM_FLOAT);
826         validate_param(10, PARAM_FLOAT);
827         validate_param('0', PARAM_FLOAT);
828         validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
829         validate_param('011.1', PARAM_FLOAT);
830         validate_param('11', PARAM_FLOAT);
831         validate_param('+.1', PARAM_FLOAT);
832         validate_param('-.1', PARAM_FLOAT);
833         validate_param('1e10', PARAM_FLOAT);
834         validate_param('.1e+10', PARAM_FLOAT);
835         validate_param('1E-1', PARAM_FLOAT);
837         try {
838             $param = validate_param('1,2', PARAM_FLOAT);
839             $this->fail('invalid_parameter_exception expected');
840         } catch (moodle_exception $ex) {
841             $this->assertInstanceOf('invalid_parameter_exception', $ex);
842         }
843         try {
844             $param = validate_param('', PARAM_FLOAT);
845             $this->fail('invalid_parameter_exception expected');
846         } catch (moodle_exception $ex) {
847             $this->assertInstanceOf('invalid_parameter_exception', $ex);
848         }
849         try {
850             $param = validate_param('.', PARAM_FLOAT);
851             $this->fail('invalid_parameter_exception expected');
852         } catch (moodle_exception $ex) {
853             $this->assertInstanceOf('invalid_parameter_exception', $ex);
854         }
855         try {
856             $param = validate_param('e10', PARAM_FLOAT);
857             $this->fail('invalid_parameter_exception expected');
858         } catch (moodle_exception $ex) {
859             $this->assertInstanceOf('invalid_parameter_exception', $ex);
860         }
861         try {
862             $param = validate_param('abc', PARAM_FLOAT);
863             $this->fail('invalid_parameter_exception expected');
864         } catch (moodle_exception $ex) {
865             $this->assertInstanceOf('invalid_parameter_exception', $ex);
866         }
867     }
869     public function test_shorten_text_no_tags_already_short_enough() {
870         // ......12345678901234567890123456.
871         $text = "short text already no tags";
872         $this->assertSame($text, shorten_text($text));
873     }
875     public function test_shorten_text_with_tags_already_short_enough() {
876         // .........123456...7890....12345678.......901234567.
877         $text = "<p>short <b>text</b> already</p><p>with tags</p>";
878         $this->assertSame($text, shorten_text($text));
879     }
881     public function test_shorten_text_no_tags_needs_shortening() {
882         // Default truncation is after 30 chars, but allowing 3 for the final '...'.
883         // ......12345678901234567890123456789023456789012345678901234.
884         $text = "long text without any tags blah de blah blah blah what";
885         $this->assertSame('long text without any tags ...', shorten_text($text));
886     }
888     public function test_shorten_text_with_tags_needs_shortening() {
889         // .......................................123456789012345678901234567890...
890         $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
891             "be chopped off but <b>should be added back again</b></blockquote></p></div>";
892         $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
893             "tags that ...</blockquote></p></div>", shorten_text($text));
894     }
896     public function test_shorten_text_with_tags_and_html_comment() {
897         $text = "<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with ".
898             "tags that will<!--<![endif]--> ".
899             "be chopped off but <b>should be added back again</b></blockquote></p></div>";
900         $this->assertEquals("<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with " .
901             "tags that ...<!--<![endif]--></blockquote></p></div>", shorten_text($text));
902     }
904     public function test_shorten_text_with_entities() {
905         // Remember to allow 3 chars for the final '...'.
906         // ......123456789012345678901234567_____890...
907         $text = "some text which shouldn't &nbsp; break there";
908         $this->assertSame("some text which shouldn't &nbsp; ...", shorten_text($text, 31));
909         $this->assertSame("some text which shouldn't &nbsp;...", shorten_text($text, 30));
910         $this->assertSame("some text which shouldn't ...", shorten_text($text, 29));
911     }
913     public function test_shorten_text_known_tricky_case() {
914         // This case caused a bug up to 1.9.5
915         // ..........123456789012345678901234567890123456789.....0_____1___2___...
916         $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
917         $this->assertSame("<h3>standard 'break-out' sub groups in ...</h3>",
918             shorten_text($text, 41));
919         $this->assertSame("<h3>standard 'break-out' sub groups in TGs?...</h3>",
920             shorten_text($text, 42));
921         $this->assertSame("<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;...",
922             shorten_text($text, 43));
923     }
925     public function test_shorten_text_no_spaces() {
926         // ..........123456789.
927         $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
928         $this->assertSame("<h1>12345...</h1>", shorten_text($text, 8));
929     }
931     public function test_shorten_text_utf8_european() {
932         // Text without tags.
933         // ......123456789012345678901234567.
934         $text = "Žluťoučký koníček přeskočil";
935         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
936         $this->assertSame("Žluťoučký koníče...", shorten_text($text, 19, true));
937         $this->assertSame("Žluťoučký ...", shorten_text($text, 19, false));
938         // And try it with 2-less (that are, in bytes, the middle of a sequence).
939         $this->assertSame("Žluťoučký koní...", shorten_text($text, 17, true));
940         $this->assertSame("Žluťoučký ...", shorten_text($text, 17, false));
942         // .........123456789012345678...901234567....89012345.
943         $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
944         $this->assertSame($text, shorten_text($text, 60));
945         $this->assertSame("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
946         $this->assertSame("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
947         $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
948         // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
949         $this->assertSame("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
950         $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
951         // And try over one tag (start/end), it does proper text len.
952         $this->assertSame("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
953         $this->assertSame("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
954         // And in the middle of one tag.
955         $this->assertSame("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
956     }
958     public function test_shorten_text_utf8_oriental() {
959         // Japanese
960         // text without tags
961         // ......123456789012345678901234.
962         $text = '言語設定言語設定abcdefghijkl';
963         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
964         $this->assertSame("言語設定言語...", shorten_text($text, 9, true));
965         $this->assertSame("言語設定言語...", shorten_text($text, 9, false));
966         $this->assertSame("言語設定言語設定ab...", shorten_text($text, 13, true));
967         $this->assertSame("言語設定言語設定...", shorten_text($text, 13, false));
969         // Chinese
970         // text without tags
971         // ......123456789012345678901234.
972         $text = '简体中文简体中文abcdefghijkl';
973         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
974         $this->assertSame("简体中文简体...", shorten_text($text, 9, true));
975         $this->assertSame("简体中文简体...", shorten_text($text, 9, false));
976         $this->assertSame("简体中文简体中文ab...", shorten_text($text, 13, true));
977         $this->assertSame("简体中文简体中文...", shorten_text($text, 13, false));
978     }
980     public function test_shorten_text_multilang() {
981         // This is not necessaryily specific to multilang. The issue is really
982         // tags with attributes, where before we were generating invalid HTML
983         // output like shorten_text('<span id="x" class="y">A</span> B', 1)
984         // returning '<span id="x" ...</span>'. It is just that multilang
985         // requires the sort of HTML that is quite likely to trigger this.
986         // ........................................1...
987         $text = '<span lang="en" class="multilang">A</span>' .
988                 '<span lang="fr" class="multilang">B</span>';
989         $this->assertSame('<span lang="en" class="multilang">...</span>',
990                 shorten_text($text, 1));
991     }
993     public function test_usergetdate() {
994         global $USER, $CFG, $DB;
995         $this->resetAfterTest();
997         $this->setAdminUser();
999         $USER->timezone = 2;// Set the timezone to a known state.
1001         $ts = 1261540267; // The time this function was created.
1003         $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
1004         $arr = array_values($arr);
1006         list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1007         $this->assertSame(7, $seconds);
1008         $this->assertSame(51, $minutes);
1009         $this->assertSame(4, $hours);
1010         $this->assertSame(23, $mday);
1011         $this->assertSame(3, $wday);
1012         $this->assertSame(12, $mon);
1013         $this->assertSame(2009, $year);
1014         $this->assertSame(356, $yday);
1015         $this->assertSame('Wednesday', $weekday);
1016         $this->assertSame('December', $month);
1017         $arr = usergetdate($ts); // Gets the timezone from the $USER object.
1018         $arr = array_values($arr);
1020         list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1021         $this->assertSame(7, $seconds);
1022         $this->assertSame(51, $minutes);
1023         $this->assertSame(5, $hours);
1024         $this->assertSame(23, $mday);
1025         $this->assertSame(3, $wday);
1026         $this->assertSame(12, $mon);
1027         $this->assertSame(2009, $year);
1028         $this->assertSame(356, $yday);
1029         $this->assertSame('Wednesday', $weekday);
1030         $this->assertSame('December', $month);
1031     }
1033     public function test_mark_user_preferences_changed() {
1034         $this->resetAfterTest();
1035         $otheruser = $this->getDataGenerator()->create_user();
1036         $otheruserid = $otheruser->id;
1038         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1039         mark_user_preferences_changed($otheruserid);
1041         $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1042         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1043     }
1045     public function test_check_user_preferences_loaded() {
1046         global $DB;
1047         $this->resetAfterTest();
1049         $otheruser = $this->getDataGenerator()->create_user();
1050         $otheruserid = $otheruser->id;
1052         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1053         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1055         $user = new stdClass();
1056         $user->id = $otheruserid;
1058         // Load.
1059         check_user_preferences_loaded($user);
1060         $this->assertTrue(isset($user->preference));
1061         $this->assertTrue(is_array($user->preference));
1062         $this->assertArrayHasKey('_lastloaded', $user->preference);
1063         $this->assertCount(1, $user->preference);
1065         // Add preference via direct call.
1066         $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1068         // No cache reload yet.
1069         check_user_preferences_loaded($user);
1070         $this->assertCount(1, $user->preference);
1072         // Forced reloading of cache.
1073         unset($user->preference);
1074         check_user_preferences_loaded($user);
1075         $this->assertCount(2, $user->preference);
1076         $this->assertSame('yyy', $user->preference['xxx']);
1078         // Add preference via direct call.
1079         $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1081         // Test timeouts and modifications from different session.
1082         set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1083         $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1084         check_user_preferences_loaded($user);
1085         $this->assertCount(2, $user->preference);
1086         check_user_preferences_loaded($user, 10);
1087         $this->assertCount(3, $user->preference);
1088         $this->assertSame('bbb', $user->preference['aaa']);
1089         set_cache_flag('userpreferenceschanged', $user->id, null);
1090     }
1092     public function test_set_user_preference() {
1093         global $DB, $USER;
1094         $this->resetAfterTest();
1096         $this->setAdminUser();
1098         $otheruser = $this->getDataGenerator()->create_user();
1099         $otheruserid = $otheruser->id;
1101         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1102         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1104         $user = new stdClass();
1105         $user->id = $otheruserid;
1107         set_user_preference('aaa', 'bbb', $otheruserid);
1108         $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1109         $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
1111         set_user_preference('xxx', 'yyy', $user);
1112         $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1113         $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
1114         $this->assertTrue(is_array($user->preference));
1115         $this->assertSame('bbb', $user->preference['aaa']);
1116         $this->assertSame('yyy', $user->preference['xxx']);
1118         set_user_preference('xxx', null, $user);
1119         $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1120         $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
1122         set_user_preference('ooo', true, $user);
1123         $prefs = get_user_preferences(null, null, $otheruserid);
1124         $this->assertSame($user->preference['aaa'], $prefs['aaa']);
1125         $this->assertSame($user->preference['ooo'], $prefs['ooo']);
1126         $this->assertSame('1', $prefs['ooo']);
1128         set_user_preference('null', 0, $user);
1129         $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1131         $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1133         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1134         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1136         // Test $USER default.
1137         set_user_preference('_test_user_preferences_pref', 'ok');
1138         $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1139         unset_user_preference('_test_user_preferences_pref');
1140         $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1142         // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
1143         $longvalue = str_repeat('a', 1333);
1144         set_user_preference('_test_long_user_preference', $longvalue);
1145         $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1146         $this->assertEquals($longvalue,
1147             $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1149         // Test > 1333 char values, coding_exception expected.
1150         $longvalue = str_repeat('a', 1334);
1151         try {
1152             set_user_preference('_test_long_user_preference', $longvalue);
1153             $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1154         } catch (moodle_exception $ex) {
1155             $this->assertInstanceOf('coding_exception', $ex);
1156         }
1158         // Test invalid params.
1159         try {
1160             set_user_preference('_test_user_preferences_pref', array());
1161             $this->fail('Exception expected - array not valid preference value');
1162         } catch (moodle_exception $ex) {
1163             $this->assertInstanceOf('coding_exception', $ex);
1164         }
1165         try {
1166             set_user_preference('_test_user_preferences_pref', new stdClass);
1167             $this->fail('Exception expected - class not valid preference value');
1168         } catch (moodle_exception $ex) {
1169             $this->assertInstanceOf('coding_exception', $ex);
1170         }
1171         try {
1172             set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1173             $this->fail('Exception expected - user instance expected');
1174         } catch (moodle_exception $ex) {
1175             $this->assertInstanceOf('coding_exception', $ex);
1176         }
1177         try {
1178             set_user_preference('_test_user_preferences_pref', 1, 'abc');
1179             $this->fail('Exception expected - user instance expected');
1180         } catch (moodle_exception $ex) {
1181             $this->assertInstanceOf('coding_exception', $ex);
1182         }
1183         try {
1184             set_user_preference('', 1);
1185             $this->fail('Exception expected - invalid name accepted');
1186         } catch (moodle_exception $ex) {
1187             $this->assertInstanceOf('coding_exception', $ex);
1188         }
1189         try {
1190             set_user_preference('1', 1);
1191             $this->fail('Exception expected - invalid name accepted');
1192         } catch (moodle_exception $ex) {
1193             $this->assertInstanceOf('coding_exception', $ex);
1194         }
1195     }
1197     public function test_get_extra_user_fields() {
1198         global $CFG, $USER, $DB;
1199         $this->resetAfterTest();
1201         $this->setAdminUser();
1203         // It would be really nice if there were a way to 'mock' has_capability
1204         // checks (either to return true or false) but as there is not, this
1205         // test doesn't test the capability check. Presumably, anyone running
1206         // unit tests will have the capability.
1207         $context = context_system::instance();
1209         // No fields.
1210         $CFG->showuseridentity = '';
1211         $this->assertEquals(array(), get_extra_user_fields($context));
1213         // One field.
1214         $CFG->showuseridentity = 'frog';
1215         $this->assertEquals(array('frog'), get_extra_user_fields($context));
1217         // Two fields.
1218         $CFG->showuseridentity = 'frog,zombie';
1219         $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1221         // No fields, except.
1222         $CFG->showuseridentity = '';
1223         $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1225         // One field.
1226         $CFG->showuseridentity = 'frog';
1227         $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1229         // Two fields.
1230         $CFG->showuseridentity = 'frog,zombie';
1231         $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1232     }
1234     public function test_get_extra_user_fields_sql() {
1235         global $CFG, $USER, $DB;
1236         $this->resetAfterTest();
1238         $this->setAdminUser();
1240         $context = context_system::instance();
1242         // No fields.
1243         $CFG->showuseridentity = '';
1244         $this->assertSame('', get_extra_user_fields_sql($context));
1246         // One field.
1247         $CFG->showuseridentity = 'frog';
1248         $this->assertSame(', frog', get_extra_user_fields_sql($context));
1250         // Two fields with table prefix.
1251         $CFG->showuseridentity = 'frog,zombie';
1252         $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1254         // Two fields with field prefix.
1255         $CFG->showuseridentity = 'frog,zombie';
1256         $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
1257             get_extra_user_fields_sql($context, '', 'u_'));
1259         // One field excluded.
1260         $CFG->showuseridentity = 'frog';
1261         $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
1263         // Two fields, one excluded, table+field prefix.
1264         $CFG->showuseridentity = 'frog,zombie';
1265         $this->assertEquals(', u1.zombie AS u_zombie',
1266             get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1267     }
1269     /**
1270      * Test some critical TZ/DST.
1271      *
1272      * This method tests some special TZ/DST combinations that were fixed
1273      * by MDL-38999. The tests are done by comparing the results of the
1274      * output using Moodle TZ/DST support and PHP native one.
1275      *
1276      * Note: If you don't trust PHP TZ/DST support, can verify the
1277      * harcoded expectations below with:
1278      * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
1279      */
1280     public function test_some_moodle_special_dst() {
1281         $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
1283         // In Europe/Tallinn it was 2013/04/08 05:00:00.
1284         $expectation = '2013/04/08 05:00:00';
1285         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1286         $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1287         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1288         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1289         $this->assertSame($expectation, $phpres);
1290         $this->assertSame($expectation, $moodleres);
1292         // In St. Johns it was 2013/04/07 23:30:00.
1293         $expectation = '2013/04/07 23:30:00';
1294         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1295         $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1296         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1297         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1298         $this->assertSame($expectation, $phpres);
1299         $this->assertSame($expectation, $moodleres);
1301         $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1303         // In Europe/Tallinn it was 2013/11/08 04:00:00.
1304         $expectation = '2013/11/08 04:00:00';
1305         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1306         $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1307         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1308         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1309         $this->assertSame($expectation, $phpres);
1310         $this->assertSame($expectation, $moodleres);
1312         // In St. Johns it was 2013/11/07 22:30:00.
1313         $expectation = '2013/11/07 22:30:00';
1314         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1315         $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1316         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1317         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1318         $this->assertSame($expectation, $phpres);
1319         $this->assertSame($expectation, $moodleres);
1320     }
1322     public function test_userdate() {
1323         global $USER, $CFG, $DB;
1324         $this->resetAfterTest();
1326         $this->setAdminUser();
1328         $testvalues = array(
1329             array(
1330                 'time' => '1309514400',
1331                 'usertimezone' => 'America/Moncton',
1332                 'timezone' => '0.0', // No dst offset.
1333                 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1334             ),
1335             array(
1336                 'time' => '1309514400',
1337                 'usertimezone' => 'America/Moncton',
1338                 'timezone' => '99', // Dst offset and timezone offset.
1339                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1340             ),
1341             array(
1342                 'time' => '1309514400',
1343                 'usertimezone' => 'America/Moncton',
1344                 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
1345                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1346             ),
1347             array(
1348                 'time' => '1293876000 ',
1349                 'usertimezone' => 'America/Moncton',
1350                 'timezone' => '0.0', // No dst offset.
1351                 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1352             ),
1353             array(
1354                 'time' => '1293876000 ',
1355                 'usertimezone' => 'America/Moncton',
1356                 'timezone' => '99', // No dst offset in jan, so just timezone offset.
1357                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1358             ),
1359             array(
1360                 'time' => '1293876000 ',
1361                 'usertimezone' => 'America/Moncton',
1362                 'timezone' => 'America/Moncton', // No dst offset in jan.
1363                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1364             ),
1365             array(
1366                 'time' => '1293876000 ',
1367                 'usertimezone' => '2',
1368                 'timezone' => '99', // Take user timezone.
1369                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1370             ),
1371             array(
1372                 'time' => '1293876000 ',
1373                 'usertimezone' => '-2',
1374                 'timezone' => '99', // Take user timezone.
1375                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1376             ),
1377             array(
1378                 'time' => '1293876000 ',
1379                 'usertimezone' => '-10',
1380                 'timezone' => '2', // Take this timezone.
1381                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1382             ),
1383             array(
1384                 'time' => '1293876000 ',
1385                 'usertimezone' => '-10',
1386                 'timezone' => '-2', // Take this timezone.
1387                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1388             ),
1389             array(
1390                 'time' => '1293876000 ',
1391                 'usertimezone' => '-10',
1392                 'timezone' => 'random/time', // This should show server time.
1393                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1394             ),
1395             array(
1396                 'time' => '1293876000 ',
1397                 'usertimezone' => '20', // Fallback to server time zone.
1398                 'timezone' => '99',     // This should show user time.
1399                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1400             ),
1401         );
1403         // Set default timezone to Australia/Perth, else time calculated
1404         // will not match expected values.
1405         $this->setTimezone(99, 'Australia/Perth');
1407         foreach ($testvalues as $vals) {
1408             $USER->timezone = $vals['usertimezone'];
1409             $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1411             // On different systems case of AM PM changes so compare case insensitive.
1412             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1413             $actualoutput = core_text::strtolower($actualoutput);
1415             $this->assertSame($vals['expectedoutput'], $actualoutput,
1416                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput} \ndata: " . var_export($vals, true));
1417         }
1418     }
1420     /**
1421      * Make sure the DST changes happen at the right time in Moodle.
1422      */
1423     public function test_dst_changes() {
1424         // DST switching in Prague.
1425         // From 2AM to 3AM in 1989.
1426         $date = new DateTime('1989-03-26T01:59:00+01:00');
1427         $this->assertSame('Sunday, 26 March 1989, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1428         $date = new DateTime('1989-03-26T02:01:00+01:00');
1429         $this->assertSame('Sunday, 26 March 1989, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1430         // From 3AM to 2AM in 1989 - not the same as the west Europe.
1431         $date = new DateTime('1989-09-24T01:59:00+01:00');
1432         $this->assertSame('Sunday, 24 September 1989, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1433         $date = new DateTime('1989-09-24T02:01:00+01:00');
1434         $this->assertSame('Sunday, 24 September 1989, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1435         // From 2AM to 3AM in 2014.
1436         $date = new DateTime('2014-03-30T01:59:00+01:00');
1437         $this->assertSame('Sunday, 30 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1438         $date = new DateTime('2014-03-30T02:01:00+01:00');
1439         $this->assertSame('Sunday, 30 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1440         // From 3AM to 2AM in 2014.
1441         $date = new DateTime('2014-10-26T01:59:00+01:00');
1442         $this->assertSame('Sunday, 26 October 2014, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1443         $date = new DateTime('2014-10-26T02:01:00+01:00');
1444         $this->assertSame('Sunday, 26 October 2014, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1445         // From 2AM to 3AM in 2020.
1446         $date = new DateTime('2020-03-29T01:59:00+01:00');
1447         $this->assertSame('Sunday, 29 March 2020, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1448         $date = new DateTime('2020-03-29T02:01:00+01:00');
1449         $this->assertSame('Sunday, 29 March 2020, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1450         // From 3AM to 2AM in 2020.
1451         $date = new DateTime('2020-10-25T01:59:00+01:00');
1452         $this->assertSame('Sunday, 25 October 2020, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1453         $date = new DateTime('2020-10-25T02:01:00+01:00');
1454         $this->assertSame('Sunday, 25 October 2020, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1456         // DST switching in NZ.
1457         // From 3AM to 2AM in 2015.
1458         $date = new DateTime('2015-04-05T02:59:00+13:00');
1459         $this->assertSame('Sunday, 5 April 2015, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1460         $date = new DateTime('2015-04-05T03:01:00+13:00');
1461         $this->assertSame('Sunday, 5 April 2015, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1462         // From 2AM to 3AM in 2009.
1463         $date = new DateTime('2015-09-27T01:59:00+12:00');
1464         $this->assertSame('Sunday, 27 September 2015, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1465         $date = new DateTime('2015-09-27T02:01:00+12:00');
1466         $this->assertSame('Sunday, 27 September 2015, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1468         // DST switching in Perth.
1469         // From 3AM to 2AM in 2009.
1470         $date = new DateTime('2008-03-30T01:59:00+08:00');
1471         $this->assertSame('Sunday, 30 March 2008, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1472         $date = new DateTime('2008-03-30T02:01:00+08:00');
1473         $this->assertSame('Sunday, 30 March 2008, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1474         // From 2AM to 3AM in 2009.
1475         $date = new DateTime('2008-10-26T01:59:00+08:00');
1476         $this->assertSame('Sunday, 26 October 2008, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1477         $date = new DateTime('2008-10-26T02:01:00+08:00');
1478         $this->assertSame('Sunday, 26 October 2008, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1480         // DST switching in US.
1481         // From 2AM to 3AM in 2014.
1482         $date = new DateTime('2014-03-09T01:59:00-05:00');
1483         $this->assertSame('Sunday, 9 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1484         $date = new DateTime('2014-03-09T02:01:00-05:00');
1485         $this->assertSame('Sunday, 9 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1486         // From 3AM to 2AM in 2014.
1487         $date = new DateTime('2014-11-02T01:59:00-04:00');
1488         $this->assertSame('Sunday, 2 November 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1489         $date = new DateTime('2014-11-02T02:01:00-04:00');
1490         $this->assertSame('Sunday, 2 November 2014, 01:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1491     }
1493     public function test_make_timestamp() {
1494         global $USER, $CFG, $DB;
1495         $this->resetAfterTest();
1497         $this->setAdminUser();
1499         $testvalues = array(
1500             array(
1501                 'usertimezone' => 'America/Moncton',
1502                 'year' => '2011',
1503                 'month' => '7',
1504                 'day' => '1',
1505                 'hour' => '10',
1506                 'minutes' => '00',
1507                 'seconds' => '00',
1508                 'timezone' => '0.0',
1509                 'applydst' => false, // No dst offset.
1510                 'expectedoutput' => '1309514400' // 6pm at UTC+0.
1511             ),
1512             array(
1513                 'usertimezone' => 'America/Moncton',
1514                 'year' => '2011',
1515                 'month' => '7',
1516                 'day' => '1',
1517                 'hour' => '10',
1518                 'minutes' => '00',
1519                 'seconds' => '00',
1520                 'timezone' => '99',  // User default timezone.
1521                 'applydst' => false, // Don't apply dst.
1522                 'expectedoutput' => '1309528800'
1523             ),
1524             array(
1525                 'usertimezone' => 'America/Moncton',
1526                 'year' => '2011',
1527                 'month' => '7',
1528                 'day' => '1',
1529                 'hour' => '10',
1530                 'minutes' => '00',
1531                 'seconds' => '00',
1532                 'timezone' => '99', // User default timezone.
1533                 'applydst' => true, // Apply dst.
1534                 'expectedoutput' => '1309525200'
1535             ),
1536             array(
1537                 'usertimezone' => 'America/Moncton',
1538                 'year' => '2011',
1539                 'month' => '7',
1540                 'day' => '1',
1541                 'hour' => '10',
1542                 'minutes' => '00',
1543                 'seconds' => '00',
1544                 'timezone' => 'America/Moncton', // String timezone.
1545                 'applydst' => true, // Apply dst.
1546                 'expectedoutput' => '1309525200'
1547             ),
1548             array(
1549                 'usertimezone' => '2', // No dst applyed.
1550                 'year' => '2011',
1551                 'month' => '7',
1552                 'day' => '1',
1553                 'hour' => '10',
1554                 'minutes' => '00',
1555                 'seconds' => '00',
1556                 'timezone' => '99', // Take user timezone.
1557                 'applydst' => true, // Apply dst.
1558                 'expectedoutput' => '1309507200'
1559             ),
1560             array(
1561                 'usertimezone' => '-2', // No dst applyed.
1562                 'year' => '2011',
1563                 'month' => '7',
1564                 'day' => '1',
1565                 'hour' => '10',
1566                 'minutes' => '00',
1567                 'seconds' => '00',
1568                 'timezone' => '99', // Take usertimezone.
1569                 'applydst' => true, // Apply dst.
1570                 'expectedoutput' => '1309521600'
1571             ),
1572             array(
1573                 'usertimezone' => '-10', // No dst applyed.
1574                 'year' => '2011',
1575                 'month' => '7',
1576                 'day' => '1',
1577                 'hour' => '10',
1578                 'minutes' => '00',
1579                 'seconds' => '00',
1580                 'timezone' => '2',  // Take this timezone.
1581                 'applydst' => true, // Apply dst.
1582                 'expectedoutput' => '1309507200'
1583             ),
1584             array(
1585                 'usertimezone' => '-10', // No dst applyed.
1586                 'year' => '2011',
1587                 'month' => '7',
1588                 'day' => '1',
1589                 'hour' => '10',
1590                 'minutes' => '00',
1591                 'seconds' => '00',
1592                 'timezone' => '-2', // Take this timezone.
1593                 'applydst' => true, // Apply dst.
1594                 'expectedoutput' => '1309521600'
1595             ),
1596             array(
1597                 'usertimezone' => '-10', // No dst applyed.
1598                 'year' => '2011',
1599                 'month' => '7',
1600                 'day' => '1',
1601                 'hour' => '10',
1602                 'minutes' => '00',
1603                 'seconds' => '00',
1604                 'timezone' => 'random/time', // This should show server time.
1605                 'applydst' => true,          // Apply dst.
1606                 'expectedoutput' => '1309485600'
1607             ),
1608             array(
1609                 'usertimezone' => '-14', // Server time.
1610                 'year' => '2011',
1611                 'month' => '7',
1612                 'day' => '1',
1613                 'hour' => '10',
1614                 'minutes' => '00',
1615                 'seconds' => '00',
1616                 'timezone' => '99', // Get user time.
1617                 'applydst' => true, // Apply dst.
1618                 'expectedoutput' => '1309485600'
1619             )
1620         );
1622         // Set default timezone to Australia/Perth, else time calculated
1623         // will not match expected values.
1624         $this->setTimezone(99, 'Australia/Perth');
1626         // Test make_timestamp with all testvals and assert if anything wrong.
1627         foreach ($testvalues as $vals) {
1628             $USER->timezone = $vals['usertimezone'];
1629             $actualoutput = make_timestamp(
1630                 $vals['year'],
1631                 $vals['month'],
1632                 $vals['day'],
1633                 $vals['hour'],
1634                 $vals['minutes'],
1635                 $vals['seconds'],
1636                 $vals['timezone'],
1637                 $vals['applydst']
1638             );
1640             // On different systems case of AM PM changes so compare case insensitive.
1641             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1642             $actualoutput = core_text::strtolower($actualoutput);
1644             $this->assertSame($vals['expectedoutput'], $actualoutput,
1645                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1646                 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1647         }
1648     }
1650     /**
1651      * Test get_string and most importantly the implementation of the lang_string
1652      * object.
1653      */
1654     public function test_get_string() {
1655         global $COURSE;
1657         // Make sure we are using English.
1658         $originallang = $COURSE->lang;
1659         $COURSE->lang = 'en';
1661         $yes = get_string('yes');
1662         $yesexpected = 'Yes';
1663         $this->assertInternalType('string', $yes);
1664         $this->assertSame($yesexpected, $yes);
1666         $yes = get_string('yes', 'moodle');
1667         $this->assertInternalType('string', $yes);
1668         $this->assertSame($yesexpected, $yes);
1670         $yes = get_string('yes', 'core');
1671         $this->assertInternalType('string', $yes);
1672         $this->assertSame($yesexpected, $yes);
1674         $yes = get_string('yes', '');
1675         $this->assertInternalType('string', $yes);
1676         $this->assertSame($yesexpected, $yes);
1678         $yes = get_string('yes', null);
1679         $this->assertInternalType('string', $yes);
1680         $this->assertSame($yesexpected, $yes);
1682         $yes = get_string('yes', null, 1);
1683         $this->assertInternalType('string', $yes);
1684         $this->assertSame($yesexpected, $yes);
1686         $days = 1;
1687         $numdays = get_string('numdays', 'core', '1');
1688         $numdaysexpected = $days.' days';
1689         $this->assertInternalType('string', $numdays);
1690         $this->assertSame($numdaysexpected, $numdays);
1692         $yes = get_string('yes', null, null, true);
1693         $this->assertInstanceOf('lang_string', $yes);
1694         $this->assertSame($yesexpected, (string)$yes);
1696         // Test using a lang_string object as the $a argument for a normal
1697         // get_string call (returning string).
1698         $test = new lang_string('yes', null, null, true);
1699         $testexpected = get_string('numdays', 'core', get_string('yes'));
1700         $testresult = get_string('numdays', null, $test);
1701         $this->assertInternalType('string', $testresult);
1702         $this->assertSame($testexpected, $testresult);
1704         // Test using a lang_string object as the $a argument for an object
1705         // get_string call (returning lang_string).
1706         $test = new lang_string('yes', null, null, true);
1707         $testexpected = get_string('numdays', 'core', get_string('yes'));
1708         $testresult = get_string('numdays', null, $test, true);
1709         $this->assertInstanceOf('lang_string', $testresult);
1710         $this->assertSame($testexpected, "$testresult");
1712         // Make sure that object properties that can't be converted don't cause
1713         // errors.
1714         // Level one: This is as deep as current language processing goes.
1715         $test = new stdClass;
1716         $test->one = 'here';
1717         $string = get_string('yes', null, $test, true);
1718         $this->assertEquals($yesexpected, $string);
1720         // Make sure that object properties that can't be converted don't cause
1721         // errors.
1722         // Level two: Language processing doesn't currently reach this deep.
1723         // only immediate scalar properties are worked with.
1724         $test = new stdClass;
1725         $test->one = new stdClass;
1726         $test->one->two = 'here';
1727         $string = get_string('yes', null, $test, true);
1728         $this->assertEquals($yesexpected, $string);
1730         // Make sure that object properties that can't be converted don't cause
1731         // errors.
1732         // Level three: It should never ever go this deep, but we're making sure
1733         // it doesn't cause any probs anyway.
1734         $test = new stdClass;
1735         $test->one = new stdClass;
1736         $test->one->two = new stdClass;
1737         $test->one->two->three = 'here';
1738         $string = get_string('yes', null, $test, true);
1739         $this->assertEquals($yesexpected, $string);
1741         // Make sure that object properties that can't be converted don't cause
1742         // errors and check lang_string properties.
1743         // Level one: This is as deep as current language processing goes.
1744         $test = new stdClass;
1745         $test->one = new lang_string('yes');
1746         $string = get_string('yes', null, $test, true);
1747         $this->assertEquals($yesexpected, $string);
1749         // Make sure that object properties that can't be converted don't cause
1750         // errors and check lang_string properties.
1751         // Level two: Language processing doesn't currently reach this deep.
1752         // only immediate scalar properties are worked with.
1753         $test = new stdClass;
1754         $test->one = new stdClass;
1755         $test->one->two = new lang_string('yes');
1756         $string = get_string('yes', null, $test, true);
1757         $this->assertEquals($yesexpected, $string);
1759         // Make sure that object properties that can't be converted don't cause
1760         // errors and check lang_string properties.
1761         // Level three: It should never ever go this deep, but we're making sure
1762         // it doesn't cause any probs anyway.
1763         $test = new stdClass;
1764         $test->one = new stdClass;
1765         $test->one->two = new stdClass;
1766         $test->one->two->three = new lang_string('yes');
1767         $string = get_string('yes', null, $test, true);
1768         $this->assertEquals($yesexpected, $string);
1770         // Make sure that array properties that can't be converted don't cause
1771         // errors.
1772         $test = array();
1773         $test['one'] = new stdClass;
1774         $test['one']->two = 'here';
1775         $string = get_string('yes', null, $test, true);
1776         $this->assertEquals($yesexpected, $string);
1778         // Same thing but as above except using an object... this is allowed :P.
1779         $string = get_string('yes', null, null, true);
1780         $object = new stdClass;
1781         $object->$string = 'Yes';
1782         $this->assertEquals($yesexpected, $string);
1783         $this->assertEquals($yesexpected, $object->$string);
1785         // Reset the language.
1786         $COURSE->lang = $originallang;
1787     }
1789     /**
1790      * @expectedException PHPUnit_Framework_Error_Warning
1791      */
1792     public function test_get_string_limitation() {
1793         // This is one of the limitations to the lang_string class. It can't be
1794         // used as a key.
1795         $array = array(get_string('yes', null, null, true) => 'yes');
1796     }
1798     /**
1799      * Test localised float formatting.
1800      */
1801     public function test_format_float() {
1803         // Special case for null.
1804         $this->assertEquals('', format_float(null));
1806         // Default 1 decimal place.
1807         $this->assertEquals('5.4', format_float(5.43));
1808         $this->assertEquals('5.0', format_float(5.001));
1810         // Custom number of decimal places.
1811         $this->assertEquals('5.43000', format_float(5.43, 5));
1813         // Option to strip ending zeros after rounding.
1814         $this->assertEquals('5.43', format_float(5.43, 5, true, true));
1815         $this->assertEquals('5', format_float(5.0001, 3, true, true));
1817         // Tests with a localised decimal separator.
1818         $this->define_local_decimal_separator();
1820         // Localisation on (default).
1821         $this->assertEquals('5X43000', format_float(5.43, 5));
1822         $this->assertEquals('5X43', format_float(5.43, 5, true, true));
1824         // Localisation off.
1825         $this->assertEquals('5.43000', format_float(5.43, 5, false));
1826         $this->assertEquals('5.43', format_float(5.43, 5, false, true));
1827     }
1829     /**
1830      * Test localised float unformatting.
1831      */
1832     public function test_unformat_float() {
1834         // Tests without the localised decimal separator.
1836         // Special case for null, empty or white spaces only strings.
1837         $this->assertEquals(null, unformat_float(null));
1838         $this->assertEquals(null, unformat_float(''));
1839         $this->assertEquals(null, unformat_float('    '));
1841         // Regular use.
1842         $this->assertEquals(5.4, unformat_float('5.4'));
1843         $this->assertEquals(5.4, unformat_float('5.4', true));
1845         // No decimal.
1846         $this->assertEquals(5.0, unformat_float('5'));
1848         // Custom number of decimal.
1849         $this->assertEquals(5.43267, unformat_float('5.43267'));
1851         // Empty decimal.
1852         $this->assertEquals(100.0, unformat_float('100.00'));
1854         // With the thousand separator.
1855         $this->assertEquals(1000.0, unformat_float('1 000'));
1856         $this->assertEquals(1000.32, unformat_float('1 000.32'));
1858         // Negative number.
1859         $this->assertEquals(-100.0, unformat_float('-100'));
1861         // Wrong value.
1862         $this->assertEquals(0.0, unformat_float('Wrong value'));
1863         // Wrong value in strict mode.
1864         $this->assertFalse(unformat_float('Wrong value', true));
1866         // Combining options.
1867         $this->assertEquals(-1023.862567, unformat_float('   -1 023.862567     '));
1869         // Bad decimal separator (should crop the decimal).
1870         $this->assertEquals(50.0, unformat_float('50,57'));
1871         // Bad decimal separator in strict mode (should return false).
1872         $this->assertFalse(unformat_float('50,57', true));
1874         // Tests with a localised decimal separator.
1875         $this->define_local_decimal_separator();
1877         // We repeat the tests above but with the current decimal separator.
1879         // Regular use without and with the localised separator.
1880         $this->assertEquals (5.4, unformat_float('5.4'));
1881         $this->assertEquals (5.4, unformat_float('5X4'));
1883         // Custom number of decimal.
1884         $this->assertEquals (5.43267, unformat_float('5X43267'));
1886         // Empty decimal.
1887         $this->assertEquals (100.0, unformat_float('100X00'));
1889         // With the thousand separator.
1890         $this->assertEquals (1000.32, unformat_float('1 000X32'));
1892         // Bad different separator (should crop the decimal).
1893         $this->assertEquals (50.0, unformat_float('50Y57'));
1894         // Bad different separator in strict mode (should return false).
1895         $this->assertFalse (unformat_float('50Y57', true));
1897         // Combining options.
1898         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     '));
1899         // Combining options in strict mode.
1900         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     ', true));
1901     }
1903     /**
1904      * Test deleting of users.
1905      */
1906     public function test_delete_user() {
1907         global $DB, $CFG;
1909         $this->resetAfterTest();
1911         $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
1912         $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
1913         $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
1915         $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
1916         $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
1917         $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
1918         $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
1919         $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => ''));
1920         $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => ''));
1922         // Delete user and capture event.
1923         $sink = $this->redirectEvents();
1924         $result = delete_user($user);
1925         $events = $sink->get_events();
1926         $sink->close();
1927         $event = array_pop($events);
1929         // Test user is deleted in DB.
1930         $this->assertTrue($result);
1931         $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
1932         $this->assertEquals(1, $deluser->deleted);
1933         $this->assertEquals(0, $deluser->picture);
1934         $this->assertSame('', $deluser->idnumber);
1935         $this->assertSame(md5($user->username), $deluser->email);
1936         $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
1938         $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
1940         // Test Event.
1941         $this->assertInstanceOf('\core\event\user_deleted', $event);
1942         $this->assertSame($user->id, $event->objectid);
1943         $this->assertSame('user_deleted', $event->get_legacy_eventname());
1944         $this->assertEventLegacyData($user, $event);
1945         $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
1946         $this->assertEventLegacyLogData($expectedlogdata, $event);
1947         $eventdata = $event->get_data();
1948         $this->assertSame($eventdata['other']['username'], $user->username);
1949         $this->assertSame($eventdata['other']['email'], $user->email);
1950         $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
1951         $this->assertSame($eventdata['other']['picture'], $user->picture);
1952         $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
1953         $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
1954         $this->assertEventContextNotUsed($event);
1956         // Try invalid params.
1957         $record = new stdClass();
1958         $record->grrr = 1;
1959         try {
1960             delete_user($record);
1961             $this->fail('Expecting exception for invalid delete_user() $user parameter');
1962         } catch (moodle_exception $ex) {
1963             $this->assertInstanceOf('coding_exception', $ex);
1964         }
1965         $record->id = 1;
1966         try {
1967             delete_user($record);
1968             $this->fail('Expecting exception for invalid delete_user() $user parameter');
1969         } catch (moodle_exception $ex) {
1970             $this->assertInstanceOf('coding_exception', $ex);
1971         }
1973         $record = new stdClass();
1974         $record->id = 666;
1975         $record->username = 'xx';
1976         $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
1977         $result = delete_user($record);
1978         $this->assertFalse($result);
1980         $result = delete_user($guest);
1981         $this->assertFalse($result);
1983         $result = delete_user($admin);
1984         $this->assertFalse($result);
1986         // Simultaneously deleting users with identical email addresses.
1987         $result1 = delete_user($usersharedemail1);
1988         $result2 = delete_user($usersharedemail2);
1990         $usersharedemail1after = $DB->get_record('user', array('id' => $usersharedemail1->id));
1991         $usersharedemail2after = $DB->get_record('user', array('id' => $usersharedemail2->id));
1992         $this->assertTrue($result1);
1993         $this->assertTrue($result2);
1994         $this->assertStringStartsWith($usersharedemail1->email . '.', $usersharedemail1after->username);
1995         $this->assertStringStartsWith($usersharedemail2->email . '.', $usersharedemail2after->username);
1997         // Simultaneously deleting users without email addresses.
1998         $result1 = delete_user($useremptyemail1);
1999         $result2 = delete_user($useremptyemail2);
2001         $useremptyemail1after = $DB->get_record('user', array('id' => $useremptyemail1->id));
2002         $useremptyemail2after = $DB->get_record('user', array('id' => $useremptyemail2->id));
2003         $this->assertTrue($result1);
2004         $this->assertTrue($result2);
2005         $this->assertStringStartsWith($useremptyemail1->username . '.' . $useremptyemail1->id . '@unknownemail.invalid.',
2006             $useremptyemail1after->username);
2007         $this->assertStringStartsWith($useremptyemail2->username . '.' . $useremptyemail2->id . '@unknownemail.invalid.',
2008             $useremptyemail2after->username);
2010         $this->resetDebugging();
2011     }
2013     /**
2014      * Test function convert_to_array()
2015      */
2016     public function test_convert_to_array() {
2017         // Check that normal classes are converted to arrays the same way as (array) would do.
2018         $obj = new stdClass();
2019         $obj->prop1 = 'hello';
2020         $obj->prop2 = array('first', 'second', 13);
2021         $obj->prop3 = 15;
2022         $this->assertEquals(convert_to_array($obj), (array)$obj);
2024         // Check that context object (with iterator) is converted to array properly.
2025         $obj = context_system::instance();
2026         $ar = array(
2027             'id'           => $obj->id,
2028             'contextlevel' => $obj->contextlevel,
2029             'instanceid'   => $obj->instanceid,
2030             'path'         => $obj->path,
2031             'depth'        => $obj->depth
2032         );
2033         $this->assertEquals(convert_to_array($obj), $ar);
2034     }
2036     /**
2037      * Test the function date_format_string().
2038      */
2039     public function test_date_format_string() {
2040         global $CFG;
2042         $this->resetAfterTest();
2043         $this->setTimezone(99, 'Australia/Perth');
2045         $tests = array(
2046             array(
2047                 'tz' => 99,
2048                 'str' => '%A, %d %B %Y, %I:%M %p',
2049                 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
2050             ),
2051             array(
2052                 'tz' => 0,
2053                 'str' => '%A, %d %B %Y, %I:%M %p',
2054                 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2055             ),
2056             array(
2057                 // Note: this function expected the timestamp in weird format before,
2058                 // since 2.9 it uses UTC.
2059                 'tz' => 'Pacific/Auckland',
2060                 'str' => '%A, %d %B %Y, %I:%M %p',
2061                 'expected' => 'Saturday, 01 January 2011, 11:00 PM'
2062             ),
2063             // Following tests pass on Windows only because en lang pack does
2064             // not contain localewincharset, in real life lang pack maintainers
2065             // may use only characters that are present in localewincharset
2066             // in format strings!
2067             array(
2068                 'tz' => 99,
2069                 'str' => 'Žluťoučký koníček %A',
2070                 'expected' => 'Žluťoučký koníček Saturday'
2071             ),
2072             array(
2073                 'tz' => 99,
2074                 'str' => '言語設定言語 %A',
2075                 'expected' => '言語設定言語 Saturday'
2076             ),
2077             array(
2078                 'tz' => 99,
2079                 'str' => '简体中文简体 %A',
2080                 'expected' => '简体中文简体 Saturday'
2081             ),
2082         );
2084         // Note: date_format_string() uses the timezone only to differenciate
2085         // the server time from the UTC time. It does not modify the timestamp.
2086         // Hence similar results for timezones <= 13.
2087         // On different systems case of AM PM changes so compare case insensitive.
2088         foreach ($tests as $test) {
2089             $str = date_format_string(1293876000, $test['str'], $test['tz']);
2090             $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
2091         }
2092     }
2094     public function test_get_config() {
2095         global $CFG;
2097         $this->resetAfterTest();
2099         // Preparation.
2100         set_config('phpunit_test_get_config_1', 'test 1');
2101         set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2102         if (!is_array($CFG->config_php_settings)) {
2103             $CFG->config_php_settings = array();
2104         }
2105         $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
2107         if (!is_array($CFG->forced_plugin_settings)) {
2108             $CFG->forced_plugin_settings = array();
2109         }
2110         if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
2111             $CFG->forced_plugin_settings['mod_forum'] = array();
2112         }
2113         $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2114         $CFG->phpunit_test_get_config_5 = 'test 5';
2116         // Testing.
2117         $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
2118         $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2119         $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
2120         $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2121         $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2122         $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2123         $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2125         // Test config we know to exist.
2126         $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
2127         $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2128         $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2129         $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2131         // Test setting a config var that already exists.
2132         set_config('phpunit_test_get_config_1', 'test a');
2133         $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
2134         $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
2136         // Test cache invalidation.
2137         $cache = cache::make('core', 'config');
2138         $this->assertInternalType('array', $cache->get('core'));
2139         $this->assertInternalType('array', $cache->get('mod_forum'));
2140         set_config('phpunit_test_get_config_1', 'test b');
2141         $this->assertFalse($cache->get('core'));
2142         set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2143         $this->assertFalse($cache->get('mod_forum'));
2144     }
2146     public function test_get_max_upload_sizes() {
2147         // Test with very low limits so we are not affected by php upload limits.
2148         // Test activity limit smallest.
2149         $sitebytes = 102400;
2150         $coursebytes = 51200;
2151         $modulebytes = 10240;
2152         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2154         $this->assertSame('Activity upload limit (10KB)', $result['0']);
2155         $this->assertCount(2, $result);
2157         // Test course limit smallest.
2158         $sitebytes = 102400;
2159         $coursebytes = 10240;
2160         $modulebytes = 51200;
2161         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2163         $this->assertSame('Course upload limit (10KB)', $result['0']);
2164         $this->assertCount(2, $result);
2166         // Test site limit smallest.
2167         $sitebytes = 10240;
2168         $coursebytes = 102400;
2169         $modulebytes = 51200;
2170         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2172         $this->assertSame('Site upload limit (10KB)', $result['0']);
2173         $this->assertCount(2, $result);
2175         // Test site limit not set.
2176         $sitebytes = 0;
2177         $coursebytes = 102400;
2178         $modulebytes = 51200;
2179         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2181         $this->assertSame('Activity upload limit (50KB)', $result['0']);
2182         $this->assertCount(3, $result);
2184         $sitebytes = 0;
2185         $coursebytes = 51200;
2186         $modulebytes = 102400;
2187         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2189         $this->assertSame('Course upload limit (50KB)', $result['0']);
2190         $this->assertCount(3, $result);
2192         // Test custom bytes in range.
2193         $sitebytes = 102400;
2194         $coursebytes = 51200;
2195         $modulebytes = 51200;
2196         $custombytes = 10240;
2197         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2199         $this->assertCount(3, $result);
2201         // Test custom bytes in range but non-standard.
2202         $sitebytes = 102400;
2203         $coursebytes = 51200;
2204         $modulebytes = 51200;
2205         $custombytes = 25600;
2206         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2208         $this->assertCount(4, $result);
2210         // Test custom bytes out of range.
2211         $sitebytes = 102400;
2212         $coursebytes = 51200;
2213         $modulebytes = 51200;
2214         $custombytes = 102400;
2215         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2217         $this->assertCount(3, $result);
2219         // Test custom bytes out of range and non-standard.
2220         $sitebytes = 102400;
2221         $coursebytes = 51200;
2222         $modulebytes = 51200;
2223         $custombytes = 256000;
2224         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2226         $this->assertCount(3, $result);
2228         // Test site limit only.
2229         $sitebytes = 51200;
2230         $result = get_max_upload_sizes($sitebytes);
2232         $this->assertSame('Site upload limit (50KB)', $result['0']);
2233         $this->assertSame('50KB', $result['51200']);
2234         $this->assertSame('10KB', $result['10240']);
2235         $this->assertCount(3, $result);
2237         // Test no limit.
2238         $result = get_max_upload_sizes();
2239         $this->assertArrayHasKey('0', $result);
2240         $this->assertArrayHasKey(get_max_upload_file_size(), $result);
2241     }
2243     /**
2244      * Test function password_is_legacy_hash().
2245      */
2246     public function test_password_is_legacy_hash() {
2247         // Well formed md5s should be matched.
2248         foreach (array('some', 'strings', 'to_check!') as $string) {
2249             $md5 = md5($string);
2250             $this->assertTrue(password_is_legacy_hash($md5));
2251         }
2252         // Strings that are not md5s should not be matched.
2253         foreach (array('', AUTH_PASSWORD_NOT_CACHED, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
2254             $this->assertFalse(password_is_legacy_hash($notmd5));
2255         }
2256     }
2258     /**
2259      * Test function validate_internal_user_password().
2260      */
2261     public function test_validate_internal_user_password() {
2262         // Test bcrypt hashes.
2263         $validhashes = array(
2264             'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2265             'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2266             'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2267             'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
2268         );
2270         foreach ($validhashes as $password => $hash) {
2271             $user = new stdClass();
2272             $user->auth = 'manual';
2273             $user->password = $hash;
2274             // The correct password should be validated.
2275             $this->assertTrue(validate_internal_user_password($user, $password));
2276             // An incorrect password should not be validated.
2277             $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2278         }
2279     }
2281     /**
2282      * Test function hash_internal_user_password().
2283      */
2284     public function test_hash_internal_user_password() {
2285         $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2287         // Check that some passwords that we convert to hashes can
2288         // be validated.
2289         foreach ($passwords as $password) {
2290             $hash = hash_internal_user_password($password);
2291             $fasthash = hash_internal_user_password($password, true);
2292             $user = new stdClass();
2293             $user->auth = 'manual';
2294             $user->password = $hash;
2295             $this->assertTrue(validate_internal_user_password($user, $password));
2297             // They should not be in md5 format.
2298             $this->assertFalse(password_is_legacy_hash($hash));
2300             // Check that cost factor in hash is correctly set.
2301             $this->assertRegExp('/\$10\$/', $hash);
2302             $this->assertRegExp('/\$04\$/', $fasthash);
2303         }
2304     }
2306     /**
2307      * Test function update_internal_user_password().
2308      */
2309     public function test_update_internal_user_password() {
2310         global $DB;
2311         $this->resetAfterTest();
2312         $passwords = array('password', '1234', 'changeme', '****');
2313         foreach ($passwords as $password) {
2314             $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2315             update_internal_user_password($user, $password);
2316             // The user object should have been updated.
2317             $this->assertTrue(validate_internal_user_password($user, $password));
2318             // The database field for the user should also have been updated to the
2319             // same value.
2320             $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
2321         }
2323         $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2324         // Manually set the user's password to the md5 of the string 'password'.
2325         $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
2327         $sink = $this->redirectEvents();
2328         // Update the password.
2329         update_internal_user_password($user, 'password');
2330         $events = $sink->get_events();
2331         $sink->close();
2332         $event = array_pop($events);
2334         // Password should have been updated to a bcrypt hash.
2335         $this->assertFalse(password_is_legacy_hash($user->password));
2337         // Verify event information.
2338         $this->assertInstanceOf('\core\event\user_password_updated', $event);
2339         $this->assertSame($user->id, $event->relateduserid);
2340         $this->assertEquals(context_user::instance($user->id), $event->get_context());
2341         $this->assertEventContextNotUsed($event);
2343         // Verify recovery of property 'auth'.
2344         unset($user->auth);
2345         update_internal_user_password($user, 'newpassword');
2346         $this->assertDebuggingCalled('User record in update_internal_user_password() must include field auth',
2347                 DEBUG_DEVELOPER);
2348         $this->assertEquals('manual', $user->auth);
2349     }
2351     /**
2352      * Testing that if the password is not cached, that it does not update
2353      * the user table and fire event.
2354      */
2355     public function test_update_internal_user_password_no_cache() {
2356         $this->resetAfterTest();
2358         $user = $this->getDataGenerator()->create_user(array('auth' => 'cas'));
2359         $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2361         $sink = $this->redirectEvents();
2362         update_internal_user_password($user, 'wonkawonka');
2363         $this->assertEquals(0, $sink->count(), 'User updated event should not fire');
2364     }
2366     /**
2367      * Test if the user has a password hash, but now their auth method
2368      * says not to cache it.  Then it should update.
2369      */
2370     public function test_update_internal_user_password_update_no_cache() {
2371         $this->resetAfterTest();
2373         $user = $this->getDataGenerator()->create_user(array('password' => 'test'));
2374         $this->assertNotEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2375         $user->auth = 'cas'; // Change to a auth that does not store passwords.
2377         $sink = $this->redirectEvents();
2378         update_internal_user_password($user, 'wonkawonka');
2379         $this->assertGreaterThanOrEqual(1, $sink->count(), 'User updated event should fire');
2381         $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2382     }
2384     public function test_fullname() {
2385         global $CFG;
2387         $this->resetAfterTest();
2389         // Create a user to test the name display on.
2390         $record = array();
2391         $record['firstname'] = 'Scott';
2392         $record['lastname'] = 'Fletcher';
2393         $record['firstnamephonetic'] = 'スコット';
2394         $record['lastnamephonetic'] = 'フレチャー';
2395         $record['alternatename'] = 'No friends';
2396         $user = $this->getDataGenerator()->create_user($record);
2398         // Back up config settings for restore later.
2399         $originalcfg = new stdClass();
2400         $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
2401         $originalcfg->alternativefullnameformat = $CFG->alternativefullnameformat;
2403         // Testing existing fullnamedisplay settings.
2404         $CFG->fullnamedisplay = 'firstname';
2405         $testname = fullname($user);
2406         $this->assertSame($user->firstname, $testname);
2408         $CFG->fullnamedisplay = 'firstname lastname';
2409         $expectedname = "$user->firstname $user->lastname";
2410         $testname = fullname($user);
2411         $this->assertSame($expectedname, $testname);
2413         $CFG->fullnamedisplay = 'lastname firstname';
2414         $expectedname = "$user->lastname $user->firstname";
2415         $testname = fullname($user);
2416         $this->assertSame($expectedname, $testname);
2418         $expectedname = get_string('fullnamedisplay', null, $user);
2419         $CFG->fullnamedisplay = 'language';
2420         $testname = fullname($user);
2421         $this->assertSame($expectedname, $testname);
2423         // Test override parameter.
2424         $CFG->fullnamedisplay = 'firstname';
2425         $expectedname = "$user->firstname $user->lastname";
2426         $testname = fullname($user, true);
2427         $this->assertSame($expectedname, $testname);
2429         // Test alternativefullnameformat setting.
2430         // Test alternativefullnameformat that has been set to nothing.
2431         $CFG->alternativefullnameformat = '';
2432         $expectedname = "$user->firstname $user->lastname";
2433         $testname = fullname($user, true);
2434         $this->assertSame($expectedname, $testname);
2436         // Test alternativefullnameformat that has been set to 'language'.
2437         $CFG->alternativefullnameformat = 'language';
2438         $expectedname = "$user->firstname $user->lastname";
2439         $testname = fullname($user, true);
2440         $this->assertSame($expectedname, $testname);
2442         // Test customising the alternativefullnameformat setting with all additional name fields.
2443         $CFG->alternativefullnameformat = 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename';
2444         $expectedname = "$user->firstname $user->lastname $user->firstnamephonetic $user->lastnamephonetic $user->middlename $user->alternatename";
2445         $testname = fullname($user, true);
2446         $this->assertSame($expectedname, $testname);
2448         // Test additional name fields.
2449         $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
2450         $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
2451         $testname = fullname($user);
2452         $this->assertSame($expectedname, $testname);
2454         // Test for handling missing data.
2455         $user->middlename = null;
2456         // Parenthesis with no data.
2457         $CFG->fullnamedisplay = 'firstname (middlename) lastname';
2458         $expectedname = "$user->firstname $user->lastname";
2459         $testname = fullname($user);
2460         $this->assertSame($expectedname, $testname);
2462         // Extra spaces due to no data.
2463         $CFG->fullnamedisplay = 'firstname middlename lastname';
2464         $expectedname = "$user->firstname $user->lastname";
2465         $testname = fullname($user);
2466         $this->assertSame($expectedname, $testname);
2468         // Regular expression testing.
2469         // Remove some data from the user fields.
2470         $user->firstnamephonetic = '';
2471         $user->lastnamephonetic = '';
2473         // Removing empty brackets and excess whitespace.
2474         // All of these configurations should resolve to just firstname lastname.
2475         $configarray = array();
2476         $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
2477         $configarray[] = 'firstname lastname \'middlename\'';
2478         $configarray[] = 'firstname "firstnamephonetic" lastname';
2479         $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
2481         foreach ($configarray as $config) {
2482             $CFG->fullnamedisplay = $config;
2483             $expectedname = "$user->firstname $user->lastname";
2484             $testname = fullname($user);
2485             $this->assertSame($expectedname, $testname);
2486         }
2488         // Check to make sure that other characters are left in place.
2489         $configarray = array();
2490         $configarray['0'] = new stdClass();
2491         $configarray['0']->config = 'lastname firstname, middlename';
2492         $configarray['0']->expectedname = "$user->lastname $user->firstname,";
2493         $configarray['1'] = new stdClass();
2494         $configarray['1']->config = 'lastname firstname + alternatename';
2495         $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
2496         $configarray['2'] = new stdClass();
2497         $configarray['2']->config = 'firstname aka: alternatename';
2498         $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
2499         $configarray['3'] = new stdClass();
2500         $configarray['3']->config = 'firstname (alternatename)';
2501         $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
2502         $configarray['4'] = new stdClass();
2503         $configarray['4']->config = 'firstname [alternatename]';
2504         $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
2505         $configarray['5'] = new stdClass();
2506         $configarray['5']->config = 'firstname "lastname"';
2507         $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
2509         foreach ($configarray as $config) {
2510             $CFG->fullnamedisplay = $config->config;
2511             $expectedname = $config->expectedname;
2512             $testname = fullname($user);
2513             $this->assertSame($expectedname, $testname);
2514         }
2516         // Test debugging message displays when
2517         // fullnamedisplay setting is "normal".
2518         $CFG->fullnamedisplay = 'firstname lastname';
2519         unset($user);
2520         $user = new stdClass();
2521         $user->firstname = 'Stan';
2522         $user->lastname = 'Lee';
2523         $namedisplay = fullname($user);
2524         $this->assertDebuggingCalled();
2526         // Tidy up after we finish testing.
2527         $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
2528         $CFG->alternativefullnameformat = $originalcfg->alternativefullnameformat;
2529     }
2531     public function test_get_all_user_name_fields() {
2532         $this->resetAfterTest();
2534         // Additional names in an array.
2535         $testarray = array('firstnamephonetic' => 'firstnamephonetic',
2536                 'lastnamephonetic' => 'lastnamephonetic',
2537                 'middlename' => 'middlename',
2538                 'alternatename' => 'alternatename',
2539                 'firstname' => 'firstname',
2540                 'lastname' => 'lastname');
2541         $this->assertEquals($testarray, get_all_user_name_fields());
2543         // Additional names as a string.
2544         $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
2545         $this->assertEquals($teststring, get_all_user_name_fields(true));
2547         // Additional names as a string with an alias.
2548         $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
2549         $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
2551         // Additional name fields with a prefix - object.
2552         $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
2553                 'lastnamephonetic' => 'authorlastnamephonetic',
2554                 'middlename' => 'authormiddlename',
2555                 'alternatename' => 'authoralternatename',
2556                 'firstname' => 'authorfirstname',
2557                 'lastname' => 'authorlastname');
2558         $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
2560         // Additional name fields with an alias and a title - string.
2561         $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';
2562         $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
2564         // Test the order parameter of the function.
2565         // Returning an array.
2566         $testarray = array('firstname' => 'firstname',
2567                 'lastname' => 'lastname',
2568                 'firstnamephonetic' => 'firstnamephonetic',
2569                 'lastnamephonetic' => 'lastnamephonetic',
2570                 'middlename' => 'middlename',
2571                 'alternatename' => 'alternatename'
2572         );
2573         $this->assertEquals($testarray, get_all_user_name_fields(false, null, null, null, true));
2575         // Returning a string.
2576         $teststring = 'firstname,lastname,firstnamephonetic,lastnamephonetic,middlename,alternatename';
2577         $this->assertEquals($teststring, get_all_user_name_fields(true, null, null, null, true));
2578     }
2580     public function test_order_in_string() {
2581         $this->resetAfterTest();
2583         // Return an array in an order as they are encountered in a string.
2584         $valuearray = array('second', 'firsthalf', 'first');
2585         $formatstring = 'first firsthalf some other text (second)';
2586         $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
2587         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2589         // Try again with a different order for the format.
2590         $valuearray = array('second', 'firsthalf', 'first');
2591         $formatstring = 'firsthalf first second';
2592         $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
2593         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2595         // Try again with yet another different order for the format.
2596         $valuearray = array('second', 'firsthalf', 'first');
2597         $formatstring = 'start seconds away second firstquater first firsthalf';
2598         $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
2599         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2600     }
2602     public function test_complete_user_login() {
2603         global $USER, $DB;
2605         $this->resetAfterTest();
2606         $user = $this->getDataGenerator()->create_user();
2607         $this->setUser(0);
2609         $sink = $this->redirectEvents();
2610         $loginuser = clone($user);
2611         $this->setCurrentTimeStart();
2612         @complete_user_login($loginuser); // Hide session header errors.
2613         $this->assertSame($loginuser, $USER);
2614         $this->assertEquals($user->id, $USER->id);
2615         $events = $sink->get_events();
2616         $sink->close();
2618         $this->assertCount(1, $events);
2619         $event = reset($events);
2620         $this->assertInstanceOf('\core\event\user_loggedin', $event);
2621         $this->assertEquals('user', $event->objecttable);
2622         $this->assertEquals($user->id, $event->objectid);
2623         $this->assertEquals(context_system::instance()->id, $event->contextid);
2624         $this->assertEventContextNotUsed($event);
2626         $user = $DB->get_record('user', array('id'=>$user->id));
2628         $this->assertTimeCurrent($user->firstaccess);
2629         $this->assertTimeCurrent($user->lastaccess);
2631         $this->assertTimeCurrent($USER->firstaccess);
2632         $this->assertTimeCurrent($USER->lastaccess);
2633         $this->assertTimeCurrent($USER->currentlogin);
2634         $this->assertSame(sesskey(), $USER->sesskey);
2635         $this->assertTimeCurrent($USER->preference['_lastloaded']);
2636         $this->assertObjectNotHasAttribute('password', $USER);
2637         $this->assertObjectNotHasAttribute('description', $USER);
2638     }
2640     /**
2641      * Test require_logout.
2642      */
2643     public function test_require_logout() {
2644         $this->resetAfterTest();
2645         $user = $this->getDataGenerator()->create_user();
2646         $this->setUser($user);
2648         $this->assertTrue(isloggedin());
2650         // Logout user and capture event.
2651         $sink = $this->redirectEvents();
2652         require_logout();
2653         $events = $sink->get_events();
2654         $sink->close();
2655         $event = array_pop($events);
2657         // Check if user is logged out.
2658         $this->assertFalse(isloggedin());
2660         // Test Event.
2661         $this->assertInstanceOf('\core\event\user_loggedout', $event);
2662         $this->assertSame($user->id, $event->objectid);
2663         $this->assertSame('user_logout', $event->get_legacy_eventname());
2664         $this->assertEventLegacyData($user, $event);
2665         $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
2666             $event->objectid);
2667         $this->assertEventLegacyLogData($expectedlogdata, $event);
2668         $this->assertEventContextNotUsed($event);
2669     }
2671     /**
2672      * A data provider for testing email messageid
2673      */
2674     public function generate_email_messageid_provider() {
2675         return array(
2676             'nopath' => array(
2677                 'wwwroot' => 'http://www.example.com',
2678                 'ids' => array(
2679                     'a-custom-id' => '<a-custom-id@www.example.com>',
2680                     'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash@www.example.com>',
2681                 ),
2682             ),
2683             'path' => array(
2684                 'wwwroot' => 'http://www.example.com/path/subdir',
2685                 'ids' => array(
2686                     'a-custom-id' => '<a-custom-id/path/subdir@www.example.com>',
2687                     'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash/path/subdir@www.example.com>',
2688                 ),
2689             ),
2690         );
2691     }
2693     /**
2694      * Test email message id generation
2695      *
2696      * @dataProvider generate_email_messageid_provider
2697      *
2698      * @param string $wwwroot The wwwroot
2699      * @param array $msgids An array of msgid local parts and the final result
2700      */
2701     public function test_generate_email_messageid($wwwroot, $msgids) {
2702         global $CFG;
2704         $this->resetAfterTest();
2705         $CFG->wwwroot = $wwwroot;
2707         foreach ($msgids as $local => $final) {
2708             $this->assertEquals($final, generate_email_messageid($local));
2709         }
2710     }
2712     /**
2713      * A data provider for testing email diversion
2714      */
2715     public function diverted_emails_provider() {
2716         return array(
2717             'nodiverts' => array(
2718                 'divertallemailsto' => null,
2719                 'divertallemailsexcept' => null,
2720                 array(
2721                     'foo@example.com',
2722                     'test@real.com',
2723                     'fred.jones@example.com',
2724                     'dev1@dev.com',
2725                     'fred@example.com',
2726                     'fred+verp@example.com',
2727                 ),
2728                 false,
2729             ),
2730             'alldiverts' => array(
2731                 'divertallemailsto' => 'somewhere@elsewhere.com',
2732                 'divertallemailsexcept' => null,
2733                 array(
2734                     'foo@example.com',
2735                     'test@real.com',
2736                     'fred.jones@example.com',
2737                     'dev1@dev.com',
2738                     'fred@example.com',
2739                     'fred+verp@example.com',
2740                 ),
2741                 true,
2742             ),
2743             'alsodiverts' => array(
2744                 'divertallemailsto' => 'somewhere@elsewhere.com',
2745                 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
2746                 array(
2747                     'foo@example.com',
2748                     'test@real.com',
2749                     'fred.jones@example.com',
2750                 ),
2751                 true,
2752             ),
2753             'divertsexceptions' => array(
2754                 'divertallemailsto' => 'somewhere@elsewhere.com',
2755                 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
2756                 array(
2757                     'dev1@dev.com',
2758                     'fred@example.com',
2759                     'fred+verp@example.com',
2760                 ),
2761                 false,
2762             ),
2763         );
2764     }
2766     /**
2767      * Test email diversion
2768      *
2769      * @dataProvider diverted_emails_provider
2770      *
2771      * @param string $divertallemailsto An optional email address
2772      * @param string $divertallemailsexcept An optional exclusion list
2773      * @param array $addresses An array of test addresses
2774      * @param boolean $expected Expected result
2775      */
2776     public function test_email_should_be_diverted($divertallemailsto, $divertallemailsexcept, $addresses, $expected) {
2777         global $CFG;
2779         $this->resetAfterTest();
2780         $CFG->divertallemailsto = $divertallemailsto;
2781         $CFG->divertallemailsexcept = $divertallemailsexcept;
2783         foreach ($addresses as $address) {
2784             $this->assertEquals($expected, email_should_be_diverted($address));
2785         }
2786     }
2788     public function test_email_to_user() {
2789         global $CFG;
2791         $this->resetAfterTest();
2793         $user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
2794         $user2 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
2795         $user3 = $this->getDataGenerator()->create_user(array('maildisplay' => 0));
2796         set_config('allowedemaildomains', "example.com\r\nmoodle.org");
2798         $subject = 'subject';
2799         $messagetext = 'message text';
2800         $subject2 = 'subject 2';
2801         $messagetext2 = 'message text 2';
2803         // Close the default email sink.
2804         $sink = $this->redirectEmails();
2805         $sink->close();
2807         $CFG->noemailever = true;
2808         $this->assertNotEmpty($CFG->noemailever);
2809         email_to_user($user1, $user2, $subject, $messagetext);
2810         $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
2812         unset_config('noemailever');
2814         email_to_user($user1, $user2, $subject, $messagetext);
2815         $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2817         $sink = $this->redirectEmails();
2818         email_to_user($user1, $user2, $subject, $messagetext);
2819         email_to_user($user2, $user1, $subject2, $messagetext2);
2820         $this->assertSame(2, $sink->count());
2821         $result = $sink->get_messages();
2822         $this->assertCount(2, $result);
2823         $sink->close();
2825         $this->assertSame($subject, $result[0]->subject);
2826         $this->assertSame($messagetext, trim($result[0]->body));
2827         $this->assertSame($user1->email, $result[0]->to);
2828         $this->assertSame($user2->email, $result[0]->from);
2830         $this->assertSame($subject2, $result[1]->subject);
2831         $this->assertSame($messagetext2, trim($result[1]->body));
2832         $this->assertSame($user2->email, $result[1]->to);
2833         $this->assertSame($user1->email, $result[1]->from);
2835         email_to_user($user1, $user2, $subject, $messagetext);
2836         $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2838         // Test that an empty noreplyaddress will default to a no-reply address.
2839         $sink = $this->redirectEmails();
2840         email_to_user($user1, $user3, $subject, $messagetext);
2841         $result = $sink->get_messages();
2842         $this->assertEquals($CFG->noreplyaddress, $result[0]->from);
2843         $sink->close();
2844         set_config('noreplyaddress', '');
2845         $sink = $this->redirectEmails();
2846         email_to_user($user1, $user3, $subject, $messagetext);
2847         $result = $sink->get_messages();
2848         $this->assertEquals('noreply@www.example.com', $result[0]->from);
2849         $sink->close();
2851         // Test $CFG->allowedemaildomains.
2852         set_config('noreplyaddress', 'noreply@www.example.com');
2853         $this->assertNotEmpty($CFG->allowedemaildomains);
2854         $sink = $this->redirectEmails();
2855         email_to_user($user1, $user2, $subject, $messagetext);
2856         unset_config('allowedemaildomains');
2857         email_to_user($user1, $user2, $subject, $messagetext);
2858         $result = $sink->get_messages();
2859         $this->assertNotEquals($CFG->noreplyaddress, $result[0]->from);
2860         $this->assertEquals($CFG->noreplyaddress, $result[1]->from);
2861         $sink->close();
2863         // Try to send an unsafe attachment, we should see an error message in the eventual mail body.
2864         $attachment = '../test.txt';
2865         $attachname = 'txt';
2867         $sink = $this->redirectEmails();
2868         email_to_user($user1, $user2, $subject, $messagetext, '', $attachment, $attachname);
2869         $this->assertSame(1, $sink->count());
2870         $result = $sink->get_messages();
2871         $this->assertCount(1, $result);
2872         $this->assertContains('error.txt', $result[0]->body);
2873         $this->assertContains('Error in attachment.  User attempted to attach a filename with a unsafe name.', $result[0]->body);
2874         $sink->close();
2875     }
2877     /**
2878      * Test setnew_password_and_mail.
2879      */
2880     public function test_setnew_password_and_mail() {
2881         global $DB, $CFG;
2883         $this->resetAfterTest();
2885         $user = $this->getDataGenerator()->create_user();
2887         // Update user password.
2888         $sink = $this->redirectEvents();
2889         $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
2890         setnew_password_and_mail($user);
2891         $events = $sink->get_events();
2892         $sink->close();
2893         $sink2->close();
2894         $event = array_pop($events);
2896         // Test updated value.
2897         $dbuser = $DB->get_record('user', array('id' => $user->id));
2898         $this->assertSame($user->firstname, $dbuser->firstname);
2899         $this->assertNotEmpty($dbuser->password);
2901         // Test event.
2902         $this->assertInstanceOf('\core\event\user_password_updated', $event);
2903         $this->assertSame($user->id, $event->relateduserid);
2904         $this->assertEquals(context_user::instance($user->id), $event->get_context());
2905         $this->assertEventContextNotUsed($event);
2906     }
2908     /**
2909      * Data provider for test_generate_confirmation_link
2910      * @return Array of confirmation urls and expected resultant confirmation links
2911      */
2912     public function generate_confirmation_link_provider() {
2913         global $CFG;
2914         return [
2915             "Simple name" => [
2916                 "username" => "simplename",
2917                 "confirmationurl" => null,
2918                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/simplename"
2919             ],
2920             "Period in between words in username" => [
2921                 "username" => "period.inbetween",
2922                 "confirmationurl" => null,
2923                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/period%2Einbetween"
2924             ],
2925             "Trailing periods in username" => [
2926                 "username" => "trailingperiods...",
2927                 "confirmationurl" => null,
2928                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/trailingperiods%2E%2E%2E"
2929             ],
2930             "At symbol in username" => [
2931                 "username" => "at@symbol",
2932                 "confirmationurl" => null,
2933                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/at%40symbol"
2934             ],
2935             "Dash symbol in username" => [
2936                 "username" => "has-dash",
2937                 "confirmationurl" => null,
2938                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/has-dash"
2939             ],
2940             "Underscore in username" => [
2941                 "username" => "under_score",
2942                 "confirmationurl" => null,
2943                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/under_score"
2944             ],
2945             "Many different characters in username" => [
2946                 "username" => "many_-.@characters@_@-..-..",
2947                 "confirmationurl" => null,
2948                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
2949             ],
2950             "Custom relative confirmation url" => [
2951                 "username" => "many_-.@characters@_@-..-..",
2952                 "confirmationurl" => "/custom/local/url.php",
2953                 "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
2954             ],
2955             "Custom relative confirmation url with parameters" => [
2956                 "username" => "many_-.@characters@_@-..-..",
2957                 "confirmationurl" => "/custom/local/url.php?with=param",
2958                 "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
2959             ],
2960             "Custom local confirmation url" => [
2961                 "username" => "many_-.@characters@_@-..-..",
2962                 "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php",
2963                 "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
2964             ],
2965             "Custom local confirmation url with parameters" => [
2966                 "username" => "many_-.@characters@_@-..-..",
2967                 "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php?with=param",
2968                 "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
2969             ],
2970             "Custom external confirmation url" => [
2971                 "username" => "many_-.@characters@_@-..-..",
2972                 "confirmationurl" => "http://moodle.org/custom/external/url.php",
2973                 "expected" => "http://moodle.org/custom/external/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
2974             ],
2975             "Custom external confirmation url with parameters" => [
2976                 "username" => "many_-.@characters@_@-..-..",
2977                 "confirmationurl" => "http://moodle.org/ext.php?with=some&param=eters",
2978                 "expected" => "http://moodle.org/ext.php?with=some&param=eters&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
2979             ],
2980             "Custom external confirmation url with parameters" => [
2981                 "username" => "many_-.@characters@_@-..-..",
2982                 "confirmationurl" => "http://moodle.org/ext.php?with=some&data=test",
2983                 "expected" => "http://moodle.org/ext.php?with=some&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
2984             ],
2985         ];
2986     }
2988     /**
2989      * Test generate_confirmation_link
2990      * @dataProvider generate_confirmation_link_provider
2991      * @param string $username The name of the user
2992      * @param string $confirmationurl The url the user should go to to confirm
2993      * @param string $expected The expected url of the confirmation link
2994      */
2995     public function test_generate_confirmation_link($username, $confirmationurl, $expected) {
2996         $this->resetAfterTest();
2997         $sink = $this->redirectEmails();
2999         $user = $this->getDataGenerator()->create_user(
3000             [
3001                 "username" => $username,
3002                 "confirmed" => false,
3003                 "email" => 'test@example.com',
3004             ]
3005         );
3007         send_confirmation_email($user, $confirmationurl);
3008         $sink->close();
3009         $messages = $sink->get_messages();
3010         $message = array_shift($messages);
3011         $messagebody = quoted_printable_decode($message->body);
3013         $this->assertContains($expected, $messagebody);
3014     }
3016     /**
3017      * Test generate_confirmation_link with custom admin link
3018      */
3019     public function test_generate_confirmation_link_with_custom_admin() {
3020         global $CFG;
3022         $this->resetAfterTest();
3023         $sink = $this->redirectEmails();
3025         $admin = $CFG->admin;
3026         $CFG->admin = 'custom/admin/path';
3028         $user = $this->getDataGenerator()->create_user(
3029             [
3030                 "username" => "many_-.@characters@_@-..-..",
3031                 "confirmed" => false,
3032                 "email" => 'test@example.com',
3033             ]
3034         );
3035         $confirmationurl = "/admin/test.php?with=params";
3036         $expected = $CFG->wwwroot . "/" . $CFG->admin . "/test.php?with=params&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E";
3038         send_confirmation_email($user, $confirmationurl);
3039         $sink->close();
3040         $messages = $sink->get_messages();
3041         $message = array_shift($messages);
3042         $messagebody = quoted_printable_decode($message->body);
3044         $sink->close();
3045         $this->assertContains($expected, $messagebody);
3047         $CFG->admin = $admin;
3048     }
3051     /**
3052      * Test remove_course_content deletes course contents
3053      * TODO Add asserts to verify other data related to course is deleted as well.
3054      */
3055     public function test_remove_course_contents() {
3057         $this->resetAfterTest();
3059         $course = $this->getDataGenerator()->create_course();
3060         $user = $this->getDataGenerator()->create_user();
3061         $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
3062         $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id));
3064         $this->assertNotEquals(false, note_load($note->id));
3065         remove_course_contents($course->id, false);
3066         $this->assertFalse(note_load($note->id));
3067     }
3069     /**
3070      * Test function username_load_fields_from_object().
3071      */
3072     public function test_username_load_fields_from_object() {
3073         $this->resetAfterTest();
3075         // This object represents the information returned from an sql query.
3076         $userinfo = new stdClass();
3077         $userinfo->userid = 1;
3078         $userinfo->username = 'loosebruce';
3079         $userinfo->firstname = 'Bruce';
3080         $userinfo->lastname = 'Campbell';
3081         $userinfo->firstnamephonetic = 'ブルース';
3082         $userinfo->lastnamephonetic = 'カンベッル';
3083         $userinfo->middlename = '';
3084         $userinfo->alternatename = '';
3085         $userinfo->email = '';
3086         $userinfo->picture = 23;
3087         $userinfo->imagealt = 'Michael Jordan draining another basket.';
3088         $userinfo->idnumber = 3982;
3090         // Just user name fields.
3091         $user = new stdClass();
3092         $user = username_load_fields_from_object($user, $userinfo);
3093         $expectedarray = new stdClass();
3094         $expectedarray->firstname = 'Bruce';
3095         $expectedarray->lastname = 'Campbell';
3096         $expectedarray->firstnamephonetic = 'ブルース';
3097         $expectedarray->lastnamephonetic = 'カンベッル';
3098         $expectedarray->middlename = '';
3099         $expectedarray->alternatename = '';
3100         $this->assertEquals($user, $expectedarray);
3102         // User information for showing a picture.
3103         $user = new stdClass();
3104         $additionalfields = explode(',', user_picture::fields());
3105         $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
3106         $user->id = $userinfo->userid;
3107         $expectedarray = new stdClass();
3108         $expectedarray->id = 1;
3109         $expectedarray->firstname = 'Bruce';
3110         $expectedarray->lastname = 'Campbell';
3111         $expectedarray->firstnamephonetic = 'ブルース';
3112         $expectedarray->lastnamephonetic = 'カンベッル';
3113         $expectedarray->middlename = '';
3114         $expectedarray->alternatename = '';
3115         $expectedarray->email = '';
3116         $expectedarray->picture = 23;
3117         $expectedarray->imagealt = 'Michael Jordan draining another basket.';
3118         $this->assertEquals($user, $expectedarray);
3120         // Alter the userinfo object to have a prefix.
3121         $userinfo->authorfirstname = 'Bruce';
3122         $userinfo->authorlastname = 'Campbell';
3123         $userinfo->authorfirstnamephonetic = 'ブルース';
3124         $userinfo->authorlastnamephonetic = 'カンベッル';
3125         $userinfo->authormiddlename = '';
3126         $userinfo->authorpicture = 23;
3127         $userinfo->authorimagealt = 'Michael Jordan draining another basket.';
3128         $userinfo->authoremail = 'test@example.com';
3131         // Return an object with user picture information.
3132         $user = new stdClass();
3133         $additionalfields = explode(',', user_picture::fields());
3134         $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
3135         $user->id = $userinfo->userid;
3136         $expectedarray = new stdClass();
3137         $expectedarray->id = 1;
3138         $expectedarray->firstname = 'Bruce';
3139         $expectedarray->lastname = 'Campbell';
3140         $expectedarray->firstnamephonetic = 'ブルース';
3141         $expectedarray->lastnamephonetic = 'カンベッル';
3142         $expectedarray->middlename = '';
3143         $expectedarray->alternatename = '';
3144         $expectedarray->email = 'test@example.com';
3145         $expectedarray->picture = 23;
3146         $expectedarray->imagealt = 'Michael Jordan draining another basket.';
3147         $this->assertEquals($user, $expectedarray);
3148     }
3150     /**
3151      * Test function count_words().
3152      */
3153     public function test_count_words() {
3154         $count = count_words("one two three'four");
3155         $this->assertEquals(3, $count);
3157         $count = count_words('one+two three’four');
3158         $this->assertEquals(3, $count);
3160         $count = count_words('one"two three-four');
3161         $this->assertEquals(2, $count);
3163         $count = count_words('one@two three_four');
3164         $this->assertEquals(4, $count);
3166         $count = count_words('one\two three/four');
3167         $this->assertEquals(4, $count);
3169         $count = count_words(' one ... two &nbsp; three...four ');
3170         $this->assertEquals(4, $count);
3172         $count = count_words('one.2 3,four');
3173         $this->assertEquals(4, $count);
3175         $count = count_words('1³ £2 €3.45 $6,789');
3176         $this->assertEquals(4, $count);
3178         $count = count_words('one—two ブルース カンベッル');
3179         $this->assertEquals(4, $count);
3181         $count = count_words('one…two ブルース … カンベッル');
3182         $this->assertEquals(4, $count);
3183     }
3184     /**
3185      * Tests the getremoteaddr() function.
3186      */
3187     public function test_getremoteaddr() {
3188         $xforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null;
3190         $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
3191         $noip = getremoteaddr('1.1.1.1');
3192         $this->assertEquals('1.1.1.1', $noip);
3194         $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
3195         $noip = getremoteaddr();
3196         $this->assertEquals('0.0.0.0', $noip);
3198         $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1';
3199         $singleip = getremoteaddr();
3200         $this->assertEquals('127.0.0.1', $singleip);
3202         $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2';
3203         $twoip = getremoteaddr();
3204         $this->assertEquals('127.0.0.1', $twoip);
3206         $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2, 127.0.0.3';
3207         $threeip = getremoteaddr();
3208         $this->assertEquals('127.0.0.1', $threeip);
3210         $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1:65535,127.0.0.2';
3211         $portip = getremoteaddr();
3212         $this->assertEquals('127.0.0.1', $portip);
3214         $_SERVER['HTTP_X_FORWARDED_FOR'] = '0:0:0:0:0:0:0:1,127.0.0.2';
3215         $portip = getremoteaddr();
3216         $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3218         $_SERVER['HTTP_X_FORWARDED_FOR'] = '0::1,127.0.0.2';
3219         $portip = getremoteaddr();
3220         $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3222         $_SERVER['HTTP_X_FORWARDED_FOR'] = '[0:0:0:0:0:0:0:1]:65535,127.0.0.2';
3223         $portip = getremoteaddr();
3224         $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3226         $_SERVER['HTTP_X_FORWARDED_FOR'] = $xforwardedfor;
3228     }
3230     /*
3231      * Test emulation of random_bytes() function.
3232      */
3233     public function test_random_bytes_emulate() {
3234         $result = random_bytes_emulate(10);
3235         $this->assertSame(10, strlen($result));
3236         $this->assertnotSame($result, random_bytes_emulate(10));
3238         $result = random_bytes_emulate(21);
3239         $this->assertSame(21, strlen($result));
3240         $this->assertnotSame($result, random_bytes_emulate(21));
3242         $result = random_bytes_emulate(666);
3243         $this->assertSame(666, strlen($result));
3245         $result = random_bytes_emulate(40);
3246         $this->assertSame(40, strlen($result));
3248         $this->assertDebuggingNotCalled();
3250        &