Merge branch 'MDL-29318-master' of git://github.com/junpataleta/moodle
[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                 'expectedoutputhtml' => '<time datetime="2011-07-01T07:00:00-03:00">Friday, 1 July 2011, 10:00 AM</time>'
1719             ),
1720             array(
1721                 'time' => '1309514400',
1722                 'usertimezone' => 'America/Moncton',
1723                 'timezone' => '99', // Dst offset and timezone offset.
1724                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM',
1725                 'expectedoutputhtml' => '<time datetime="2011-07-01T07:00:00-03:00">Friday, 1 July 2011, 7:00 AM</time>'
1726             ),
1727             array(
1728                 'time' => '1309514400',
1729                 'usertimezone' => 'America/Moncton',
1730                 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
1731                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM',
1732                 'expectedoutputhtml' => '<time datetime="2011-07-01t07:00:00-03:00">Friday, 1 July 2011, 7:00 AM</time>'
1733             ),
1734             array(
1735                 'time' => '1293876000 ',
1736                 'usertimezone' => 'America/Moncton',
1737                 'timezone' => '0.0', // No dst offset.
1738                 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM',
1739                 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 10:00 AM</time>'
1740             ),
1741             array(
1742                 'time' => '1293876000 ',
1743                 'usertimezone' => 'America/Moncton',
1744                 'timezone' => '99', // No dst offset in jan, so just timezone offset.
1745                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM',
1746                 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 6:00 AM</time>'
1747             ),
1748             array(
1749                 'time' => '1293876000 ',
1750                 'usertimezone' => 'America/Moncton',
1751                 'timezone' => 'America/Moncton', // No dst offset in jan.
1752                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM',
1753                 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 6:00 AM</time>'
1754             ),
1755             array(
1756                 'time' => '1293876000 ',
1757                 'usertimezone' => '2',
1758                 'timezone' => '99', // Take user timezone.
1759                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM',
1760                 'expectedoutputhtml' => '<time datetime="2011-01-01T12:00:00+02:00">Saturday, 1 January 2011, 12:00 PM</time>'
1761             ),
1762             array(
1763                 'time' => '1293876000 ',
1764                 'usertimezone' => '-2',
1765                 'timezone' => '99', // Take user timezone.
1766                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM',
1767                 'expectedoutputhtml' => '<time datetime="2011-01-01T08:00:00-02:00">Saturday, 1 January 2011, 8:00 AM</time>'
1768             ),
1769             array(
1770                 'time' => '1293876000 ',
1771                 'usertimezone' => '-10',
1772                 'timezone' => '2', // Take this timezone.
1773                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM',
1774                 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 12:00 PM</time>'
1775             ),
1776             array(
1777                 'time' => '1293876000 ',
1778                 'usertimezone' => '-10',
1779                 'timezone' => '-2', // Take this timezone.
1780                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM',
1781                 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 8:00 AM</time>'
1782             ),
1783             array(
1784                 'time' => '1293876000 ',
1785                 'usertimezone' => '-10',
1786                 'timezone' => 'random/time', // This should show server time.
1787                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM',
1788                 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 6:00 PM</time>'
1789             ),
1790             array(
1791                 'time' => '1293876000 ',
1792                 'usertimezone' => '20', // Fallback to server time zone.
1793                 'timezone' => '99',     // This should show user time.
1794                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM',
1795                 'expectedoutputhtml' => '<time datetime="2011-01-01T18:00:00+08:00">Saturday, 1 January 2011, 6:00 PM</time>'
1796             ),
1797         );
1799         // Set default timezone to Australia/Perth, else time calculated
1800         // will not match expected values.
1801         $this->setTimezone(99, 'Australia/Perth');
1803         foreach ($testvalues as $vals) {
1804             $USER->timezone = $vals['usertimezone'];
1805             $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1806             $actualoutputhtml = userdate_htmltime($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1808             // On different systems case of AM PM changes so compare case insensitive.
1809             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1810             $vals['expectedoutputhtml'] = core_text::strtolower($vals['expectedoutputhtml']);
1811             $actualoutput = core_text::strtolower($actualoutput);
1812             $actualoutputhtml = core_text::strtolower($actualoutputhtml);
1814             $this->assertSame($vals['expectedoutput'], $actualoutput,
1815                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput} \ndata: " . var_export($vals, true));
1816             $this->assertSame($vals['expectedoutputhtml'], $actualoutputhtml,
1817                 "Expected: {$vals['expectedoutputhtml']} => Actual: {$actualoutputhtml} \ndata: " . var_export($vals, true));
1818         }
1819     }
1821     /**
1822      * Make sure the DST changes happen at the right time in Moodle.
1823      */
1824     public function test_dst_changes() {
1825         // DST switching in Prague.
1826         // From 2AM to 3AM in 1989.
1827         $date = new DateTime('1989-03-26T01:59:00+01:00');
1828         $this->assertSame('Sunday, 26 March 1989, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1829         $date = new DateTime('1989-03-26T02:01:00+01:00');
1830         $this->assertSame('Sunday, 26 March 1989, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1831         // From 3AM to 2AM in 1989 - not the same as the west Europe.
1832         $date = new DateTime('1989-09-24T01:59:00+01:00');
1833         $this->assertSame('Sunday, 24 September 1989, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1834         $date = new DateTime('1989-09-24T02:01:00+01:00');
1835         $this->assertSame('Sunday, 24 September 1989, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1836         // From 2AM to 3AM in 2014.
1837         $date = new DateTime('2014-03-30T01:59:00+01:00');
1838         $this->assertSame('Sunday, 30 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1839         $date = new DateTime('2014-03-30T02:01:00+01:00');
1840         $this->assertSame('Sunday, 30 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1841         // From 3AM to 2AM in 2014.
1842         $date = new DateTime('2014-10-26T01:59:00+01:00');
1843         $this->assertSame('Sunday, 26 October 2014, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1844         $date = new DateTime('2014-10-26T02:01:00+01:00');
1845         $this->assertSame('Sunday, 26 October 2014, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1846         // From 2AM to 3AM in 2020.
1847         $date = new DateTime('2020-03-29T01:59:00+01:00');
1848         $this->assertSame('Sunday, 29 March 2020, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1849         $date = new DateTime('2020-03-29T02:01:00+01:00');
1850         $this->assertSame('Sunday, 29 March 2020, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1851         // From 3AM to 2AM in 2020.
1852         $date = new DateTime('2020-10-25T01:59:00+01:00');
1853         $this->assertSame('Sunday, 25 October 2020, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1854         $date = new DateTime('2020-10-25T02:01:00+01:00');
1855         $this->assertSame('Sunday, 25 October 2020, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1857         // DST switching in NZ.
1858         // From 3AM to 2AM in 2015.
1859         $date = new DateTime('2015-04-05T02:59:00+13:00');
1860         $this->assertSame('Sunday, 5 April 2015, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1861         $date = new DateTime('2015-04-05T03:01:00+13:00');
1862         $this->assertSame('Sunday, 5 April 2015, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1863         // From 2AM to 3AM in 2009.
1864         $date = new DateTime('2015-09-27T01:59:00+12:00');
1865         $this->assertSame('Sunday, 27 September 2015, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1866         $date = new DateTime('2015-09-27T02:01:00+12:00');
1867         $this->assertSame('Sunday, 27 September 2015, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1869         // DST switching in Perth.
1870         // From 3AM to 2AM in 2009.
1871         $date = new DateTime('2008-03-30T01:59:00+08:00');
1872         $this->assertSame('Sunday, 30 March 2008, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1873         $date = new DateTime('2008-03-30T02:01:00+08:00');
1874         $this->assertSame('Sunday, 30 March 2008, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1875         // From 2AM to 3AM in 2009.
1876         $date = new DateTime('2008-10-26T01:59:00+08:00');
1877         $this->assertSame('Sunday, 26 October 2008, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1878         $date = new DateTime('2008-10-26T02:01:00+08:00');
1879         $this->assertSame('Sunday, 26 October 2008, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1881         // DST switching in US.
1882         // From 2AM to 3AM in 2014.
1883         $date = new DateTime('2014-03-09T01:59:00-05:00');
1884         $this->assertSame('Sunday, 9 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1885         $date = new DateTime('2014-03-09T02:01:00-05:00');
1886         $this->assertSame('Sunday, 9 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1887         // From 3AM to 2AM in 2014.
1888         $date = new DateTime('2014-11-02T01:59:00-04:00');
1889         $this->assertSame('Sunday, 2 November 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1890         $date = new DateTime('2014-11-02T02:01:00-04:00');
1891         $this->assertSame('Sunday, 2 November 2014, 01:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1892     }
1894     public function test_make_timestamp() {
1895         global $USER, $CFG, $DB;
1896         $this->resetAfterTest();
1898         $this->setAdminUser();
1900         $testvalues = array(
1901             array(
1902                 'usertimezone' => 'America/Moncton',
1903                 'year' => '2011',
1904                 'month' => '7',
1905                 'day' => '1',
1906                 'hour' => '10',
1907                 'minutes' => '00',
1908                 'seconds' => '00',
1909                 'timezone' => '0.0',
1910                 'applydst' => false, // No dst offset.
1911                 'expectedoutput' => '1309514400' // 6pm at UTC+0.
1912             ),
1913             array(
1914                 'usertimezone' => 'America/Moncton',
1915                 'year' => '2011',
1916                 'month' => '7',
1917                 'day' => '1',
1918                 'hour' => '10',
1919                 'minutes' => '00',
1920                 'seconds' => '00',
1921                 'timezone' => '99',  // User default timezone.
1922                 'applydst' => false, // Don't apply dst.
1923                 'expectedoutput' => '1309528800'
1924             ),
1925             array(
1926                 'usertimezone' => 'America/Moncton',
1927                 'year' => '2011',
1928                 'month' => '7',
1929                 'day' => '1',
1930                 'hour' => '10',
1931                 'minutes' => '00',
1932                 'seconds' => '00',
1933                 'timezone' => '99', // User default timezone.
1934                 'applydst' => true, // Apply dst.
1935                 'expectedoutput' => '1309525200'
1936             ),
1937             array(
1938                 'usertimezone' => 'America/Moncton',
1939                 'year' => '2011',
1940                 'month' => '7',
1941                 'day' => '1',
1942                 'hour' => '10',
1943                 'minutes' => '00',
1944                 'seconds' => '00',
1945                 'timezone' => 'America/Moncton', // String timezone.
1946                 'applydst' => true, // Apply dst.
1947                 'expectedoutput' => '1309525200'
1948             ),
1949             array(
1950                 'usertimezone' => '2', // No dst applyed.
1951                 'year' => '2011',
1952                 'month' => '7',
1953                 'day' => '1',
1954                 'hour' => '10',
1955                 'minutes' => '00',
1956                 'seconds' => '00',
1957                 'timezone' => '99', // Take user timezone.
1958                 'applydst' => true, // Apply dst.
1959                 'expectedoutput' => '1309507200'
1960             ),
1961             array(
1962                 'usertimezone' => '-2', // No dst applyed.
1963                 'year' => '2011',
1964                 'month' => '7',
1965                 'day' => '1',
1966                 'hour' => '10',
1967                 'minutes' => '00',
1968                 'seconds' => '00',
1969                 'timezone' => '99', // Take usertimezone.
1970                 'applydst' => true, // Apply dst.
1971                 'expectedoutput' => '1309521600'
1972             ),
1973             array(
1974                 'usertimezone' => '-10', // No dst applyed.
1975                 'year' => '2011',
1976                 'month' => '7',
1977                 'day' => '1',
1978                 'hour' => '10',
1979                 'minutes' => '00',
1980                 'seconds' => '00',
1981                 'timezone' => '2',  // Take this timezone.
1982                 'applydst' => true, // Apply dst.
1983                 'expectedoutput' => '1309507200'
1984             ),
1985             array(
1986                 'usertimezone' => '-10', // No dst applyed.
1987                 'year' => '2011',
1988                 'month' => '7',
1989                 'day' => '1',
1990                 'hour' => '10',
1991                 'minutes' => '00',
1992                 'seconds' => '00',
1993                 'timezone' => '-2', // Take this timezone.
1994                 'applydst' => true, // Apply dst.
1995                 'expectedoutput' => '1309521600'
1996             ),
1997             array(
1998                 'usertimezone' => '-10', // No dst applyed.
1999                 'year' => '2011',
2000                 'month' => '7',
2001                 'day' => '1',
2002                 'hour' => '10',
2003                 'minutes' => '00',
2004                 'seconds' => '00',
2005                 'timezone' => 'random/time', // This should show server time.
2006                 'applydst' => true,          // Apply dst.
2007                 'expectedoutput' => '1309485600'
2008             ),
2009             array(
2010                 'usertimezone' => '-14', // Server time.
2011                 'year' => '2011',
2012                 'month' => '7',
2013                 'day' => '1',
2014                 'hour' => '10',
2015                 'minutes' => '00',
2016                 'seconds' => '00',
2017                 'timezone' => '99', // Get user time.
2018                 'applydst' => true, // Apply dst.
2019                 'expectedoutput' => '1309485600'
2020             )
2021         );
2023         // Set default timezone to Australia/Perth, else time calculated
2024         // will not match expected values.
2025         $this->setTimezone(99, 'Australia/Perth');
2027         // Test make_timestamp with all testvals and assert if anything wrong.
2028         foreach ($testvalues as $vals) {
2029             $USER->timezone = $vals['usertimezone'];
2030             $actualoutput = make_timestamp(
2031                 $vals['year'],
2032                 $vals['month'],
2033                 $vals['day'],
2034                 $vals['hour'],
2035                 $vals['minutes'],
2036                 $vals['seconds'],
2037                 $vals['timezone'],
2038                 $vals['applydst']
2039             );
2041             // On different systems case of AM PM changes so compare case insensitive.
2042             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
2043             $actualoutput = core_text::strtolower($actualoutput);
2045             $this->assertSame($vals['expectedoutput'], $actualoutput,
2046                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
2047                 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
2048         }
2049     }
2051     /**
2052      * Test get_string and most importantly the implementation of the lang_string
2053      * object.
2054      */
2055     public function test_get_string() {
2056         global $COURSE;
2058         // Make sure we are using English.
2059         $originallang = $COURSE->lang;
2060         $COURSE->lang = 'en';
2062         $yes = get_string('yes');
2063         $yesexpected = 'Yes';
2064         $this->assertInternalType('string', $yes);
2065         $this->assertSame($yesexpected, $yes);
2067         $yes = get_string('yes', 'moodle');
2068         $this->assertInternalType('string', $yes);
2069         $this->assertSame($yesexpected, $yes);
2071         $yes = get_string('yes', 'core');
2072         $this->assertInternalType('string', $yes);
2073         $this->assertSame($yesexpected, $yes);
2075         $yes = get_string('yes', '');
2076         $this->assertInternalType('string', $yes);
2077         $this->assertSame($yesexpected, $yes);
2079         $yes = get_string('yes', null);
2080         $this->assertInternalType('string', $yes);
2081         $this->assertSame($yesexpected, $yes);
2083         $yes = get_string('yes', null, 1);
2084         $this->assertInternalType('string', $yes);
2085         $this->assertSame($yesexpected, $yes);
2087         $days = 1;
2088         $numdays = get_string('numdays', 'core', '1');
2089         $numdaysexpected = $days.' days';
2090         $this->assertInternalType('string', $numdays);
2091         $this->assertSame($numdaysexpected, $numdays);
2093         $yes = get_string('yes', null, null, true);
2094         $this->assertInstanceOf('lang_string', $yes);
2095         $this->assertSame($yesexpected, (string)$yes);
2097         // Test using a lang_string object as the $a argument for a normal
2098         // get_string call (returning string).
2099         $test = new lang_string('yes', null, null, true);
2100         $testexpected = get_string('numdays', 'core', get_string('yes'));
2101         $testresult = get_string('numdays', null, $test);
2102         $this->assertInternalType('string', $testresult);
2103         $this->assertSame($testexpected, $testresult);
2105         // Test using a lang_string object as the $a argument for an object
2106         // get_string call (returning lang_string).
2107         $test = new lang_string('yes', null, null, true);
2108         $testexpected = get_string('numdays', 'core', get_string('yes'));
2109         $testresult = get_string('numdays', null, $test, true);
2110         $this->assertInstanceOf('lang_string', $testresult);
2111         $this->assertSame($testexpected, "$testresult");
2113         // Make sure that object properties that can't be converted don't cause
2114         // errors.
2115         // Level one: This is as deep as current language processing goes.
2116         $test = new stdClass;
2117         $test->one = 'here';
2118         $string = get_string('yes', null, $test, true);
2119         $this->assertEquals($yesexpected, $string);
2121         // Make sure that object properties that can't be converted don't cause
2122         // errors.
2123         // Level two: Language processing doesn't currently reach this deep.
2124         // only immediate scalar properties are worked with.
2125         $test = new stdClass;
2126         $test->one = new stdClass;
2127         $test->one->two = 'here';
2128         $string = get_string('yes', null, $test, true);
2129         $this->assertEquals($yesexpected, $string);
2131         // Make sure that object properties that can't be converted don't cause
2132         // errors.
2133         // Level three: It should never ever go this deep, but we're making sure
2134         // it doesn't cause any probs anyway.
2135         $test = new stdClass;
2136         $test->one = new stdClass;
2137         $test->one->two = new stdClass;
2138         $test->one->two->three = 'here';
2139         $string = get_string('yes', null, $test, true);
2140         $this->assertEquals($yesexpected, $string);
2142         // Make sure that object properties that can't be converted don't cause
2143         // errors and check lang_string properties.
2144         // Level one: This is as deep as current language processing goes.
2145         $test = new stdClass;
2146         $test->one = new lang_string('yes');
2147         $string = get_string('yes', null, $test, true);
2148         $this->assertEquals($yesexpected, $string);
2150         // Make sure that object properties that can't be converted don't cause
2151         // errors and check lang_string properties.
2152         // Level two: Language processing doesn't currently reach this deep.
2153         // only immediate scalar properties are worked with.
2154         $test = new stdClass;
2155         $test->one = new stdClass;
2156         $test->one->two = new lang_string('yes');
2157         $string = get_string('yes', null, $test, true);
2158         $this->assertEquals($yesexpected, $string);
2160         // Make sure that object properties that can't be converted don't cause
2161         // errors and check lang_string properties.
2162         // Level three: It should never ever go this deep, but we're making sure
2163         // it doesn't cause any probs anyway.
2164         $test = new stdClass;
2165         $test->one = new stdClass;
2166         $test->one->two = new stdClass;
2167         $test->one->two->three = new lang_string('yes');
2168         $string = get_string('yes', null, $test, true);
2169         $this->assertEquals($yesexpected, $string);
2171         // Make sure that array properties that can't be converted don't cause
2172         // errors.
2173         $test = array();
2174         $test['one'] = new stdClass;
2175         $test['one']->two = 'here';
2176         $string = get_string('yes', null, $test, true);
2177         $this->assertEquals($yesexpected, $string);
2179         // Same thing but as above except using an object... this is allowed :P.
2180         $string = get_string('yes', null, null, true);
2181         $object = new stdClass;
2182         $object->$string = 'Yes';
2183         $this->assertEquals($yesexpected, $string);
2184         $this->assertEquals($yesexpected, $object->$string);
2186         // Reset the language.
2187         $COURSE->lang = $originallang;
2188     }
2190     /**
2191      * @expectedException PHPUnit\Framework\Error\Warning
2192      */
2193     public function test_get_string_limitation() {
2194         // This is one of the limitations to the lang_string class. It can't be
2195         // used as a key.
2196         $array = array(get_string('yes', null, null, true) => 'yes');
2197     }
2199     /**
2200      * Test localised float formatting.
2201      */
2202     public function test_format_float() {
2204         // Special case for null.
2205         $this->assertEquals('', format_float(null));
2207         // Default 1 decimal place.
2208         $this->assertEquals('5.4', format_float(5.43));
2209         $this->assertEquals('5.0', format_float(5.001));
2211         // Custom number of decimal places.
2212         $this->assertEquals('5.43000', format_float(5.43, 5));
2214         // Option to strip ending zeros after rounding.
2215         $this->assertEquals('5.43', format_float(5.43, 5, true, true));
2216         $this->assertEquals('5', format_float(5.0001, 3, true, true));
2218         // Tests with a localised decimal separator.
2219         $this->define_local_decimal_separator();
2221         // Localisation on (default).
2222         $this->assertEquals('5X43000', format_float(5.43, 5));
2223         $this->assertEquals('5X43', format_float(5.43, 5, true, true));
2225         // Localisation off.
2226         $this->assertEquals('5.43000', format_float(5.43, 5, false));
2227         $this->assertEquals('5.43', format_float(5.43, 5, false, true));
2228     }
2230     /**
2231      * Test localised float unformatting.
2232      */
2233     public function test_unformat_float() {
2235         // Tests without the localised decimal separator.
2237         // Special case for null, empty or white spaces only strings.
2238         $this->assertEquals(null, unformat_float(null));
2239         $this->assertEquals(null, unformat_float(''));
2240         $this->assertEquals(null, unformat_float('    '));
2242         // Regular use.
2243         $this->assertEquals(5.4, unformat_float('5.4'));
2244         $this->assertEquals(5.4, unformat_float('5.4', true));
2246         // No decimal.
2247         $this->assertEquals(5.0, unformat_float('5'));
2249         // Custom number of decimal.
2250         $this->assertEquals(5.43267, unformat_float('5.43267'));
2252         // Empty decimal.
2253         $this->assertEquals(100.0, unformat_float('100.00'));
2255         // With the thousand separator.
2256         $this->assertEquals(1000.0, unformat_float('1 000'));
2257         $this->assertEquals(1000.32, unformat_float('1 000.32'));
2259         // Negative number.
2260         $this->assertEquals(-100.0, unformat_float('-100'));
2262         // Wrong value.
2263         $this->assertEquals(0.0, unformat_float('Wrong value'));
2264         // Wrong value in strict mode.
2265         $this->assertFalse(unformat_float('Wrong value', true));
2267         // Combining options.
2268         $this->assertEquals(-1023.862567, unformat_float('   -1 023.862567     '));
2270         // Bad decimal separator (should crop the decimal).
2271         $this->assertEquals(50.0, unformat_float('50,57'));
2272         // Bad decimal separator in strict mode (should return false).
2273         $this->assertFalse(unformat_float('50,57', true));
2275         // Tests with a localised decimal separator.
2276         $this->define_local_decimal_separator();
2278         // We repeat the tests above but with the current decimal separator.
2280         // Regular use without and with the localised separator.
2281         $this->assertEquals (5.4, unformat_float('5.4'));
2282         $this->assertEquals (5.4, unformat_float('5X4'));
2284         // Custom number of decimal.
2285         $this->assertEquals (5.43267, unformat_float('5X43267'));
2287         // Empty decimal.
2288         $this->assertEquals (100.0, unformat_float('100X00'));
2290         // With the thousand separator.
2291         $this->assertEquals (1000.32, unformat_float('1 000X32'));
2293         // Bad different separator (should crop the decimal).
2294         $this->assertEquals (50.0, unformat_float('50Y57'));
2295         // Bad different separator in strict mode (should return false).
2296         $this->assertFalse (unformat_float('50Y57', true));
2298         // Combining options.
2299         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     '));
2300         // Combining options in strict mode.
2301         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     ', true));
2302     }
2304     /**
2305      * Test deleting of users.
2306      */
2307     public function test_delete_user() {
2308         global $DB, $CFG;
2310         $this->resetAfterTest();
2312         $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
2313         $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
2314         $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
2316         $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
2317         $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
2318         $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
2319         $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
2320         $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => ''));
2321         $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => ''));
2323         // Delete user and capture event.
2324         $sink = $this->redirectEvents();
2325         $result = delete_user($user);
2326         $events = $sink->get_events();
2327         $sink->close();
2328         $event = array_pop($events);
2330         // Test user is deleted in DB.
2331         $this->assertTrue($result);
2332         $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
2333         $this->assertEquals(1, $deluser->deleted);
2334         $this->assertEquals(0, $deluser->picture);
2335         $this->assertSame('', $deluser->idnumber);
2336         $this->assertSame(md5($user->username), $deluser->email);
2337         $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
2339         $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
2341         // Test Event.
2342         $this->assertInstanceOf('\core\event\user_deleted', $event);
2343         $this->assertSame($user->id, $event->objectid);
2344         $this->assertSame('user_deleted', $event->get_legacy_eventname());
2345         $this->assertEventLegacyData($user, $event);
2346         $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
2347         $this->assertEventLegacyLogData($expectedlogdata, $event);
2348         $eventdata = $event->get_data();
2349         $this->assertSame($eventdata['other']['username'], $user->username);
2350         $this->assertSame($eventdata['other']['email'], $user->email);
2351         $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
2352         $this->assertSame($eventdata['other']['picture'], $user->picture);
2353         $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
2354         $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
2355         $this->assertEventContextNotUsed($event);
2357         // Try invalid params.
2358         $record = new stdClass();
2359         $record->grrr = 1;
2360         try {
2361             delete_user($record);
2362             $this->fail('Expecting exception for invalid delete_user() $user parameter');
2363         } catch (moodle_exception $ex) {
2364             $this->assertInstanceOf('coding_exception', $ex);
2365         }
2366         $record->id = 1;
2367         try {
2368             delete_user($record);
2369             $this->fail('Expecting exception for invalid delete_user() $user parameter');
2370         } catch (moodle_exception $ex) {
2371             $this->assertInstanceOf('coding_exception', $ex);
2372         }
2374         $record = new stdClass();
2375         $record->id = 666;
2376         $record->username = 'xx';
2377         $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
2378         $result = delete_user($record);
2379         $this->assertFalse($result);
2381         $result = delete_user($guest);
2382         $this->assertFalse($result);
2384         $result = delete_user($admin);
2385         $this->assertFalse($result);
2387         // Simultaneously deleting users with identical email addresses.
2388         $result1 = delete_user($usersharedemail1);
2389         $result2 = delete_user($usersharedemail2);
2391         $usersharedemail1after = $DB->get_record('user', array('id' => $usersharedemail1->id));
2392         $usersharedemail2after = $DB->get_record('user', array('id' => $usersharedemail2->id));
2393         $this->assertTrue($result1);
2394         $this->assertTrue($result2);
2395         $this->assertStringStartsWith($usersharedemail1->email . '.', $usersharedemail1after->username);
2396         $this->assertStringStartsWith($usersharedemail2->email . '.', $usersharedemail2after->username);
2398         // Simultaneously deleting users without email addresses.
2399         $result1 = delete_user($useremptyemail1);
2400         $result2 = delete_user($useremptyemail2);
2402         $useremptyemail1after = $DB->get_record('user', array('id' => $useremptyemail1->id));
2403         $useremptyemail2after = $DB->get_record('user', array('id' => $useremptyemail2->id));
2404         $this->assertTrue($result1);
2405         $this->assertTrue($result2);
2406         $this->assertStringStartsWith($useremptyemail1->username . '.' . $useremptyemail1->id . '@unknownemail.invalid.',
2407             $useremptyemail1after->username);
2408         $this->assertStringStartsWith($useremptyemail2->username . '.' . $useremptyemail2->id . '@unknownemail.invalid.',
2409             $useremptyemail2after->username);
2411         $this->resetDebugging();
2412     }
2414     /**
2415      * Test function convert_to_array()
2416      */
2417     public function test_convert_to_array() {
2418         // Check that normal classes are converted to arrays the same way as (array) would do.
2419         $obj = new stdClass();
2420         $obj->prop1 = 'hello';
2421         $obj->prop2 = array('first', 'second', 13);
2422         $obj->prop3 = 15;
2423         $this->assertEquals(convert_to_array($obj), (array)$obj);
2425         // Check that context object (with iterator) is converted to array properly.
2426         $obj = context_system::instance();
2427         $ar = array(
2428             'id'           => $obj->id,
2429             'contextlevel' => $obj->contextlevel,
2430             'instanceid'   => $obj->instanceid,
2431             'path'         => $obj->path,
2432             'depth'        => $obj->depth,
2433             'locked'       => $obj->locked,
2434         );
2435         $this->assertEquals(convert_to_array($obj), $ar);
2436     }
2438     /**
2439      * Test the function date_format_string().
2440      */
2441     public function test_date_format_string() {
2442         global $CFG;
2444         $this->resetAfterTest();
2445         $this->setTimezone(99, 'Australia/Perth');
2447         $tests = array(
2448             array(
2449                 'tz' => 99,
2450                 'str' => '%A, %d %B %Y, %I:%M %p',
2451                 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
2452             ),
2453             array(
2454                 'tz' => 0,
2455                 'str' => '%A, %d %B %Y, %I:%M %p',
2456                 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2457             ),
2458             array(
2459                 // Note: this function expected the timestamp in weird format before,
2460                 // since 2.9 it uses UTC.
2461                 'tz' => 'Pacific/Auckland',
2462                 'str' => '%A, %d %B %Y, %I:%M %p',
2463                 'expected' => 'Saturday, 01 January 2011, 11:00 PM'
2464             ),
2465             // Following tests pass on Windows only because en lang pack does
2466             // not contain localewincharset, in real life lang pack maintainers
2467             // may use only characters that are present in localewincharset
2468             // in format strings!
2469             array(
2470                 'tz' => 99,
2471                 'str' => 'Žluťoučký koníček %A',
2472                 'expected' => 'Žluťoučký koníček Saturday'
2473             ),
2474             array(
2475                 'tz' => 99,
2476                 'str' => '言語設定言語 %A',
2477                 'expected' => '言語設定言語 Saturday'
2478             ),
2479             array(
2480                 'tz' => 99,
2481                 'str' => '简体中文简体 %A',
2482                 'expected' => '简体中文简体 Saturday'
2483             ),
2484         );
2486         // Note: date_format_string() uses the timezone only to differenciate
2487         // the server time from the UTC time. It does not modify the timestamp.
2488         // Hence similar results for timezones <= 13.
2489         // On different systems case of AM PM changes so compare case insensitive.
2490         foreach ($tests as $test) {
2491             $str = date_format_string(1293876000, $test['str'], $test['tz']);
2492             $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
2493         }
2494     }
2496     public function test_get_config() {
2497         global $CFG;
2499         $this->resetAfterTest();
2501         // Preparation.
2502         set_config('phpunit_test_get_config_1', 'test 1');
2503         set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2504         if (!is_array($CFG->config_php_settings)) {
2505             $CFG->config_php_settings = array();
2506         }
2507         $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
2509         if (!is_array($CFG->forced_plugin_settings)) {
2510             $CFG->forced_plugin_settings = array();
2511         }
2512         if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
2513             $CFG->forced_plugin_settings['mod_forum'] = array();
2514         }
2515         $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2516         $CFG->phpunit_test_get_config_5 = 'test 5';
2518         // Testing.
2519         $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
2520         $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2521         $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
2522         $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2523         $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2524         $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2525         $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2527         // Test config we know to exist.
2528         $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
2529         $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2530         $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2531         $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2533         // Test setting a config var that already exists.
2534         set_config('phpunit_test_get_config_1', 'test a');
2535         $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
2536         $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
2538         // Test cache invalidation.
2539         $cache = cache::make('core', 'config');
2540         $this->assertInternalType('array', $cache->get('core'));
2541         $this->assertInternalType('array', $cache->get('mod_forum'));
2542         set_config('phpunit_test_get_config_1', 'test b');
2543         $this->assertFalse($cache->get('core'));
2544         set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2545         $this->assertFalse($cache->get('mod_forum'));
2546     }
2548     public function test_get_max_upload_sizes() {
2549         // Test with very low limits so we are not affected by php upload limits.
2550         // Test activity limit smallest.
2551         $sitebytes = 102400;
2552         $coursebytes = 51200;
2553         $modulebytes = 10240;
2554         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2556         $this->assertSame('Activity upload limit (10KB)', $result['0']);
2557         $this->assertCount(2, $result);
2559         // Test course limit smallest.
2560         $sitebytes = 102400;
2561         $coursebytes = 10240;
2562         $modulebytes = 51200;
2563         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2565         $this->assertSame('Course upload limit (10KB)', $result['0']);
2566         $this->assertCount(2, $result);
2568         // Test site limit smallest.
2569         $sitebytes = 10240;
2570         $coursebytes = 102400;
2571         $modulebytes = 51200;
2572         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2574         $this->assertSame('Site upload limit (10KB)', $result['0']);
2575         $this->assertCount(2, $result);
2577         // Test site limit not set.
2578         $sitebytes = 0;
2579         $coursebytes = 102400;
2580         $modulebytes = 51200;
2581         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2583         $this->assertSame('Activity upload limit (50KB)', $result['0']);
2584         $this->assertCount(3, $result);
2586         $sitebytes = 0;
2587         $coursebytes = 51200;
2588         $modulebytes = 102400;
2589         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2591         $this->assertSame('Course upload limit (50KB)', $result['0']);
2592         $this->assertCount(3, $result);
2594         // Test custom bytes in range.
2595         $sitebytes = 102400;
2596         $coursebytes = 51200;
2597         $modulebytes = 51200;
2598         $custombytes = 10240;
2599         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2601         $this->assertCount(3, $result);
2603         // Test custom bytes in range but non-standard.
2604         $sitebytes = 102400;
2605         $coursebytes = 51200;
2606         $modulebytes = 51200;
2607         $custombytes = 25600;
2608         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2610         $this->assertCount(4, $result);
2612         // Test custom bytes out of range.
2613         $sitebytes = 102400;
2614         $coursebytes = 51200;
2615         $modulebytes = 51200;
2616         $custombytes = 102400;
2617         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2619         $this->assertCount(3, $result);
2621         // Test custom bytes out of range and non-standard.
2622         $sitebytes = 102400;
2623         $coursebytes = 51200;
2624         $modulebytes = 51200;
2625         $custombytes = 256000;
2626         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2628         $this->assertCount(3, $result);
2630         // Test site limit only.
2631         $sitebytes = 51200;
2632         $result = get_max_upload_sizes($sitebytes);
2634         $this->assertSame('Site upload limit (50KB)', $result['0']);
2635         $this->assertSame('50KB', $result['51200']);
2636         $this->assertSame('10KB', $result['10240']);
2637         $this->assertCount(3, $result);
2639         // Test no limit.
2640         $result = get_max_upload_sizes();
2641         $this->assertArrayHasKey('0', $result);
2642         $this->assertArrayHasKey(get_max_upload_file_size(), $result);
2643     }
2645     /**
2646      * Test function password_is_legacy_hash().
2647      */
2648     public function test_password_is_legacy_hash() {
2649         // Well formed md5s should be matched.
2650         foreach (array('some', 'strings', 'to_check!') as $string) {
2651             $md5 = md5($string);
2652             $this->assertTrue(password_is_legacy_hash($md5));
2653         }
2654         // Strings that are not md5s should not be matched.
2655         foreach (array('', AUTH_PASSWORD_NOT_CACHED, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
2656             $this->assertFalse(password_is_legacy_hash($notmd5));
2657         }
2658     }
2660     /**
2661      * Test function validate_internal_user_password().
2662      */
2663     public function test_validate_internal_user_password() {
2664         // Test bcrypt hashes.
2665         $validhashes = array(
2666             'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2667             'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2668             'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2669             'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
2670         );
2672         foreach ($validhashes as $password => $hash) {
2673             $user = new stdClass();
2674             $user->auth = 'manual';
2675             $user->password = $hash;
2676             // The correct password should be validated.
2677             $this->assertTrue(validate_internal_user_password($user, $password));
2678             // An incorrect password should not be validated.
2679             $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2680         }
2681     }
2683     /**
2684      * Test function hash_internal_user_password().
2685      */
2686     public function test_hash_internal_user_password() {
2687         $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2689         // Check that some passwords that we convert to hashes can
2690         // be validated.
2691         foreach ($passwords as $password) {
2692             $hash = hash_internal_user_password($password);
2693             $fasthash = hash_internal_user_password($password, true);
2694             $user = new stdClass();
2695             $user->auth = 'manual';
2696             $user->password = $hash;
2697             $this->assertTrue(validate_internal_user_password($user, $password));
2699             // They should not be in md5 format.
2700             $this->assertFalse(password_is_legacy_hash($hash));
2702             // Check that cost factor in hash is correctly set.
2703             $this->assertRegExp('/\$10\$/', $hash);
2704             $this->assertRegExp('/\$04\$/', $fasthash);
2705         }
2706     }
2708     /**
2709      * Test function update_internal_user_password().
2710      */
2711     public function test_update_internal_user_password() {
2712         global $DB;
2713         $this->resetAfterTest();
2714         $passwords = array('password', '1234', 'changeme', '****');
2715         foreach ($passwords as $password) {
2716             $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2717             update_internal_user_password($user, $password);
2718             // The user object should have been updated.
2719             $this->assertTrue(validate_internal_user_password($user, $password));
2720             // The database field for the user should also have been updated to the
2721             // same value.
2722             $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
2723         }
2725         $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2726         // Manually set the user's password to the md5 of the string 'password'.
2727         $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
2729         $sink = $this->redirectEvents();
2730         // Update the password.
2731         update_internal_user_password($user, 'password');
2732         $events = $sink->get_events();
2733         $sink->close();
2734         $event = array_pop($events);
2736         // Password should have been updated to a bcrypt hash.
2737         $this->assertFalse(password_is_legacy_hash($user->password));
2739         // Verify event information.
2740         $this->assertInstanceOf('\core\event\user_password_updated', $event);
2741         $this->assertSame($user->id, $event->relateduserid);
2742         $this->assertEquals(context_user::instance($user->id), $event->get_context());
2743         $this->assertEventContextNotUsed($event);
2745         // Verify recovery of property 'auth'.
2746         unset($user->auth);
2747         update_internal_user_password($user, 'newpassword');
2748         $this->assertDebuggingCalled('User record in update_internal_user_password() must include field auth',
2749                 DEBUG_DEVELOPER);
2750         $this->assertEquals('manual', $user->auth);
2751     }
2753     /**
2754      * Testing that if the password is not cached, that it does not update
2755      * the user table and fire event.
2756      */
2757     public function test_update_internal_user_password_no_cache() {
2758         $this->resetAfterTest();
2760         $user = $this->getDataGenerator()->create_user(array('auth' => 'cas'));
2761         $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2763         $sink = $this->redirectEvents();
2764         update_internal_user_password($user, 'wonkawonka');
2765         $this->assertEquals(0, $sink->count(), 'User updated event should not fire');
2766     }
2768     /**
2769      * Test if the user has a password hash, but now their auth method
2770      * says not to cache it.  Then it should update.
2771      */
2772     public function test_update_internal_user_password_update_no_cache() {
2773         $this->resetAfterTest();
2775         $user = $this->getDataGenerator()->create_user(array('password' => 'test'));
2776         $this->assertNotEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2777         $user->auth = 'cas'; // Change to a auth that does not store passwords.
2779         $sink = $this->redirectEvents();
2780         update_internal_user_password($user, 'wonkawonka');
2781         $this->assertGreaterThanOrEqual(1, $sink->count(), 'User updated event should fire');
2783         $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2784     }
2786     public function test_fullname() {
2787         global $CFG;
2789         $this->resetAfterTest();
2791         // Create a user to test the name display on.
2792         $record = array();
2793         $record['firstname'] = 'Scott';
2794         $record['lastname'] = 'Fletcher';
2795         $record['firstnamephonetic'] = 'スコット';
2796         $record['lastnamephonetic'] = 'フレチャー';
2797         $record['alternatename'] = 'No friends';
2798         $user = $this->getDataGenerator()->create_user($record);
2800         // Back up config settings for restore later.
2801         $originalcfg = new stdClass();
2802         $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
2803         $originalcfg->alternativefullnameformat = $CFG->alternativefullnameformat;
2805         // Testing existing fullnamedisplay settings.
2806         $CFG->fullnamedisplay = 'firstname';
2807         $testname = fullname($user);
2808         $this->assertSame($user->firstname, $testname);
2810         $CFG->fullnamedisplay = 'firstname lastname';
2811         $expectedname = "$user->firstname $user->lastname";
2812         $testname = fullname($user);
2813         $this->assertSame($expectedname, $testname);
2815         $CFG->fullnamedisplay = 'lastname firstname';
2816         $expectedname = "$user->lastname $user->firstname";
2817         $testname = fullname($user);
2818         $this->assertSame($expectedname, $testname);
2820         $expectedname = get_string('fullnamedisplay', null, $user);
2821         $CFG->fullnamedisplay = 'language';
2822         $testname = fullname($user);
2823         $this->assertSame($expectedname, $testname);
2825         // Test override parameter.
2826         $CFG->fullnamedisplay = 'firstname';
2827         $expectedname = "$user->firstname $user->lastname";
2828         $testname = fullname($user, true);
2829         $this->assertSame($expectedname, $testname);
2831         // Test alternativefullnameformat setting.
2832         // Test alternativefullnameformat that has been set to nothing.
2833         $CFG->alternativefullnameformat = '';
2834         $expectedname = "$user->firstname $user->lastname";
2835         $testname = fullname($user, true);
2836         $this->assertSame($expectedname, $testname);
2838         // Test alternativefullnameformat that has been set to 'language'.
2839         $CFG->alternativefullnameformat = 'language';
2840         $expectedname = "$user->firstname $user->lastname";
2841         $testname = fullname($user, true);
2842         $this->assertSame($expectedname, $testname);
2844         // Test customising the alternativefullnameformat setting with all additional name fields.
2845         $CFG->alternativefullnameformat = 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename';
2846         $expectedname = "$user->firstname $user->lastname $user->firstnamephonetic $user->lastnamephonetic $user->middlename $user->alternatename";
2847         $testname = fullname($user, true);
2848         $this->assertSame($expectedname, $testname);
2850         // Test additional name fields.
2851         $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
2852         $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
2853         $testname = fullname($user);
2854         $this->assertSame($expectedname, $testname);
2856         // Test for handling missing data.
2857         $user->middlename = null;
2858         // Parenthesis with no data.
2859         $CFG->fullnamedisplay = 'firstname (middlename) lastname';
2860         $expectedname = "$user->firstname $user->lastname";
2861         $testname = fullname($user);
2862         $this->assertSame($expectedname, $testname);
2864         // Extra spaces due to no data.
2865         $CFG->fullnamedisplay = 'firstname middlename lastname';
2866         $expectedname = "$user->firstname $user->lastname";
2867         $testname = fullname($user);
2868         $this->assertSame($expectedname, $testname);
2870         // Regular expression testing.
2871         // Remove some data from the user fields.
2872         $user->firstnamephonetic = '';
2873         $user->lastnamephonetic = '';
2875         // Removing empty brackets and excess whitespace.
2876         // All of these configurations should resolve to just firstname lastname.
2877         $configarray = array();
2878         $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
2879         $configarray[] = 'firstname lastname \'middlename\'';
2880         $configarray[] = 'firstname "firstnamephonetic" lastname';
2881         $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
2883         foreach ($configarray as $config) {
2884             $CFG->fullnamedisplay = $config;
2885             $expectedname = "$user->firstname $user->lastname";
2886             $testname = fullname($user);
2887             $this->assertSame($expectedname, $testname);
2888         }
2890         // Check to make sure that other characters are left in place.
2891         $configarray = array();
2892         $configarray['0'] = new stdClass();
2893         $configarray['0']->config = 'lastname firstname, middlename';
2894         $configarray['0']->expectedname = "$user->lastname $user->firstname,";
2895         $configarray['1'] = new stdClass();
2896         $configarray['1']->config = 'lastname firstname + alternatename';
2897         $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
2898         $configarray['2'] = new stdClass();
2899         $configarray['2']->config = 'firstname aka: alternatename';
2900         $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
2901         $configarray['3'] = new stdClass();
2902         $configarray['3']->config = 'firstname (alternatename)';
2903         $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
2904         $configarray['4'] = new stdClass();
2905         $configarray['4']->config = 'firstname [alternatename]';
2906         $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
2907         $configarray['5'] = new stdClass();
2908         $configarray['5']->config = 'firstname "lastname"';
2909         $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
2911         foreach ($configarray as $config) {
2912             $CFG->fullnamedisplay = $config->config;
2913             $expectedname = $config->expectedname;
2914             $testname = fullname($user);
2915             $this->assertSame($expectedname, $testname);
2916         }
2918         // Test debugging message displays when
2919         // fullnamedisplay setting is "normal".
2920         $CFG->fullnamedisplay = 'firstname lastname';
2921         unset($user);
2922         $user = new stdClass();
2923         $user->firstname = 'Stan';
2924         $user->lastname = 'Lee';
2925         $namedisplay = fullname($user);
2926         $this->assertDebuggingCalled();
2928         // Tidy up after we finish testing.
2929         $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
2930         $CFG->alternativefullnameformat = $originalcfg->alternativefullnameformat;
2931     }
2933     public function test_get_all_user_name_fields() {
2934         $this->resetAfterTest();
2936         // Additional names in an array.
2937         $testarray = array('firstnamephonetic' => 'firstnamephonetic',
2938                 'lastnamephonetic' => 'lastnamephonetic',
2939                 'middlename' => 'middlename',
2940                 'alternatename' => 'alternatename',
2941                 'firstname' => 'firstname',
2942                 'lastname' => 'lastname');
2943         $this->assertEquals($testarray, get_all_user_name_fields());
2945         // Additional names as a string.
2946         $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
2947         $this->assertEquals($teststring, get_all_user_name_fields(true));
2949         // Additional names as a string with an alias.
2950         $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
2951         $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
2953         // Additional name fields with a prefix - object.
2954         $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
2955                 'lastnamephonetic' => 'authorlastnamephonetic',
2956                 'middlename' => 'authormiddlename',
2957                 'alternatename' => 'authoralternatename',
2958                 'firstname' => 'authorfirstname',
2959                 'lastname' => 'authorlastname');
2960         $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
2962         // Additional name fields with an alias and a title - string.
2963         $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';
2964         $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
2966         // Test the order parameter of the function.
2967         // Returning an array.
2968         $testarray = array('firstname' => 'firstname',
2969                 'lastname' => 'lastname',
2970                 'firstnamephonetic' => 'firstnamephonetic',
2971                 'lastnamephonetic' => 'lastnamephonetic',
2972                 'middlename' => 'middlename',
2973                 'alternatename' => 'alternatename'
2974         );
2975         $this->assertEquals($testarray, get_all_user_name_fields(false, null, null, null, true));
2977         // Returning a string.
2978         $teststring = 'firstname,lastname,firstnamephonetic,lastnamephonetic,middlename,alternatename';
2979         $this->assertEquals($teststring, get_all_user_name_fields(true, null, null, null, true));
2980     }
2982     public function test_order_in_string() {
2983         $this->resetAfterTest();
2985         // Return an array in an order as they are encountered in a string.
2986         $valuearray = array('second', 'firsthalf', 'first');
2987         $formatstring = 'first firsthalf some other text (second)';
2988         $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
2989         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2991         // Try again with a different order for the format.
2992         $valuearray = array('second', 'firsthalf', 'first');
2993         $formatstring = 'firsthalf first second';
2994         $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
2995         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2997         // Try again with yet another different order for the format.
2998         $valuearray = array('second', 'firsthalf', 'first');
2999         $formatstring = 'start seconds away second firstquater first firsthalf';
3000         $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
3001         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
3002     }
3004     public function test_complete_user_login() {
3005         global $USER, $DB;
3007         $this->resetAfterTest();
3008         $user = $this->getDataGenerator()->create_user();
3009         $this->setUser(0);
3011         $sink = $this->redirectEvents();
3012         $loginuser = clone($user);
3013         $this->setCurrentTimeStart();
3014         @complete_user_login($loginuser); // Hide session header errors.
3015         $this->assertSame($loginuser, $USER);
3016         $this->assertEquals($user->id, $USER->id);
3017         $events = $sink->get_events();
3018         $sink->close();
3020         $this->assertCount(1, $events);
3021         $event = reset($events);
3022         $this->assertInstanceOf('\core\event\user_loggedin', $event);
3023         $this->assertEquals('user', $event->objecttable);
3024         $this->assertEquals($user->id, $event->objectid);
3025         $this->assertEquals(context_system::instance()->id, $event->contextid);
3026         $this->assertEventContextNotUsed($event);
3028         $user = $DB->get_record('user', array('id'=>$user->id));
3030         $this->assertTimeCurrent($user->firstaccess);
3031         $this->assertTimeCurrent($user->lastaccess);
3033         $this->assertTimeCurrent($USER->firstaccess);
3034         $this->assertTimeCurrent($USER->lastaccess);
3035         $this->assertTimeCurrent($USER->currentlogin);
3036         $this->assertSame(sesskey(), $USER->sesskey);
3037         $this->assertTimeCurrent($USER->preference['_lastloaded']);
3038         $this->assertObjectNotHasAttribute('password', $USER);
3039         $this->assertObjectNotHasAttribute('description', $USER);
3040     }
3042     /**
3043      * Test require_logout.
3044      */
3045     public function test_require_logout() {
3046         $this->resetAfterTest();
3047         $user = $this->getDataGenerator()->create_user();
3048         $this->setUser($user);
3050         $this->assertTrue(isloggedin());
3052         // Logout user and capture event.
3053         $sink = $this->redirectEvents();
3054         require_logout();
3055         $events = $sink->get_events();
3056         $sink->close();
3057         $event = array_pop($events);
3059         // Check if user is logged out.
3060         $this->assertFalse(isloggedin());
3062         // Test Event.
3063         $this->assertInstanceOf('\core\event\user_loggedout', $event);
3064         $this->assertSame($user->id, $event->objectid);
3065         $this->assertSame('user_logout', $event->get_legacy_eventname());
3066         $this->assertEventLegacyData($user, $event);
3067         $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
3068             $event->objectid);
3069         $this->assertEventLegacyLogData($expectedlogdata, $event);
3070         $this->assertEventContextNotUsed($event);
3071     }
3073     /**
3074      * A data provider for testing email messageid
3075      */
3076     public function generate_email_messageid_provider() {
3077         return array(
3078             'nopath' => array(
3079                 'wwwroot' => 'http://www.example.com',
3080                 'ids' => array(
3081                     'a-custom-id' => '<a-custom-id@www.example.com>',
3082                     'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash@www.example.com>',
3083                 ),
3084             ),
3085             'path' => array(
3086                 'wwwroot' => 'http://www.example.com/path/subdir',
3087                 'ids' => array(
3088                     'a-custom-id' => '<a-custom-id/path/subdir@www.example.com>',
3089                     'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash/path/subdir@www.example.com>',
3090                 ),
3091             ),
3092         );
3093     }
3095     /**
3096      * Test email message id generation
3097      *
3098      * @dataProvider generate_email_messageid_provider
3099      *
3100      * @param string $wwwroot The wwwroot
3101      * @param array $msgids An array of msgid local parts and the final result
3102      */
3103     public function test_generate_email_messageid($wwwroot, $msgids) {
3104         global $CFG;
3106         $this->resetAfterTest();
3107         $CFG->wwwroot = $wwwroot;
3109         foreach ($msgids as $local => $final) {
3110             $this->assertEquals($final, generate_email_messageid($local));
3111         }
3112     }
3114     /**
3115      * A data provider for testing email diversion
3116      */
3117     public function diverted_emails_provider() {
3118         return array(
3119             'nodiverts' => array(
3120                 'divertallemailsto' => null,
3121                 'divertallemailsexcept' => null,
3122                 array(
3123                     'foo@example.com',
3124                     'test@real.com',
3125                     'fred.jones@example.com',
3126                     'dev1@dev.com',
3127                     'fred@example.com',
3128                     'fred+verp@example.com',
3129                 ),
3130                 false,
3131             ),
3132             'alldiverts' => array(
3133                 'divertallemailsto' => 'somewhere@elsewhere.com',
3134                 'divertallemailsexcept' => null,
3135                 array(
3136                     'foo@example.com',
3137                     'test@real.com',
3138                     'fred.jones@example.com',
3139                     'dev1@dev.com',
3140                     'fred@example.com',
3141                     'fred+verp@example.com',
3142                 ),
3143                 true,
3144             ),
3145             'alsodiverts' => array(
3146                 'divertallemailsto' => 'somewhere@elsewhere.com',
3147                 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
3148                 array(
3149                     'foo@example.com',
3150                     'test@real.com',
3151                     'fred.jones@example.com',
3152                 ),
3153                 true,
3154             ),
3155             'divertsexceptions' => array(
3156                 'divertallemailsto' => 'somewhere@elsewhere.com',
3157                 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
3158                 array(
3159                     'dev1@dev.com',
3160                     'fred@example.com',
3161                     'fred+verp@example.com',
3162                 ),
3163                 false,
3164             ),
3165         );
3166     }
3168     /**
3169      * Test email diversion
3170      *
3171      * @dataProvider diverted_emails_provider
3172      *
3173      * @param string $divertallemailsto An optional email address
3174      * @param string $divertallemailsexcept An optional exclusion list
3175      * @param array $addresses An array of test addresses
3176      * @param boolean $expected Expected result
3177      */
3178     public function test_email_should_be_diverted($divertallemailsto, $divertallemailsexcept, $addresses, $expected) {
3179         global $CFG;
3181         $this->resetAfterTest();
3182         $CFG->divertallemailsto = $divertallemailsto;
3183         $CFG->divertallemailsexcept = $divertallemailsexcept;
3185         foreach ($addresses as $address) {
3186             $this->assertEquals($expected, email_should_be_diverted($address));
3187         }
3188     }
3190     public function test_email_to_user() {
3191         global $CFG;
3193         $this->resetAfterTest();
3195         $user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
3196         $user2 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
3197         $user3 = $this->getDataGenerator()->create_user(array('maildisplay' => 0));
3198         set_config('allowedemaildomains', "example.com\r\nmoodle.org");
3200         $subject = 'subject';
3201         $messagetext = 'message text';
3202         $subject2 = 'subject 2';
3203         $messagetext2 = 'message text 2';
3205         // Close the default email sink.
3206         $sink = $this->redirectEmails();
3207         $sink->close();
3209         $CFG->noemailever = true;
3210         $this->assertNotEmpty($CFG->noemailever);
3211         email_to_user($user1, $user2, $subject, $messagetext);
3212         $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
3214         unset_config('noemailever');
3216         email_to_user($user1, $user2, $subject, $messagetext);
3217         $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
3219         $sink = $this->redirectEmails();
3220         email_to_user($user1, $user2, $subject, $messagetext);
3221         email_to_user($user2, $user1, $subject2, $messagetext2);
3222         $this->assertSame(2, $sink->count());
3223         $result = $sink->get_messages();
3224         $this->assertCount(2, $result);