163d795de10e7025449082251f5a106179663c9c
[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     /**
1114      * Provider for long filenames and its expected result, with and without hash.
1115      *
1116      * @return array of ($filename, $length, $expected, $includehash)
1117      */
1118     public function shorten_filenames_provider() {
1119         $shortfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque';
1120         $longfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium totam rem';
1121         $extfilename = $longfilename.'.zip';
1122         $expected = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot';
1123         $expectedwithhash = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8';
1124         $expectedext = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot.zip';
1125         $expectedextwithhash = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8.zip';
1126         $expected50 = 'sed ut perspiciatis unde omnis iste natus error si';
1127         $expected50withhash = 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8';
1128         $expected50ext = 'sed ut perspiciatis unde omnis iste natus error si.zip';
1129         $expected50extwithhash = 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8.zip';
1130         $expected50short = 'sed ut perspiciatis unde omnis iste n - 5fb6543490';
1132         return [
1133             'Empty array without hash' => [
1134                 [],
1135                 null,
1136                 [],
1137                 false,
1138             ],
1139             'Empty array with hash' => [
1140                 [],
1141                 null,
1142                 [],
1143                 true,
1144             ],
1145             'Array with less than 100 characters' => [
1146                 [$shortfilename, $shortfilename, $shortfilename],
1147                 null,
1148                 [$shortfilename, $shortfilename, $shortfilename],
1149                 false,
1150             ],
1151             'Array with more than 100 characters without hash' => [
1152                 [$longfilename, $longfilename, $longfilename],
1153                 null,
1154                 [$expected, $expected, $expected],
1155                 false,
1156             ],
1157             'Array with more than 100 characters with hash' => [
1158                 [$longfilename, $longfilename, $longfilename],
1159                 null,
1160                 [$expectedwithhash, $expectedwithhash, $expectedwithhash],
1161                 true,
1162             ],
1163             'Array with more than 100 characters with extension' => [
1164                 [$extfilename, $extfilename, $extfilename],
1165                 null,
1166                 [$expectedext, $expectedext, $expectedext],
1167                 false,
1168             ],
1169             'Array with more than 100 characters with extension and hash' => [
1170                 [$extfilename, $extfilename, $extfilename],
1171                 null,
1172                 [$expectedextwithhash, $expectedextwithhash, $expectedextwithhash],
1173                 true,
1174             ],
1175             'Array with more than 100 characters mix (short, long, with extension) without hash' => [
1176                 [$shortfilename, $longfilename, $extfilename],
1177                 null,
1178                 [$shortfilename, $expected, $expectedext],
1179                 false,
1180             ],
1181             'Array with more than 100 characters mix (short, long, with extension) with hash' => [
1182                 [$shortfilename, $longfilename, $extfilename],
1183                 null,
1184                 [$shortfilename, $expectedwithhash, $expectedextwithhash],
1185                 true,
1186             ],
1187             'Array with less than 50 characters without hash' => [
1188                 [$longfilename, $longfilename, $longfilename],
1189                 50,
1190                 [$expected50, $expected50, $expected50],
1191                 false,
1192             ],
1193             'Array with less than 50 characters with hash' => [
1194                 [$longfilename, $longfilename, $longfilename],
1195                 50,
1196                 [$expected50withhash, $expected50withhash, $expected50withhash],
1197                 true,
1198             ],
1199             'Array with less than 50 characters with extension' => [
1200                 [$extfilename, $extfilename, $extfilename],
1201                 50,
1202                 [$expected50ext, $expected50ext, $expected50ext],
1203                 false,
1204             ],
1205             'Array with less than 50 characters with extension and hash' => [
1206                 [$extfilename, $extfilename, $extfilename],
1207                 50,
1208                 [$expected50extwithhash, $expected50extwithhash, $expected50extwithhash],
1209                 true,
1210             ],
1211             'Array with less than 50 characters mix (short, long, with extension) without hash' => [
1212                 [$shortfilename, $longfilename, $extfilename],
1213                 50,
1214                 [$expected50, $expected50, $expected50ext],
1215                 false,
1216             ],
1217             'Array with less than 50 characters mix (short, long, with extension) with hash' => [
1218                 [$shortfilename, $longfilename, $extfilename],
1219                 50,
1220                 [$expected50short, $expected50withhash, $expected50extwithhash],
1221                 true,
1222             ],
1223         ];
1224     }
1226     /**
1227      * Test the {@link shorten_filenames()} method.
1228      *
1229      * @dataProvider shorten_filenames_provider
1230      *
1231      * @param string $filenames
1232      * @param int $length
1233      * @param string $expected
1234      * @param boolean $includehash
1235      */
1236     public function test_shorten_filenames($filenames, $length, $expected, $includehash) {
1237         if (null === $length) {
1238             $length = MAX_FILENAME_SIZE;
1239         }
1241         $this->assertSame($expected, shorten_filenames($filenames, $length, $includehash));
1242     }
1244     public function test_usergetdate() {
1245         global $USER, $CFG, $DB;
1246         $this->resetAfterTest();
1248         $this->setAdminUser();
1250         $USER->timezone = 2;// Set the timezone to a known state.
1252         $ts = 1261540267; // The time this function was created.
1254         $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
1255         $arr = array_values($arr);
1257         list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1258         $this->assertSame(7, $seconds);
1259         $this->assertSame(51, $minutes);
1260         $this->assertSame(4, $hours);
1261         $this->assertSame(23, $mday);
1262         $this->assertSame(3, $wday);
1263         $this->assertSame(12, $mon);
1264         $this->assertSame(2009, $year);
1265         $this->assertSame(356, $yday);
1266         $this->assertSame('Wednesday', $weekday);
1267         $this->assertSame('December', $month);
1268         $arr = usergetdate($ts); // Gets the timezone from the $USER object.
1269         $arr = array_values($arr);
1271         list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1272         $this->assertSame(7, $seconds);
1273         $this->assertSame(51, $minutes);
1274         $this->assertSame(5, $hours);
1275         $this->assertSame(23, $mday);
1276         $this->assertSame(3, $wday);
1277         $this->assertSame(12, $mon);
1278         $this->assertSame(2009, $year);
1279         $this->assertSame(356, $yday);
1280         $this->assertSame('Wednesday', $weekday);
1281         $this->assertSame('December', $month);
1282     }
1284     public function test_mark_user_preferences_changed() {
1285         $this->resetAfterTest();
1286         $otheruser = $this->getDataGenerator()->create_user();
1287         $otheruserid = $otheruser->id;
1289         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1290         mark_user_preferences_changed($otheruserid);
1292         $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1293         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1294     }
1296     public function test_check_user_preferences_loaded() {
1297         global $DB;
1298         $this->resetAfterTest();
1300         $otheruser = $this->getDataGenerator()->create_user();
1301         $otheruserid = $otheruser->id;
1303         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1304         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1306         $user = new stdClass();
1307         $user->id = $otheruserid;
1309         // Load.
1310         check_user_preferences_loaded($user);
1311         $this->assertTrue(isset($user->preference));
1312         $this->assertTrue(is_array($user->preference));
1313         $this->assertArrayHasKey('_lastloaded', $user->preference);
1314         $this->assertCount(1, $user->preference);
1316         // Add preference via direct call.
1317         $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1319         // No cache reload yet.
1320         check_user_preferences_loaded($user);
1321         $this->assertCount(1, $user->preference);
1323         // Forced reloading of cache.
1324         unset($user->preference);
1325         check_user_preferences_loaded($user);
1326         $this->assertCount(2, $user->preference);
1327         $this->assertSame('yyy', $user->preference['xxx']);
1329         // Add preference via direct call.
1330         $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1332         // Test timeouts and modifications from different session.
1333         set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1334         $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1335         check_user_preferences_loaded($user);
1336         $this->assertCount(2, $user->preference);
1337         check_user_preferences_loaded($user, 10);
1338         $this->assertCount(3, $user->preference);
1339         $this->assertSame('bbb', $user->preference['aaa']);
1340         set_cache_flag('userpreferenceschanged', $user->id, null);
1341     }
1343     public function test_set_user_preference() {
1344         global $DB, $USER;
1345         $this->resetAfterTest();
1347         $this->setAdminUser();
1349         $otheruser = $this->getDataGenerator()->create_user();
1350         $otheruserid = $otheruser->id;
1352         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1353         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1355         $user = new stdClass();
1356         $user->id = $otheruserid;
1358         set_user_preference('aaa', 'bbb', $otheruserid);
1359         $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1360         $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
1362         set_user_preference('xxx', 'yyy', $user);
1363         $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1364         $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
1365         $this->assertTrue(is_array($user->preference));
1366         $this->assertSame('bbb', $user->preference['aaa']);
1367         $this->assertSame('yyy', $user->preference['xxx']);
1369         set_user_preference('xxx', null, $user);
1370         $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1371         $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
1373         set_user_preference('ooo', true, $user);
1374         $prefs = get_user_preferences(null, null, $otheruserid);
1375         $this->assertSame($user->preference['aaa'], $prefs['aaa']);
1376         $this->assertSame($user->preference['ooo'], $prefs['ooo']);
1377         $this->assertSame('1', $prefs['ooo']);
1379         set_user_preference('null', 0, $user);
1380         $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1382         $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1384         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1385         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1387         // Test $USER default.
1388         set_user_preference('_test_user_preferences_pref', 'ok');
1389         $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1390         unset_user_preference('_test_user_preferences_pref');
1391         $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1393         // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
1394         $longvalue = str_repeat('a', 1333);
1395         set_user_preference('_test_long_user_preference', $longvalue);
1396         $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1397         $this->assertEquals($longvalue,
1398             $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1400         // Test > 1333 char values, coding_exception expected.
1401         $longvalue = str_repeat('a', 1334);
1402         try {
1403             set_user_preference('_test_long_user_preference', $longvalue);
1404             $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1405         } catch (moodle_exception $ex) {
1406             $this->assertInstanceOf('coding_exception', $ex);
1407         }
1409         // Test invalid params.
1410         try {
1411             set_user_preference('_test_user_preferences_pref', array());
1412             $this->fail('Exception expected - array not valid preference value');
1413         } catch (moodle_exception $ex) {
1414             $this->assertInstanceOf('coding_exception', $ex);
1415         }
1416         try {
1417             set_user_preference('_test_user_preferences_pref', new stdClass);
1418             $this->fail('Exception expected - class not valid preference value');
1419         } catch (moodle_exception $ex) {
1420             $this->assertInstanceOf('coding_exception', $ex);
1421         }
1422         try {
1423             set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1424             $this->fail('Exception expected - user instance expected');
1425         } catch (moodle_exception $ex) {
1426             $this->assertInstanceOf('coding_exception', $ex);
1427         }
1428         try {
1429             set_user_preference('_test_user_preferences_pref', 1, 'abc');
1430             $this->fail('Exception expected - user instance expected');
1431         } catch (moodle_exception $ex) {
1432             $this->assertInstanceOf('coding_exception', $ex);
1433         }
1434         try {
1435             set_user_preference('', 1);
1436             $this->fail('Exception expected - invalid name accepted');
1437         } catch (moodle_exception $ex) {
1438             $this->assertInstanceOf('coding_exception', $ex);
1439         }
1440         try {
1441             set_user_preference('1', 1);
1442             $this->fail('Exception expected - invalid name accepted');
1443         } catch (moodle_exception $ex) {
1444             $this->assertInstanceOf('coding_exception', $ex);
1445         }
1446     }
1448     public function test_set_user_preference_for_current_user() {
1449         global $USER;
1450         $this->resetAfterTest();
1451         $this->setAdminUser();
1453         set_user_preference('test_pref', 2);
1454         set_user_preference('test_pref', 1, $USER->id);
1455         $this->assertEquals(1, get_user_preferences('test_pref'));
1456     }
1458     public function test_unset_user_preference_for_current_user() {
1459         global $USER;
1460         $this->resetAfterTest();
1461         $this->setAdminUser();
1463         set_user_preference('test_pref', 1);
1464         unset_user_preference('test_pref', $USER->id);
1465         $this->assertNull(get_user_preferences('test_pref'));
1466     }
1468     /**
1469      * Test essential features implementation of {@link get_extra_user_fields()} as the admin user with all capabilities.
1470      */
1471     public function test_get_extra_user_fields_essentials() {
1472         global $CFG, $USER, $DB;
1473         $this->resetAfterTest();
1475         $this->setAdminUser();
1476         $context = context_system::instance();
1478         // No fields.
1479         $CFG->showuseridentity = '';
1480         $this->assertEquals(array(), get_extra_user_fields($context));
1482         // One field.
1483         $CFG->showuseridentity = 'frog';
1484         $this->assertEquals(array('frog'), get_extra_user_fields($context));
1486         // Two fields.
1487         $CFG->showuseridentity = 'frog,zombie';
1488         $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1490         // No fields, except.
1491         $CFG->showuseridentity = '';
1492         $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1494         // One field.
1495         $CFG->showuseridentity = 'frog';
1496         $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1498         // Two fields.
1499         $CFG->showuseridentity = 'frog,zombie';
1500         $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1501     }
1503     /**
1504      * Prepare environment for couple of tests related to permission checks in {@link get_extra_user_fields()}.
1505      *
1506      * @return stdClass
1507      */
1508     protected function environment_for_get_extra_user_fields_tests() {
1509         global $CFG, $DB;
1511         $CFG->showuseridentity = 'idnumber,country,city';
1512         $CFG->hiddenuserfields = 'country,city';
1514         $env = new stdClass();
1516         $env->course = $this->getDataGenerator()->create_course();
1517         $env->coursecontext = context_course::instance($env->course->id);
1519         $env->teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
1520         $env->studentrole = $DB->get_record('role', array('shortname' => 'student'));
1521         $env->managerrole = $DB->get_record('role', array('shortname' => 'manager'));
1523         $env->student = $this->getDataGenerator()->create_user();
1524         $env->teacher = $this->getDataGenerator()->create_user();
1525         $env->manager = $this->getDataGenerator()->create_user();
1527         role_assign($env->studentrole->id, $env->student->id, $env->coursecontext->id);
1528         role_assign($env->teacherrole->id, $env->teacher->id, $env->coursecontext->id);
1529         role_assign($env->managerrole->id, $env->manager->id, SYSCONTEXTID);
1531         return $env;
1532     }
1534     /**
1535      * No identity fields shown to student user (no permission to view identity fields).
1536      */
1537     public function test_get_extra_user_fields_no_access() {
1539         $this->resetAfterTest();
1540         $env = $this->environment_for_get_extra_user_fields_tests();
1541         $this->setUser($env->student);
1543         $this->assertEquals(array(), get_extra_user_fields($env->coursecontext));
1544         $this->assertEquals(array(), get_extra_user_fields(context_system::instance()));
1545     }
1547     /**
1548      * Teacher can see students' identity fields only within the course.
1549      */
1550     public function test_get_extra_user_fields_course_only_access() {
1552         $this->resetAfterTest();
1553         $env = $this->environment_for_get_extra_user_fields_tests();
1554         $this->setUser($env->teacher);
1556         $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields($env->coursecontext));
1557         $this->assertEquals(array(), get_extra_user_fields(context_system::instance()));
1558     }
1560     /**
1561      * Teacher can be prevented from seeing students' identity fields even within the course.
1562      */
1563     public function test_get_extra_user_fields_course_prevented_access() {
1565         $this->resetAfterTest();
1566         $env = $this->environment_for_get_extra_user_fields_tests();
1567         $this->setUser($env->teacher);
1569         assign_capability('moodle/course:viewhiddenuserfields', CAP_PREVENT, $env->teacherrole->id, $env->coursecontext->id);
1570         $this->assertEquals(array('idnumber'), get_extra_user_fields($env->coursecontext));
1571     }
1573     /**
1574      * Manager can see students' identity fields anywhere.
1575      */
1576     public function test_get_extra_user_fields_anywhere_access() {
1578         $this->resetAfterTest();
1579         $env = $this->environment_for_get_extra_user_fields_tests();
1580         $this->setUser($env->manager);
1582         $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields($env->coursecontext));
1583         $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields(context_system::instance()));
1584     }
1586     /**
1587      * Manager can be prevented from seeing hidden fields outside the course.
1588      */
1589     public function test_get_extra_user_fields_schismatic_access() {
1591         $this->resetAfterTest();
1592         $env = $this->environment_for_get_extra_user_fields_tests();
1593         $this->setUser($env->manager);
1595         assign_capability('moodle/user:viewhiddendetails', CAP_PREVENT, $env->managerrole->id, SYSCONTEXTID, true);
1596         $this->assertEquals(array('idnumber'), get_extra_user_fields(context_system::instance()));
1597         // Note that inside the course, the manager can still see the hidden identifiers as this is currently
1598         // controlled by a separate capability for legacy reasons.
1599         $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields($env->coursecontext));
1600     }
1602     /**
1603      * Two capabilities must be currently set to prevent manager from seeing hidden fields.
1604      */
1605     public function test_get_extra_user_fields_hard_to_prevent_access() {
1607         $this->resetAfterTest();
1608         $env = $this->environment_for_get_extra_user_fields_tests();
1609         $this->setUser($env->manager);
1611         assign_capability('moodle/user:viewhiddendetails', CAP_PREVENT, $env->managerrole->id, SYSCONTEXTID, true);
1612         assign_capability('moodle/course:viewhiddenuserfields', CAP_PREVENT, $env->managerrole->id, SYSCONTEXTID, true);
1614         $this->assertEquals(array('idnumber'), get_extra_user_fields(context_system::instance()));
1615         $this->assertEquals(array('idnumber'), get_extra_user_fields($env->coursecontext));
1616     }
1618     public function test_get_extra_user_fields_sql() {
1619         global $CFG, $USER, $DB;
1620         $this->resetAfterTest();
1622         $this->setAdminUser();
1624         $context = context_system::instance();
1626         // No fields.
1627         $CFG->showuseridentity = '';
1628         $this->assertSame('', get_extra_user_fields_sql($context));
1630         // One field.
1631         $CFG->showuseridentity = 'frog';
1632         $this->assertSame(', frog', get_extra_user_fields_sql($context));
1634         // Two fields with table prefix.
1635         $CFG->showuseridentity = 'frog,zombie';
1636         $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1638         // Two fields with field prefix.
1639         $CFG->showuseridentity = 'frog,zombie';
1640         $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
1641             get_extra_user_fields_sql($context, '', 'u_'));
1643         // One field excluded.
1644         $CFG->showuseridentity = 'frog';
1645         $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
1647         // Two fields, one excluded, table+field prefix.
1648         $CFG->showuseridentity = 'frog,zombie';
1649         $this->assertEquals(', u1.zombie AS u_zombie',
1650             get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1651     }
1653     /**
1654      * Test some critical TZ/DST.
1655      *
1656      * This method tests some special TZ/DST combinations that were fixed
1657      * by MDL-38999. The tests are done by comparing the results of the
1658      * output using Moodle TZ/DST support and PHP native one.
1659      *
1660      * Note: If you don't trust PHP TZ/DST support, can verify the
1661      * harcoded expectations below with:
1662      * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
1663      */
1664     public function test_some_moodle_special_dst() {
1665         $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
1667         // In Europe/Tallinn it was 2013/04/08 05:00:00.
1668         $expectation = '2013/04/08 05:00:00';
1669         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1670         $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1671         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1672         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1673         $this->assertSame($expectation, $phpres);
1674         $this->assertSame($expectation, $moodleres);
1676         // In St. Johns it was 2013/04/07 23:30:00.
1677         $expectation = '2013/04/07 23:30:00';
1678         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1679         $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1680         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1681         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1682         $this->assertSame($expectation, $phpres);
1683         $this->assertSame($expectation, $moodleres);
1685         $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1687         // In Europe/Tallinn it was 2013/11/08 04:00:00.
1688         $expectation = '2013/11/08 04:00:00';
1689         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1690         $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1691         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1692         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1693         $this->assertSame($expectation, $phpres);
1694         $this->assertSame($expectation, $moodleres);
1696         // In St. Johns it was 2013/11/07 22:30:00.
1697         $expectation = '2013/11/07 22:30:00';
1698         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1699         $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1700         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1701         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1702         $this->assertSame($expectation, $phpres);
1703         $this->assertSame($expectation, $moodleres);
1704     }
1706     public function test_userdate() {
1707         global $USER, $CFG, $DB;
1708         $this->resetAfterTest();
1710         $this->setAdminUser();
1712         $testvalues = array(
1713             array(
1714                 'time' => '1309514400',
1715                 'usertimezone' => 'America/Moncton',
1716                 'timezone' => '0.0', // No dst offset.
1717                 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1718             ),
1719             array(
1720                 'time' => '1309514400',
1721                 'usertimezone' => 'America/Moncton',
1722                 'timezone' => '99', // Dst offset and timezone offset.
1723                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1724             ),
1725             array(
1726                 'time' => '1309514400',
1727                 'usertimezone' => 'America/Moncton',
1728                 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
1729                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1730             ),
1731             array(
1732                 'time' => '1293876000 ',
1733                 'usertimezone' => 'America/Moncton',
1734                 'timezone' => '0.0', // No dst offset.
1735                 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1736             ),
1737             array(
1738                 'time' => '1293876000 ',
1739                 'usertimezone' => 'America/Moncton',
1740                 'timezone' => '99', // No dst offset in jan, so just timezone offset.
1741                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1742             ),
1743             array(
1744                 'time' => '1293876000 ',
1745                 'usertimezone' => 'America/Moncton',
1746                 'timezone' => 'America/Moncton', // No dst offset in jan.
1747                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1748             ),
1749             array(
1750                 'time' => '1293876000 ',
1751                 'usertimezone' => '2',
1752                 'timezone' => '99', // Take user timezone.
1753                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1754             ),
1755             array(
1756                 'time' => '1293876000 ',
1757                 'usertimezone' => '-2',
1758                 'timezone' => '99', // Take user timezone.
1759                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1760             ),
1761             array(
1762                 'time' => '1293876000 ',
1763                 'usertimezone' => '-10',
1764                 'timezone' => '2', // Take this timezone.
1765                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1766             ),
1767             array(
1768                 'time' => '1293876000 ',
1769                 'usertimezone' => '-10',
1770                 'timezone' => '-2', // Take this timezone.
1771                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1772             ),
1773             array(
1774                 'time' => '1293876000 ',
1775                 'usertimezone' => '-10',
1776                 'timezone' => 'random/time', // This should show server time.
1777                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1778             ),
1779             array(
1780                 'time' => '1293876000 ',
1781                 'usertimezone' => '20', // Fallback to server time zone.
1782                 'timezone' => '99',     // This should show user time.
1783                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1784             ),
1785         );
1787         // Set default timezone to Australia/Perth, else time calculated
1788         // will not match expected values.
1789         $this->setTimezone(99, 'Australia/Perth');
1791         foreach ($testvalues as $vals) {
1792             $USER->timezone = $vals['usertimezone'];
1793             $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1795             // On different systems case of AM PM changes so compare case insensitive.
1796             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1797             $actualoutput = core_text::strtolower($actualoutput);
1799             $this->assertSame($vals['expectedoutput'], $actualoutput,
1800                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput} \ndata: " . var_export($vals, true));
1801         }
1802     }
1804     /**
1805      * Make sure the DST changes happen at the right time in Moodle.
1806      */
1807     public function test_dst_changes() {
1808         // DST switching in Prague.
1809         // From 2AM to 3AM in 1989.
1810         $date = new DateTime('1989-03-26T01:59:00+01:00');
1811         $this->assertSame('Sunday, 26 March 1989, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1812         $date = new DateTime('1989-03-26T02:01:00+01:00');
1813         $this->assertSame('Sunday, 26 March 1989, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1814         // From 3AM to 2AM in 1989 - not the same as the west Europe.
1815         $date = new DateTime('1989-09-24T01:59:00+01:00');
1816         $this->assertSame('Sunday, 24 September 1989, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1817         $date = new DateTime('1989-09-24T02:01:00+01:00');
1818         $this->assertSame('Sunday, 24 September 1989, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1819         // From 2AM to 3AM in 2014.
1820         $date = new DateTime('2014-03-30T01:59:00+01:00');
1821         $this->assertSame('Sunday, 30 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1822         $date = new DateTime('2014-03-30T02:01:00+01:00');
1823         $this->assertSame('Sunday, 30 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1824         // From 3AM to 2AM in 2014.
1825         $date = new DateTime('2014-10-26T01:59:00+01:00');
1826         $this->assertSame('Sunday, 26 October 2014, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1827         $date = new DateTime('2014-10-26T02:01:00+01:00');
1828         $this->assertSame('Sunday, 26 October 2014, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1829         // From 2AM to 3AM in 2020.
1830         $date = new DateTime('2020-03-29T01:59:00+01:00');
1831         $this->assertSame('Sunday, 29 March 2020, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1832         $date = new DateTime('2020-03-29T02:01:00+01:00');
1833         $this->assertSame('Sunday, 29 March 2020, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1834         // From 3AM to 2AM in 2020.
1835         $date = new DateTime('2020-10-25T01:59:00+01:00');
1836         $this->assertSame('Sunday, 25 October 2020, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1837         $date = new DateTime('2020-10-25T02:01:00+01:00');
1838         $this->assertSame('Sunday, 25 October 2020, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1840         // DST switching in NZ.
1841         // From 3AM to 2AM in 2015.
1842         $date = new DateTime('2015-04-05T02:59:00+13:00');
1843         $this->assertSame('Sunday, 5 April 2015, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1844         $date = new DateTime('2015-04-05T03:01:00+13:00');
1845         $this->assertSame('Sunday, 5 April 2015, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1846         // From 2AM to 3AM in 2009.
1847         $date = new DateTime('2015-09-27T01:59:00+12:00');
1848         $this->assertSame('Sunday, 27 September 2015, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1849         $date = new DateTime('2015-09-27T02:01:00+12:00');
1850         $this->assertSame('Sunday, 27 September 2015, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1852         // DST switching in Perth.
1853         // From 3AM to 2AM in 2009.
1854         $date = new DateTime('2008-03-30T01:59:00+08:00');
1855         $this->assertSame('Sunday, 30 March 2008, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1856         $date = new DateTime('2008-03-30T02:01:00+08:00');
1857         $this->assertSame('Sunday, 30 March 2008, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1858         // From 2AM to 3AM in 2009.
1859         $date = new DateTime('2008-10-26T01:59:00+08:00');
1860         $this->assertSame('Sunday, 26 October 2008, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1861         $date = new DateTime('2008-10-26T02:01:00+08:00');
1862         $this->assertSame('Sunday, 26 October 2008, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1864         // DST switching in US.
1865         // From 2AM to 3AM in 2014.
1866         $date = new DateTime('2014-03-09T01:59:00-05:00');
1867         $this->assertSame('Sunday, 9 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1868         $date = new DateTime('2014-03-09T02:01:00-05:00');
1869         $this->assertSame('Sunday, 9 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1870         // From 3AM to 2AM in 2014.
1871         $date = new DateTime('2014-11-02T01:59:00-04:00');
1872         $this->assertSame('Sunday, 2 November 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1873         $date = new DateTime('2014-11-02T02:01:00-04:00');
1874         $this->assertSame('Sunday, 2 November 2014, 01:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1875     }
1877     public function test_make_timestamp() {
1878         global $USER, $CFG, $DB;
1879         $this->resetAfterTest();
1881         $this->setAdminUser();
1883         $testvalues = array(
1884             array(
1885                 'usertimezone' => 'America/Moncton',
1886                 'year' => '2011',
1887                 'month' => '7',
1888                 'day' => '1',
1889                 'hour' => '10',
1890                 'minutes' => '00',
1891                 'seconds' => '00',
1892                 'timezone' => '0.0',
1893                 'applydst' => false, // No dst offset.
1894                 'expectedoutput' => '1309514400' // 6pm at UTC+0.
1895             ),
1896             array(
1897                 'usertimezone' => 'America/Moncton',
1898                 'year' => '2011',
1899                 'month' => '7',
1900                 'day' => '1',
1901                 'hour' => '10',
1902                 'minutes' => '00',
1903                 'seconds' => '00',
1904                 'timezone' => '99',  // User default timezone.
1905                 'applydst' => false, // Don't apply dst.
1906                 'expectedoutput' => '1309528800'
1907             ),
1908             array(
1909                 'usertimezone' => 'America/Moncton',
1910                 'year' => '2011',
1911                 'month' => '7',
1912                 'day' => '1',
1913                 'hour' => '10',
1914                 'minutes' => '00',
1915                 'seconds' => '00',
1916                 'timezone' => '99', // User default timezone.
1917                 'applydst' => true, // Apply dst.
1918                 'expectedoutput' => '1309525200'
1919             ),
1920             array(
1921                 'usertimezone' => 'America/Moncton',
1922                 'year' => '2011',
1923                 'month' => '7',
1924                 'day' => '1',
1925                 'hour' => '10',
1926                 'minutes' => '00',
1927                 'seconds' => '00',
1928                 'timezone' => 'America/Moncton', // String timezone.
1929                 'applydst' => true, // Apply dst.
1930                 'expectedoutput' => '1309525200'
1931             ),
1932             array(
1933                 'usertimezone' => '2', // No dst applyed.
1934                 'year' => '2011',
1935                 'month' => '7',
1936                 'day' => '1',
1937                 'hour' => '10',
1938                 'minutes' => '00',
1939                 'seconds' => '00',
1940                 'timezone' => '99', // Take user timezone.
1941                 'applydst' => true, // Apply dst.
1942                 'expectedoutput' => '1309507200'
1943             ),
1944             array(
1945                 'usertimezone' => '-2', // No dst applyed.
1946                 'year' => '2011',
1947                 'month' => '7',
1948                 'day' => '1',
1949                 'hour' => '10',
1950                 'minutes' => '00',
1951                 'seconds' => '00',
1952                 'timezone' => '99', // Take usertimezone.
1953                 'applydst' => true, // Apply dst.
1954                 'expectedoutput' => '1309521600'
1955             ),
1956             array(
1957                 'usertimezone' => '-10', // No dst applyed.
1958                 'year' => '2011',
1959                 'month' => '7',
1960                 'day' => '1',
1961                 'hour' => '10',
1962                 'minutes' => '00',
1963                 'seconds' => '00',
1964                 'timezone' => '2',  // Take this timezone.
1965                 'applydst' => true, // Apply dst.
1966                 'expectedoutput' => '1309507200'
1967             ),
1968             array(
1969                 'usertimezone' => '-10', // No dst applyed.
1970                 'year' => '2011',
1971                 'month' => '7',
1972                 'day' => '1',
1973                 'hour' => '10',
1974                 'minutes' => '00',
1975                 'seconds' => '00',
1976                 'timezone' => '-2', // Take this timezone.
1977                 'applydst' => true, // Apply dst.
1978                 'expectedoutput' => '1309521600'
1979             ),
1980             array(
1981                 'usertimezone' => '-10', // No dst applyed.
1982                 'year' => '2011',
1983                 'month' => '7',
1984                 'day' => '1',
1985                 'hour' => '10',
1986                 'minutes' => '00',
1987                 'seconds' => '00',
1988                 'timezone' => 'random/time', // This should show server time.
1989                 'applydst' => true,          // Apply dst.
1990                 'expectedoutput' => '1309485600'
1991             ),
1992             array(
1993                 'usertimezone' => '-14', // Server time.
1994                 'year' => '2011',
1995                 'month' => '7',
1996                 'day' => '1',
1997                 'hour' => '10',
1998                 'minutes' => '00',
1999                 'seconds' => '00',
2000                 'timezone' => '99', // Get user time.
2001                 'applydst' => true, // Apply dst.
2002                 'expectedoutput' => '1309485600'
2003             )
2004         );
2006         // Set default timezone to Australia/Perth, else time calculated
2007         // will not match expected values.
2008         $this->setTimezone(99, 'Australia/Perth');
2010         // Test make_timestamp with all testvals and assert if anything wrong.
2011         foreach ($testvalues as $vals) {
2012             $USER->timezone = $vals['usertimezone'];
2013             $actualoutput = make_timestamp(
2014                 $vals['year'],
2015                 $vals['month'],
2016                 $vals['day'],
2017                 $vals['hour'],
2018                 $vals['minutes'],
2019                 $vals['seconds'],
2020                 $vals['timezone'],
2021                 $vals['applydst']
2022             );
2024             // On different systems case of AM PM changes so compare case insensitive.
2025             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
2026             $actualoutput = core_text::strtolower($actualoutput);
2028             $this->assertSame($vals['expectedoutput'], $actualoutput,
2029                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
2030                 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
2031         }
2032     }
2034     /**
2035      * Test get_string and most importantly the implementation of the lang_string
2036      * object.
2037      */
2038     public function test_get_string() {
2039         global $COURSE;
2041         // Make sure we are using English.
2042         $originallang = $COURSE->lang;
2043         $COURSE->lang = 'en';
2045         $yes = get_string('yes');
2046         $yesexpected = 'Yes';
2047         $this->assertInternalType('string', $yes);
2048         $this->assertSame($yesexpected, $yes);
2050         $yes = get_string('yes', 'moodle');
2051         $this->assertInternalType('string', $yes);
2052         $this->assertSame($yesexpected, $yes);
2054         $yes = get_string('yes', 'core');
2055         $this->assertInternalType('string', $yes);
2056         $this->assertSame($yesexpected, $yes);
2058         $yes = get_string('yes', '');
2059         $this->assertInternalType('string', $yes);
2060         $this->assertSame($yesexpected, $yes);
2062         $yes = get_string('yes', null);
2063         $this->assertInternalType('string', $yes);
2064         $this->assertSame($yesexpected, $yes);
2066         $yes = get_string('yes', null, 1);
2067         $this->assertInternalType('string', $yes);
2068         $this->assertSame($yesexpected, $yes);
2070         $days = 1;
2071         $numdays = get_string('numdays', 'core', '1');
2072         $numdaysexpected = $days.' days';
2073         $this->assertInternalType('string', $numdays);
2074         $this->assertSame($numdaysexpected, $numdays);
2076         $yes = get_string('yes', null, null, true);
2077         $this->assertInstanceOf('lang_string', $yes);
2078         $this->assertSame($yesexpected, (string)$yes);
2080         // Test using a lang_string object as the $a argument for a normal
2081         // get_string call (returning string).
2082         $test = new lang_string('yes', null, null, true);
2083         $testexpected = get_string('numdays', 'core', get_string('yes'));
2084         $testresult = get_string('numdays', null, $test);
2085         $this->assertInternalType('string', $testresult);
2086         $this->assertSame($testexpected, $testresult);
2088         // Test using a lang_string object as the $a argument for an object
2089         // get_string call (returning lang_string).
2090         $test = new lang_string('yes', null, null, true);
2091         $testexpected = get_string('numdays', 'core', get_string('yes'));
2092         $testresult = get_string('numdays', null, $test, true);
2093         $this->assertInstanceOf('lang_string', $testresult);
2094         $this->assertSame($testexpected, "$testresult");
2096         // Make sure that object properties that can't be converted don't cause
2097         // errors.
2098         // Level one: This is as deep as current language processing goes.
2099         $test = new stdClass;
2100         $test->one = 'here';
2101         $string = get_string('yes', null, $test, true);
2102         $this->assertEquals($yesexpected, $string);
2104         // Make sure that object properties that can't be converted don't cause
2105         // errors.
2106         // Level two: Language processing doesn't currently reach this deep.
2107         // only immediate scalar properties are worked with.
2108         $test = new stdClass;
2109         $test->one = new stdClass;
2110         $test->one->two = 'here';
2111         $string = get_string('yes', null, $test, true);
2112         $this->assertEquals($yesexpected, $string);
2114         // Make sure that object properties that can't be converted don't cause
2115         // errors.
2116         // Level three: It should never ever go this deep, but we're making sure
2117         // it doesn't cause any probs anyway.
2118         $test = new stdClass;
2119         $test->one = new stdClass;
2120         $test->one->two = new stdClass;
2121         $test->one->two->three = 'here';
2122         $string = get_string('yes', null, $test, true);
2123         $this->assertEquals($yesexpected, $string);
2125         // Make sure that object properties that can't be converted don't cause
2126         // errors and check lang_string properties.
2127         // Level one: This is as deep as current language processing goes.
2128         $test = new stdClass;
2129         $test->one = new lang_string('yes');
2130         $string = get_string('yes', null, $test, true);
2131         $this->assertEquals($yesexpected, $string);
2133         // Make sure that object properties that can't be converted don't cause
2134         // errors and check lang_string properties.
2135         // Level two: Language processing doesn't currently reach this deep.
2136         // only immediate scalar properties are worked with.
2137         $test = new stdClass;
2138         $test->one = new stdClass;
2139         $test->one->two = new lang_string('yes');
2140         $string = get_string('yes', null, $test, true);
2141         $this->assertEquals($yesexpected, $string);
2143         // Make sure that object properties that can't be converted don't cause
2144         // errors and check lang_string properties.
2145         // Level three: It should never ever go this deep, but we're making sure
2146         // it doesn't cause any probs anyway.
2147         $test = new stdClass;
2148         $test->one = new stdClass;
2149         $test->one->two = new stdClass;
2150         $test->one->two->three = new lang_string('yes');
2151         $string = get_string('yes', null, $test, true);
2152         $this->assertEquals($yesexpected, $string);
2154         // Make sure that array properties that can't be converted don't cause
2155         // errors.
2156         $test = array();
2157         $test['one'] = new stdClass;
2158         $test['one']->two = 'here';
2159         $string = get_string('yes', null, $test, true);
2160         $this->assertEquals($yesexpected, $string);
2162         // Same thing but as above except using an object... this is allowed :P.
2163         $string = get_string('yes', null, null, true);
2164         $object = new stdClass;
2165         $object->$string = 'Yes';
2166         $this->assertEquals($yesexpected, $string);
2167         $this->assertEquals($yesexpected, $object->$string);
2169         // Reset the language.
2170         $COURSE->lang = $originallang;
2171     }
2173     /**
2174      * @expectedException PHPUnit\Framework\Error\Warning
2175      */
2176     public function test_get_string_limitation() {
2177         // This is one of the limitations to the lang_string class. It can't be
2178         // used as a key.
2179         $array = array(get_string('yes', null, null, true) => 'yes');
2180     }
2182     /**
2183      * Test localised float formatting.
2184      */
2185     public function test_format_float() {
2187         // Special case for null.
2188         $this->assertEquals('', format_float(null));
2190         // Default 1 decimal place.
2191         $this->assertEquals('5.4', format_float(5.43));
2192         $this->assertEquals('5.0', format_float(5.001));
2194         // Custom number of decimal places.
2195         $this->assertEquals('5.43000', format_float(5.43, 5));
2197         // Option to strip ending zeros after rounding.
2198         $this->assertEquals('5.43', format_float(5.43, 5, true, true));
2199         $this->assertEquals('5', format_float(5.0001, 3, true, true));
2201         // Tests with a localised decimal separator.
2202         $this->define_local_decimal_separator();
2204         // Localisation on (default).
2205         $this->assertEquals('5X43000', format_float(5.43, 5));
2206         $this->assertEquals('5X43', format_float(5.43, 5, true, true));
2208         // Localisation off.
2209         $this->assertEquals('5.43000', format_float(5.43, 5, false));
2210         $this->assertEquals('5.43', format_float(5.43, 5, false, true));
2211     }
2213     /**
2214      * Test localised float unformatting.
2215      */
2216     public function test_unformat_float() {
2218         // Tests without the localised decimal separator.
2220         // Special case for null, empty or white spaces only strings.
2221         $this->assertEquals(null, unformat_float(null));
2222         $this->assertEquals(null, unformat_float(''));
2223         $this->assertEquals(null, unformat_float('    '));
2225         // Regular use.
2226         $this->assertEquals(5.4, unformat_float('5.4'));
2227         $this->assertEquals(5.4, unformat_float('5.4', true));
2229         // No decimal.
2230         $this->assertEquals(5.0, unformat_float('5'));
2232         // Custom number of decimal.
2233         $this->assertEquals(5.43267, unformat_float('5.43267'));
2235         // Empty decimal.
2236         $this->assertEquals(100.0, unformat_float('100.00'));
2238         // With the thousand separator.
2239         $this->assertEquals(1000.0, unformat_float('1 000'));
2240         $this->assertEquals(1000.32, unformat_float('1 000.32'));
2242         // Negative number.
2243         $this->assertEquals(-100.0, unformat_float('-100'));
2245         // Wrong value.
2246         $this->assertEquals(0.0, unformat_float('Wrong value'));
2247         // Wrong value in strict mode.
2248         $this->assertFalse(unformat_float('Wrong value', true));
2250         // Combining options.
2251         $this->assertEquals(-1023.862567, unformat_float('   -1 023.862567     '));
2253         // Bad decimal separator (should crop the decimal).
2254         $this->assertEquals(50.0, unformat_float('50,57'));
2255         // Bad decimal separator in strict mode (should return false).
2256         $this->assertFalse(unformat_float('50,57', true));
2258         // Tests with a localised decimal separator.
2259         $this->define_local_decimal_separator();
2261         // We repeat the tests above but with the current decimal separator.
2263         // Regular use without and with the localised separator.
2264         $this->assertEquals (5.4, unformat_float('5.4'));
2265         $this->assertEquals (5.4, unformat_float('5X4'));
2267         // Custom number of decimal.
2268         $this->assertEquals (5.43267, unformat_float('5X43267'));
2270         // Empty decimal.
2271         $this->assertEquals (100.0, unformat_float('100X00'));
2273         // With the thousand separator.
2274         $this->assertEquals (1000.32, unformat_float('1 000X32'));
2276         // Bad different separator (should crop the decimal).
2277         $this->assertEquals (50.0, unformat_float('50Y57'));
2278         // Bad different separator in strict mode (should return false).
2279         $this->assertFalse (unformat_float('50Y57', true));
2281         // Combining options.
2282         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     '));
2283         // Combining options in strict mode.
2284         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     ', true));
2285     }
2287     /**
2288      * Test deleting of users.
2289      */
2290     public function test_delete_user() {
2291         global $DB, $CFG;
2293         $this->resetAfterTest();
2295         $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
2296         $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
2297         $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
2299         $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
2300         $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
2301         $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
2302         $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
2303         $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => ''));
2304         $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => ''));
2306         // Delete user and capture event.
2307         $sink = $this->redirectEvents();
2308         $result = delete_user($user);
2309         $events = $sink->get_events();
2310         $sink->close();
2311         $event = array_pop($events);
2313         // Test user is deleted in DB.
2314         $this->assertTrue($result);
2315         $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
2316         $this->assertEquals(1, $deluser->deleted);
2317         $this->assertEquals(0, $deluser->picture);
2318         $this->assertSame('', $deluser->idnumber);
2319         $this->assertSame(md5($user->username), $deluser->email);
2320         $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
2322         $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
2324         // Test Event.
2325         $this->assertInstanceOf('\core\event\user_deleted', $event);
2326         $this->assertSame($user->id, $event->objectid);
2327         $this->assertSame('user_deleted', $event->get_legacy_eventname());
2328         $this->assertEventLegacyData($user, $event);
2329         $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
2330         $this->assertEventLegacyLogData($expectedlogdata, $event);
2331         $eventdata = $event->get_data();
2332         $this->assertSame($eventdata['other']['username'], $user->username);
2333         $this->assertSame($eventdata['other']['email'], $user->email);
2334         $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
2335         $this->assertSame($eventdata['other']['picture'], $user->picture);
2336         $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
2337         $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
2338         $this->assertEventContextNotUsed($event);
2340         // Try invalid params.
2341         $record = new stdClass();
2342         $record->grrr = 1;
2343         try {
2344             delete_user($record);
2345             $this->fail('Expecting exception for invalid delete_user() $user parameter');
2346         } catch (moodle_exception $ex) {
2347             $this->assertInstanceOf('coding_exception', $ex);
2348         }
2349         $record->id = 1;
2350         try {
2351             delete_user($record);
2352             $this->fail('Expecting exception for invalid delete_user() $user parameter');
2353         } catch (moodle_exception $ex) {
2354             $this->assertInstanceOf('coding_exception', $ex);
2355         }
2357         $record = new stdClass();
2358         $record->id = 666;
2359         $record->username = 'xx';
2360         $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
2361         $result = delete_user($record);
2362         $this->assertFalse($result);
2364         $result = delete_user($guest);
2365         $this->assertFalse($result);
2367         $result = delete_user($admin);
2368         $this->assertFalse($result);
2370         // Simultaneously deleting users with identical email addresses.
2371         $result1 = delete_user($usersharedemail1);
2372         $result2 = delete_user($usersharedemail2);
2374         $usersharedemail1after = $DB->get_record('user', array('id' => $usersharedemail1->id));
2375         $usersharedemail2after = $DB->get_record('user', array('id' => $usersharedemail2->id));
2376         $this->assertTrue($result1);
2377         $this->assertTrue($result2);
2378         $this->assertStringStartsWith($usersharedemail1->email . '.', $usersharedemail1after->username);
2379         $this->assertStringStartsWith($usersharedemail2->email . '.', $usersharedemail2after->username);
2381         // Simultaneously deleting users without email addresses.
2382         $result1 = delete_user($useremptyemail1);
2383         $result2 = delete_user($useremptyemail2);
2385         $useremptyemail1after = $DB->get_record('user', array('id' => $useremptyemail1->id));
2386         $useremptyemail2after = $DB->get_record('user', array('id' => $useremptyemail2->id));
2387         $this->assertTrue($result1);
2388         $this->assertTrue($result2);
2389         $this->assertStringStartsWith($useremptyemail1->username . '.' . $useremptyemail1->id . '@unknownemail.invalid.',
2390             $useremptyemail1after->username);
2391         $this->assertStringStartsWith($useremptyemail2->username . '.' . $useremptyemail2->id . '@unknownemail.invalid.',
2392             $useremptyemail2after->username);
2394         $this->resetDebugging();
2395     }
2397     /**
2398      * Test function convert_to_array()
2399      */
2400     public function test_convert_to_array() {
2401         // Check that normal classes are converted to arrays the same way as (array) would do.
2402         $obj = new stdClass();
2403         $obj->prop1 = 'hello';
2404         $obj->prop2 = array('first', 'second', 13);
2405         $obj->prop3 = 15;
2406         $this->assertEquals(convert_to_array($obj), (array)$obj);
2408         // Check that context object (with iterator) is converted to array properly.
2409         $obj = context_system::instance();
2410         $ar = array(
2411             'id'           => $obj->id,
2412             'contextlevel' => $obj->contextlevel,
2413             'instanceid'   => $obj->instanceid,
2414             'path'         => $obj->path,
2415             'depth'        => $obj->depth
2416         );
2417         $this->assertEquals(convert_to_array($obj), $ar);
2418     }
2420     /**
2421      * Test the function date_format_string().
2422      */
2423     public function test_date_format_string() {
2424         global $CFG;
2426         $this->resetAfterTest();
2427         $this->setTimezone(99, 'Australia/Perth');
2429         $tests = array(
2430             array(
2431                 'tz' => 99,
2432                 'str' => '%A, %d %B %Y, %I:%M %p',
2433                 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
2434             ),
2435             array(
2436                 'tz' => 0,
2437                 'str' => '%A, %d %B %Y, %I:%M %p',
2438                 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2439             ),
2440             array(
2441                 // Note: this function expected the timestamp in weird format before,
2442                 // since 2.9 it uses UTC.
2443                 'tz' => 'Pacific/Auckland',
2444                 'str' => '%A, %d %B %Y, %I:%M %p',
2445                 'expected' => 'Saturday, 01 January 2011, 11:00 PM'
2446             ),
2447             // Following tests pass on Windows only because en lang pack does
2448             // not contain localewincharset, in real life lang pack maintainers
2449             // may use only characters that are present in localewincharset
2450             // in format strings!
2451             array(
2452                 'tz' => 99,
2453                 'str' => 'Žluťoučký koníček %A',
2454                 'expected' => 'Žluťoučký koníček Saturday'
2455             ),
2456             array(
2457                 'tz' => 99,
2458                 'str' => '言語設定言語 %A',
2459                 'expected' => '言語設定言語 Saturday'
2460             ),
2461             array(
2462                 'tz' => 99,
2463                 'str' => '简体中文简体 %A',
2464                 'expected' => '简体中文简体 Saturday'
2465             ),
2466         );
2468         // Note: date_format_string() uses the timezone only to differenciate
2469         // the server time from the UTC time. It does not modify the timestamp.
2470         // Hence similar results for timezones <= 13.
2471         // On different systems case of AM PM changes so compare case insensitive.
2472         foreach ($tests as $test) {
2473             $str = date_format_string(1293876000, $test['str'], $test['tz']);
2474             $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
2475         }
2476     }
2478     public function test_get_config() {
2479         global $CFG;
2481         $this->resetAfterTest();
2483         // Preparation.
2484         set_config('phpunit_test_get_config_1', 'test 1');
2485         set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2486         if (!is_array($CFG->config_php_settings)) {
2487             $CFG->config_php_settings = array();
2488         }
2489         $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
2491         if (!is_array($CFG->forced_plugin_settings)) {
2492             $CFG->forced_plugin_settings = array();
2493         }
2494         if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
2495             $CFG->forced_plugin_settings['mod_forum'] = array();
2496         }
2497         $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2498         $CFG->phpunit_test_get_config_5 = 'test 5';
2500         // Testing.
2501         $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
2502         $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2503         $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
2504         $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2505         $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2506         $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2507         $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2509         // Test config we know to exist.
2510         $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
2511         $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2512         $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2513         $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2515         // Test setting a config var that already exists.
2516         set_config('phpunit_test_get_config_1', 'test a');
2517         $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
2518         $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
2520         // Test cache invalidation.
2521         $cache = cache::make('core', 'config');
2522         $this->assertInternalType('array', $cache->get('core'));
2523         $this->assertInternalType('array', $cache->get('mod_forum'));
2524         set_config('phpunit_test_get_config_1', 'test b');
2525         $this->assertFalse($cache->get('core'));
2526         set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2527         $this->assertFalse($cache->get('mod_forum'));
2528     }
2530     public function test_get_max_upload_sizes() {
2531         // Test with very low limits so we are not affected by php upload limits.
2532         // Test activity limit smallest.
2533         $sitebytes = 102400;
2534         $coursebytes = 51200;
2535         $modulebytes = 10240;
2536         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2538         $this->assertSame('Activity upload limit (10KB)', $result['0']);
2539         $this->assertCount(2, $result);
2541         // Test course limit smallest.
2542         $sitebytes = 102400;
2543         $coursebytes = 10240;
2544         $modulebytes = 51200;
2545         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2547         $this->assertSame('Course upload limit (10KB)', $result['0']);
2548         $this->assertCount(2, $result);
2550         // Test site limit smallest.
2551         $sitebytes = 10240;
2552         $coursebytes = 102400;
2553         $modulebytes = 51200;
2554         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2556         $this->assertSame('Site upload limit (10KB)', $result['0']);
2557         $this->assertCount(2, $result);
2559         // Test site limit not set.
2560         $sitebytes = 0;
2561         $coursebytes = 102400;
2562         $modulebytes = 51200;
2563         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2565         $this->assertSame('Activity upload limit (50KB)', $result['0']);
2566         $this->assertCount(3, $result);
2568         $sitebytes = 0;
2569         $coursebytes = 51200;
2570         $modulebytes = 102400;
2571         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2573         $this->assertSame('Course upload limit (50KB)', $result['0']);
2574         $this->assertCount(3, $result);
2576         // Test custom bytes in range.
2577         $sitebytes = 102400;
2578         $coursebytes = 51200;
2579         $modulebytes = 51200;
2580         $custombytes = 10240;
2581         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2583         $this->assertCount(3, $result);
2585         // Test custom bytes in range but non-standard.
2586         $sitebytes = 102400;
2587         $coursebytes = 51200;
2588         $modulebytes = 51200;
2589         $custombytes = 25600;
2590         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2592         $this->assertCount(4, $result);
2594         // Test custom bytes out of range.
2595         $sitebytes = 102400;
2596         $coursebytes = 51200;
2597         $modulebytes = 51200;
2598         $custombytes = 102400;
2599         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2601         $this->assertCount(3, $result);
2603         // Test custom bytes out of range and non-standard.
2604         $sitebytes = 102400;
2605         $coursebytes = 51200;
2606         $modulebytes = 51200;
2607         $custombytes = 256000;
2608         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2610         $this->assertCount(3, $result);
2612         // Test site limit only.
2613         $sitebytes = 51200;
2614         $result = get_max_upload_sizes($sitebytes);
2616         $this->assertSame('Site upload limit (50KB)', $result['0']);
2617         $this->assertSame('50KB', $result['51200']);
2618         $this->assertSame('10KB', $result['10240']);
2619         $this->assertCount(3, $result);
2621         // Test no limit.
2622         $result = get_max_upload_sizes();
2623         $this->assertArrayHasKey('0', $result);
2624         $this->assertArrayHasKey(get_max_upload_file_size(), $result);
2625     }
2627     /**
2628      * Test function password_is_legacy_hash().
2629      */
2630     public function test_password_is_legacy_hash() {
2631         // Well formed md5s should be matched.
2632         foreach (array('some', 'strings', 'to_check!') as $string) {
2633             $md5 = md5($string);
2634             $this->assertTrue(password_is_legacy_hash($md5));
2635         }
2636         // Strings that are not md5s should not be matched.
2637         foreach (array('', AUTH_PASSWORD_NOT_CACHED, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
2638             $this->assertFalse(password_is_legacy_hash($notmd5));
2639         }
2640     }
2642     /**
2643      * Test function validate_internal_user_password().
2644      */
2645     public function test_validate_internal_user_password() {
2646         // Test bcrypt hashes.
2647         $validhashes = array(
2648             'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2649             'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2650             'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2651             'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
2652         );
2654         foreach ($validhashes as $password => $hash) {
2655             $user = new stdClass();
2656             $user->auth = 'manual';
2657             $user->password = $hash;
2658             // The correct password should be validated.
2659             $this->assertTrue(validate_internal_user_password($user, $password));
2660             // An incorrect password should not be validated.
2661             $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2662         }
2663     }
2665     /**
2666      * Test function hash_internal_user_password().
2667      */
2668     public function test_hash_internal_user_password() {
2669         $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2671         // Check that some passwords that we convert to hashes can
2672         // be validated.
2673         foreach ($passwords as $password) {
2674             $hash = hash_internal_user_password($password);
2675             $fasthash = hash_internal_user_password($password, true);
2676             $user = new stdClass();
2677             $user->auth = 'manual';
2678             $user->password = $hash;
2679             $this->assertTrue(validate_internal_user_password($user, $password));
2681             // They should not be in md5 format.
2682             $this->assertFalse(password_is_legacy_hash($hash));
2684             // Check that cost factor in hash is correctly set.
2685             $this->assertRegExp('/\$10\$/', $hash);
2686             $this->assertRegExp('/\$04\$/', $fasthash);
2687         }
2688     }
2690     /**
2691      * Test function update_internal_user_password().
2692      */
2693     public function test_update_internal_user_password() {
2694         global $DB;
2695         $this->resetAfterTest();
2696         $passwords = array('password', '1234', 'changeme', '****');
2697         foreach ($passwords as $password) {
2698             $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2699             update_internal_user_password($user, $password);
2700             // The user object should have been updated.
2701             $this->assertTrue(validate_internal_user_password($user, $password));
2702             // The database field for the user should also have been updated to the
2703             // same value.
2704             $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
2705         }
2707         $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2708         // Manually set the user's password to the md5 of the string 'password'.
2709         $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
2711         $sink = $this->redirectEvents();
2712         // Update the password.
2713         update_internal_user_password($user, 'password');
2714         $events = $sink->get_events();
2715         $sink->close();
2716         $event = array_pop($events);
2718         // Password should have been updated to a bcrypt hash.
2719         $this->assertFalse(password_is_legacy_hash($user->password));
2721         // Verify event information.
2722         $this->assertInstanceOf('\core\event\user_password_updated', $event);
2723         $this->assertSame($user->id, $event->relateduserid);
2724         $this->assertEquals(context_user::instance($user->id), $event->get_context());
2725         $this->assertEventContextNotUsed($event);
2727         // Verify recovery of property 'auth'.
2728         unset($user->auth);
2729         update_internal_user_password($user, 'newpassword');
2730         $this->assertDebuggingCalled('User record in update_internal_user_password() must include field auth',
2731                 DEBUG_DEVELOPER);
2732         $this->assertEquals('manual', $user->auth);
2733     }
2735     /**
2736      * Testing that if the password is not cached, that it does not update
2737      * the user table and fire event.
2738      */
2739     public function test_update_internal_user_password_no_cache() {
2740         $this->resetAfterTest();
2742         $user = $this->getDataGenerator()->create_user(array('auth' => 'cas'));
2743         $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2745         $sink = $this->redirectEvents();
2746         update_internal_user_password($user, 'wonkawonka');
2747         $this->assertEquals(0, $sink->count(), 'User updated event should not fire');
2748     }
2750     /**
2751      * Test if the user has a password hash, but now their auth method
2752      * says not to cache it.  Then it should update.
2753      */
2754     public function test_update_internal_user_password_update_no_cache() {
2755         $this->resetAfterTest();
2757         $user = $this->getDataGenerator()->create_user(array('password' => 'test'));
2758         $this->assertNotEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2759         $user->auth = 'cas'; // Change to a auth that does not store passwords.
2761         $sink = $this->redirectEvents();
2762         update_internal_user_password($user, 'wonkawonka');
2763         $this->assertGreaterThanOrEqual(1, $sink->count(), 'User updated event should fire');
2765         $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2766     }
2768     public function test_fullname() {
2769         global $CFG;
2771         $this->resetAfterTest();
2773         // Create a user to test the name display on.
2774         $record = array();
2775         $record['firstname'] = 'Scott';
2776         $record['lastname'] = 'Fletcher';
2777         $record['firstnamephonetic'] = 'スコット';
2778         $record['lastnamephonetic'] = 'フレチャー';
2779         $record['alternatename'] = 'No friends';
2780         $user = $this->getDataGenerator()->create_user($record);
2782         // Back up config settings for restore later.
2783         $originalcfg = new stdClass();
2784         $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
2785         $originalcfg->alternativefullnameformat = $CFG->alternativefullnameformat;
2787         // Testing existing fullnamedisplay settings.
2788         $CFG->fullnamedisplay = 'firstname';
2789         $testname = fullname($user);
2790         $this->assertSame($user->firstname, $testname);
2792         $CFG->fullnamedisplay = 'firstname lastname';
2793         $expectedname = "$user->firstname $user->lastname";
2794         $testname = fullname($user);
2795         $this->assertSame($expectedname, $testname);
2797         $CFG->fullnamedisplay = 'lastname firstname';
2798         $expectedname = "$user->lastname $user->firstname";
2799         $testname = fullname($user);
2800         $this->assertSame($expectedname, $testname);
2802         $expectedname = get_string('fullnamedisplay', null, $user);
2803         $CFG->fullnamedisplay = 'language';
2804         $testname = fullname($user);
2805         $this->assertSame($expectedname, $testname);
2807         // Test override parameter.
2808         $CFG->fullnamedisplay = 'firstname';
2809         $expectedname = "$user->firstname $user->lastname";
2810         $testname = fullname($user, true);
2811         $this->assertSame($expectedname, $testname);
2813         // Test alternativefullnameformat setting.
2814         // Test alternativefullnameformat that has been set to nothing.
2815         $CFG->alternativefullnameformat = '';
2816         $expectedname = "$user->firstname $user->lastname";
2817         $testname = fullname($user, true);
2818         $this->assertSame($expectedname, $testname);
2820         // Test alternativefullnameformat that has been set to 'language'.
2821         $CFG->alternativefullnameformat = 'language';
2822         $expectedname = "$user->firstname $user->lastname";
2823         $testname = fullname($user, true);
2824         $this->assertSame($expectedname, $testname);
2826         // Test customising the alternativefullnameformat setting with all additional name fields.
2827         $CFG->alternativefullnameformat = 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename';
2828         $expectedname = "$user->firstname $user->lastname $user->firstnamephonetic $user->lastnamephonetic $user->middlename $user->alternatename";
2829         $testname = fullname($user, true);
2830         $this->assertSame($expectedname, $testname);
2832         // Test additional name fields.
2833         $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
2834         $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
2835         $testname = fullname($user);
2836         $this->assertSame($expectedname, $testname);
2838         // Test for handling missing data.
2839         $user->middlename = null;
2840         // Parenthesis with no data.
2841         $CFG->fullnamedisplay = 'firstname (middlename) lastname';
2842         $expectedname = "$user->firstname $user->lastname";
2843         $testname = fullname($user);
2844         $this->assertSame($expectedname, $testname);
2846         // Extra spaces due to no data.
2847         $CFG->fullnamedisplay = 'firstname middlename lastname';
2848         $expectedname = "$user->firstname $user->lastname";
2849         $testname = fullname($user);
2850         $this->assertSame($expectedname, $testname);
2852         // Regular expression testing.
2853         // Remove some data from the user fields.
2854         $user->firstnamephonetic = '';
2855         $user->lastnamephonetic = '';
2857         // Removing empty brackets and excess whitespace.
2858         // All of these configurations should resolve to just firstname lastname.
2859         $configarray = array();
2860         $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
2861         $configarray[] = 'firstname lastname \'middlename\'';
2862         $configarray[] = 'firstname "firstnamephonetic" lastname';
2863         $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
2865         foreach ($configarray as $config) {
2866             $CFG->fullnamedisplay = $config;
2867             $expectedname = "$user->firstname $user->lastname";
2868             $testname = fullname($user);
2869             $this->assertSame($expectedname, $testname);
2870         }
2872         // Check to make sure that other characters are left in place.
2873         $configarray = array();
2874         $configarray['0'] = new stdClass();
2875         $configarray['0']->config = 'lastname firstname, middlename';
2876         $configarray['0']->expectedname = "$user->lastname $user->firstname,";
2877         $configarray['1'] = new stdClass();
2878         $configarray['1']->config = 'lastname firstname + alternatename';
2879         $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
2880         $configarray['2'] = new stdClass();
2881         $configarray['2']->config = 'firstname aka: alternatename';
2882         $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
2883         $configarray['3'] = new stdClass();
2884         $configarray['3']->config = 'firstname (alternatename)';
2885         $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
2886         $configarray['4'] = new stdClass();
2887         $configarray['4']->config = 'firstname [alternatename]';
2888         $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
2889         $configarray['5'] = new stdClass();
2890         $configarray['5']->config = 'firstname "lastname"';
2891         $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
2893         foreach ($configarray as $config) {
2894             $CFG->fullnamedisplay = $config->config;
2895             $expectedname = $config->expectedname;
2896             $testname = fullname($user);
2897             $this->assertSame($expectedname, $testname);
2898         }
2900         // Test debugging message displays when
2901         // fullnamedisplay setting is "normal".
2902         $CFG->fullnamedisplay = 'firstname lastname';
2903         unset($user);
2904         $user = new stdClass();
2905         $user->firstname = 'Stan';
2906         $user->lastname = 'Lee';
2907         $namedisplay = fullname($user);
2908         $this->assertDebuggingCalled();
2910         // Tidy up after we finish testing.
2911         $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
2912         $CFG->alternativefullnameformat = $originalcfg->alternativefullnameformat;
2913     }
2915     public function test_get_all_user_name_fields() {
2916         $this->resetAfterTest();
2918         // Additional names in an array.
2919         $testarray = array('firstnamephonetic' => 'firstnamephonetic',
2920                 'lastnamephonetic' => 'lastnamephonetic',
2921                 'middlename' => 'middlename',
2922                 'alternatename' => 'alternatename',
2923                 'firstname' => 'firstname',
2924                 'lastname' => 'lastname');
2925         $this->assertEquals($testarray, get_all_user_name_fields());
2927         // Additional names as a string.
2928         $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
2929         $this->assertEquals($teststring, get_all_user_name_fields(true));
2931         // Additional names as a string with an alias.
2932         $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
2933         $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
2935         // Additional name fields with a prefix - object.
2936         $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
2937                 'lastnamephonetic' => 'authorlastnamephonetic',
2938                 'middlename' => 'authormiddlename',
2939                 'alternatename' => 'authoralternatename',
2940                 'firstname' => 'authorfirstname',
2941                 'lastname' => 'authorlastname');
2942         $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
2944         // Additional name fields with an alias and a title - string.
2945         $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';
2946         $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
2948         // Test the order parameter of the function.
2949         // Returning an array.
2950         $testarray = array('firstname' => 'firstname',
2951                 'lastname' => 'lastname',
2952                 'firstnamephonetic' => 'firstnamephonetic',
2953                 'lastnamephonetic' => 'lastnamephonetic',
2954                 'middlename' => 'middlename',
2955                 'alternatename' => 'alternatename'
2956         );
2957         $this->assertEquals($testarray, get_all_user_name_fields(false, null, null, null, true));
2959         // Returning a string.
2960         $teststring = 'firstname,lastname,firstnamephonetic,lastnamephonetic,middlename,alternatename';
2961         $this->assertEquals($teststring, get_all_user_name_fields(true, null, null, null, true));
2962     }
2964     public function test_order_in_string() {
2965         $this->resetAfterTest();
2967         // Return an array in an order as they are encountered in a string.
2968         $valuearray = array('second', 'firsthalf', 'first');
2969         $formatstring = 'first firsthalf some other text (second)';
2970         $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
2971         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2973         // Try again with a different order for the format.
2974         $valuearray = array('second', 'firsthalf', 'first');
2975         $formatstring = 'firsthalf first second';
2976         $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
2977         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2979         // Try again with yet another different order for the format.
2980         $valuearray = array('second', 'firsthalf', 'first');
2981         $formatstring = 'start seconds away second firstquater first firsthalf';
2982         $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
2983         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2984     }
2986     public function test_complete_user_login() {
2987         global $USER, $DB;
2989         $this->resetAfterTest();
2990         $user = $this->getDataGenerator()->create_user();
2991         $this->setUser(0);
2993         $sink = $this->redirectEvents();
2994         $loginuser = clone($user);
2995         $this->setCurrentTimeStart();
2996         @complete_user_login($loginuser); // Hide session header errors.
2997         $this->assertSame($loginuser, $USER);
2998         $this->assertEquals($user->id, $USER->id);
2999         $events = $sink->get_events();
3000         $sink->close();
3002         $this->assertCount(1, $events);
3003         $event = reset($events);
3004         $this->assertInstanceOf('\core\event\user_loggedin', $event);
3005         $this->assertEquals('user', $event->objecttable);
3006         $this->assertEquals($user->id, $event->objectid);
3007         $this->assertEquals(context_system::instance()->id, $event->contextid);
3008         $this->assertEventContextNotUsed($event);
3010         $user = $DB->get_record('user', array('id'=>$user->id));
3012         $this->assertTimeCurrent($user->firstaccess);
3013         $this->assertTimeCurrent($user->lastaccess);
3015         $this->assertTimeCurrent($USER->firstaccess);
3016         $this->assertTimeCurrent($USER->lastaccess);
3017         $this->assertTimeCurrent($USER->currentlogin);
3018         $this->assertSame(sesskey(), $USER->sesskey);
3019         $this->assertTimeCurrent($USER->preference['_lastloaded']);
3020         $this->assertObjectNotHasAttribute('password', $USER);
3021         $this->assertObjectNotHasAttribute('description', $USER);
3022     }
3024     /**
3025      * Test require_logout.
3026      */
3027     public function test_require_logout() {
3028         $this->resetAfterTest();
3029         $user = $this->getDataGenerator()->create_user();
3030         $this->setUser($user);
3032         $this->assertTrue(isloggedin());
3034         // Logout user and capture event.
3035         $sink = $this->redirectEvents();
3036         require_logout();
3037         $events = $sink->get_events();
3038         $sink->close();
3039         $event = array_pop($events);
3041         // Check if user is logged out.
3042         $this->assertFalse(isloggedin());
3044         // Test Event.
3045         $this->assertInstanceOf('\core\event\user_loggedout', $event);
3046         $this->assertSame($user->id, $event->objectid);
3047         $this->assertSame('user_logout', $event->get_legacy_eventname());
3048         $this->assertEventLegacyData($user, $event);
3049         $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
3050             $event->objectid);
3051         $this->assertEventLegacyLogData($expectedlogdata, $event);
3052         $this->assertEventContextNotUsed($event);
3053     }
3055     /**
3056      * A data provider for testing email messageid
3057      */
3058     public function generate_email_messageid_provider() {
3059         return array(
3060             'nopath' => array(
3061                 'wwwroot' => 'http://www.example.com',
3062                 'ids' => array(
3063                     'a-custom-id' => '<a-custom-id@www.example.com>',
3064                     'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash@www.example.com>',
3065                 ),
3066             ),
3067             'path' => array(
3068                 'wwwroot' => 'http://www.example.com/path/subdir',
3069                 'ids' => array(
3070                     'a-custom-id' => '<a-custom-id/path/subdir@www.example.com>',
3071                     'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash/path/subdir@www.example.com>',
3072                 ),
3073             ),
3074         );
3075     }
3077     /**
3078      * Test email message id generation
3079      *
3080      * @dataProvider generate_email_messageid_provider
3081      *
3082      * @param string $wwwroot The wwwroot
3083      * @param array $msgids An array of msgid local parts and the final result
3084      */
3085     public function test_generate_email_messageid($wwwroot, $msgids) {
3086         global $CFG;
3088         $this->resetAfterTest();
3089         $CFG->wwwroot = $wwwroot;
3091         foreach ($msgids as $local => $final) {
3092             $this->assertEquals($final, generate_email_messageid($local));
3093         }
3094     }
3096     /**
3097      * A data provider for testing email diversion
3098      */
3099     public function diverted_emails_provider() {
3100         return array(
3101             'nodiverts' => array(
3102                 'divertallemailsto' => null,
3103                 'divertallemailsexcept' => null,
3104                 array(
3105                     'foo@example.com',
3106                     'test@real.com',
3107                     'fred.jones@example.com',
3108                     'dev1@dev.com',
3109                     'fred@example.com',
3110                     'fred+verp@example.com',
3111                 ),
3112                 false,
3113             ),
3114             'alldiverts' => array(
3115                 'divertallemailsto' => 'somewhere@elsewhere.com',
3116                 'divertallemailsexcept' => null,
3117                 array(
3118                     'foo@example.com',
3119                     'test@real.com',
3120                     'fred.jones@example.com',
3121                     'dev1@dev.com',
3122                     'fred@example.com',
3123                     'fred+verp@example.com',
3124                 ),
3125                 true,
3126             ),
3127             'alsodiverts' => array(
3128                 'divertallemailsto' => 'somewhere@elsewhere.com',
3129                 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
3130                 array(
3131                     'foo@example.com',
3132                     'test@real.com',
3133                     'fred.jones@example.com',
3134                 ),
3135                 true,
3136             ),
3137             'divertsexceptions' => array(
3138                 'divertallemailsto' => 'somewhere@elsewhere.com',
3139                 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
3140                 array(
3141                     'dev1@dev.com',
3142                     'fred@example.com',
3143                     'fred+verp@example.com',
3144                 ),
3145                 false,
3146             ),
3147         );
3148     }
3150     /**
3151      * Test email diversion
3152      *
3153      * @dataProvider diverted_emails_provider
3154      *
3155      * @param string $divertallemailsto An optional email address
3156      * @param string $divertallemailsexcept An optional exclusion list
3157      * @param array $addresses An array of test addresses
3158      * @param boolean $expected Expected result
3159      */
3160     public function test_email_should_be_diverted($divertallemailsto, $divertallemailsexcept, $addresses, $expected) {
3161         global $CFG;
3163         $this->resetAfterTest();
3164         $CFG->divertallemailsto = $divertallemailsto;
3165         $CFG->divertallemailsexcept = $divertallemailsexcept;
3167         foreach ($addresses as $address) {
3168             $this->assertEquals($expected, email_should_be_diverted($address));
3169         }
3170     }
3172     public function test_email_to_user() {
3173         global $CFG;
3175         $this->resetAfterTest();
3177         $user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
3178         $user2 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
3179         $user3 = $this->getDataGenerator()->create_user(array('maildisplay' => 0));
3180         set_config('allowedemaildomains', "example.com\r\nmoodle.org");
3182         $subject = 'subject';
3183         $messagetext = 'message text';
3184         $subject2 = 'subject 2';
3185         $messagetext2 = 'message text 2';
3187         // Close the default email sink.
3188         $sink = $this->redirectEmails();
3189         $sink->close();
3191         $CFG->noemailever = true;
3192         $this->assertNotEmpty($CFG->noemailever);
3193         email_to_user($user1, $user2, $subject, $messagetext);
3194         $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
3196         unset_config('noemailever');
3198         email_to_user($user1, $user2, $subject, $messagetext);
3199         $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
3201         $sink = $this->redirectEmails();
3202         email_to_user($user1, $user2, $subject, $messagetext);
3203         email_to_user($user2, $user1, $subject2, $messagetext2);
3204         $this->assertSame(2, $sink->count());
3205         $result = $sink->get_messages();
3206         $this->assertCount(2, $result);
3207         $sink->close();
3209         $this->assertSame($subject, $result[0]->subject);
3210         $this->assertSame($messagetext, trim($result[0]->body));
3211         $this->assertSame($user1->email, $result[0]->to);
3212         $this->assertSame($user2->email, $result[0]->from);
3214         $this->assertSame($subject2, $result[1]->subject);
3215         $this->assertSame($messagetext2, trim($result[1]->body));
3216         $this->assertSame($user2->email, $result[1]->to);
3217         $this->assertSame($user1->email, $result[1]->from);
3219         email_to_user($user1, $user2, $subject, $messagetext);
3220         $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
3222         // Test that an empty noreplyaddress will default to a no-reply address.
3223         $sink = $this->redirectEmails();
3224         email_to_user($user1, $user3, $subject, $messagetext);
3225         $result = $sink->get_messages();
3226         $this->assertEquals($CFG->noreplyaddress, $result[0]->from);
3227         $sink->close();
3228         set_config('noreplyaddress', '');
3229         $sink = $this->redirectEmails();
3230         email_to_user($user1, $user3, $subject, $messagetext);
3231         $result = $sink->get_messages();
3232         $this->assertEquals('noreply@www.example.com', $result[0]->from);
3233         $sink->close();
3235         // Test $CFG->allowedemaildomains.
3236         set_config('noreplyaddress', 'noreply@www.example.com');
3237         $this->assertNotEmpty($CFG->allowedemaildomains);