MDL-62240 file: Add includehash to shorten_filename + unit tests
[moodle.git] / lib / tests / moodlelib_test.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Unit tests for (some of) ../moodlelib.php.
19  *
20  * @package    core
21  * @category   phpunit
22  * @copyright  &copy; 2006 The Open University
23  * @author     T.J.Hunt@open.ac.uk
24  * @author     nicolas@moodle.com
25  */
27 defined('MOODLE_INTERNAL') || die();
29 class core_moodlelib_testcase extends advanced_testcase {
31     public static $includecoverage = array('lib/moodlelib.php');
33     /**
34      * Define a local decimal separator.
35      *
36      * It is not possible to directly change the result of get_string in
37      * a unit test. Instead, we create a language pack for language 'xx' in
38      * dataroot and make langconfig.php with the string we need to change.
39      * The example separator used here is 'X'; on PHP 5.3 and before this
40      * must be a single byte character due to PHP bug/limitation in
41      * number_format, so you can't use UTF-8 characters.
42      */
43     protected function define_local_decimal_separator() {
44         global $SESSION, $CFG;
46         $SESSION->lang = 'xx';
47         $langconfig = "<?php\n\$string['decsep'] = 'X';";
48         $langfolder = $CFG->dataroot . '/lang/xx';
49         check_dir_exists($langfolder);
50         file_put_contents($langfolder . '/langconfig.php', $langconfig);
51     }
53     public function test_cleanremoteaddr() {
54         // IPv4.
55         $this->assertNull(cleanremoteaddr('1023.121.234.1'));
56         $this->assertSame('123.121.234.1', cleanremoteaddr('123.121.234.01 '));
58         // IPv6.
59         $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:0:0'));
60         $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:abh'));
61         $this->assertNull(cleanremoteaddr('0:0:0:::0:0:1'));
62         $this->assertSame('::', cleanremoteaddr('0:0:0:0:0:0:0:0', true));
63         $this->assertSame('::1:1', cleanremoteaddr('0:0:0:0:0:0:1:1', true));
64         $this->assertSame('abcd:ef::', cleanremoteaddr('abcd:00ef:0:0:0:0:0:0', true));
65         $this->assertSame('1::1', cleanremoteaddr('1:0:0:0:0:0:0:1', true));
66         $this->assertSame('0:0:0:0:0:0:10:1', cleanremoteaddr('::10:1', false));
67         $this->assertSame('1:1:0:0:0:0:0:0', cleanremoteaddr('01:1::', false));
68         $this->assertSame('10:0:0:0:0:0:0:10', cleanremoteaddr('10::10', false));
69         $this->assertSame('::ffff:c0a8:11', cleanremoteaddr('::ffff:192.168.1.1', true));
70     }
72     public function test_address_in_subnet() {
73         // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask).
74         $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.1/32'));
75         $this->assertFalse(address_in_subnet('123.121.23.1', '123.121.23.0/32'));
76         $this->assertTrue(address_in_subnet('10.10.10.100',  '123.121.23.45/0'));
77         $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/24'));
78         $this->assertFalse(address_in_subnet('123.121.34.1', '123.121.234.0/24'));
79         $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/30'));
80         $this->assertFalse(address_in_subnet('123.121.23.8', '123.121.23.0/30'));
81         $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
82         $this->assertFalse(address_in_subnet('bab:baba::baba', 'bab:baba::cece/128'));
83         $this->assertTrue(address_in_subnet('baba:baba::baba', 'cece:cece::cece/0'));
84         $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
85         $this->assertTrue(address_in_subnet('baba:baba::00ba', 'baba:baba::/120'));
86         $this->assertFalse(address_in_subnet('baba:baba::aba', 'baba:baba::/120'));
87         $this->assertTrue(address_in_subnet('baba::baba:00ba', 'baba::baba:0/112'));
88         $this->assertFalse(address_in_subnet('baba::aba:00ba', 'baba::baba:0/112'));
89         $this->assertFalse(address_in_subnet('aba::baba:0000', 'baba::baba:0/112'));
91         // Fixed input.
92         $this->assertTrue(address_in_subnet('123.121.23.1   ', ' 123.121.23.0 / 24'));
93         $this->assertTrue(address_in_subnet('::ffff:10.1.1.1', ' 0:0:0:000:0:ffff:a1:10 / 126'));
95         // Incorrect input.
96         $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/-2'));
97         $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/64'));
98         $this->assertFalse(address_in_subnet('123.121.234.x', '123.121.234.1/24'));
99         $this->assertFalse(address_in_subnet('123.121.234.0', '123.121.234.xx/24'));
100         $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/xx0'));
101         $this->assertFalse(address_in_subnet('::1', '::aa:0/xx0'));
102         $this->assertFalse(address_in_subnet('::1', '::aa:0/-5'));
103         $this->assertFalse(address_in_subnet('::1', '::aa:0/130'));
104         $this->assertFalse(address_in_subnet('x:1', '::aa:0/130'));
105         $this->assertFalse(address_in_subnet('::1', '::ax:0/130'));
107         // 2: xxx.xxx.xxx.xxx-yyy or  xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy (a range of IP addresses in the last group).
108         $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12-14'));
109         $this->assertTrue(address_in_subnet('123.121.234.13', '123.121.234.12-14'));
110         $this->assertTrue(address_in_subnet('123.121.234.14', '123.121.234.12-14'));
111         $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.12-14'));
112         $this->assertFalse(address_in_subnet('123.121.234.20', '123.121.234.12-14'));
113         $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.234.12-14'));
114         $this->assertFalse(address_in_subnet('123.12.234.12', '123.121.234.12-14'));
115         $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba-babe'));
116         $this->assertTrue(address_in_subnet('baba:baba::babc', 'baba:baba::baba-babe'));
117         $this->assertTrue(address_in_subnet('baba:baba::babe', 'baba:baba::baba-babe'));
118         $this->assertFalse(address_in_subnet('bab:baba::bab0', 'bab:baba::baba-babe'));
119         $this->assertFalse(address_in_subnet('bab:baba::babf', 'bab:baba::baba-babe'));
120         $this->assertFalse(address_in_subnet('bab:baba::bfbe', 'bab:baba::baba-babe'));
121         $this->assertFalse(address_in_subnet('bfb:baba::babe', 'bab:baba::baba-babe'));
123         // Fixed input.
124         $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12 - 14 '));
125         $this->assertTrue(address_in_subnet('bab:baba::babe', 'bab:baba::baba - babe  '));
127         // Incorrect input.
128         $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-234.14'));
129         $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-256'));
130         $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12--256'));
132         // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-).
133         $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12'));
134         $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.23.13'));
135         $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.'));
136         $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234'));
137         $this->assertTrue(address_in_subnet('123.121.234.12', '123.121'));
138         $this->assertTrue(address_in_subnet('123.121.234.12', '123'));
139         $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234.'));
140         $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234'));
141         $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba::bab'));
142         $this->assertFalse(address_in_subnet('baba:baba::ba', 'baba:baba::bc'));
143         $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba'));
144         $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:'));
145         $this->assertFalse(address_in_subnet('bab:baba::bab', 'baba:'));
147         // Multiple subnets.
148         $this->assertTrue(address_in_subnet('123.121.234.12', '::1/64, 124., 123.121.234.10-30'));
149         $this->assertTrue(address_in_subnet('124.121.234.12', '::1/64, 124., 123.121.234.10-30'));
150         $this->assertTrue(address_in_subnet('::2',            '::1/64, 124., 123.121.234.10-30'));
151         $this->assertFalse(address_in_subnet('12.121.234.12', '::1/64, 124., 123.121.234.10-30'));
153         // Other incorrect input.
154         $this->assertFalse(address_in_subnet('123.123.123.123', ''));
155     }
157     public function test_fix_utf8() {
158         // Make sure valid data including other types is not changed.
159         $this->assertSame(null, fix_utf8(null));
160         $this->assertSame(1, fix_utf8(1));
161         $this->assertSame(1.1, fix_utf8(1.1));
162         $this->assertSame(true, fix_utf8(true));
163         $this->assertSame('', fix_utf8(''));
164         $this->assertSame('abc', fix_utf8('abc'));
165         $array = array('do', 're', 'mi');
166         $this->assertSame($array, fix_utf8($array));
167         $object = new stdClass();
168         $object->a = 'aa';
169         $object->b = 'bb';
170         $this->assertEquals($object, fix_utf8($object));
172         // valid utf8 string
173         $this->assertSame("žlutý koníček přeskočil potůček \n\t\r", fix_utf8("žlutý koníček přeskočil potůček \n\t\r\0"));
175         // Invalid utf8 string.
176         $this->assertSame('aš', fix_utf8('a'.chr(130).'š'), 'This fails with buggy iconv() when mbstring extenstion is not available as fallback.');
177     }
179     public function test_optional_param() {
180         global $CFG;
182         $_POST['username'] = 'post_user';
183         $_GET['username'] = 'get_user';
184         $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
186         unset($_POST['username']);
187         $this->assertSame($_GET['username'], optional_param('username', 'default_user', PARAM_RAW));
189         unset($_GET['username']);
190         $this->assertSame('default_user', optional_param('username', 'default_user', PARAM_RAW));
192         // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
193         $_POST['username'] = 'post_user';
194         try {
195             optional_param('username', 'default_user', null);
196             $this->fail('coding_exception expected');
197         } catch (moodle_exception $ex) {
198             $this->assertInstanceOf('coding_exception', $ex);
199         }
200         try {
201             @optional_param('username', 'default_user');
202             $this->fail('coding_exception expected');
203         } catch (moodle_exception $ex) {
204             $this->assertInstanceOf('coding_exception', $ex);
205         } catch (Error $error) {
206             // PHP 7.1 throws Error even earlier.
207             $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
208         }
209         try {
210             @optional_param('username');
211             $this->fail('coding_exception expected');
212         } catch (moodle_exception $ex) {
213             $this->assertInstanceOf('coding_exception', $ex);
214         } catch (Error $error) {
215             // PHP 7.1 throws Error even earlier.
216             $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
217         }
218         try {
219             optional_param('', 'default_user', PARAM_RAW);
220             $this->fail('coding_exception expected');
221         } catch (moodle_exception $ex) {
222             $this->assertInstanceOf('coding_exception', $ex);
223         }
225         // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
226         $_POST['username'] = array('a'=>'a');
227         $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
228         $this->assertDebuggingCalled();
229     }
231     public function test_optional_param_array() {
232         global $CFG;
234         $_POST['username'] = array('a'=>'post_user');
235         $_GET['username'] = array('a'=>'get_user');
236         $this->assertSame($_POST['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
238         unset($_POST['username']);
239         $this->assertSame($_GET['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
241         unset($_GET['username']);
242         $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
244         // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
245         $_POST['username'] = array('a'=>'post_user');
246         try {
247             optional_param_array('username', array('a'=>'default_user'), null);
248             $this->fail('coding_exception expected');
249         } catch (moodle_exception $ex) {
250             $this->assertInstanceOf('coding_exception', $ex);
251         }
252         try {
253             @optional_param_array('username', array('a'=>'default_user'));
254             $this->fail('coding_exception expected');
255         } catch (moodle_exception $ex) {
256             $this->assertInstanceOf('coding_exception', $ex);
257         } catch (Error $error) {
258             // PHP 7.1 throws Error even earlier.
259             $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
260         }
261         try {
262             @optional_param_array('username');
263             $this->fail('coding_exception expected');
264         } catch (moodle_exception $ex) {
265             $this->assertInstanceOf('coding_exception', $ex);
266         } catch (Error $error) {
267             // PHP 7.1 throws Error even earlier.
268             $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
269         }
270         try {
271             optional_param_array('', array('a'=>'default_user'), PARAM_RAW);
272             $this->fail('coding_exception expected');
273         } catch (moodle_exception $ex) {
274             $this->assertInstanceOf('coding_exception', $ex);
275         }
277         // Do not allow nested arrays.
278         try {
279             $_POST['username'] = array('a'=>array('b'=>'post_user'));
280             optional_param_array('username', array('a'=>'default_user'), PARAM_RAW);
281             $this->fail('coding_exception expected');
282         } catch (coding_exception $ex) {
283             $this->assertTrue(true);
284         }
286         // Do not allow non-arrays.
287         $_POST['username'] = 'post_user';
288         $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
289         $this->assertDebuggingCalled();
291         // Make sure array keys are sanitised.
292         $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
293         $this->assertSame(array('a1_-'=>'post_user'), optional_param_array('username', array(), PARAM_RAW));
294         $this->assertDebuggingCalled();
295     }
297     public function test_required_param() {
298         $_POST['username'] = 'post_user';
299         $_GET['username'] = 'get_user';
300         $this->assertSame('post_user', required_param('username', PARAM_RAW));
302         unset($_POST['username']);
303         $this->assertSame('get_user', required_param('username', PARAM_RAW));
305         unset($_GET['username']);
306         try {
307             $this->assertSame('default_user', required_param('username', PARAM_RAW));
308             $this->fail('moodle_exception expected');
309         } catch (moodle_exception $ex) {
310             $this->assertInstanceOf('moodle_exception', $ex);
311         }
313         // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
314         $_POST['username'] = 'post_user';
315         try {
316             @required_param('username');
317             $this->fail('coding_exception expected');
318         } catch (moodle_exception $ex) {
319             $this->assertInstanceOf('coding_exception', $ex);
320         } catch (Error $error) {
321             // PHP 7.1 throws Error even earlier.
322             $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
323         }
324         try {
325             required_param('username', '');
326             $this->fail('coding_exception expected');
327         } catch (moodle_exception $ex) {
328             $this->assertInstanceOf('coding_exception', $ex);
329         }
330         try {
331             required_param('', PARAM_RAW);
332             $this->fail('coding_exception expected');
333         } catch (moodle_exception $ex) {
334             $this->assertInstanceOf('coding_exception', $ex);
335         }
337         // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
338         $_POST['username'] = array('a'=>'a');
339         $this->assertSame($_POST['username'], required_param('username', PARAM_RAW));
340         $this->assertDebuggingCalled();
341     }
343     public function test_required_param_array() {
344         global $CFG;
346         $_POST['username'] = array('a'=>'post_user');
347         $_GET['username'] = array('a'=>'get_user');
348         $this->assertSame($_POST['username'], required_param_array('username', PARAM_RAW));
350         unset($_POST['username']);
351         $this->assertSame($_GET['username'], required_param_array('username', PARAM_RAW));
353         // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
354         $_POST['username'] = array('a'=>'post_user');
355         try {
356             required_param_array('username', null);
357             $this->fail('coding_exception expected');
358         } catch (moodle_exception $ex) {
359             $this->assertInstanceOf('coding_exception', $ex);
360         }
361         try {
362             @required_param_array('username');
363             $this->fail('coding_exception expected');
364         } catch (moodle_exception $ex) {
365             $this->assertInstanceOf('coding_exception', $ex);
366         } catch (Error $error) {
367             // PHP 7.1 throws Error.
368             $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
369         }
370         try {
371             required_param_array('', PARAM_RAW);
372             $this->fail('coding_exception expected');
373         } catch (moodle_exception $ex) {
374             $this->assertInstanceOf('coding_exception', $ex);
375         }
377         // Do not allow nested arrays.
378         try {
379             $_POST['username'] = array('a'=>array('b'=>'post_user'));
380             required_param_array('username', PARAM_RAW);
381             $this->fail('coding_exception expected');
382         } catch (moodle_exception $ex) {
383             $this->assertInstanceOf('coding_exception', $ex);
384         }
386         // Do not allow non-arrays.
387         try {
388             $_POST['username'] = 'post_user';
389             required_param_array('username', PARAM_RAW);
390             $this->fail('moodle_exception expected');
391         } catch (moodle_exception $ex) {
392             $this->assertInstanceOf('moodle_exception', $ex);
393         }
395         // Make sure array keys are sanitised.
396         $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
397         $this->assertSame(array('a1_-'=>'post_user'), required_param_array('username', PARAM_RAW));
398         $this->assertDebuggingCalled();
399     }
401     public function test_clean_param() {
402         // Forbid objects and arrays.
403         try {
404             clean_param(array('x', 'y'), PARAM_RAW);
405             $this->fail('coding_exception expected');
406         } catch (moodle_exception $ex) {
407             $this->assertInstanceOf('coding_exception', $ex);
408         }
409         try {
410             $param = new stdClass();
411             $param->id = 1;
412             clean_param($param, PARAM_RAW);
413             $this->fail('coding_exception expected');
414         } catch (moodle_exception $ex) {
415             $this->assertInstanceOf('coding_exception', $ex);
416         }
418         // Require correct type.
419         try {
420             clean_param('x', 'xxxxxx');
421             $this->fail('moodle_exception expected');
422         } catch (moodle_exception $ex) {
423             $this->assertInstanceOf('moodle_exception', $ex);
424         }
425         try {
426             @clean_param('x');
427             $this->fail('moodle_exception expected');
428         } catch (moodle_exception $ex) {
429             $this->assertInstanceOf('moodle_exception', $ex);
430         } catch (Error $error) {
431             // PHP 7.1 throws Error even earlier.
432             $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
433         }
434     }
436     public function test_clean_param_array() {
437         $this->assertSame(array(), clean_param_array(null, PARAM_RAW));
438         $this->assertSame(array('a', 'b'), clean_param_array(array('a', 'b'), PARAM_RAW));
439         $this->assertSame(array('a', array('b')), clean_param_array(array('a', array('b')), PARAM_RAW, true));
441         // Require correct type.
442         try {
443             clean_param_array(array('x'), 'xxxxxx');
444             $this->fail('moodle_exception expected');
445         } catch (moodle_exception $ex) {
446             $this->assertInstanceOf('moodle_exception', $ex);
447         }
448         try {
449             @clean_param_array(array('x'));
450             $this->fail('moodle_exception expected');
451         } catch (moodle_exception $ex) {
452             $this->assertInstanceOf('moodle_exception', $ex);
453         } catch (Error $error) {
454             // PHP 7.1 throws Error even earlier.
455             $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
456         }
458         try {
459             clean_param_array(array('x', array('y')), PARAM_RAW);
460             $this->fail('coding_exception expected');
461         } catch (moodle_exception $ex) {
462             $this->assertInstanceOf('coding_exception', $ex);
463         }
465         // Test recursive.
466     }
468     public function test_clean_param_raw() {
469         $this->assertSame(
470             '#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)',
471             clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_RAW));
472     }
474     public function test_clean_param_trim() {
475         $this->assertSame('Frog toad', clean_param("   Frog toad   \r\n  ", PARAM_RAW_TRIMMED));
476     }
478     public function test_clean_param_clean() {
479         // PARAM_CLEAN is an ugly hack, do not use in new code (skodak),
480         // instead use more specific type, or submit sothing that can be verified properly.
481         $this->assertSame('xx', clean_param('xx<script>', PARAM_CLEAN));
482     }
484     public function test_clean_param_alpha() {
485         $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHA));
486     }
488     public function test_clean_param_alphanum() {
489         $this->assertSame('978942897DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHANUM));
490     }
492     public function test_clean_param_alphaext() {
493         $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHAEXT));
494     }
496     public function test_clean_param_sequence() {
497         $this->assertSame(',9789,42897', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_SEQUENCE));
498     }
500     public function test_clean_param_component() {
501         // Please note the cleaning of component names is very strict, no guessing here.
502         $this->assertSame('mod_forum', clean_param('mod_forum', PARAM_COMPONENT));
503         $this->assertSame('block_online_users', clean_param('block_online_users', PARAM_COMPONENT));
504         $this->assertSame('block_blond_online_users', clean_param('block_blond_online_users', PARAM_COMPONENT));
505         $this->assertSame('mod_something2', clean_param('mod_something2', PARAM_COMPONENT));
506         $this->assertSame('forum', clean_param('forum', PARAM_COMPONENT));
507         $this->assertSame('user', clean_param('user', PARAM_COMPONENT));
508         $this->assertSame('rating', clean_param('rating', PARAM_COMPONENT));
509         $this->assertSame('feedback360', clean_param('feedback360', PARAM_COMPONENT));
510         $this->assertSame('mod_feedback360', clean_param('mod_feedback360', PARAM_COMPONENT));
511         $this->assertSame('', clean_param('mod_2something', PARAM_COMPONENT));
512         $this->assertSame('', clean_param('2mod_something', PARAM_COMPONENT));
513         $this->assertSame('', clean_param('mod_something_xx', PARAM_COMPONENT));
514         $this->assertSame('', clean_param('auth_something__xx', PARAM_COMPONENT));
515         $this->assertSame('', clean_param('mod_Something', PARAM_COMPONENT));
516         $this->assertSame('', clean_param('mod_somethíng', PARAM_COMPONENT));
517         $this->assertSame('', clean_param('mod__something', PARAM_COMPONENT));
518         $this->assertSame('', clean_param('auth_xx-yy', PARAM_COMPONENT));
519         $this->assertSame('', clean_param('_auth_xx', PARAM_COMPONENT));
520         $this->assertSame('', clean_param('a2uth_xx', PARAM_COMPONENT));
521         $this->assertSame('', clean_param('auth_xx_', PARAM_COMPONENT));
522         $this->assertSame('', clean_param('auth_xx.old', PARAM_COMPONENT));
523         $this->assertSame('', clean_param('_user', PARAM_COMPONENT));
524         $this->assertSame('', clean_param('2rating', PARAM_COMPONENT));
525         $this->assertSame('', clean_param('user_', PARAM_COMPONENT));
526     }
528     public function test_is_valid_plugin_name() {
529         $this->assertTrue(is_valid_plugin_name('forum'));
530         $this->assertTrue(is_valid_plugin_name('forum2'));
531         $this->assertTrue(is_valid_plugin_name('feedback360'));
532         $this->assertTrue(is_valid_plugin_name('online_users'));
533         $this->assertTrue(is_valid_plugin_name('blond_online_users'));
534         $this->assertFalse(is_valid_plugin_name('online__users'));
535         $this->assertFalse(is_valid_plugin_name('forum '));
536         $this->assertFalse(is_valid_plugin_name('forum.old'));
537         $this->assertFalse(is_valid_plugin_name('xx-yy'));
538         $this->assertFalse(is_valid_plugin_name('2xx'));
539         $this->assertFalse(is_valid_plugin_name('Xx'));
540         $this->assertFalse(is_valid_plugin_name('_xx'));
541         $this->assertFalse(is_valid_plugin_name('xx_'));
542     }
544     public function test_clean_param_plugin() {
545         // Please note the cleaning of plugin names is very strict, no guessing here.
546         $this->assertSame('forum', clean_param('forum', PARAM_PLUGIN));
547         $this->assertSame('forum2', clean_param('forum2', PARAM_PLUGIN));
548         $this->assertSame('feedback360', clean_param('feedback360', PARAM_PLUGIN));
549         $this->assertSame('online_users', clean_param('online_users', PARAM_PLUGIN));
550         $this->assertSame('blond_online_users', clean_param('blond_online_users', PARAM_PLUGIN));
551         $this->assertSame('', clean_param('online__users', PARAM_PLUGIN));
552         $this->assertSame('', clean_param('forum ', PARAM_PLUGIN));
553         $this->assertSame('', clean_param('forum.old', PARAM_PLUGIN));
554         $this->assertSame('', clean_param('xx-yy', PARAM_PLUGIN));
555         $this->assertSame('', clean_param('2xx', PARAM_PLUGIN));
556         $this->assertSame('', clean_param('Xx', PARAM_PLUGIN));
557         $this->assertSame('', clean_param('_xx', PARAM_PLUGIN));
558         $this->assertSame('', clean_param('xx_', PARAM_PLUGIN));
559     }
561     public function test_clean_param_area() {
562         // Please note the cleaning of area names is very strict, no guessing here.
563         $this->assertSame('something', clean_param('something', PARAM_AREA));
564         $this->assertSame('something2', clean_param('something2', PARAM_AREA));
565         $this->assertSame('some_thing', clean_param('some_thing', PARAM_AREA));
566         $this->assertSame('some_thing_xx', clean_param('some_thing_xx', PARAM_AREA));
567         $this->assertSame('feedback360', clean_param('feedback360', PARAM_AREA));
568         $this->assertSame('', clean_param('_something', PARAM_AREA));
569         $this->assertSame('', clean_param('something_', PARAM_AREA));
570         $this->assertSame('', clean_param('2something', PARAM_AREA));
571         $this->assertSame('', clean_param('Something', PARAM_AREA));
572         $this->assertSame('', clean_param('some-thing', PARAM_AREA));
573         $this->assertSame('', clean_param('somethííng', PARAM_AREA));
574         $this->assertSame('', clean_param('something.x', PARAM_AREA));
575     }
577     public function test_clean_param_text() {
578         $this->assertSame(PARAM_TEXT, PARAM_MULTILANG);
579         // Standard.
580         $this->assertSame('xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>', clean_param('xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>', PARAM_TEXT));
581         $this->assertSame('<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>', clean_param('<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>', PARAM_TEXT));
582         $this->assertSame('xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>', clean_param('xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>', PARAM_TEXT));
583         // Malformed.
584         $this->assertSame('<span lang="en" class="multilang">aa</span>', clean_param('<span lang="en" class="multilang">aa</span>', PARAM_TEXT));
585         $this->assertSame('aa', clean_param('<span lang="en" class="nothing" class="multilang">aa</span>', PARAM_TEXT));
586         $this->assertSame('aa', clean_param('<lang lang="en" class="multilang">aa</lang>', PARAM_TEXT));
587         $this->assertSame('aa', clean_param('<lang lang="en!!">aa</lang>', PARAM_TEXT));
588         $this->assertSame('aa', clean_param('<span lang="en==" class="multilang">aa</span>', PARAM_TEXT));
589         $this->assertSame('abc', clean_param('a<em>b</em>c', PARAM_TEXT));
590         $this->assertSame('a>c>', clean_param('a><xx >c>', PARAM_TEXT)); // Standard strip_tags() behaviour.
591         $this->assertSame('a', clean_param('a<b', PARAM_TEXT));
592         $this->assertSame('a>b', clean_param('a>b', PARAM_TEXT));
593         $this->assertSame('<lang lang="en">a>a</lang>', clean_param('<lang lang="en">a>a</lang>', PARAM_TEXT)); // Standard strip_tags() behaviour.
594         $this->assertSame('a', clean_param('<lang lang="en">a<a</lang>', PARAM_TEXT));
595         $this->assertSame('<lang lang="en">aa</lang>', clean_param('<lang lang="en">a<br>a</lang>', PARAM_TEXT));
596     }
598     public function test_clean_param_url() {
599         // Test PARAM_URL and PARAM_LOCALURL a bit.
600         // Valid URLs.
601         $this->assertSame('http://google.com/', clean_param('http://google.com/', PARAM_URL));
602         $this->assertSame('http://some.very.long.and.silly.domain/with/a/path/', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_URL));
603         $this->assertSame('http://localhost/', clean_param('http://localhost/', PARAM_URL));
604         $this->assertSame('http://0.255.1.1/numericip.php', clean_param('http://0.255.1.1/numericip.php', PARAM_URL));
605         $this->assertSame('https://google.com/', clean_param('https://google.com/', PARAM_URL));
606         $this->assertSame('https://some.very.long.and.silly.domain/with/a/path/', clean_param('https://some.very.long.and.silly.domain/with/a/path/', PARAM_URL));
607         $this->assertSame('https://localhost/', clean_param('https://localhost/', PARAM_URL));
608         $this->assertSame('https://0.255.1.1/numericip.php', clean_param('https://0.255.1.1/numericip.php', PARAM_URL));
609         $this->assertSame('ftp://ftp.debian.org/debian/', clean_param('ftp://ftp.debian.org/debian/', PARAM_URL));
610         $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_URL));
611         // Invalid URLs.
612         $this->assertSame('', clean_param('funny:thing', PARAM_URL));
613         $this->assertSame('', clean_param('http://example.ee/sdsf"f', PARAM_URL));
614         $this->assertSame('', clean_param('javascript://comment%0Aalert(1)', PARAM_URL));
615         $this->assertSame('', clean_param('rtmp://example.com/livestream', PARAM_URL));
616         $this->assertSame('', clean_param('rtmp://example.com/live&foo', PARAM_URL));
617         $this->assertSame('', clean_param('rtmp://example.com/fms&mp4:path/to/file.mp4', PARAM_URL));
618         $this->assertSame('', clean_param('mailto:support@moodle.org', PARAM_URL));
619         $this->assertSame('', clean_param('mailto:support@moodle.org?subject=Hello%20Moodle', PARAM_URL));
620         $this->assertSame('', clean_param('mailto:support@moodle.org?subject=Hello%20Moodle&cc=feedback@moodle.org', PARAM_URL));
621     }
623     public function test_clean_param_localurl() {
624         global $CFG;
626         $this->resetAfterTest();
628         // External, invalid.
629         $this->assertSame('', clean_param('funny:thing', PARAM_LOCALURL));
630         $this->assertSame('', clean_param('http://google.com/', PARAM_LOCALURL));
631         $this->assertSame('', clean_param('https://google.com/?test=true', PARAM_LOCALURL));
632         $this->assertSame('', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL));
634         // Local absolute.
635         $this->assertSame(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
636         $this->assertSame($CFG->wwwroot . '/with/something?else=true',
637             clean_param($CFG->wwwroot . '/with/something?else=true', PARAM_LOCALURL));
639         // Local relative.
640         $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_LOCALURL));
641         $this->assertSame('course/view.php?id=3', clean_param('course/view.php?id=3', PARAM_LOCALURL));
643         // Local absolute HTTPS in a non HTTPS site.
644         $CFG->wwwroot = str_replace('https:', 'http:', $CFG->wwwroot); // Need to simulate non-https site.
645         $httpsroot = str_replace('http:', 'https:', $CFG->wwwroot);
646         $this->assertSame('', clean_param($httpsroot, PARAM_LOCALURL));
647         $this->assertSame('', clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL));
649         // Local absolute HTTPS in a HTTPS site.
650         $CFG->wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
651         $httpsroot = $CFG->wwwroot;
652         $this->assertSame($httpsroot, clean_param($httpsroot, PARAM_LOCALURL));
653         $this->assertSame($httpsroot . '/with/something?else=true',
654             clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL));
656         // Test open redirects are not possible.
657         $CFG->wwwroot = 'http://www.example.com';
658         $this->assertSame('', clean_param('http://www.example.com.evil.net/hack.php', PARAM_LOCALURL));
659         $CFG->wwwroot = 'https://www.example.com';
660         $this->assertSame('', clean_param('https://www.example.com.evil.net/hack.php', PARAM_LOCALURL));
661     }
663     public function test_clean_param_file() {
664         $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_FILE));
665         $this->assertSame('badfile.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE));
666         $this->assertSame('..parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_FILE));
667         $this->assertSame('....grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_FILE));
668         $this->assertSame('..winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_FILE));
669         $this->assertSame('....wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_FILE));
670         $this->assertSame('myfile.a.b.txt', clean_param('myfile.a.b.txt', PARAM_FILE));
671         $this->assertSame('myfile..a..b.txt', clean_param('myfile..a..b.txt', PARAM_FILE));
672         $this->assertSame('myfile.a..b...txt', clean_param('myfile.a..b...txt', PARAM_FILE));
673         $this->assertSame('myfile.a.txt', clean_param('myfile.a.txt', PARAM_FILE));
674         $this->assertSame('myfile...txt', clean_param('myfile...txt', PARAM_FILE));
675         $this->assertSame('...jpg', clean_param('...jpg', PARAM_FILE));
676         $this->assertSame('.a.b.', clean_param('.a.b.', PARAM_FILE));
677         $this->assertSame('', clean_param('.', PARAM_FILE));
678         $this->assertSame('', clean_param('..', PARAM_FILE));
679         $this->assertSame('...', clean_param('...', PARAM_FILE));
680         $this->assertSame('. . . .', clean_param('. . . .', PARAM_FILE));
681         $this->assertSame('dontrtrim.me. .. .. . ', clean_param('dontrtrim.me. .. .. . ', PARAM_FILE));
682         $this->assertSame(' . .dontltrim.me', clean_param(' . .dontltrim.me', PARAM_FILE));
683         $this->assertSame('here is a tab.txt', clean_param("here is a tab\t.txt", PARAM_FILE));
684         $this->assertSame('here is a linebreak.txt', clean_param("here is a line\r\nbreak.txt", PARAM_FILE));
686         // The following behaviours have been maintained although they seem a little odd.
687         $this->assertSame('funnything', clean_param('funny:thing', PARAM_FILE));
688         $this->assertSame('.currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_FILE));
689         $this->assertSame('ctempwindowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_FILE));
690         $this->assertSame('homeuserlinuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_FILE));
691         $this->assertSame('~myfile.txt', clean_param('~/myfile.txt', PARAM_FILE));
692     }
694     public function test_clean_param_path() {
695         $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_PATH));
696         $this->assertSame('bad/file.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH));
697         $this->assertSame('/parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_PATH));
698         $this->assertSame('/grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_PATH));
699         $this->assertSame('/winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_PATH));
700         $this->assertSame('/wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_PATH));
701         $this->assertSame('funnything', clean_param('funny:thing', PARAM_PATH));
702         $this->assertSame('./here', clean_param('./././here', PARAM_PATH));
703         $this->assertSame('./currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_PATH));
704         $this->assertSame('c/temp/windowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_PATH));
705         $this->assertSame('/home/user/linuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_PATH));
706         $this->assertSame('/home../user ./.linuxfile.txt', clean_param('/home../user ./.linuxfile.txt', PARAM_PATH));
707         $this->assertSame('~/myfile.txt', clean_param('~/myfile.txt', PARAM_PATH));
708         $this->assertSame('~/myfile.txt', clean_param('~/../myfile.txt', PARAM_PATH));
709         $this->assertSame('/..b../.../myfile.txt', clean_param('/..b../.../myfile.txt', PARAM_PATH));
710         $this->assertSame('..b../.../myfile.txt', clean_param('..b../.../myfile.txt', PARAM_PATH));
711         $this->assertSame('/super/slashes/', clean_param('/super//slashes///', PARAM_PATH));
712     }
714     public function test_clean_param_username() {
715         global $CFG;
716         $currentstatus =  $CFG->extendedusernamechars;
718         // Run tests with extended character == false;.
719         $CFG->extendedusernamechars = false;
720         $this->assertSame('johndoe123', clean_param('johndoe123', PARAM_USERNAME) );
721         $this->assertSame('john.doe', clean_param('john.doe', PARAM_USERNAME));
722         $this->assertSame('john-doe', clean_param('john-doe', PARAM_USERNAME));
723         $this->assertSame('john-doe', clean_param('john- doe', PARAM_USERNAME));
724         $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
725         $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
726         $this->assertSame('johndoe', clean_param('john~doe', PARAM_USERNAME));
727         $this->assertSame('johndoe', clean_param('john´doe', PARAM_USERNAME));
728         $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john_');
729         $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john_');
730         $this->assertSame(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
731         $this->assertSame('johnd', clean_param('JOHNdóé ', PARAM_USERNAME));
732         $this->assertSame(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýá\9e?\9eý??\9adoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
734         // Test success condition, if extendedusernamechars == ENABLE;.
735         $CFG->extendedusernamechars = true;
736         $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
737         $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
738         $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john# $%&()+_^');
739         $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john# $%&()+_^');
740         $this->assertSame('john~doe', clean_param('john~doe', PARAM_USERNAME));
741         $this->assertSame('john´doe', clean_param('joHN´doe', PARAM_USERNAME));
742         $this->assertSame('johndoe', clean_param('johnDOE', PARAM_USERNAME));
743         $this->assertSame('johndóé', clean_param('johndóé ', PARAM_USERNAME));
745         $CFG->extendedusernamechars = $currentstatus;
746     }
748     public function test_clean_param_stringid() {
749         // Test string identifiers validation.
750         // Valid strings.
751         $this->assertSame('validstring', clean_param('validstring', PARAM_STRINGID));
752         $this->assertSame('mod/foobar:valid_capability', clean_param('mod/foobar:valid_capability', PARAM_STRINGID));
753         $this->assertSame('CZ', clean_param('CZ', PARAM_STRINGID));
754         $this->assertSame('application/vnd.ms-powerpoint', clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID));
755         $this->assertSame('grade2', clean_param('grade2', PARAM_STRINGID));
756         // Invalid strings.
757         $this->assertSame('', clean_param('trailing ', PARAM_STRINGID));
758         $this->assertSame('', clean_param('space bar', PARAM_STRINGID));
759         $this->assertSame('', clean_param('0numeric', PARAM_STRINGID));
760         $this->assertSame('', clean_param('*', PARAM_STRINGID));
761         $this->assertSame('', clean_param(' ', PARAM_STRINGID));
762     }
764     public function test_clean_param_timezone() {
765         // Test timezone validation.
766         $testvalues = array (
767             'America/Jamaica'                => 'America/Jamaica',
768             'America/Argentina/Cordoba'      => 'America/Argentina/Cordoba',
769             'America/Port-au-Prince'         => 'America/Port-au-Prince',
770             'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
771             'PST8PDT'                        => 'PST8PDT',
772             'Wrong.Value'                    => '',
773             'Wrong/.Value'                   => '',
774             'Wrong(Value)'                   => '',
775             '0'                              => '0',
776             '0.0'                            => '0.0',
777             '0.5'                            => '0.5',
778             '9.0'                            => '9.0',
779             '-9.0'                           => '-9.0',
780             '+9.0'                           => '+9.0',
781             '9.5'                            => '9.5',
782             '-9.5'                           => '-9.5',
783             '+9.5'                           => '+9.5',
784             '12.0'                           => '12.0',
785             '-12.0'                          => '-12.0',
786             '+12.0'                          => '+12.0',
787             '12.5'                           => '12.5',
788             '-12.5'                          => '-12.5',
789             '+12.5'                          => '+12.5',
790             '13.0'                           => '13.0',
791             '-13.0'                          => '-13.0',
792             '+13.0'                          => '+13.0',
793             '13.5'                           => '',
794             '+13.5'                          => '',
795             '-13.5'                          => '',
796             '0.2'                            => '');
798         foreach ($testvalues as $testvalue => $expectedvalue) {
799             $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
800             $this->assertEquals($expectedvalue, $actualvalue);
801         }
802     }
804     public function test_validate_param() {
805         try {
806             $param = validate_param('11a', PARAM_INT);
807             $this->fail('invalid_parameter_exception expected');
808         } catch (moodle_exception $ex) {
809             $this->assertInstanceOf('invalid_parameter_exception', $ex);
810         }
812         $param = validate_param('11', PARAM_INT);
813         $this->assertSame(11, $param);
815         try {
816             $param = validate_param(null, PARAM_INT, false);
817             $this->fail('invalid_parameter_exception expected');
818         } catch (moodle_exception $ex) {
819             $this->assertInstanceOf('invalid_parameter_exception', $ex);
820         }
822         $param = validate_param(null, PARAM_INT, true);
823         $this->assertSame(null, $param);
825         try {
826             $param = validate_param(array(), PARAM_INT);
827             $this->fail('invalid_parameter_exception expected');
828         } catch (moodle_exception $ex) {
829             $this->assertInstanceOf('invalid_parameter_exception', $ex);
830         }
831         try {
832             $param = validate_param(new stdClass, PARAM_INT);
833             $this->fail('invalid_parameter_exception expected');
834         } catch (moodle_exception $ex) {
835             $this->assertInstanceOf('invalid_parameter_exception', $ex);
836         }
838         $param = validate_param('1.0', PARAM_FLOAT);
839         $this->assertSame(1.0, $param);
841         // Make sure valid floats do not cause exception.
842         validate_param(1.0, PARAM_FLOAT);
843         validate_param(10, PARAM_FLOAT);
844         validate_param('0', PARAM_FLOAT);
845         validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
846         validate_param('011.1', PARAM_FLOAT);
847         validate_param('11', PARAM_FLOAT);
848         validate_param('+.1', PARAM_FLOAT);
849         validate_param('-.1', PARAM_FLOAT);
850         validate_param('1e10', PARAM_FLOAT);
851         validate_param('.1e+10', PARAM_FLOAT);
852         validate_param('1E-1', PARAM_FLOAT);
854         try {
855             $param = validate_param('1,2', PARAM_FLOAT);
856             $this->fail('invalid_parameter_exception expected');
857         } catch (moodle_exception $ex) {
858             $this->assertInstanceOf('invalid_parameter_exception', $ex);
859         }
860         try {
861             $param = validate_param('', PARAM_FLOAT);
862             $this->fail('invalid_parameter_exception expected');
863         } catch (moodle_exception $ex) {
864             $this->assertInstanceOf('invalid_parameter_exception', $ex);
865         }
866         try {
867             $param = validate_param('.', PARAM_FLOAT);
868             $this->fail('invalid_parameter_exception expected');
869         } catch (moodle_exception $ex) {
870             $this->assertInstanceOf('invalid_parameter_exception', $ex);
871         }
872         try {
873             $param = validate_param('e10', PARAM_FLOAT);
874             $this->fail('invalid_parameter_exception expected');
875         } catch (moodle_exception $ex) {
876             $this->assertInstanceOf('invalid_parameter_exception', $ex);
877         }
878         try {
879             $param = validate_param('abc', PARAM_FLOAT);
880             $this->fail('invalid_parameter_exception expected');
881         } catch (moodle_exception $ex) {
882             $this->assertInstanceOf('invalid_parameter_exception', $ex);
883         }
884     }
886     public function test_shorten_text_no_tags_already_short_enough() {
887         // ......12345678901234567890123456.
888         $text = "short text already no tags";
889         $this->assertSame($text, shorten_text($text));
890     }
892     public function test_shorten_text_with_tags_already_short_enough() {
893         // .........123456...7890....12345678.......901234567.
894         $text = "<p>short <b>text</b> already</p><p>with tags</p>";
895         $this->assertSame($text, shorten_text($text));
896     }
898     public function test_shorten_text_no_tags_needs_shortening() {
899         // Default truncation is after 30 chars, but allowing 3 for the final '...'.
900         // ......12345678901234567890123456789023456789012345678901234.
901         $text = "long text without any tags blah de blah blah blah what";
902         $this->assertSame('long text without any tags ...', shorten_text($text));
903     }
905     public function test_shorten_text_with_tags_needs_shortening() {
906         // .......................................123456789012345678901234567890...
907         $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
908             "be chopped off but <b>should be added back again</b></blockquote></p></div>";
909         $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
910             "tags that ...</blockquote></p></div>", shorten_text($text));
911     }
913     public function test_shorten_text_with_tags_and_html_comment() {
914         $text = "<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with ".
915             "tags that will<!--<![endif]--> ".
916             "be chopped off but <b>should be added back again</b></blockquote></p></div>";
917         $this->assertEquals("<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with " .
918             "tags that ...<!--<![endif]--></blockquote></p></div>", shorten_text($text));
919     }
921     public function test_shorten_text_with_entities() {
922         // Remember to allow 3 chars for the final '...'.
923         // ......123456789012345678901234567_____890...
924         $text = "some text which shouldn't &nbsp; break there";
925         $this->assertSame("some text which shouldn't &nbsp; ...", shorten_text($text, 31));
926         $this->assertSame("some text which shouldn't &nbsp;...", shorten_text($text, 30));
927         $this->assertSame("some text which shouldn't ...", shorten_text($text, 29));
928     }
930     public function test_shorten_text_known_tricky_case() {
931         // This case caused a bug up to 1.9.5
932         // ..........123456789012345678901234567890123456789.....0_____1___2___...
933         $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
934         $this->assertSame("<h3>standard 'break-out' sub groups in ...</h3>",
935             shorten_text($text, 41));
936         $this->assertSame("<h3>standard 'break-out' sub groups in TGs?...</h3>",
937             shorten_text($text, 42));
938         $this->assertSame("<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;...",
939             shorten_text($text, 43));
940     }
942     public function test_shorten_text_no_spaces() {
943         // ..........123456789.
944         $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
945         $this->assertSame("<h1>12345...</h1>", shorten_text($text, 8));
946     }
948     public function test_shorten_text_utf8_european() {
949         // Text without tags.
950         // ......123456789012345678901234567.
951         $text = "Žluťoučký koníček přeskočil";
952         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
953         $this->assertSame("Žluťoučký koníče...", shorten_text($text, 19, true));
954         $this->assertSame("Žluťoučký ...", shorten_text($text, 19, false));
955         // And try it with 2-less (that are, in bytes, the middle of a sequence).
956         $this->assertSame("Žluťoučký koní...", shorten_text($text, 17, true));
957         $this->assertSame("Žluťoučký ...", shorten_text($text, 17, false));
959         // .........123456789012345678...901234567....89012345.
960         $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
961         $this->assertSame($text, shorten_text($text, 60));
962         $this->assertSame("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
963         $this->assertSame("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
964         $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
965         // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
966         $this->assertSame("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
967         $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
968         // And try over one tag (start/end), it does proper text len.
969         $this->assertSame("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
970         $this->assertSame("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
971         // And in the middle of one tag.
972         $this->assertSame("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
973     }
975     public function test_shorten_text_utf8_oriental() {
976         // Japanese
977         // text without tags
978         // ......123456789012345678901234.
979         $text = '言語設定言語設定abcdefghijkl';
980         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
981         $this->assertSame("言語設定言語...", shorten_text($text, 9, true));
982         $this->assertSame("言語設定言語...", shorten_text($text, 9, false));
983         $this->assertSame("言語設定言語設定ab...", shorten_text($text, 13, true));
984         $this->assertSame("言語設定言語設定...", shorten_text($text, 13, false));
986         // Chinese
987         // text without tags
988         // ......123456789012345678901234.
989         $text = '简体中文简体中文abcdefghijkl';
990         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
991         $this->assertSame("简体中文简体...", shorten_text($text, 9, true));
992         $this->assertSame("简体中文简体...", shorten_text($text, 9, false));
993         $this->assertSame("简体中文简体中文ab...", shorten_text($text, 13, true));
994         $this->assertSame("简体中文简体中文...", shorten_text($text, 13, false));
995     }
997     public function test_shorten_text_multilang() {
998         // This is not necessaryily specific to multilang. The issue is really
999         // tags with attributes, where before we were generating invalid HTML
1000         // output like shorten_text('<span id="x" class="y">A</span> B', 1)
1001         // returning '<span id="x" ...</span>'. It is just that multilang
1002         // requires the sort of HTML that is quite likely to trigger this.
1003         // ........................................1...
1004         $text = '<span lang="en" class="multilang">A</span>' .
1005                 '<span lang="fr" class="multilang">B</span>';
1006         $this->assertSame('<span lang="en" class="multilang">...</span>',
1007                 shorten_text($text, 1));
1008     }
1010     /**
1011      * Provider for long filenames and its expected result, with and without hash.
1012      *
1013      * @return array of ($filename, $length, $expected, $includehash)
1014      */
1015     public function shorten_filename_provider() {
1016         $filename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium totam rem';
1017         $shortfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque';
1019         return [
1020             'More than 100 characters' => [
1021                 $filename,
1022                 null,
1023                 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot',
1024                 false,
1025             ],
1026             'More than 100 characters with hash' => [
1027                 $filename,
1028                 null,
1029                 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8',
1030                 true,
1031             ],
1032             'More than 100 characters with extension' => [
1033                 "{$filename}.zip",
1034                 null,
1035                 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot.zip',
1036                 false,
1037             ],
1038             'More than 100 characters with extension and hash' => [
1039                 "{$filename}.zip",
1040                 null,
1041                 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8.zip',
1042                 true,
1043             ],
1044             'Limit filename to 50 chars' => [
1045                 $filename,
1046                 50,
1047                 'sed ut perspiciatis unde omnis iste natus error si',
1048                 false,
1049             ],
1050             'Limit filename to 50 chars with hash' => [
1051                 $filename,
1052                 50,
1053                 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8',
1054                 true,
1055             ],
1056             'Limit filename to 50 chars with extension' => [
1057                 "{$filename}.zip",
1058                 50,
1059                 'sed ut perspiciatis unde omnis iste natus error si.zip',
1060                 false,
1061             ],
1062             'Limit filename to 50 chars with extension and hash' => [
1063                 "{$filename}.zip",
1064                 50,
1065                 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8.zip',
1066                 true,
1067             ],
1068             'Test filename that contains less than 100 characters' => [
1069                 $shortfilename,
1070                 null,
1071                 $shortfilename,
1072                 false,
1073             ],
1074             'Test filename that contains less than 100 characters and hash' => [
1075                 $shortfilename,
1076                 null,
1077                 $shortfilename,
1078                 true,
1079             ],
1080             'Test filename that contains less than 100 characters with extension' => [
1081                 "{$shortfilename}.zip",
1082                 null,
1083                 "{$shortfilename}.zip",
1084                 false,
1085             ],
1086             'Test filename that contains less than 100 characters with extension and hash' => [
1087                 "{$shortfilename}.zip",
1088                 null,
1089                 "{$shortfilename}.zip",
1090                 true,
1091             ],
1092         ];
1093     }
1095     /**
1096      * Test the {@link shorten_filename()} method.
1097      *
1098      * @dataProvider shorten_filename_provider
1099      *
1100      * @param string $filename
1101      * @param int $length
1102      * @param string $expected
1103      * @param boolean $includehash
1104      */
1105     public function test_shorten_filename($filename, $length, $expected, $includehash) {
1106         if (null === $length) {
1107             $length = MAX_FILENAME_SIZE;
1108         }
1110         $this->assertSame($expected, shorten_filename($filename, $length, $includehash));
1111     }
1113     public function test_usergetdate() {
1114         global $USER, $CFG, $DB;
1115         $this->resetAfterTest();
1117         $this->setAdminUser();
1119         $USER->timezone = 2;// Set the timezone to a known state.
1121         $ts = 1261540267; // The time this function was created.
1123         $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
1124         $arr = array_values($arr);
1126         list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1127         $this->assertSame(7, $seconds);
1128         $this->assertSame(51, $minutes);
1129         $this->assertSame(4, $hours);
1130         $this->assertSame(23, $mday);
1131         $this->assertSame(3, $wday);
1132         $this->assertSame(12, $mon);
1133         $this->assertSame(2009, $year);
1134         $this->assertSame(356, $yday);
1135         $this->assertSame('Wednesday', $weekday);
1136         $this->assertSame('December', $month);
1137         $arr = usergetdate($ts); // Gets the timezone from the $USER object.
1138         $arr = array_values($arr);
1140         list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1141         $this->assertSame(7, $seconds);
1142         $this->assertSame(51, $minutes);
1143         $this->assertSame(5, $hours);
1144         $this->assertSame(23, $mday);
1145         $this->assertSame(3, $wday);
1146         $this->assertSame(12, $mon);
1147         $this->assertSame(2009, $year);
1148         $this->assertSame(356, $yday);
1149         $this->assertSame('Wednesday', $weekday);
1150         $this->assertSame('December', $month);
1151     }
1153     public function test_mark_user_preferences_changed() {
1154         $this->resetAfterTest();
1155         $otheruser = $this->getDataGenerator()->create_user();
1156         $otheruserid = $otheruser->id;
1158         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1159         mark_user_preferences_changed($otheruserid);
1161         $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1162         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1163     }
1165     public function test_check_user_preferences_loaded() {
1166         global $DB;
1167         $this->resetAfterTest();
1169         $otheruser = $this->getDataGenerator()->create_user();
1170         $otheruserid = $otheruser->id;
1172         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1173         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1175         $user = new stdClass();
1176         $user->id = $otheruserid;
1178         // Load.
1179         check_user_preferences_loaded($user);
1180         $this->assertTrue(isset($user->preference));
1181         $this->assertTrue(is_array($user->preference));
1182         $this->assertArrayHasKey('_lastloaded', $user->preference);
1183         $this->assertCount(1, $user->preference);
1185         // Add preference via direct call.
1186         $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1188         // No cache reload yet.
1189         check_user_preferences_loaded($user);
1190         $this->assertCount(1, $user->preference);
1192         // Forced reloading of cache.
1193         unset($user->preference);
1194         check_user_preferences_loaded($user);
1195         $this->assertCount(2, $user->preference);
1196         $this->assertSame('yyy', $user->preference['xxx']);
1198         // Add preference via direct call.
1199         $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1201         // Test timeouts and modifications from different session.
1202         set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1203         $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1204         check_user_preferences_loaded($user);
1205         $this->assertCount(2, $user->preference);
1206         check_user_preferences_loaded($user, 10);
1207         $this->assertCount(3, $user->preference);
1208         $this->assertSame('bbb', $user->preference['aaa']);
1209         set_cache_flag('userpreferenceschanged', $user->id, null);
1210     }
1212     public function test_set_user_preference() {
1213         global $DB, $USER;
1214         $this->resetAfterTest();
1216         $this->setAdminUser();
1218         $otheruser = $this->getDataGenerator()->create_user();
1219         $otheruserid = $otheruser->id;
1221         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1222         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1224         $user = new stdClass();
1225         $user->id = $otheruserid;
1227         set_user_preference('aaa', 'bbb', $otheruserid);
1228         $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1229         $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
1231         set_user_preference('xxx', 'yyy', $user);
1232         $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1233         $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
1234         $this->assertTrue(is_array($user->preference));
1235         $this->assertSame('bbb', $user->preference['aaa']);
1236         $this->assertSame('yyy', $user->preference['xxx']);
1238         set_user_preference('xxx', null, $user);
1239         $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1240         $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
1242         set_user_preference('ooo', true, $user);
1243         $prefs = get_user_preferences(null, null, $otheruserid);
1244         $this->assertSame($user->preference['aaa'], $prefs['aaa']);
1245         $this->assertSame($user->preference['ooo'], $prefs['ooo']);
1246         $this->assertSame('1', $prefs['ooo']);
1248         set_user_preference('null', 0, $user);
1249         $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1251         $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1253         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1254         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1256         // Test $USER default.
1257         set_user_preference('_test_user_preferences_pref', 'ok');
1258         $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1259         unset_user_preference('_test_user_preferences_pref');
1260         $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1262         // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
1263         $longvalue = str_repeat('a', 1333);
1264         set_user_preference('_test_long_user_preference', $longvalue);
1265         $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1266         $this->assertEquals($longvalue,
1267             $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1269         // Test > 1333 char values, coding_exception expected.
1270         $longvalue = str_repeat('a', 1334);
1271         try {
1272             set_user_preference('_test_long_user_preference', $longvalue);
1273             $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1274         } catch (moodle_exception $ex) {
1275             $this->assertInstanceOf('coding_exception', $ex);
1276         }
1278         // Test invalid params.
1279         try {
1280             set_user_preference('_test_user_preferences_pref', array());
1281             $this->fail('Exception expected - array not valid preference value');
1282         } catch (moodle_exception $ex) {
1283             $this->assertInstanceOf('coding_exception', $ex);
1284         }
1285         try {
1286             set_user_preference('_test_user_preferences_pref', new stdClass);
1287             $this->fail('Exception expected - class not valid preference value');
1288         } catch (moodle_exception $ex) {
1289             $this->assertInstanceOf('coding_exception', $ex);
1290         }
1291         try {
1292             set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1293             $this->fail('Exception expected - user instance expected');
1294         } catch (moodle_exception $ex) {
1295             $this->assertInstanceOf('coding_exception', $ex);
1296         }
1297         try {
1298             set_user_preference('_test_user_preferences_pref', 1, 'abc');
1299             $this->fail('Exception expected - user instance expected');
1300         } catch (moodle_exception $ex) {
1301             $this->assertInstanceOf('coding_exception', $ex);
1302         }
1303         try {
1304             set_user_preference('', 1);
1305             $this->fail('Exception expected - invalid name accepted');
1306         } catch (moodle_exception $ex) {
1307             $this->assertInstanceOf('coding_exception', $ex);
1308         }
1309         try {
1310             set_user_preference('1', 1);
1311             $this->fail('Exception expected - invalid name accepted');
1312         } catch (moodle_exception $ex) {
1313             $this->assertInstanceOf('coding_exception', $ex);
1314         }
1315     }
1317     public function test_set_user_preference_for_current_user() {
1318         global $USER;
1319         $this->resetAfterTest();
1320         $this->setAdminUser();
1322         set_user_preference('test_pref', 2);
1323         set_user_preference('test_pref', 1, $USER->id);
1324         $this->assertEquals(1, get_user_preferences('test_pref'));
1325     }
1327     public function test_unset_user_preference_for_current_user() {
1328         global $USER;
1329         $this->resetAfterTest();
1330         $this->setAdminUser();
1332         set_user_preference('test_pref', 1);
1333         unset_user_preference('test_pref', $USER->id);
1334         $this->assertNull(get_user_preferences('test_pref'));
1335     }
1337     public function test_get_extra_user_fields() {
1338         global $CFG, $USER, $DB;
1339         $this->resetAfterTest();
1341         $this->setAdminUser();
1343         // It would be really nice if there were a way to 'mock' has_capability
1344         // checks (either to return true or false) but as there is not, this
1345         // test doesn't test the capability check. Presumably, anyone running
1346         // unit tests will have the capability.
1347         $context = context_system::instance();
1349         // No fields.
1350         $CFG->showuseridentity = '';
1351         $this->assertEquals(array(), get_extra_user_fields($context));
1353         // One field.
1354         $CFG->showuseridentity = 'frog';
1355         $this->assertEquals(array('frog'), get_extra_user_fields($context));
1357         // Two fields.
1358         $CFG->showuseridentity = 'frog,zombie';
1359         $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1361         // No fields, except.
1362         $CFG->showuseridentity = '';
1363         $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1365         // One field.
1366         $CFG->showuseridentity = 'frog';
1367         $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1369         // Two fields.
1370         $CFG->showuseridentity = 'frog,zombie';
1371         $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1372     }
1374     public function test_get_extra_user_fields_sql() {
1375         global $CFG, $USER, $DB;
1376         $this->resetAfterTest();
1378         $this->setAdminUser();
1380         $context = context_system::instance();
1382         // No fields.
1383         $CFG->showuseridentity = '';
1384         $this->assertSame('', get_extra_user_fields_sql($context));
1386         // One field.
1387         $CFG->showuseridentity = 'frog';
1388         $this->assertSame(', frog', get_extra_user_fields_sql($context));
1390         // Two fields with table prefix.
1391         $CFG->showuseridentity = 'frog,zombie';
1392         $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1394         // Two fields with field prefix.
1395         $CFG->showuseridentity = 'frog,zombie';
1396         $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
1397             get_extra_user_fields_sql($context, '', 'u_'));
1399         // One field excluded.
1400         $CFG->showuseridentity = 'frog';
1401         $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
1403         // Two fields, one excluded, table+field prefix.
1404         $CFG->showuseridentity = 'frog,zombie';
1405         $this->assertEquals(', u1.zombie AS u_zombie',
1406             get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1407     }
1409     /**
1410      * Test some critical TZ/DST.
1411      *
1412      * This method tests some special TZ/DST combinations that were fixed
1413      * by MDL-38999. The tests are done by comparing the results of the
1414      * output using Moodle TZ/DST support and PHP native one.
1415      *
1416      * Note: If you don't trust PHP TZ/DST support, can verify the
1417      * harcoded expectations below with:
1418      * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
1419      */
1420     public function test_some_moodle_special_dst() {
1421         $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
1423         // In Europe/Tallinn it was 2013/04/08 05:00:00.
1424         $expectation = '2013/04/08 05:00:00';
1425         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1426         $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1427         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1428         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1429         $this->assertSame($expectation, $phpres);
1430         $this->assertSame($expectation, $moodleres);
1432         // In St. Johns it was 2013/04/07 23:30:00.
1433         $expectation = '2013/04/07 23:30:00';
1434         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1435         $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1436         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1437         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1438         $this->assertSame($expectation, $phpres);
1439         $this->assertSame($expectation, $moodleres);
1441         $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1443         // In Europe/Tallinn it was 2013/11/08 04:00:00.
1444         $expectation = '2013/11/08 04:00:00';
1445         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1446         $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1447         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1448         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1449         $this->assertSame($expectation, $phpres);
1450         $this->assertSame($expectation, $moodleres);
1452         // In St. Johns it was 2013/11/07 22:30:00.
1453         $expectation = '2013/11/07 22:30:00';
1454         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1455         $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1456         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1457         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1458         $this->assertSame($expectation, $phpres);
1459         $this->assertSame($expectation, $moodleres);
1460     }
1462     public function test_userdate() {
1463         global $USER, $CFG, $DB;
1464         $this->resetAfterTest();
1466         $this->setAdminUser();
1468         $testvalues = array(
1469             array(
1470                 'time' => '1309514400',
1471                 'usertimezone' => 'America/Moncton',
1472                 'timezone' => '0.0', // No dst offset.
1473                 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1474             ),
1475             array(
1476                 'time' => '1309514400',
1477                 'usertimezone' => 'America/Moncton',
1478                 'timezone' => '99', // Dst offset and timezone offset.
1479                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1480             ),
1481             array(
1482                 'time' => '1309514400',
1483                 'usertimezone' => 'America/Moncton',
1484                 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
1485                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1486             ),
1487             array(
1488                 'time' => '1293876000 ',
1489                 'usertimezone' => 'America/Moncton',
1490                 'timezone' => '0.0', // No dst offset.
1491                 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1492             ),
1493             array(
1494                 'time' => '1293876000 ',
1495                 'usertimezone' => 'America/Moncton',
1496                 'timezone' => '99', // No dst offset in jan, so just timezone offset.
1497                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1498             ),
1499             array(
1500                 'time' => '1293876000 ',
1501                 'usertimezone' => 'America/Moncton',
1502                 'timezone' => 'America/Moncton', // No dst offset in jan.
1503                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1504             ),
1505             array(
1506                 'time' => '1293876000 ',
1507                 'usertimezone' => '2',
1508                 'timezone' => '99', // Take user timezone.
1509                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1510             ),
1511             array(
1512                 'time' => '1293876000 ',
1513                 'usertimezone' => '-2',
1514                 'timezone' => '99', // Take user timezone.
1515                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1516             ),
1517             array(
1518                 'time' => '1293876000 ',
1519                 'usertimezone' => '-10',
1520                 'timezone' => '2', // Take this timezone.
1521                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1522             ),
1523             array(
1524                 'time' => '1293876000 ',
1525                 'usertimezone' => '-10',
1526                 'timezone' => '-2', // Take this timezone.
1527                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1528             ),
1529             array(
1530                 'time' => '1293876000 ',
1531                 'usertimezone' => '-10',
1532                 'timezone' => 'random/time', // This should show server time.
1533                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1534             ),
1535             array(
1536                 'time' => '1293876000 ',
1537                 'usertimezone' => '20', // Fallback to server time zone.
1538                 'timezone' => '99',     // This should show user time.
1539                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1540             ),
1541         );
1543         // Set default timezone to Australia/Perth, else time calculated
1544         // will not match expected values.
1545         $this->setTimezone(99, 'Australia/Perth');
1547         foreach ($testvalues as $vals) {
1548             $USER->timezone = $vals['usertimezone'];
1549             $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1551             // On different systems case of AM PM changes so compare case insensitive.
1552             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1553             $actualoutput = core_text::strtolower($actualoutput);
1555             $this->assertSame($vals['expectedoutput'], $actualoutput,
1556                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput} \ndata: " . var_export($vals, true));
1557         }
1558     }
1560     /**
1561      * Make sure the DST changes happen at the right time in Moodle.
1562      */
1563     public function test_dst_changes() {
1564         // DST switching in Prague.
1565         // From 2AM to 3AM in 1989.
1566         $date = new DateTime('1989-03-26T01:59:00+01:00');
1567         $this->assertSame('Sunday, 26 March 1989, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1568         $date = new DateTime('1989-03-26T02:01:00+01:00');
1569         $this->assertSame('Sunday, 26 March 1989, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1570         // From 3AM to 2AM in 1989 - not the same as the west Europe.
1571         $date = new DateTime('1989-09-24T01:59:00+01:00');
1572         $this->assertSame('Sunday, 24 September 1989, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1573         $date = new DateTime('1989-09-24T02:01:00+01:00');
1574         $this->assertSame('Sunday, 24 September 1989, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1575         // From 2AM to 3AM in 2014.
1576         $date = new DateTime('2014-03-30T01:59:00+01:00');
1577         $this->assertSame('Sunday, 30 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1578         $date = new DateTime('2014-03-30T02:01:00+01:00');
1579         $this->assertSame('Sunday, 30 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1580         // From 3AM to 2AM in 2014.
1581         $date = new DateTime('2014-10-26T01:59:00+01:00');
1582         $this->assertSame('Sunday, 26 October 2014, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1583         $date = new DateTime('2014-10-26T02:01:00+01:00');
1584         $this->assertSame('Sunday, 26 October 2014, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1585         // From 2AM to 3AM in 2020.
1586         $date = new DateTime('2020-03-29T01:59:00+01:00');
1587         $this->assertSame('Sunday, 29 March 2020, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1588         $date = new DateTime('2020-03-29T02:01:00+01:00');
1589         $this->assertSame('Sunday, 29 March 2020, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1590         // From 3AM to 2AM in 2020.
1591         $date = new DateTime('2020-10-25T01:59:00+01:00');
1592         $this->assertSame('Sunday, 25 October 2020, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1593         $date = new DateTime('2020-10-25T02:01:00+01:00');
1594         $this->assertSame('Sunday, 25 October 2020, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1596         // DST switching in NZ.
1597         // From 3AM to 2AM in 2015.
1598         $date = new DateTime('2015-04-05T02:59:00+13:00');
1599         $this->assertSame('Sunday, 5 April 2015, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1600         $date = new DateTime('2015-04-05T03:01:00+13:00');
1601         $this->assertSame('Sunday, 5 April 2015, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1602         // From 2AM to 3AM in 2009.
1603         $date = new DateTime('2015-09-27T01:59:00+12:00');
1604         $this->assertSame('Sunday, 27 September 2015, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1605         $date = new DateTime('2015-09-27T02:01:00+12:00');
1606         $this->assertSame('Sunday, 27 September 2015, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1608         // DST switching in Perth.
1609         // From 3AM to 2AM in 2009.
1610         $date = new DateTime('2008-03-30T01:59:00+08:00');
1611         $this->assertSame('Sunday, 30 March 2008, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1612         $date = new DateTime('2008-03-30T02:01:00+08:00');
1613         $this->assertSame('Sunday, 30 March 2008, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1614         // From 2AM to 3AM in 2009.
1615         $date = new DateTime('2008-10-26T01:59:00+08:00');
1616         $this->assertSame('Sunday, 26 October 2008, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1617         $date = new DateTime('2008-10-26T02:01:00+08:00');
1618         $this->assertSame('Sunday, 26 October 2008, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1620         // DST switching in US.
1621         // From 2AM to 3AM in 2014.
1622         $date = new DateTime('2014-03-09T01:59:00-05:00');
1623         $this->assertSame('Sunday, 9 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1624         $date = new DateTime('2014-03-09T02:01:00-05:00');
1625         $this->assertSame('Sunday, 9 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1626         // From 3AM to 2AM in 2014.
1627         $date = new DateTime('2014-11-02T01:59:00-04:00');
1628         $this->assertSame('Sunday, 2 November 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1629         $date = new DateTime('2014-11-02T02:01:00-04:00');
1630         $this->assertSame('Sunday, 2 November 2014, 01:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1631     }
1633     public function test_make_timestamp() {
1634         global $USER, $CFG, $DB;
1635         $this->resetAfterTest();
1637         $this->setAdminUser();
1639         $testvalues = array(
1640             array(
1641                 'usertimezone' => 'America/Moncton',
1642                 'year' => '2011',
1643                 'month' => '7',
1644                 'day' => '1',
1645                 'hour' => '10',
1646                 'minutes' => '00',
1647                 'seconds' => '00',
1648                 'timezone' => '0.0',
1649                 'applydst' => false, // No dst offset.
1650                 'expectedoutput' => '1309514400' // 6pm at UTC+0.
1651             ),
1652             array(
1653                 'usertimezone' => 'America/Moncton',
1654                 'year' => '2011',
1655                 'month' => '7',
1656                 'day' => '1',
1657                 'hour' => '10',
1658                 'minutes' => '00',
1659                 'seconds' => '00',
1660                 'timezone' => '99',  // User default timezone.
1661                 'applydst' => false, // Don't apply dst.
1662                 'expectedoutput' => '1309528800'
1663             ),
1664             array(
1665                 'usertimezone' => 'America/Moncton',
1666                 'year' => '2011',
1667                 'month' => '7',
1668                 'day' => '1',
1669                 'hour' => '10',
1670                 'minutes' => '00',
1671                 'seconds' => '00',
1672                 'timezone' => '99', // User default timezone.
1673                 'applydst' => true, // Apply dst.
1674                 'expectedoutput' => '1309525200'
1675             ),
1676             array(
1677                 'usertimezone' => 'America/Moncton',
1678                 'year' => '2011',
1679                 'month' => '7',
1680                 'day' => '1',
1681                 'hour' => '10',
1682                 'minutes' => '00',
1683                 'seconds' => '00',
1684                 'timezone' => 'America/Moncton', // String timezone.
1685                 'applydst' => true, // Apply dst.
1686                 'expectedoutput' => '1309525200'
1687             ),
1688             array(
1689                 'usertimezone' => '2', // No dst applyed.
1690                 'year' => '2011',
1691                 'month' => '7',
1692                 'day' => '1',
1693                 'hour' => '10',
1694                 'minutes' => '00',
1695                 'seconds' => '00',
1696                 'timezone' => '99', // Take user timezone.
1697                 'applydst' => true, // Apply dst.
1698                 'expectedoutput' => '1309507200'
1699             ),
1700             array(
1701                 'usertimezone' => '-2', // No dst applyed.
1702                 'year' => '2011',
1703                 'month' => '7',
1704                 'day' => '1',
1705                 'hour' => '10',
1706                 'minutes' => '00',
1707                 'seconds' => '00',
1708                 'timezone' => '99', // Take usertimezone.
1709                 'applydst' => true, // Apply dst.
1710                 'expectedoutput' => '1309521600'
1711             ),
1712             array(
1713                 'usertimezone' => '-10', // No dst applyed.
1714                 'year' => '2011',
1715                 'month' => '7',
1716                 'day' => '1',
1717                 'hour' => '10',
1718                 'minutes' => '00',
1719                 'seconds' => '00',
1720                 'timezone' => '2',  // Take this timezone.
1721                 'applydst' => true, // Apply dst.
1722                 'expectedoutput' => '1309507200'
1723             ),
1724             array(
1725                 'usertimezone' => '-10', // No dst applyed.
1726                 'year' => '2011',
1727                 'month' => '7',
1728                 'day' => '1',
1729                 'hour' => '10',
1730                 'minutes' => '00',
1731                 'seconds' => '00',
1732                 'timezone' => '-2', // Take this timezone.
1733                 'applydst' => true, // Apply dst.
1734                 'expectedoutput' => '1309521600'
1735             ),
1736             array(
1737                 'usertimezone' => '-10', // No dst applyed.
1738                 'year' => '2011',
1739                 'month' => '7',
1740                 'day' => '1',
1741                 'hour' => '10',
1742                 'minutes' => '00',
1743                 'seconds' => '00',
1744                 'timezone' => 'random/time', // This should show server time.
1745                 'applydst' => true,          // Apply dst.
1746                 'expectedoutput' => '1309485600'
1747             ),
1748             array(
1749                 'usertimezone' => '-14', // Server time.
1750                 'year' => '2011',
1751                 'month' => '7',
1752                 'day' => '1',
1753                 'hour' => '10',
1754                 'minutes' => '00',
1755                 'seconds' => '00',
1756                 'timezone' => '99', // Get user time.
1757                 'applydst' => true, // Apply dst.
1758                 'expectedoutput' => '1309485600'
1759             )
1760         );
1762         // Set default timezone to Australia/Perth, else time calculated
1763         // will not match expected values.
1764         $this->setTimezone(99, 'Australia/Perth');
1766         // Test make_timestamp with all testvals and assert if anything wrong.
1767         foreach ($testvalues as $vals) {
1768             $USER->timezone = $vals['usertimezone'];
1769             $actualoutput = make_timestamp(
1770                 $vals['year'],
1771                 $vals['month'],
1772                 $vals['day'],
1773                 $vals['hour'],
1774                 $vals['minutes'],
1775                 $vals['seconds'],
1776                 $vals['timezone'],
1777                 $vals['applydst']
1778             );
1780             // On different systems case of AM PM changes so compare case insensitive.
1781             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1782             $actualoutput = core_text::strtolower($actualoutput);
1784             $this->assertSame($vals['expectedoutput'], $actualoutput,
1785                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1786                 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1787         }
1788     }
1790     /**
1791      * Test get_string and most importantly the implementation of the lang_string
1792      * object.
1793      */
1794     public function test_get_string() {
1795         global $COURSE;
1797         // Make sure we are using English.
1798         $originallang = $COURSE->lang;
1799         $COURSE->lang = 'en';
1801         $yes = get_string('yes');
1802         $yesexpected = 'Yes';
1803         $this->assertInternalType('string', $yes);
1804         $this->assertSame($yesexpected, $yes);
1806         $yes = get_string('yes', 'moodle');
1807         $this->assertInternalType('string', $yes);
1808         $this->assertSame($yesexpected, $yes);
1810         $yes = get_string('yes', 'core');
1811         $this->assertInternalType('string', $yes);
1812         $this->assertSame($yesexpected, $yes);
1814         $yes = get_string('yes', '');
1815         $this->assertInternalType('string', $yes);
1816         $this->assertSame($yesexpected, $yes);
1818         $yes = get_string('yes', null);
1819         $this->assertInternalType('string', $yes);
1820         $this->assertSame($yesexpected, $yes);
1822         $yes = get_string('yes', null, 1);
1823         $this->assertInternalType('string', $yes);
1824         $this->assertSame($yesexpected, $yes);
1826         $days = 1;
1827         $numdays = get_string('numdays', 'core', '1');
1828         $numdaysexpected = $days.' days';
1829         $this->assertInternalType('string', $numdays);
1830         $this->assertSame($numdaysexpected, $numdays);
1832         $yes = get_string('yes', null, null, true);
1833         $this->assertInstanceOf('lang_string', $yes);
1834         $this->assertSame($yesexpected, (string)$yes);
1836         // Test using a lang_string object as the $a argument for a normal
1837         // get_string call (returning string).
1838         $test = new lang_string('yes', null, null, true);
1839         $testexpected = get_string('numdays', 'core', get_string('yes'));
1840         $testresult = get_string('numdays', null, $test);
1841         $this->assertInternalType('string', $testresult);
1842         $this->assertSame($testexpected, $testresult);
1844         // Test using a lang_string object as the $a argument for an object
1845         // get_string call (returning lang_string).
1846         $test = new lang_string('yes', null, null, true);
1847         $testexpected = get_string('numdays', 'core', get_string('yes'));
1848         $testresult = get_string('numdays', null, $test, true);
1849         $this->assertInstanceOf('lang_string', $testresult);
1850         $this->assertSame($testexpected, "$testresult");
1852         // Make sure that object properties that can't be converted don't cause
1853         // errors.
1854         // Level one: This is as deep as current language processing goes.
1855         $test = new stdClass;
1856         $test->one = 'here';
1857         $string = get_string('yes', null, $test, true);
1858         $this->assertEquals($yesexpected, $string);
1860         // Make sure that object properties that can't be converted don't cause
1861         // errors.
1862         // Level two: Language processing doesn't currently reach this deep.
1863         // only immediate scalar properties are worked with.
1864         $test = new stdClass;
1865         $test->one = new stdClass;
1866         $test->one->two = 'here';
1867         $string = get_string('yes', null, $test, true);
1868         $this->assertEquals($yesexpected, $string);
1870         // Make sure that object properties that can't be converted don't cause
1871         // errors.
1872         // Level three: It should never ever go this deep, but we're making sure
1873         // it doesn't cause any probs anyway.
1874         $test = new stdClass;
1875         $test->one = new stdClass;
1876         $test->one->two = new stdClass;
1877         $test->one->two->three = 'here';
1878         $string = get_string('yes', null, $test, true);
1879         $this->assertEquals($yesexpected, $string);
1881         // Make sure that object properties that can't be converted don't cause
1882         // errors and check lang_string properties.
1883         // Level one: This is as deep as current language processing goes.
1884         $test = new stdClass;
1885         $test->one = new lang_string('yes');
1886         $string = get_string('yes', null, $test, true);
1887         $this->assertEquals($yesexpected, $string);
1889         // Make sure that object properties that can't be converted don't cause
1890         // errors and check lang_string properties.
1891         // Level two: Language processing doesn't currently reach this deep.
1892         // only immediate scalar properties are worked with.
1893         $test = new stdClass;
1894         $test->one = new stdClass;
1895         $test->one->two = new lang_string('yes');
1896         $string = get_string('yes', null, $test, true);
1897         $this->assertEquals($yesexpected, $string);
1899         // Make sure that object properties that can't be converted don't cause
1900         // errors and check lang_string properties.
1901         // Level three: It should never ever go this deep, but we're making sure
1902         // it doesn't cause any probs anyway.
1903         $test = new stdClass;
1904         $test->one = new stdClass;
1905         $test->one->two = new stdClass;
1906         $test->one->two->three = new lang_string('yes');
1907         $string = get_string('yes', null, $test, true);
1908         $this->assertEquals($yesexpected, $string);
1910         // Make sure that array properties that can't be converted don't cause
1911         // errors.
1912         $test = array();
1913         $test['one'] = new stdClass;
1914         $test['one']->two = 'here';
1915         $string = get_string('yes', null, $test, true);
1916         $this->assertEquals($yesexpected, $string);
1918         // Same thing but as above except using an object... this is allowed :P.
1919         $string = get_string('yes', null, null, true);
1920         $object = new stdClass;
1921         $object->$string = 'Yes';
1922         $this->assertEquals($yesexpected, $string);
1923         $this->assertEquals($yesexpected, $object->$string);
1925         // Reset the language.
1926         $COURSE->lang = $originallang;
1927     }
1929     /**
1930      * @expectedException PHPUnit\Framework\Error\Warning
1931      */
1932     public function test_get_string_limitation() {
1933         // This is one of the limitations to the lang_string class. It can't be
1934         // used as a key.
1935         $array = array(get_string('yes', null, null, true) => 'yes');
1936     }
1938     /**
1939      * Test localised float formatting.
1940      */
1941     public function test_format_float() {
1943         // Special case for null.
1944         $this->assertEquals('', format_float(null));
1946         // Default 1 decimal place.
1947         $this->assertEquals('5.4', format_float(5.43));
1948         $this->assertEquals('5.0', format_float(5.001));
1950         // Custom number of decimal places.
1951         $this->assertEquals('5.43000', format_float(5.43, 5));
1953         // Option to strip ending zeros after rounding.
1954         $this->assertEquals('5.43', format_float(5.43, 5, true, true));
1955         $this->assertEquals('5', format_float(5.0001, 3, true, true));
1957         // Tests with a localised decimal separator.
1958         $this->define_local_decimal_separator();
1960         // Localisation on (default).
1961         $this->assertEquals('5X43000', format_float(5.43, 5));
1962         $this->assertEquals('5X43', format_float(5.43, 5, true, true));
1964         // Localisation off.
1965         $this->assertEquals('5.43000', format_float(5.43, 5, false));
1966         $this->assertEquals('5.43', format_float(5.43, 5, false, true));
1967     }
1969     /**
1970      * Test localised float unformatting.
1971      */
1972     public function test_unformat_float() {
1974         // Tests without the localised decimal separator.
1976         // Special case for null, empty or white spaces only strings.
1977         $this->assertEquals(null, unformat_float(null));
1978         $this->assertEquals(null, unformat_float(''));
1979         $this->assertEquals(null, unformat_float('    '));
1981         // Regular use.
1982         $this->assertEquals(5.4, unformat_float('5.4'));
1983         $this->assertEquals(5.4, unformat_float('5.4', true));
1985         // No decimal.
1986         $this->assertEquals(5.0, unformat_float('5'));
1988         // Custom number of decimal.
1989         $this->assertEquals(5.43267, unformat_float('5.43267'));
1991         // Empty decimal.
1992         $this->assertEquals(100.0, unformat_float('100.00'));
1994         // With the thousand separator.
1995         $this->assertEquals(1000.0, unformat_float('1 000'));
1996         $this->assertEquals(1000.32, unformat_float('1 000.32'));
1998         // Negative number.
1999         $this->assertEquals(-100.0, unformat_float('-100'));
2001         // Wrong value.
2002         $this->assertEquals(0.0, unformat_float('Wrong value'));
2003         // Wrong value in strict mode.
2004         $this->assertFalse(unformat_float('Wrong value', true));
2006         // Combining options.
2007         $this->assertEquals(-1023.862567, unformat_float('   -1 023.862567     '));
2009         // Bad decimal separator (should crop the decimal).
2010         $this->assertEquals(50.0, unformat_float('50,57'));
2011         // Bad decimal separator in strict mode (should return false).
2012         $this->assertFalse(unformat_float('50,57', true));
2014         // Tests with a localised decimal separator.
2015         $this->define_local_decimal_separator();
2017         // We repeat the tests above but with the current decimal separator.
2019         // Regular use without and with the localised separator.
2020         $this->assertEquals (5.4, unformat_float('5.4'));
2021         $this->assertEquals (5.4, unformat_float('5X4'));
2023         // Custom number of decimal.
2024         $this->assertEquals (5.43267, unformat_float('5X43267'));
2026         // Empty decimal.
2027         $this->assertEquals (100.0, unformat_float('100X00'));
2029         // With the thousand separator.
2030         $this->assertEquals (1000.32, unformat_float('1 000X32'));
2032         // Bad different separator (should crop the decimal).
2033         $this->assertEquals (50.0, unformat_float('50Y57'));
2034         // Bad different separator in strict mode (should return false).
2035         $this->assertFalse (unformat_float('50Y57', true));
2037         // Combining options.
2038         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     '));
2039         // Combining options in strict mode.
2040         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     ', true));
2041     }
2043     /**
2044      * Test deleting of users.
2045      */
2046     public function test_delete_user() {
2047         global $DB, $CFG;
2049         $this->resetAfterTest();
2051         $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
2052         $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
2053         $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
2055         $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
2056         $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
2057         $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
2058         $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
2059         $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => ''));
2060         $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => ''));
2062         // Delete user and capture event.
2063         $sink = $this->redirectEvents();
2064         $result = delete_user($user);
2065         $events = $sink->get_events();
2066         $sink->close();
2067         $event = array_pop($events);
2069         // Test user is deleted in DB.
2070         $this->assertTrue($result);
2071         $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
2072         $this->assertEquals(1, $deluser->deleted);
2073         $this->assertEquals(0, $deluser->picture);
2074         $this->assertSame('', $deluser->idnumber);
2075         $this->assertSame(md5($user->username), $deluser->email);
2076         $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
2078         $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
2080         // Test Event.
2081         $this->assertInstanceOf('\core\event\user_deleted', $event);
2082         $this->assertSame($user->id, $event->objectid);
2083         $this->assertSame('user_deleted', $event->get_legacy_eventname());
2084         $this->assertEventLegacyData($user, $event);
2085         $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
2086         $this->assertEventLegacyLogData($expectedlogdata, $event);
2087         $eventdata = $event->get_data();
2088         $this->assertSame($eventdata['other']['username'], $user->username);
2089         $this->assertSame($eventdata['other']['email'], $user->email);
2090         $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
2091         $this->assertSame($eventdata['other']['picture'], $user->picture);
2092         $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
2093         $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
2094         $this->assertEventContextNotUsed($event);
2096         // Try invalid params.
2097         $record = new stdClass();
2098         $record->grrr = 1;
2099         try {
2100             delete_user($record);
2101             $this->fail('Expecting exception for invalid delete_user() $user parameter');
2102         } catch (moodle_exception $ex) {
2103             $this->assertInstanceOf('coding_exception', $ex);
2104         }
2105         $record->id = 1;
2106         try {
2107             delete_user($record);
2108             $this->fail('Expecting exception for invalid delete_user() $user parameter');
2109         } catch (moodle_exception $ex) {
2110             $this->assertInstanceOf('coding_exception', $ex);
2111         }
2113         $record = new stdClass();
2114         $record->id = 666;
2115         $record->username = 'xx';
2116         $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
2117         $result = delete_user($record);
2118         $this->assertFalse($result);
2120         $result = delete_user($guest);
2121         $this->assertFalse($result);
2123         $result = delete_user($admin);
2124         $this->assertFalse($result);
2126         // Simultaneously deleting users with identical email addresses.
2127         $result1 = delete_user($usersharedemail1);
2128         $result2 = delete_user($usersharedemail2);
2130         $usersharedemail1after = $DB->get_record('user', array('id' => $usersharedemail1->id));
2131         $usersharedemail2after = $DB->get_record('user', array('id' => $usersharedemail2->id));
2132         $this->assertTrue($result1);
2133         $this->assertTrue($result2);
2134         $this->assertStringStartsWith($usersharedemail1->email . '.', $usersharedemail1after->username);
2135         $this->assertStringStartsWith($usersharedemail2->email . '.', $usersharedemail2after->username);
2137         // Simultaneously deleting users without email addresses.
2138         $result1 = delete_user($useremptyemail1);
2139         $result2 = delete_user($useremptyemail2);
2141         $useremptyemail1after = $DB->get_record('user', array('id' => $useremptyemail1->id));
2142         $useremptyemail2after = $DB->get_record('user', array('id' => $useremptyemail2->id));
2143         $this->assertTrue($result1);
2144         $this->assertTrue($result2);
2145         $this->assertStringStartsWith($useremptyemail1->username . '.' . $useremptyemail1->id . '@unknownemail.invalid.',
2146             $useremptyemail1after->username);
2147         $this->assertStringStartsWith($useremptyemail2->username . '.' . $useremptyemail2->id . '@unknownemail.invalid.',
2148             $useremptyemail2after->username);
2150         $this->resetDebugging();
2151     }
2153     /**
2154      * Test function convert_to_array()
2155      */
2156     public function test_convert_to_array() {
2157         // Check that normal classes are converted to arrays the same way as (array) would do.
2158         $obj = new stdClass();
2159         $obj->prop1 = 'hello';
2160         $obj->prop2 = array('first', 'second', 13);
2161         $obj->prop3 = 15;
2162         $this->assertEquals(convert_to_array($obj), (array)$obj);
2164         // Check that context object (with iterator) is converted to array properly.
2165         $obj = context_system::instance();
2166         $ar = array(
2167             'id'           => $obj->id,
2168             'contextlevel' => $obj->contextlevel,
2169             'instanceid'   => $obj->instanceid,
2170             'path'         => $obj->path,
2171             'depth'        => $obj->depth
2172         );
2173         $this->assertEquals(convert_to_array($obj), $ar);
2174     }
2176     /**
2177      * Test the function date_format_string().
2178      */
2179     public function test_date_format_string() {
2180         global $CFG;
2182         $this->resetAfterTest();
2183         $this->setTimezone(99, 'Australia/Perth');
2185         $tests = array(
2186             array(
2187                 'tz' => 99,
2188                 'str' => '%A, %d %B %Y, %I:%M %p',
2189                 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
2190             ),
2191             array(
2192                 'tz' => 0,
2193                 'str' => '%A, %d %B %Y, %I:%M %p',
2194                 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2195             ),
2196             array(
2197                 // Note: this function expected the timestamp in weird format before,
2198                 // since 2.9 it uses UTC.
2199                 'tz' => 'Pacific/Auckland',
2200                 'str' => '%A, %d %B %Y, %I:%M %p',
2201                 'expected' => 'Saturday, 01 January 2011, 11:00 PM'
2202             ),
2203             // Following tests pass on Windows only because en lang pack does
2204             // not contain localewincharset, in real life lang pack maintainers
2205             // may use only characters that are present in localewincharset
2206             // in format strings!
2207             array(
2208                 'tz' => 99,
2209                 'str' => 'Žluťoučký koníček %A',
2210                 'expected' => 'Žluťoučký koníček Saturday'
2211             ),
2212             array(
2213                 'tz' => 99,
2214                 'str' => '言語設定言語 %A',
2215                 'expected' => '言語設定言語 Saturday'
2216             ),
2217             array(
2218                 'tz' => 99,
2219                 'str' => '简体中文简体 %A',
2220                 'expected' => '简体中文简体 Saturday'
2221             ),
2222         );
2224         // Note: date_format_string() uses the timezone only to differenciate
2225         // the server time from the UTC time. It does not modify the timestamp.
2226         // Hence similar results for timezones <= 13.
2227         // On different systems case of AM PM changes so compare case insensitive.
2228         foreach ($tests as $test) {
2229             $str = date_format_string(1293876000, $test['str'], $test['tz']);
2230             $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
2231         }
2232     }
2234     public function test_get_config() {
2235         global $CFG;
2237         $this->resetAfterTest();
2239         // Preparation.
2240         set_config('phpunit_test_get_config_1', 'test 1');
2241         set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2242         if (!is_array($CFG->config_php_settings)) {
2243             $CFG->config_php_settings = array();
2244         }
2245         $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
2247         if (!is_array($CFG->forced_plugin_settings)) {
2248             $CFG->forced_plugin_settings = array();
2249         }
2250         if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
2251             $CFG->forced_plugin_settings['mod_forum'] = array();
2252         }
2253         $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2254         $CFG->phpunit_test_get_config_5 = 'test 5';
2256         // Testing.
2257         $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
2258         $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2259         $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
2260         $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2261         $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2262         $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2263         $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2265         // Test config we know to exist.
2266         $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
2267         $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2268         $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2269         $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2271         // Test setting a config var that already exists.
2272         set_config('phpunit_test_get_config_1', 'test a');
2273         $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
2274         $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
2276         // Test cache invalidation.
2277         $cache = cache::make('core', 'config');
2278         $this->assertInternalType('array', $cache->get('core'));
2279         $this->assertInternalType('array', $cache->get('mod_forum'));
2280         set_config('phpunit_test_get_config_1', 'test b');
2281         $this->assertFalse($cache->get('core'));
2282         set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2283         $this->assertFalse($cache->get('mod_forum'));
2284     }
2286     public function test_get_max_upload_sizes() {
2287         // Test with very low limits so we are not affected by php upload limits.
2288         // Test activity limit smallest.
2289         $sitebytes = 102400;
2290         $coursebytes = 51200;
2291         $modulebytes = 10240;
2292         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2294         $this->assertSame('Activity upload limit (10KB)', $result['0']);
2295         $this->assertCount(2, $result);
2297         // Test course limit smallest.
2298         $sitebytes = 102400;
2299         $coursebytes = 10240;
2300         $modulebytes = 51200;
2301         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2303         $this->assertSame('Course upload limit (10KB)', $result['0']);
2304         $this->assertCount(2, $result);
2306         // Test site limit smallest.
2307         $sitebytes = 10240;
2308         $coursebytes = 102400;
2309         $modulebytes = 51200;
2310         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2312         $this->assertSame('Site upload limit (10KB)', $result['0']);
2313         $this->assertCount(2, $result);
2315         // Test site limit not set.
2316         $sitebytes = 0;
2317         $coursebytes = 102400;
2318         $modulebytes = 51200;
2319         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2321         $this->assertSame('Activity upload limit (50KB)', $result['0']);
2322         $this->assertCount(3, $result);
2324         $sitebytes = 0;
2325         $coursebytes = 51200;
2326         $modulebytes = 102400;
2327         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2329         $this->assertSame('Course upload limit (50KB)', $result['0']);
2330         $this->assertCount(3, $result);
2332         // Test custom bytes in range.
2333         $sitebytes = 102400;
2334         $coursebytes = 51200;
2335         $modulebytes = 51200;
2336         $custombytes = 10240;
2337         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2339         $this->assertCount(3, $result);
2341         // Test custom bytes in range but non-standard.
2342         $sitebytes = 102400;
2343         $coursebytes = 51200;
2344         $modulebytes = 51200;
2345         $custombytes = 25600;
2346         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2348         $this->assertCount(4, $result);
2350         // Test custom bytes out of range.
2351         $sitebytes = 102400;
2352         $coursebytes = 51200;
2353         $modulebytes = 51200;
2354         $custombytes = 102400;
2355         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2357         $this->assertCount(3, $result);
2359         // Test custom bytes out of range and non-standard.
2360         $sitebytes = 102400;
2361         $coursebytes = 51200;
2362         $modulebytes = 51200;
2363         $custombytes = 256000;
2364         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2366         $this->assertCount(3, $result);
2368         // Test site limit only.
2369         $sitebytes = 51200;
2370         $result = get_max_upload_sizes($sitebytes);
2372         $this->assertSame('Site upload limit (50KB)', $result['0']);
2373         $this->assertSame('50KB', $result['51200']);
2374         $this->assertSame('10KB', $result['10240']);
2375         $this->assertCount(3, $result);
2377         // Test no limit.
2378         $result = get_max_upload_sizes();
2379         $this->assertArrayHasKey('0', $result);
2380         $this->assertArrayHasKey(get_max_upload_file_size(), $result);
2381     }
2383     /**
2384      * Test function password_is_legacy_hash().
2385      */
2386     public function test_password_is_legacy_hash() {
2387         // Well formed md5s should be matched.
2388         foreach (array('some', 'strings', 'to_check!') as $string) {
2389             $md5 = md5($string);
2390             $this->assertTrue(password_is_legacy_hash($md5));
2391         }
2392         // Strings that are not md5s should not be matched.
2393         foreach (array('', AUTH_PASSWORD_NOT_CACHED, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
2394             $this->assertFalse(password_is_legacy_hash($notmd5));
2395         }
2396     }
2398     /**
2399      * Test function validate_internal_user_password().
2400      */
2401     public function test_validate_internal_user_password() {
2402         // Test bcrypt hashes.
2403         $validhashes = array(
2404             'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2405             'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2406             'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2407             'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
2408         );
2410         foreach ($validhashes as $password => $hash) {
2411             $user = new stdClass();
2412             $user->auth = 'manual';
2413             $user->password = $hash;
2414             // The correct password should be validated.
2415             $this->assertTrue(validate_internal_user_password($user, $password));
2416             // An incorrect password should not be validated.
2417             $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2418         }
2419     }
2421     /**
2422      * Test function hash_internal_user_password().
2423      */
2424     public function test_hash_internal_user_password() {
2425         $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2427         // Check that some passwords that we convert to hashes can
2428         // be validated.
2429         foreach ($passwords as $password) {
2430             $hash = hash_internal_user_password($password);
2431             $fasthash = hash_internal_user_password($password, true);
2432             $user = new stdClass();
2433             $user->auth = 'manual';
2434             $user->password = $hash;
2435             $this->assertTrue(validate_internal_user_password($user, $password));
2437             // They should not be in md5 format.
2438             $this->assertFalse(password_is_legacy_hash($hash));
2440             // Check that cost factor in hash is correctly set.
2441             $this->assertRegExp('/\$10\$/', $hash);
2442             $this->assertRegExp('/\$04\$/', $fasthash);
2443         }
2444     }
2446     /**
2447      * Test function update_internal_user_password().
2448      */
2449     public function test_update_internal_user_password() {
2450         global $DB;
2451         $this->resetAfterTest();
2452         $passwords = array('password', '1234', 'changeme', '****');
2453         foreach ($passwords as $password) {
2454             $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2455             update_internal_user_password($user, $password);
2456             // The user object should have been updated.
2457             $this->assertTrue(validate_internal_user_password($user, $password));
2458             // The database field for the user should also have been updated to the
2459             // same value.
2460             $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
2461         }
2463         $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2464         // Manually set the user's password to the md5 of the string 'password'.
2465         $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
2467         $sink = $this->redirectEvents();
2468         // Update the password.
2469         update_internal_user_password($user, 'password');
2470         $events = $sink->get_events();
2471         $sink->close();
2472         $event = array_pop($events);
2474         // Password should have been updated to a bcrypt hash.
2475         $this->assertFalse(password_is_legacy_hash($user->password));
2477         // Verify event information.
2478         $this->assertInstanceOf('\core\event\user_password_updated', $event);
2479         $this->assertSame($user->id, $event->relateduserid);
2480         $this->assertEquals(context_user::instance($user->id), $event->get_context());
2481         $this->assertEventContextNotUsed($event);
2483         // Verify recovery of property 'auth'.
2484         unset($user->auth);
2485         update_internal_user_password($user, 'newpassword');
2486         $this->assertDebuggingCalled('User record in update_internal_user_password() must include field auth',
2487                 DEBUG_DEVELOPER);
2488         $this->assertEquals('manual', $user->auth);
2489     }
2491     /**
2492      * Testing that if the password is not cached, that it does not update
2493      * the user table and fire event.
2494      */
2495     public function test_update_internal_user_password_no_cache() {
2496         $this->resetAfterTest();
2498         $user = $this->getDataGenerator()->create_user(array('auth' => 'cas'));
2499         $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2501         $sink = $this->redirectEvents();
2502         update_internal_user_password($user, 'wonkawonka');
2503         $this->assertEquals(0, $sink->count(), 'User updated event should not fire');
2504     }
2506     /**
2507      * Test if the user has a password hash, but now their auth method
2508      * says not to cache it.  Then it should update.
2509      */
2510     public function test_update_internal_user_password_update_no_cache() {
2511         $this->resetAfterTest();
2513         $user = $this->getDataGenerator()->create_user(array('password' => 'test'));
2514         $this->assertNotEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2515         $user->auth = 'cas'; // Change to a auth that does not store passwords.
2517         $sink = $this->redirectEvents();
2518         update_internal_user_password($user, 'wonkawonka');
2519         $this->assertGreaterThanOrEqual(1, $sink->count(), 'User updated event should fire');
2521         $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2522     }
2524     public function test_fullname() {
2525         global $CFG;
2527         $this->resetAfterTest();
2529         // Create a user to test the name display on.
2530         $record = array();
2531         $record['firstname'] = 'Scott';
2532         $record['lastname'] = 'Fletcher';
2533         $record['firstnamephonetic'] = 'スコット';
2534         $record['lastnamephonetic'] = 'フレチャー';
2535         $record['alternatename'] = 'No friends';
2536         $user = $this->getDataGenerator()->create_user($record);
2538         // Back up config settings for restore later.
2539         $originalcfg = new stdClass();
2540         $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
2541         $originalcfg->alternativefullnameformat = $CFG->alternativefullnameformat;
2543         // Testing existing fullnamedisplay settings.
2544         $CFG->fullnamedisplay = 'firstname';
2545         $testname = fullname($user);
2546         $this->assertSame($user->firstname, $testname);
2548         $CFG->fullnamedisplay = 'firstname lastname';
2549         $expectedname = "$user->firstname $user->lastname";
2550         $testname = fullname($user);
2551         $this->assertSame($expectedname, $testname);
2553         $CFG->fullnamedisplay = 'lastname firstname';
2554         $expectedname = "$user->lastname $user->firstname";
2555         $testname = fullname($user);
2556         $this->assertSame($expectedname, $testname);
2558         $expectedname = get_string('fullnamedisplay', null, $user);
2559         $CFG->fullnamedisplay = 'language';
2560         $testname = fullname($user);
2561         $this->assertSame($expectedname, $testname);
2563         // Test override parameter.
2564         $CFG->fullnamedisplay = 'firstname';
2565         $expectedname = "$user->firstname $user->lastname";
2566         $testname = fullname($user, true);
2567         $this->assertSame($expectedname, $testname);
2569         // Test alternativefullnameformat setting.
2570         // Test alternativefullnameformat that has been set to nothing.
2571         $CFG->alternativefullnameformat = '';
2572         $expectedname = "$user->firstname $user->lastname";
2573         $testname = fullname($user, true);
2574         $this->assertSame($expectedname, $testname);
2576         // Test alternativefullnameformat that has been set to 'language'.
2577         $CFG->alternativefullnameformat = 'language';
2578         $expectedname = "$user->firstname $user->lastname";
2579         $testname = fullname($user, true);
2580         $this->assertSame($expectedname, $testname);
2582         // Test customising the alternativefullnameformat setting with all additional name fields.
2583         $CFG->alternativefullnameformat = 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename';
2584         $expectedname = "$user->firstname $user->lastname $user->firstnamephonetic $user->lastnamephonetic $user->middlename $user->alternatename";
2585         $testname = fullname($user, true);
2586         $this->assertSame($expectedname, $testname);
2588         // Test additional name fields.
2589         $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
2590         $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
2591         $testname = fullname($user);
2592         $this->assertSame($expectedname, $testname);
2594         // Test for handling missing data.
2595         $user->middlename = null;
2596         // Parenthesis with no data.
2597         $CFG->fullnamedisplay = 'firstname (middlename) lastname';
2598         $expectedname = "$user->firstname $user->lastname";
2599         $testname = fullname($user);
2600         $this->assertSame($expectedname, $testname);
2602         // Extra spaces due to no data.
2603         $CFG->fullnamedisplay = 'firstname middlename lastname';
2604         $expectedname = "$user->firstname $user->lastname";
2605         $testname = fullname($user);
2606         $this->assertSame($expectedname, $testname);
2608         // Regular expression testing.
2609         // Remove some data from the user fields.
2610         $user->firstnamephonetic = '';
2611         $user->lastnamephonetic = '';
2613         // Removing empty brackets and excess whitespace.
2614         // All of these configurations should resolve to just firstname lastname.
2615         $configarray = array();
2616         $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
2617         $configarray[] = 'firstname lastname \'middlename\'';
2618         $configarray[] = 'firstname "firstnamephonetic" lastname';
2619         $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
2621         foreach ($configarray as $config) {
2622             $CFG->fullnamedisplay = $config;
2623             $expectedname = "$user->firstname $user->lastname";
2624             $testname = fullname($user);
2625             $this->assertSame($expectedname, $testname);
2626         }
2628         // Check to make sure that other characters are left in place.
2629         $configarray = array();
2630         $configarray['0'] = new stdClass();
2631         $configarray['0']->config = 'lastname firstname, middlename';
2632         $configarray['0']->expectedname = "$user->lastname $user->firstname,";
2633         $configarray['1'] = new stdClass();
2634         $configarray['1']->config = 'lastname firstname + alternatename';
2635         $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
2636         $configarray['2'] = new stdClass();
2637         $configarray['2']->config = 'firstname aka: alternatename';
2638         $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
2639         $configarray['3'] = new stdClass();
2640         $configarray['3']->config = 'firstname (alternatename)';
2641         $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
2642         $configarray['4'] = new stdClass();
2643         $configarray['4']->config = 'firstname [alternatename]';
2644         $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
2645         $configarray['5'] = new stdClass();
2646         $configarray['5']->config = 'firstname "lastname"';
2647         $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
2649         foreach ($configarray as $config) {
2650             $CFG->fullnamedisplay = $config->config;
2651             $expectedname = $config->expectedname;
2652             $testname = fullname($user);
2653             $this->assertSame($expectedname, $testname);
2654         }
2656         // Test debugging message displays when
2657         // fullnamedisplay setting is "normal".
2658         $CFG->fullnamedisplay = 'firstname lastname';
2659         unset($user);
2660         $user = new stdClass();
2661         $user->firstname = 'Stan';
2662         $user->lastname = 'Lee';
2663         $namedisplay = fullname($user);
2664         $this->assertDebuggingCalled();
2666         // Tidy up after we finish testing.
2667         $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
2668         $CFG->alternativefullnameformat = $originalcfg->alternativefullnameformat;
2669     }
2671     public function test_get_all_user_name_fields() {
2672         $this->resetAfterTest();
2674         // Additional names in an array.
2675         $testarray = array('firstnamephonetic' => 'firstnamephonetic',
2676                 'lastnamephonetic' => 'lastnamephonetic',
2677                 'middlename' => 'middlename',
2678                 'alternatename' => 'alternatename',
2679                 'firstname' => 'firstname',
2680                 'lastname' => 'lastname');
2681         $this->assertEquals($testarray, get_all_user_name_fields());
2683         // Additional names as a string.
2684         $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
2685         $this->assertEquals($teststring, get_all_user_name_fields(true));
2687         // Additional names as a string with an alias.
2688         $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
2689         $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
2691         // Additional name fields with a prefix - object.
2692         $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
2693                 'lastnamephonetic' => 'authorlastnamephonetic',
2694                 'middlename' => 'authormiddlename',
2695                 'alternatename' => 'authoralternatename',
2696                 'firstname' => 'authorfirstname',
2697                 'lastname' => 'authorlastname');
2698         $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
2700         // Additional name fields with an alias and a title - string.
2701         $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';
2702         $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
2704         // Test the order parameter of the function.
2705         // Returning an array.
2706         $testarray = array('firstname' => 'firstname',
2707                 'lastname' => 'lastname',
2708                 'firstnamephonetic' => 'firstnamephonetic',
2709                 'lastnamephonetic' => 'lastnamephonetic',
2710                 'middlename' => 'middlename',
2711                 'alternatename' => 'alternatename'
2712         );
2713         $this->assertEquals($testarray, get_all_user_name_fields(false, null, null, null, true));
2715         // Returning a string.
2716         $teststring = 'firstname,lastname,firstnamephonetic,lastnamephonetic,middlename,alternatename';
2717         $this->assertEquals($teststring, get_all_user_name_fields(true, null, null, null, true));
2718     }
2720     public function test_order_in_string() {
2721         $this->resetAfterTest();
2723         // Return an array in an order as they are encountered in a string.
2724         $valuearray = array('second', 'firsthalf', 'first');
2725         $formatstring = 'first firsthalf some other text (second)';
2726         $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
2727         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2729         // Try again with a different order for the format.
2730         $valuearray = array('second', 'firsthalf', 'first');
2731         $formatstring = 'firsthalf first second';
2732         $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
2733         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2735         // Try again with yet another different order for the format.
2736         $valuearray = array('second', 'firsthalf', 'first');
2737         $formatstring = 'start seconds away second firstquater first firsthalf';
2738         $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
2739         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2740     }
2742     public function test_complete_user_login() {
2743         global $USER, $DB;
2745         $this->resetAfterTest();
2746         $user = $this->getDataGenerator()->create_user();
2747         $this->setUser(0);
2749         $sink = $this->redirectEvents();
2750         $loginuser = clone($user);
2751         $this->setCurrentTimeStart();
2752         @complete_user_login($loginuser); // Hide session header errors.
2753         $this->assertSame($loginuser, $USER);
2754         $this->assertEquals($user->id, $USER->id);
2755         $events = $sink->get_events();
2756         $sink->close();
2758         $this->assertCount(1, $events);
2759         $event = reset($events);
2760         $this->assertInstanceOf('\core\event\user_loggedin', $event);
2761         $this->assertEquals('user', $event->objecttable);
2762         $this->assertEquals($user->id, $event->objectid);
2763         $this->assertEquals(context_system::instance()->id, $event->contextid);
2764         $this->assertEventContextNotUsed($event);
2766         $user = $DB->get_record('user', array('id'=>$user->id));
2768         $this->assertTimeCurrent($user->firstaccess);
2769         $this->assertTimeCurrent($user->lastaccess);
2771         $this->assertTimeCurrent($USER->firstaccess);
2772         $this->assertTimeCurrent($USER->lastaccess);
2773         $this->assertTimeCurrent($USER->currentlogin);
2774         $this->assertSame(sesskey(), $USER->sesskey);
2775         $this->assertTimeCurrent($USER->preference['_lastloaded']);
2776         $this->assertObjectNotHasAttribute('password', $USER);
2777         $this->assertObjectNotHasAttribute('description', $USER);
2778     }
2780     /**
2781      * Test require_logout.
2782      */
2783     public function test_require_logout() {
2784         $this->resetAfterTest();
2785         $user = $this->getDataGenerator()->create_user();
2786         $this->setUser($user);
2788         $this->assertTrue(isloggedin());
2790         // Logout user and capture event.
2791         $sink = $this->redirectEvents();
2792         require_logout();
2793         $events = $sink->get_events();
2794         $sink->close();
2795         $event = array_pop($events);
2797         // Check if user is logged out.
2798         $this->assertFalse(isloggedin());
2800         // Test Event.
2801         $this->assertInstanceOf('\core\event\user_loggedout', $event);
2802         $this->assertSame($user->id, $event->objectid);
2803         $this->assertSame('user_logout', $event->get_legacy_eventname());
2804         $this->assertEventLegacyData($user, $event);
2805         $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
2806             $event->objectid);
2807         $this->assertEventLegacyLogData($expectedlogdata, $event);
2808         $this->assertEventContextNotUsed($event);
2809     }
2811     /**
2812      * A data provider for testing email messageid
2813      */
2814     public function generate_email_messageid_provider() {
2815         return array(
2816             'nopath' => array(
2817                 'wwwroot' => 'http://www.example.com',
2818                 'ids' => array(
2819                     'a-custom-id' => '<a-custom-id@www.example.com>',
2820                     'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash@www.example.com>',
2821                 ),
2822             ),
2823             'path' => array(
2824                 'wwwroot' => 'http://www.example.com/path/subdir',
2825                 'ids' => array(
2826                     'a-custom-id' => '<a-custom-id/path/subdir@www.example.com>',
2827                     'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash/path/subdir@www.example.com>',
2828                 ),
2829             ),
2830         );
2831     }
2833     /**
2834      * Test email message id generation
2835      *
2836      * @dataProvider generate_email_messageid_provider
2837      *
2838      * @param string $wwwroot The wwwroot
2839      * @param array $msgids An array of msgid local parts and the final result
2840      */
2841     public function test_generate_email_messageid($wwwroot, $msgids) {
2842         global $CFG;
2844         $this->resetAfterTest();
2845         $CFG->wwwroot = $wwwroot;
2847         foreach ($msgids as $local => $final) {
2848             $this->assertEquals($final, generate_email_messageid($local));
2849         }
2850     }
2852     /**
2853      * A data provider for testing email diversion
2854      */
2855     public function diverted_emails_provider() {
2856         return array(
2857             'nodiverts' => array(
2858                 'divertallemailsto' => null,
2859                 'divertallemailsexcept' => null,
2860                 array(
2861                     'foo@example.com',
2862                     'test@real.com',
2863                     'fred.jones@example.com',
2864                     'dev1@dev.com',
2865                     'fred@example.com',
2866                     'fred+verp@example.com',
2867                 ),
2868                 false,
2869             ),
2870             'alldiverts' => array(
2871                 'divertallemailsto' => 'somewhere@elsewhere.com',
2872                 'divertallemailsexcept' => null,
2873                 array(
2874                     'foo@example.com',
2875                     'test@real.com',
2876                     'fred.jones@example.com',
2877                     'dev1@dev.com',
2878                     'fred@example.com',
2879                     'fred+verp@example.com',
2880                 ),
2881                 true,
2882             ),
2883             'alsodiverts' => array(
2884                 'divertallemailsto' => 'somewhere@elsewhere.com',
2885                 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
2886                 array(
2887                     'foo@example.com',
2888                     'test@real.com',
2889                     'fred.jones@example.com',
2890                 ),
2891                 true,
2892             ),
2893             'divertsexceptions' => array(
2894                 'divertallemailsto' => 'somewhere@elsewhere.com',
2895                 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
2896                 array(
2897                     'dev1@dev.com',
2898                     'fred@example.com',
2899                     'fred+verp@example.com',
2900                 ),
2901                 false,
2902             ),
2903         );
2904     }
2906     /**
2907      * Test email diversion
2908      *
2909      * @dataProvider diverted_emails_provider
2910      *
2911      * @param string $divertallemailsto An optional email address
2912      * @param string $divertallemailsexcept An optional exclusion list
2913      * @param array $addresses An array of test addresses
2914      * @param boolean $expected Expected result
2915      */
2916     public function test_email_should_be_diverted($divertallemailsto, $divertallemailsexcept, $addresses, $expected) {
2917         global $CFG;
2919         $this->resetAfterTest();
2920         $CFG->divertallemailsto = $divertallemailsto;
2921         $CFG->divertallemailsexcept = $divertallemailsexcept;
2923         foreach ($addresses as $address) {
2924             $this->assertEquals($expected, email_should_be_diverted($address));
2925         }
2926     }
2928     public function test_email_to_user() {
2929         global $CFG;
2931         $this->resetAfterTest();
2933         $user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
2934         $user2 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
2935         $user3 = $this->getDataGenerator()->create_user(array('maildisplay' => 0));
2936         set_config('allowedemaildomains', "example.com\r\nmoodle.org");
2938         $subject = 'subject';
2939         $messagetext = 'message text';
2940         $subject2 = 'subject 2';
2941         $messagetext2 = 'message text 2';
2943         // Close the default email sink.
2944         $sink = $this->redirectEmails();
2945         $sink->close();
2947         $CFG->noemailever = true;
2948         $this->assertNotEmpty($CFG->noemailever);
2949         email_to_user($user1, $user2, $subject, $messagetext);
2950         $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
2952         unset_config('noemailever');
2954         email_to_user($user1, $user2, $subject, $messagetext);
2955         $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2957         $sink = $this->redirectEmails();
2958         email_to_user($user1, $user2, $subject, $messagetext);
2959         email_to_user($user2, $user1, $subject2, $messagetext2);
2960         $this->assertSame(2, $sink->count());
2961         $result = $sink->get_messages();
2962         $this->assertCount(2, $result);
2963         $sink->close();
2965         $this->assertSame($subject, $result[0]->subject);
2966         $this->assertSame($messagetext, trim($result[0]->body));
2967         $this->assertSame($user1->email, $result[0]->to);
2968         $this->assertSame($user2->email, $result[0]->from);
2970         $this->assertSame($subject2, $result[1]->subject);
2971         $this->assertSame($messagetext2, trim($result[1]->body));
2972         $this->assertSame($user2->email, $result[1]->to);
2973         $this->assertSame($user1->email, $result[1]->from);
2975         email_to_user($user1, $user2, $subject, $messagetext);
2976         $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2978         // Test that an empty noreplyaddress will default to a no-reply address.
2979         $sink = $this->redirectEmails();
2980         email_to_user($user1, $user3, $subject, $messagetext);
2981         $result = $sink->get_messages();
2982         $this->assertEquals($CFG->noreplyaddress, $result[0]->from);
2983         $sink->close();
2984         set_config('noreplyaddress', '');
2985         $sink = $this->redirectEmails();
2986         email_to_user($user1, $user3, $subject, $messagetext);
2987         $result = $sink->get_messages();
2988         $this->assertEquals('noreply@www.example.com', $result[0]->from);
2989         $sink->close();
2991         // Test $CFG->allowedemaildomains.
2992         set_config('noreplyaddress', 'noreply@www.example.com');
2993         $this->assertNotEmpty($CFG->allowedemaildomains);
2994         $sink = $this->redirectEmails();
2995         email_to_user($user1, $user2, $subject, $messagetext);
2996         unset_config('allowedemaildomains');
2997         email_to_user($user1, $user2, $subject, $messagetext);
2998         $result = $sink->get_messages();
2999         $this->assertNotEquals($CFG->noreplyaddress, $result[0]->from);
3000         $this->assertEquals($CFG->noreplyaddress, $result[1]->from);
3001         $sink->close();
3003         // Try to send an unsafe attachment, we should see an error message in the eventual mail body.
3004         $attachment = '../test.txt';
3005         $attachname = 'txt';
3007         $sink = $this->redirectEmails();
3008         email_to_user($user1, $user2, $subject, $messagetext, '', $attachment, $attachname);
3009         $this->assertSame(1, $sink->count());
3010         $result = $sink->get_messages();
3011         $this->assertCount(1, $result);
3012         $this->assertContains('error.txt', $result[0]->body);
3013         $this->assertContains('Error in attachment.  User attempted to attach a filename with a unsafe name.', $result[0]->body);
3014         $sink->close();
3015     }
3017     /**
3018      * Test setnew_password_and_mail.
3019      */
3020     public function test_setnew_password_and_mail() {
3021         global $DB, $CFG;
3023         $this->resetAfterTest();
3025         $user = $this->getDataGenerator()->create_user();
3027         // Update user password.
3028         $sink = $this->redirectEvents();
3029         $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
3030         setnew_password_and_mail($user);
3031         $events = $sink->get_events();
3032         $sink->close();
3033         $sink2->close();
3034         $event = array_pop($events);
3036         // Test updated value.
3037         $dbuser = $DB->get_record('user', array('id' => $user->id));
3038         $this->assertSame($user->firstname, $dbuser->firstname);
3039         $this->assertNotEmpty($dbuser->password);
3041         // Test event.
3042         $this->assertInstanceOf('\core\event\user_password_updated', $event);
3043         $this->assertSame($user->id, $event->relateduserid);
3044         $this->assertEquals(context_user::instance($user->id), $event->get_context());
3045         $this->assertEventContextNotUsed($event);
3046     }
3048     /**
3049      * Data provider for test_generate_confirmation_link
3050      * @return Array of confirmation urls and expected resultant confirmation links
3051      */
3052     public function generate_confirmation_link_provider() {
3053         global $CFG;
3054         return [
3055             "Simple name" => [
3056                 "username" => "simplename",
3057                 "confirmationurl" => null,
3058                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/simplename"
3059             ],
3060             "Period in between words in username" => [
3061                 "username" => "period.inbetween",
3062                 "confirmationurl" => null,
3063                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/period%2Einbetween"
3064             ],
3065             "Trailing periods in username" => [
3066                 "username" => "trailingperiods...",
3067                 "confirmationurl" => null,
3068                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/trailingperiods%2E%2E%2E"
3069             ],
3070             "At symbol in username" => [
3071                 "username" => "at@symbol",
3072                 "confirmationurl" => null,
3073                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/at%40symbol"
3074             ],
3075             "Dash symbol in username" => [
3076                 "username" => "has-dash",
3077                 "confirmationurl" => null,
3078                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/has-dash"
3079             ],
3080             "Underscore in username" => [
3081                 "username" => "under_score",
3082                 "confirmationurl" => null,
3083                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/under_score"
3084             ],
3085             "Many different characters in username" => [
3086                 "username" => "many_-.@characters@_@-..-..",
3087                 "confirmationurl" => null,
3088                 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3089             ],
3090             "Custom relative confirmation url" => [
3091                 "username" => "many_-.@characters@_@-..-..",
3092                 "confirmationurl" => "/custom/local/url.php",
3093                 "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3094             ],
3095             "Custom relative confirmation url with parameters" => [
3096                 "username" => "many_-.@characters@_@-..-..",
3097                 "confirmationurl" => "/custom/local/url.php?with=param",
3098                 "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3099             ],
3100             "Custom local confirmation url" => [
3101                 "username" => "many_-.@characters@_@-..-..",
3102                 "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php",
3103                 "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3104             ],
3105             "Custom local confirmation url with parameters" => [
3106                 "username" => "many_-.@characters@_@-..-..",
3107                 "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php?with=param",
3108                 "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3109             ],
3110             "Custom external confirmation url" => [
3111                 "username" => "many_-.@characters@_@-..-..",
3112                 "confirmationurl" => "http://moodle.org/custom/external/url.php",
3113                 "expected" => "http://moodle.org/custom/external/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3114             ],
3115             "Custom external confirmation url with parameters" => [
3116                 "username" => "many_-.@characters@_@-..-..",
3117                 "confirmationurl" => "http://moodle.org/ext.php?with=some&param=eters",
3118                 "expected" => "http://moodle.org/ext.php?with=some&param=eters&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3119             ],
3120             "Custom external confirmation url with parameters" => [
3121                 "username" => "many_-.@characters@_@-..-..",
3122                 "confirmationurl" => "http://moodle.org/ext.php?with=some&data=test",
3123                 "expected" => "http://moodle.org/ext.php?with=some&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3124             ],
3125         ];
3126     }
3128     /**
3129      * Test generate_confirmation_link
3130      * @dataProvider generate_confirmation_link_provider
3131      * @param string $username The name of the user
3132      * @param string $confirmationurl The url the user should go to to confirm
3133      * @param string $expected The expected url of the confirmation link
3134      */
3135     public function test_generate_confirmation_link($username, $confirmationurl, $expected) {
3136         $this->resetAfterTest();
3137         $sink = $this->redirectEmails();
3139         $user = $this->getDataGenerator()->create_user(
3140             [
3141                 "username" => $username,
3142                 "confirmed" => false,
3143                 "email" => 'test@example.com',
3144             ]
3145         );
3147         send_confirmation_email($user, $confirmationurl);
3148         $sink->close();
3149         $messages = $sink->get_messages();
3150         $message = array_shift($messages);
3151         $messagebody = quoted_printable_decode($message->body);
3153         $this->assertContains($expected, $messagebody);
3154     }
3156     /**
3157      * Test generate_confirmation_link with custom admin link
3158      */
3159     public function test_generate_confirmation_link_with_custom_admin() {
3160         global $CFG;
3162         $this->resetAfterTest();
3163         $sink = $this->redirectEmails();
3165         $admin = $CFG->admin;
3166         $CFG->admin = 'custom/admin/path';
3168         $user = $this->getDataGenerator()->create_user(
3169             [
3170                 "username" => "many_-.@characters@_@-..-..",
3171                 "confirmed" => false,
3172                 "email" => 'test@example.com',
3173             ]
3174         );
3175         $confirmationurl = "/admin/test.php?with=params";
3176         $expected = $CFG->wwwroot . "/" . $CFG->admin . "/test.php?with=params&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E";
3178         send_confirmation_email($user, $confirmationurl);
3179         $sink->close();
3180         $messages = $sink->get_messages();
3181         $message = array_shift($messages);
3182         $messagebody = quoted_printable_decode($message->body);
3184         $sink->close();
3185         $this->assertContains($expected, $messagebody);
3187         $CFG->admin = $admin;
3188     }
3191     /**
3192      * Test remove_course_content deletes course contents
3193      * TODO Add asserts to verify other data related to course is deleted as well.
3194      */
3195     public function test_remove_course_contents() {
3197         $this->resetAfterTest();
3199         $course = $this->getDataGenerator()->create_course();
3200         $user = $this->getDataGenerator()->create_user();
3201         $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
3202         $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id));
3204         $this->assertNotEquals(false, note_load($note->id));
3205         remove_course_contents($course->id, false);
3206         $this->assertFalse(note_load($note->id));
3207     }
3209     /**
3210      * Test function username_load_fields_from_object().
3211      */
3212     public function test_username_load_fields_from_object() {
3213         $this->resetAfterTest();
3215         // This object represents the information returned from an sql query.
3216         $userinfo = new stdClass();
3217         $userinfo->userid = 1;
3218         $userinfo->username = 'loosebruce';
3219         $userinfo->firstname = 'Bruce';
3220         $userinfo->lastname = 'Campbell';
3221         $userinfo->firstnamephonetic = 'ブルース';
3222         $userinfo->lastnamephonetic = 'カンベッル';
3223         $userinfo->middlename = '';
3224         $userinfo->alternatename = '';
3225         $userinfo->email = '';
3226         $userinfo->picture = 23;
3227         $userinfo->imagealt = 'Michael Jordan draining another basket.';
3228         $userinfo->idnumber = 3982;
3230         // Just user name fields.
3231         $user = new stdClass();
3232         $user = username_load_fields_from_object($user, $userinfo);