Merge branch 'MDL-40046-master' of git://github.com/ankitagarwal/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         }
206         try {
207             @optional_param('username');
208             $this->fail('coding_exception expected');
209         } catch (moodle_exception $ex) {
210             $this->assertInstanceOf('coding_exception', $ex);
211         }
212         try {
213             optional_param('', 'default_user', PARAM_RAW);
214             $this->fail('coding_exception expected');
215         } catch (moodle_exception $ex) {
216             $this->assertInstanceOf('coding_exception', $ex);
217         }
219         // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
220         $_POST['username'] = array('a'=>'a');
221         $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
222         $this->assertDebuggingCalled();
223     }
225     public function test_optional_param_array() {
226         global $CFG;
228         $_POST['username'] = array('a'=>'post_user');
229         $_GET['username'] = array('a'=>'get_user');
230         $this->assertSame($_POST['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
232         unset($_POST['username']);
233         $this->assertSame($_GET['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
235         unset($_GET['username']);
236         $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
238         // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
239         $_POST['username'] = array('a'=>'post_user');
240         try {
241             optional_param_array('username', array('a'=>'default_user'), null);
242             $this->fail('coding_exception expected');
243         } catch (moodle_exception $ex) {
244             $this->assertInstanceOf('coding_exception', $ex);
245         }
246         try {
247             @optional_param_array('username', array('a'=>'default_user'));
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');
254             $this->fail('coding_exception expected');
255         } catch (moodle_exception $ex) {
256             $this->assertInstanceOf('coding_exception', $ex);
257         }
258         try {
259             optional_param_array('', array('a'=>'default_user'), PARAM_RAW);
260             $this->fail('coding_exception expected');
261         } catch (moodle_exception $ex) {
262             $this->assertInstanceOf('coding_exception', $ex);
263         }
265         // Do not allow nested arrays.
266         try {
267             $_POST['username'] = array('a'=>array('b'=>'post_user'));
268             optional_param_array('username', array('a'=>'default_user'), PARAM_RAW);
269             $this->fail('coding_exception expected');
270         } catch (coding_exception $ex) {
271             $this->assertTrue(true);
272         }
274         // Do not allow non-arrays.
275         $_POST['username'] = 'post_user';
276         $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
277         $this->assertDebuggingCalled();
279         // Make sure array keys are sanitised.
280         $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
281         $this->assertSame(array('a1_-'=>'post_user'), optional_param_array('username', array(), PARAM_RAW));
282         $this->assertDebuggingCalled();
283     }
285     public function test_required_param() {
286         $_POST['username'] = 'post_user';
287         $_GET['username'] = 'get_user';
288         $this->assertSame('post_user', required_param('username', PARAM_RAW));
290         unset($_POST['username']);
291         $this->assertSame('get_user', required_param('username', PARAM_RAW));
293         unset($_GET['username']);
294         try {
295             $this->assertSame('default_user', required_param('username', PARAM_RAW));
296             $this->fail('moodle_exception expected');
297         } catch (moodle_exception $ex) {
298             $this->assertInstanceOf('moodle_exception', $ex);
299         }
301         // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
302         $_POST['username'] = 'post_user';
303         try {
304             @required_param('username');
305             $this->fail('coding_exception expected');
306         } catch (moodle_exception $ex) {
307             $this->assertInstanceOf('coding_exception', $ex);
308         }
309         try {
310             required_param('username', '');
311             $this->fail('coding_exception expected');
312         } catch (moodle_exception $ex) {
313             $this->assertInstanceOf('coding_exception', $ex);
314         }
315         try {
316             required_param('', PARAM_RAW);
317             $this->fail('coding_exception expected');
318         } catch (moodle_exception $ex) {
319             $this->assertInstanceOf('coding_exception', $ex);
320         }
322         // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
323         $_POST['username'] = array('a'=>'a');
324         $this->assertSame($_POST['username'], required_param('username', PARAM_RAW));
325         $this->assertDebuggingCalled();
326     }
328     public function test_required_param_array() {
329         global $CFG;
331         $_POST['username'] = array('a'=>'post_user');
332         $_GET['username'] = array('a'=>'get_user');
333         $this->assertSame($_POST['username'], required_param_array('username', PARAM_RAW));
335         unset($_POST['username']);
336         $this->assertSame($_GET['username'], required_param_array('username', PARAM_RAW));
338         // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
339         $_POST['username'] = array('a'=>'post_user');
340         try {
341             required_param_array('username', null);
342             $this->fail('coding_exception expected');
343         } catch (moodle_exception $ex) {
344             $this->assertInstanceOf('coding_exception', $ex);
345         }
346         try {
347             @required_param_array('username');
348             $this->fail('coding_exception expected');
349         } catch (moodle_exception $ex) {
350             $this->assertInstanceOf('coding_exception', $ex);
351         }
352         try {
353             required_param_array('', PARAM_RAW);
354             $this->fail('coding_exception expected');
355         } catch (moodle_exception $ex) {
356             $this->assertInstanceOf('coding_exception', $ex);
357         }
359         // Do not allow nested arrays.
360         try {
361             $_POST['username'] = array('a'=>array('b'=>'post_user'));
362             required_param_array('username', PARAM_RAW);
363             $this->fail('coding_exception expected');
364         } catch (moodle_exception $ex) {
365             $this->assertInstanceOf('coding_exception', $ex);
366         }
368         // Do not allow non-arrays.
369         try {
370             $_POST['username'] = 'post_user';
371             required_param_array('username', PARAM_RAW);
372             $this->fail('moodle_exception expected');
373         } catch (moodle_exception $ex) {
374             $this->assertInstanceOf('moodle_exception', $ex);
375         }
377         // Make sure array keys are sanitised.
378         $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
379         $this->assertSame(array('a1_-'=>'post_user'), required_param_array('username', PARAM_RAW));
380         $this->assertDebuggingCalled();
381     }
383     public function test_clean_param() {
384         // Forbid objects and arrays.
385         try {
386             clean_param(array('x', 'y'), PARAM_RAW);
387             $this->fail('coding_exception expected');
388         } catch (moodle_exception $ex) {
389             $this->assertInstanceOf('coding_exception', $ex);
390         }
391         try {
392             $param = new stdClass();
393             $param->id = 1;
394             clean_param($param, PARAM_RAW);
395             $this->fail('coding_exception expected');
396         } catch (moodle_exception $ex) {
397             $this->assertInstanceOf('coding_exception', $ex);
398         }
400         // Require correct type.
401         try {
402             clean_param('x', 'xxxxxx');
403             $this->fail('moodle_exception expected');
404         } catch (moodle_exception $ex) {
405             $this->assertInstanceOf('moodle_exception', $ex);
406         }
407         try {
408             @clean_param('x');
409             $this->fail('moodle_exception expected');
410         } catch (moodle_exception $ex) {
411             $this->assertInstanceOf('moodle_exception', $ex);
412         }
413     }
415     public function test_clean_param_array() {
416         $this->assertSame(array(), clean_param_array(null, PARAM_RAW));
417         $this->assertSame(array('a', 'b'), clean_param_array(array('a', 'b'), PARAM_RAW));
418         $this->assertSame(array('a', array('b')), clean_param_array(array('a', array('b')), PARAM_RAW, true));
420         // Require correct type.
421         try {
422             clean_param_array(array('x'), 'xxxxxx');
423             $this->fail('moodle_exception expected');
424         } catch (moodle_exception $ex) {
425             $this->assertInstanceOf('moodle_exception', $ex);
426         }
427         try {
428             @clean_param_array(array('x'));
429             $this->fail('moodle_exception expected');
430         } catch (moodle_exception $ex) {
431             $this->assertInstanceOf('moodle_exception', $ex);
432         }
434         try {
435             clean_param_array(array('x', array('y')), PARAM_RAW);
436             $this->fail('coding_exception expected');
437         } catch (moodle_exception $ex) {
438             $this->assertInstanceOf('coding_exception', $ex);
439         }
441         // Test recursive.
442     }
444     public function test_clean_param_raw() {
445         $this->assertSame(
446             '#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)',
447             clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_RAW));
448     }
450     public function test_clean_param_trim() {
451         $this->assertSame('Frog toad', clean_param("   Frog toad   \r\n  ", PARAM_RAW_TRIMMED));
452     }
454     public function test_clean_param_clean() {
455         // PARAM_CLEAN is an ugly hack, do not use in new code (skodak),
456         // instead use more specific type, or submit sothing that can be verified properly.
457         $this->assertSame('xx', clean_param('xx<script>', PARAM_CLEAN));
458     }
460     public function test_clean_param_alpha() {
461         $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHA));
462     }
464     public function test_clean_param_alphanum() {
465         $this->assertSame('978942897DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHANUM));
466     }
468     public function test_clean_param_alphaext() {
469         $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHAEXT));
470     }
472     public function test_clean_param_sequence() {
473         $this->assertSame(',9789,42897', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_SEQUENCE));
474     }
476     public function test_clean_param_component() {
477         // Please note the cleaning of component names is very strict, no guessing here.
478         $this->assertSame('mod_forum', clean_param('mod_forum', PARAM_COMPONENT));
479         $this->assertSame('block_online_users', clean_param('block_online_users', PARAM_COMPONENT));
480         $this->assertSame('block_blond_online_users', clean_param('block_blond_online_users', PARAM_COMPONENT));
481         $this->assertSame('mod_something2', clean_param('mod_something2', PARAM_COMPONENT));
482         $this->assertSame('forum', clean_param('forum', PARAM_COMPONENT));
483         $this->assertSame('user', clean_param('user', PARAM_COMPONENT));
484         $this->assertSame('rating', clean_param('rating', PARAM_COMPONENT));
485         $this->assertSame('', clean_param('mod_2something', PARAM_COMPONENT));
486         $this->assertSame('', clean_param('2mod_something', PARAM_COMPONENT));
487         $this->assertSame('', clean_param('mod_something_xx', PARAM_COMPONENT));
488         $this->assertSame('', clean_param('auth_something__xx', PARAM_COMPONENT));
489         $this->assertSame('', clean_param('mod_Something', PARAM_COMPONENT));
490         $this->assertSame('', clean_param('mod_somethíng', PARAM_COMPONENT));
491         $this->assertSame('', clean_param('auth_xx-yy', PARAM_COMPONENT));
492         $this->assertSame('', clean_param('_auth_xx', PARAM_COMPONENT));
493         $this->assertSame('', clean_param('a2uth_xx', PARAM_COMPONENT));
494         $this->assertSame('', clean_param('auth_xx_', PARAM_COMPONENT));
495         $this->assertSame('', clean_param('auth_xx.old', PARAM_COMPONENT));
496         $this->assertSame('', clean_param('_user', PARAM_COMPONENT));
497         $this->assertSame('', clean_param('2rating', PARAM_COMPONENT));
498         $this->assertSame('', clean_param('user_', PARAM_COMPONENT));
499     }
501     public function test_is_valid_plugin_name() {
502         $this->assertTrue(is_valid_plugin_name('forum'));
503         $this->assertTrue(is_valid_plugin_name('forum2'));
504         $this->assertTrue(is_valid_plugin_name('online_users'));
505         $this->assertTrue(is_valid_plugin_name('blond_online_users'));
506         $this->assertFalse(is_valid_plugin_name('online__users'));
507         $this->assertFalse(is_valid_plugin_name('forum '));
508         $this->assertFalse(is_valid_plugin_name('forum.old'));
509         $this->assertFalse(is_valid_plugin_name('xx-yy'));
510         $this->assertFalse(is_valid_plugin_name('2xx'));
511         $this->assertFalse(is_valid_plugin_name('Xx'));
512         $this->assertFalse(is_valid_plugin_name('_xx'));
513         $this->assertFalse(is_valid_plugin_name('xx_'));
514     }
516     public function test_clean_param_plugin() {
517         // Please note the cleaning of plugin names is very strict, no guessing here.
518         $this->assertSame('forum', clean_param('forum', PARAM_PLUGIN));
519         $this->assertSame('forum2', clean_param('forum2', PARAM_PLUGIN));
520         $this->assertSame('online_users', clean_param('online_users', PARAM_PLUGIN));
521         $this->assertSame('blond_online_users', clean_param('blond_online_users', PARAM_PLUGIN));
522         $this->assertSame('', clean_param('online__users', PARAM_PLUGIN));
523         $this->assertSame('', clean_param('forum ', PARAM_PLUGIN));
524         $this->assertSame('', clean_param('forum.old', PARAM_PLUGIN));
525         $this->assertSame('', clean_param('xx-yy', PARAM_PLUGIN));
526         $this->assertSame('', clean_param('2xx', PARAM_PLUGIN));
527         $this->assertSame('', clean_param('Xx', PARAM_PLUGIN));
528         $this->assertSame('', clean_param('_xx', PARAM_PLUGIN));
529         $this->assertSame('', clean_param('xx_', PARAM_PLUGIN));
530     }
532     public function test_clean_param_area() {
533         // Please note the cleaning of area names is very strict, no guessing here.
534         $this->assertSame('something', clean_param('something', PARAM_AREA));
535         $this->assertSame('something2', clean_param('something2', PARAM_AREA));
536         $this->assertSame('some_thing', clean_param('some_thing', PARAM_AREA));
537         $this->assertSame('some_thing_xx', clean_param('some_thing_xx', PARAM_AREA));
538         $this->assertSame('', clean_param('_something', PARAM_AREA));
539         $this->assertSame('', clean_param('something_', PARAM_AREA));
540         $this->assertSame('', clean_param('2something', PARAM_AREA));
541         $this->assertSame('', clean_param('Something', PARAM_AREA));
542         $this->assertSame('', clean_param('some-thing', PARAM_AREA));
543         $this->assertSame('', clean_param('somethííng', PARAM_AREA));
544         $this->assertSame('', clean_param('something.x', PARAM_AREA));
545     }
547     public function test_clean_param_text() {
548         $this->assertSame(PARAM_TEXT, PARAM_MULTILANG);
549         // Standard.
550         $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));
551         $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));
552         $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));
553         // Malformed.
554         $this->assertSame('<span lang="en" class="multilang">aa</span>', clean_param('<span lang="en" class="multilang">aa</span>', PARAM_TEXT));
555         $this->assertSame('aa', clean_param('<span lang="en" class="nothing" class="multilang">aa</span>', PARAM_TEXT));
556         $this->assertSame('aa', clean_param('<lang lang="en" class="multilang">aa</lang>', PARAM_TEXT));
557         $this->assertSame('aa', clean_param('<lang lang="en!!">aa</lang>', PARAM_TEXT));
558         $this->assertSame('aa', clean_param('<span lang="en==" class="multilang">aa</span>', PARAM_TEXT));
559         $this->assertSame('abc', clean_param('a<em>b</em>c', PARAM_TEXT));
560         $this->assertSame('a>c>', clean_param('a><xx >c>', PARAM_TEXT)); // Standard strip_tags() behaviour.
561         $this->assertSame('a', clean_param('a<b', PARAM_TEXT));
562         $this->assertSame('a>b', clean_param('a>b', PARAM_TEXT));
563         $this->assertSame('<lang lang="en">a>a</lang>', clean_param('<lang lang="en">a>a</lang>', PARAM_TEXT)); // Standard strip_tags() behaviour.
564         $this->assertSame('a', clean_param('<lang lang="en">a<a</lang>', PARAM_TEXT));
565         $this->assertSame('<lang lang="en">aa</lang>', clean_param('<lang lang="en">a<br>a</lang>', PARAM_TEXT));
566     }
568     public function test_clean_param_url() {
569         // Test PARAM_URL and PARAM_LOCALURL a bit.
570         $this->assertSame('http://google.com/', clean_param('http://google.com/', PARAM_URL));
571         $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));
572         $this->assertSame('http://localhost/', clean_param('http://localhost/', PARAM_URL));
573         $this->assertSame('http://0.255.1.1/numericip.php', clean_param('http://0.255.1.1/numericip.php', PARAM_URL));
574         $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_URL));
575         $this->assertSame('', clean_param('funny:thing', PARAM_URL));
576     }
578     public function test_clean_param_localurl() {
579         global $CFG;
580         $this->assertSame('', clean_param('http://google.com/', PARAM_LOCALURL));
581         $this->assertSame('', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL));
582         $this->assertSame(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
583         $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_LOCALURL));
584         $this->assertSame('', clean_param('funny:thing', PARAM_LOCALURL));
585         $this->assertSame('course/view.php?id=3', clean_param('course/view.php?id=3', PARAM_LOCALURL));
586     }
588     public function test_clean_param_file() {
589         $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_FILE));
590         $this->assertSame('badfile.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE));
591         $this->assertSame('..parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_FILE));
592         $this->assertSame('....grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_FILE));
593         $this->assertSame('..winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_FILE));
594         $this->assertSame('....wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_FILE));
595         $this->assertSame('myfile.a.b.txt', clean_param('myfile.a.b.txt', PARAM_FILE));
596         $this->assertSame('myfile..a..b.txt', clean_param('myfile..a..b.txt', PARAM_FILE));
597         $this->assertSame('myfile.a..b...txt', clean_param('myfile.a..b...txt', PARAM_FILE));
598         $this->assertSame('myfile.a.txt', clean_param('myfile.a.txt', PARAM_FILE));
599         $this->assertSame('myfile...txt', clean_param('myfile...txt', PARAM_FILE));
600         $this->assertSame('...jpg', clean_param('...jpg', PARAM_FILE));
601         $this->assertSame('.a.b.', clean_param('.a.b.', PARAM_FILE));
602         $this->assertSame('', clean_param('.', PARAM_FILE));
603         $this->assertSame('', clean_param('..', PARAM_FILE));
604         $this->assertSame('...', clean_param('...', PARAM_FILE));
605         $this->assertSame('. . . .', clean_param('. . . .', PARAM_FILE));
606         $this->assertSame('dontrtrim.me. .. .. . ', clean_param('dontrtrim.me. .. .. . ', PARAM_FILE));
607         $this->assertSame(' . .dontltrim.me', clean_param(' . .dontltrim.me', PARAM_FILE));
608         $this->assertSame('here is a tab.txt', clean_param("here is a tab\t.txt", PARAM_FILE));
609         $this->assertSame('here is a linebreak.txt', clean_param("here is a line\r\nbreak.txt", PARAM_FILE));
611         // The following behaviours have been maintained although they seem a little odd.
612         $this->assertSame('funnything', clean_param('funny:thing', PARAM_FILE));
613         $this->assertSame('.currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_FILE));
614         $this->assertSame('ctempwindowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_FILE));
615         $this->assertSame('homeuserlinuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_FILE));
616         $this->assertSame('~myfile.txt', clean_param('~/myfile.txt', PARAM_FILE));
617     }
619     public function test_clean_param_path() {
620         $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_PATH));
621         $this->assertSame('bad/file.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH));
622         $this->assertSame('/parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_PATH));
623         $this->assertSame('/grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_PATH));
624         $this->assertSame('/winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_PATH));
625         $this->assertSame('/wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_PATH));
626         $this->assertSame('funnything', clean_param('funny:thing', PARAM_PATH));
627         $this->assertSame('./here', clean_param('./././here', PARAM_PATH));
628         $this->assertSame('./currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_PATH));
629         $this->assertSame('c/temp/windowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_PATH));
630         $this->assertSame('/home/user/linuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_PATH));
631         $this->assertSame('/home../user ./.linuxfile.txt', clean_param('/home../user ./.linuxfile.txt', PARAM_PATH));
632         $this->assertSame('~/myfile.txt', clean_param('~/myfile.txt', PARAM_PATH));
633         $this->assertSame('~/myfile.txt', clean_param('~/../myfile.txt', PARAM_PATH));
634         $this->assertSame('/..b../.../myfile.txt', clean_param('/..b../.../myfile.txt', PARAM_PATH));
635         $this->assertSame('..b../.../myfile.txt', clean_param('..b../.../myfile.txt', PARAM_PATH));
636         $this->assertSame('/super/slashes/', clean_param('/super//slashes///', PARAM_PATH));
637     }
639     public function test_clean_param_username() {
640         global $CFG;
641         $currentstatus =  $CFG->extendedusernamechars;
643         // Run tests with extended character == false;.
644         $CFG->extendedusernamechars = false;
645         $this->assertSame('johndoe123', clean_param('johndoe123', PARAM_USERNAME) );
646         $this->assertSame('john.doe', clean_param('john.doe', PARAM_USERNAME));
647         $this->assertSame('john-doe', clean_param('john-doe', PARAM_USERNAME));
648         $this->assertSame('john-doe', clean_param('john- doe', PARAM_USERNAME));
649         $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
650         $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
651         $this->assertSame('johndoe', clean_param('john~doe', PARAM_USERNAME));
652         $this->assertSame('johndoe', clean_param('john´doe', PARAM_USERNAME));
653         $this->assertSame(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
654         $this->assertSame('johnd', clean_param('JOHNdóé ', PARAM_USERNAME));
655         $this->assertSame(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýá\9e?\9eý??\9adoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
657         // Test success condition, if extendedusernamechars == ENABLE;.
658         $CFG->extendedusernamechars = true;
659         $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
660         $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
661         $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john#$%&()+_^');
662         $this->assertSame('john~doe', clean_param('john~doe', PARAM_USERNAME));
663         $this->assertSame('john´doe', clean_param('joHN´doe', PARAM_USERNAME));
664         $this->assertSame('johndoe', clean_param('johnDOE', PARAM_USERNAME));
665         $this->assertSame('johndóé', clean_param('johndóé ', PARAM_USERNAME));
667         $CFG->extendedusernamechars = $currentstatus;
668     }
670     public function test_clean_param_stringid() {
671         // Test string identifiers validation.
672         // Valid strings.
673         $this->assertSame('validstring', clean_param('validstring', PARAM_STRINGID));
674         $this->assertSame('mod/foobar:valid_capability', clean_param('mod/foobar:valid_capability', PARAM_STRINGID));
675         $this->assertSame('CZ', clean_param('CZ', PARAM_STRINGID));
676         $this->assertSame('application/vnd.ms-powerpoint', clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID));
677         $this->assertSame('grade2', clean_param('grade2', PARAM_STRINGID));
678         // Invalid strings.
679         $this->assertSame('', clean_param('trailing ', PARAM_STRINGID));
680         $this->assertSame('', clean_param('space bar', PARAM_STRINGID));
681         $this->assertSame('', clean_param('0numeric', PARAM_STRINGID));
682         $this->assertSame('', clean_param('*', PARAM_STRINGID));
683         $this->assertSame('', clean_param(' ', PARAM_STRINGID));
684     }
686     public function test_clean_param_timezone() {
687         // Test timezone validation.
688         $testvalues = array (
689             'America/Jamaica'                => 'America/Jamaica',
690             'America/Argentina/Cordoba'      => 'America/Argentina/Cordoba',
691             'America/Port-au-Prince'         => 'America/Port-au-Prince',
692             'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
693             'PST8PDT'                        => 'PST8PDT',
694             'Wrong.Value'                    => '',
695             'Wrong/.Value'                   => '',
696             'Wrong(Value)'                   => '',
697             '0'                              => '0',
698             '0.0'                            => '0.0',
699             '0.5'                            => '0.5',
700             '9.0'                            => '9.0',
701             '-9.0'                           => '-9.0',
702             '+9.0'                           => '+9.0',
703             '9.5'                            => '9.5',
704             '-9.5'                           => '-9.5',
705             '+9.5'                           => '+9.5',
706             '12.0'                           => '12.0',
707             '-12.0'                          => '-12.0',
708             '+12.0'                          => '+12.0',
709             '12.5'                           => '12.5',
710             '-12.5'                          => '-12.5',
711             '+12.5'                          => '+12.5',
712             '13.0'                           => '13.0',
713             '-13.0'                          => '-13.0',
714             '+13.0'                          => '+13.0',
715             '13.5'                           => '',
716             '+13.5'                          => '',
717             '-13.5'                          => '',
718             '0.2'                            => '');
720         foreach ($testvalues as $testvalue => $expectedvalue) {
721             $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
722             $this->assertEquals($expectedvalue, $actualvalue);
723         }
724     }
726     public function test_validate_param() {
727         try {
728             $param = validate_param('11a', PARAM_INT);
729             $this->fail('invalid_parameter_exception expected');
730         } catch (moodle_exception $ex) {
731             $this->assertInstanceOf('invalid_parameter_exception', $ex);
732         }
734         $param = validate_param('11', PARAM_INT);
735         $this->assertSame(11, $param);
737         try {
738             $param = validate_param(null, PARAM_INT, false);
739             $this->fail('invalid_parameter_exception expected');
740         } catch (moodle_exception $ex) {
741             $this->assertInstanceOf('invalid_parameter_exception', $ex);
742         }
744         $param = validate_param(null, PARAM_INT, true);
745         $this->assertSame(null, $param);
747         try {
748             $param = validate_param(array(), PARAM_INT);
749             $this->fail('invalid_parameter_exception expected');
750         } catch (moodle_exception $ex) {
751             $this->assertInstanceOf('invalid_parameter_exception', $ex);
752         }
753         try {
754             $param = validate_param(new stdClass, PARAM_INT);
755             $this->fail('invalid_parameter_exception expected');
756         } catch (moodle_exception $ex) {
757             $this->assertInstanceOf('invalid_parameter_exception', $ex);
758         }
760         $param = validate_param('1.0', PARAM_FLOAT);
761         $this->assertSame(1.0, $param);
763         // Make sure valid floats do not cause exception.
764         validate_param(1.0, PARAM_FLOAT);
765         validate_param(10, PARAM_FLOAT);
766         validate_param('0', PARAM_FLOAT);
767         validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
768         validate_param('011.1', PARAM_FLOAT);
769         validate_param('11', PARAM_FLOAT);
770         validate_param('+.1', PARAM_FLOAT);
771         validate_param('-.1', PARAM_FLOAT);
772         validate_param('1e10', PARAM_FLOAT);
773         validate_param('.1e+10', PARAM_FLOAT);
774         validate_param('1E-1', PARAM_FLOAT);
776         try {
777             $param = validate_param('1,2', PARAM_FLOAT);
778             $this->fail('invalid_parameter_exception expected');
779         } catch (moodle_exception $ex) {
780             $this->assertInstanceOf('invalid_parameter_exception', $ex);
781         }
782         try {
783             $param = validate_param('', PARAM_FLOAT);
784             $this->fail('invalid_parameter_exception expected');
785         } catch (moodle_exception $ex) {
786             $this->assertInstanceOf('invalid_parameter_exception', $ex);
787         }
788         try {
789             $param = validate_param('.', PARAM_FLOAT);
790             $this->fail('invalid_parameter_exception expected');
791         } catch (moodle_exception $ex) {
792             $this->assertInstanceOf('invalid_parameter_exception', $ex);
793         }
794         try {
795             $param = validate_param('e10', PARAM_FLOAT);
796             $this->fail('invalid_parameter_exception expected');
797         } catch (moodle_exception $ex) {
798             $this->assertInstanceOf('invalid_parameter_exception', $ex);
799         }
800         try {
801             $param = validate_param('abc', PARAM_FLOAT);
802             $this->fail('invalid_parameter_exception expected');
803         } catch (moodle_exception $ex) {
804             $this->assertInstanceOf('invalid_parameter_exception', $ex);
805         }
806     }
808     public function test_shorten_text_no_tags_already_short_enough() {
809         // ......12345678901234567890123456.
810         $text = "short text already no tags";
811         $this->assertSame($text, shorten_text($text));
812     }
814     public function test_shorten_text_with_tags_already_short_enough() {
815         // .........123456...7890....12345678.......901234567.
816         $text = "<p>short <b>text</b> already</p><p>with tags</p>";
817         $this->assertSame($text, shorten_text($text));
818     }
820     public function test_shorten_text_no_tags_needs_shortening() {
821         // Default truncation is after 30 chars, but allowing 3 for the final '...'.
822         // ......12345678901234567890123456789023456789012345678901234.
823         $text = "long text without any tags blah de blah blah blah what";
824         $this->assertSame('long text without any tags ...', shorten_text($text));
825     }
827     public function test_shorten_text_with_tags_needs_shortening() {
828         // .......................................123456789012345678901234567890...
829         $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
830             "be chopped off but <b>should be added back again</b></blockquote></p></div>";
831         $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
832             "tags that ...</blockquote></p></div>", shorten_text($text));
833     }
835     public function test_shorten_text_with_entities() {
836         // Remember to allow 3 chars for the final '...'.
837         // ......123456789012345678901234567_____890...
838         $text = "some text which shouldn't &nbsp; break there";
839         $this->assertSame("some text which shouldn't &nbsp; ...", shorten_text($text, 31));
840         $this->assertSame("some text which shouldn't &nbsp;...", shorten_text($text, 30));
841         $this->assertSame("some text which shouldn't ...", shorten_text($text, 29));
842     }
844     public function test_shorten_text_known_tricky_case() {
845         // This case caused a bug up to 1.9.5
846         // ..........123456789012345678901234567890123456789.....0_____1___2___...
847         $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
848         $this->assertSame("<h3>standard 'break-out' sub groups in ...</h3>",
849             shorten_text($text, 41));
850         $this->assertSame("<h3>standard 'break-out' sub groups in TGs?...</h3>",
851             shorten_text($text, 42));
852         $this->assertSame("<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;...",
853             shorten_text($text, 43));
854     }
856     public function test_shorten_text_no_spaces() {
857         // ..........123456789.
858         $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
859         $this->assertSame("<h1>12345...</h1>", shorten_text($text, 8));
860     }
862     public function test_shorten_text_utf8_european() {
863         // Text without tags.
864         // ......123456789012345678901234567.
865         $text = "Žluťoučký koníček přeskočil";
866         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
867         $this->assertSame("Žluťoučký koníče...", shorten_text($text, 19, true));
868         $this->assertSame("Žluťoučký ...", shorten_text($text, 19, false));
869         // And try it with 2-less (that are, in bytes, the middle of a sequence).
870         $this->assertSame("Žluťoučký koní...", shorten_text($text, 17, true));
871         $this->assertSame("Žluťoučký ...", shorten_text($text, 17, false));
873         // .........123456789012345678...901234567....89012345.
874         $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
875         $this->assertSame($text, shorten_text($text, 60));
876         $this->assertSame("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
877         $this->assertSame("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
878         $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
879         // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
880         $this->assertSame("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
881         $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
882         // And try over one tag (start/end), it does proper text len.
883         $this->assertSame("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
884         $this->assertSame("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
885         // And in the middle of one tag.
886         $this->assertSame("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
887     }
889     public function test_shorten_text_utf8_oriental() {
890         // Japanese
891         // text without tags
892         // ......123456789012345678901234.
893         $text = '言語設定言語設定abcdefghijkl';
894         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
895         $this->assertSame("言語設定言語...", shorten_text($text, 9, true));
896         $this->assertSame("言語設定言語...", shorten_text($text, 9, false));
897         $this->assertSame("言語設定言語設定ab...", shorten_text($text, 13, true));
898         $this->assertSame("言語設定言語設定...", shorten_text($text, 13, false));
900         // Chinese
901         // text without tags
902         // ......123456789012345678901234.
903         $text = '简体中文简体中文abcdefghijkl';
904         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
905         $this->assertSame("简体中文简体...", shorten_text($text, 9, true));
906         $this->assertSame("简体中文简体...", shorten_text($text, 9, false));
907         $this->assertSame("简体中文简体中文ab...", shorten_text($text, 13, true));
908         $this->assertSame("简体中文简体中文...", shorten_text($text, 13, false));
909     }
911     public function test_shorten_text_multilang() {
912         // This is not necessaryily specific to multilang. The issue is really
913         // tags with attributes, where before we were generating invalid HTML
914         // output like shorten_text('<span id="x" class="y">A</span> B', 1)
915         // returning '<span id="x" ...</span>'. It is just that multilang
916         // requires the sort of HTML that is quite likely to trigger this.
917         // ........................................1...
918         $text = '<span lang="en" class="multilang">A</span>' .
919                 '<span lang="fr" class="multilang">B</span>';
920         $this->assertSame('<span lang="en" class="multilang">...</span>',
921                 shorten_text($text, 1));
922     }
924     public function test_usergetdate() {
925         global $USER, $CFG, $DB;
926         $this->resetAfterTest();
928         // Check if forcetimezone is set then save it and set it to use user timezone.
929         $cfgforcetimezone = null;
930         if (isset($CFG->forcetimezone)) {
931             $cfgforcetimezone = $CFG->forcetimezone;
932             $CFG->forcetimezone = 99; // Get user default timezone.
933         }
935         $this->setAdminUser();
937         $userstimezone = $USER->timezone;
938         $USER->timezone = 2;// Set the timezone to a known state.
940         // The string version of date comes from server locale setting and does
941         // not respect user language, so it is necessary to reset that.
942         $oldlocale = setlocale(LC_TIME, '0');
943         setlocale(LC_TIME, 'en_AU.UTF-8');
945         $ts = 1261540267; // The time this function was created.
947         $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
948         $arr = array_values($arr);
950         list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
951         $this->assertSame(7, $seconds);
952         $this->assertSame(51, $minutes);
953         $this->assertSame(4, $hours);
954         $this->assertSame(23, $mday);
955         $this->assertSame(3, $wday);
956         $this->assertSame(12, $mon);
957         $this->assertSame(2009, $year);
958         $this->assertSame(356, $yday);
959         $this->assertSame('Wednesday', $weekday);
960         $this->assertSame('December', $month);
961         $arr = usergetdate($ts); // Gets the timezone from the $USER object.
962         $arr = array_values($arr);
964         list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
965         $this->assertSame(7, $seconds);
966         $this->assertSame(51, $minutes);
967         $this->assertSame(5, $hours);
968         $this->assertSame(23, $mday);
969         $this->assertSame(3, $wday);
970         $this->assertSame(12, $mon);
971         $this->assertSame(2009, $year);
972         $this->assertSame(356, $yday);
973         $this->assertSame('Wednesday', $weekday);
974         $this->assertSame('December', $month);
975         // Set the timezone back to what it was.
976         $USER->timezone = $userstimezone;
978         // Restore forcetimezone if changed.
979         if (!is_null($cfgforcetimezone)) {
980             $CFG->forcetimezone = $cfgforcetimezone;
981         }
983         setlocale(LC_TIME, $oldlocale);
984     }
986     public function test_mark_user_preferences_changed() {
987         $this->resetAfterTest();
988         $otheruser = $this->getDataGenerator()->create_user();
989         $otheruserid = $otheruser->id;
991         set_cache_flag('userpreferenceschanged', $otheruserid, null);
992         mark_user_preferences_changed($otheruserid);
994         $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
995         set_cache_flag('userpreferenceschanged', $otheruserid, null);
996     }
998     public function test_check_user_preferences_loaded() {
999         global $DB;
1000         $this->resetAfterTest();
1002         $otheruser = $this->getDataGenerator()->create_user();
1003         $otheruserid = $otheruser->id;
1005         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1006         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1008         $user = new stdClass();
1009         $user->id = $otheruserid;
1011         // Load.
1012         check_user_preferences_loaded($user);
1013         $this->assertTrue(isset($user->preference));
1014         $this->assertTrue(is_array($user->preference));
1015         $this->assertArrayHasKey('_lastloaded', $user->preference);
1016         $this->assertCount(1, $user->preference);
1018         // Add preference via direct call.
1019         $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1021         // No cache reload yet.
1022         check_user_preferences_loaded($user);
1023         $this->assertCount(1, $user->preference);
1025         // Forced reloading of cache.
1026         unset($user->preference);
1027         check_user_preferences_loaded($user);
1028         $this->assertCount(2, $user->preference);
1029         $this->assertSame('yyy', $user->preference['xxx']);
1031         // Add preference via direct call.
1032         $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1034         // Test timeouts and modifications from different session.
1035         set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1036         $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1037         check_user_preferences_loaded($user);
1038         $this->assertCount(2, $user->preference);
1039         check_user_preferences_loaded($user, 10);
1040         $this->assertCount(3, $user->preference);
1041         $this->assertSame('bbb', $user->preference['aaa']);
1042         set_cache_flag('userpreferenceschanged', $user->id, null);
1043     }
1045     public function test_set_user_preference() {
1046         global $DB, $USER;
1047         $this->resetAfterTest();
1049         $this->setAdminUser();
1051         $otheruser = $this->getDataGenerator()->create_user();
1052         $otheruserid = $otheruser->id;
1054         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1055         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1057         $user = new stdClass();
1058         $user->id = $otheruserid;
1060         set_user_preference('aaa', 'bbb', $otheruserid);
1061         $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1062         $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
1064         set_user_preference('xxx', 'yyy', $user);
1065         $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1066         $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
1067         $this->assertTrue(is_array($user->preference));
1068         $this->assertSame('bbb', $user->preference['aaa']);
1069         $this->assertSame('yyy', $user->preference['xxx']);
1071         set_user_preference('xxx', null, $user);
1072         $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1073         $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
1075         set_user_preference('ooo', true, $user);
1076         $prefs = get_user_preferences(null, null, $otheruserid);
1077         $this->assertSame($user->preference['aaa'], $prefs['aaa']);
1078         $this->assertSame($user->preference['ooo'], $prefs['ooo']);
1079         $this->assertSame('1', $prefs['ooo']);
1081         set_user_preference('null', 0, $user);
1082         $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1084         $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1086         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1087         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1089         // Test $USER default.
1090         set_user_preference('_test_user_preferences_pref', 'ok');
1091         $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1092         unset_user_preference('_test_user_preferences_pref');
1093         $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1095         // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
1096         $longvalue = str_repeat('a', 1333);
1097         set_user_preference('_test_long_user_preference', $longvalue);
1098         $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1099         $this->assertEquals($longvalue,
1100             $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1102         // Test > 1333 char values, coding_exception expected.
1103         $longvalue = str_repeat('a', 1334);
1104         try {
1105             set_user_preference('_test_long_user_preference', $longvalue);
1106             $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1107         } catch (moodle_exception $ex) {
1108             $this->assertInstanceOf('coding_exception', $ex);
1109         }
1111         // Test invalid params.
1112         try {
1113             set_user_preference('_test_user_preferences_pref', array());
1114             $this->fail('Exception expected - array not valid preference value');
1115         } catch (moodle_exception $ex) {
1116             $this->assertInstanceOf('coding_exception', $ex);
1117         }
1118         try {
1119             set_user_preference('_test_user_preferences_pref', new stdClass);
1120             $this->fail('Exception expected - class not valid preference value');
1121         } catch (moodle_exception $ex) {
1122             $this->assertInstanceOf('coding_exception', $ex);
1123         }
1124         try {
1125             set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1126             $this->fail('Exception expected - user instance expected');
1127         } catch (moodle_exception $ex) {
1128             $this->assertInstanceOf('coding_exception', $ex);
1129         }
1130         try {
1131             set_user_preference('_test_user_preferences_pref', 1, 'abc');
1132             $this->fail('Exception expected - user instance expected');
1133         } catch (moodle_exception $ex) {
1134             $this->assertInstanceOf('coding_exception', $ex);
1135         }
1136         try {
1137             set_user_preference('', 1);
1138             $this->fail('Exception expected - invalid name accepted');
1139         } catch (moodle_exception $ex) {
1140             $this->assertInstanceOf('coding_exception', $ex);
1141         }
1142         try {
1143             set_user_preference('1', 1);
1144             $this->fail('Exception expected - invalid name accepted');
1145         } catch (moodle_exception $ex) {
1146             $this->assertInstanceOf('coding_exception', $ex);
1147         }
1148     }
1150     public function test_get_extra_user_fields() {
1151         global $CFG, $USER, $DB;
1152         $this->resetAfterTest();
1154         $this->setAdminUser();
1156         // It would be really nice if there were a way to 'mock' has_capability
1157         // checks (either to return true or false) but as there is not, this
1158         // test doesn't test the capability check. Presumably, anyone running
1159         // unit tests will have the capability.
1160         $context = context_system::instance();
1162         // No fields.
1163         $CFG->showuseridentity = '';
1164         $this->assertEquals(array(), get_extra_user_fields($context));
1166         // One field.
1167         $CFG->showuseridentity = 'frog';
1168         $this->assertEquals(array('frog'), get_extra_user_fields($context));
1170         // Two fields.
1171         $CFG->showuseridentity = 'frog,zombie';
1172         $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1174         // No fields, except.
1175         $CFG->showuseridentity = '';
1176         $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1178         // One field.
1179         $CFG->showuseridentity = 'frog';
1180         $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1182         // Two fields.
1183         $CFG->showuseridentity = 'frog,zombie';
1184         $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1185     }
1187     public function test_get_extra_user_fields_sql() {
1188         global $CFG, $USER, $DB;
1189         $this->resetAfterTest();
1191         $this->setAdminUser();
1193         $context = context_system::instance();
1195         // No fields.
1196         $CFG->showuseridentity = '';
1197         $this->assertSame('', get_extra_user_fields_sql($context));
1199         // One field.
1200         $CFG->showuseridentity = 'frog';
1201         $this->assertSame(', frog', get_extra_user_fields_sql($context));
1203         // Two fields with table prefix.
1204         $CFG->showuseridentity = 'frog,zombie';
1205         $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1207         // Two fields with field prefix.
1208         $CFG->showuseridentity = 'frog,zombie';
1209         $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
1210             get_extra_user_fields_sql($context, '', 'u_'));
1212         // One field excluded.
1213         $CFG->showuseridentity = 'frog';
1214         $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
1216         // Two fields, one excluded, table+field prefix.
1217         $CFG->showuseridentity = 'frog,zombie';
1218         $this->assertEquals(', u1.zombie AS u_zombie',
1219             get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1220     }
1222     /**
1223      * Test some critical TZ/DST.
1224      *
1225      * This method tests some special TZ/DST combinations that were fixed
1226      * by MDL-38999. The tests are done by comparing the results of the
1227      * output using Moodle TZ/DST support and PHP native one.
1228      *
1229      * Note: If you don't trust PHP TZ/DST support, can verify the
1230      * harcoded expectations below with:
1231      * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
1232      */
1233     public function test_some_moodle_special_dst() {
1234         $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
1236         // In Europe/Tallinn it was 2013/04/08 05:00:00.
1237         $expectation = '2013/04/08 05:00:00';
1238         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1239         $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1240         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1241         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1242         $this->assertSame($expectation, $phpres);
1243         $this->assertSame($expectation, $moodleres);
1245         // In St. Johns it was 2013/04/07 23:30:00.
1246         $expectation = '2013/04/07 23:30:00';
1247         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1248         $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1249         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1250         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1251         $this->assertSame($expectation, $phpres);
1252         $this->assertSame($expectation, $moodleres);
1254         $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1256         // In Europe/Tallinn it was 2013/11/08 04:00:00.
1257         $expectation = '2013/11/08 04:00:00';
1258         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1259         $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1260         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1261         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1262         $this->assertSame($expectation, $phpres);
1263         $this->assertSame($expectation, $moodleres);
1265         // In St. Johns it was 2013/11/07 22:30:00.
1266         $expectation = '2013/11/07 22:30:00';
1267         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1268         $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1269         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1270         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1271         $this->assertSame($expectation, $phpres);
1272         $this->assertSame($expectation, $moodleres);
1273     }
1275     public function test_userdate() {
1276         global $USER, $CFG, $DB;
1277         $this->resetAfterTest();
1279         $this->setAdminUser();
1281         $testvalues = array(
1282             array(
1283                 'time' => '1309514400',
1284                 'usertimezone' => 'America/Moncton',
1285                 'timezone' => '0.0', // No dst offset.
1286                 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1287             ),
1288             array(
1289                 'time' => '1309514400',
1290                 'usertimezone' => 'America/Moncton',
1291                 'timezone' => '99', // Dst offset and timezone offset.
1292                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1293             ),
1294             array(
1295                 'time' => '1309514400',
1296                 'usertimezone' => 'America/Moncton',
1297                 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
1298                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1299             ),
1300             array(
1301                 'time' => '1293876000 ',
1302                 'usertimezone' => 'America/Moncton',
1303                 'timezone' => '0.0', // No dst offset.
1304                 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1305             ),
1306             array(
1307                 'time' => '1293876000 ',
1308                 'usertimezone' => 'America/Moncton',
1309                 'timezone' => '99', // No dst offset in jan, so just timezone offset.
1310                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1311             ),
1312             array(
1313                 'time' => '1293876000 ',
1314                 'usertimezone' => 'America/Moncton',
1315                 'timezone' => 'America/Moncton', // No dst offset in jan.
1316                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1317             ),
1318             array(
1319                 'time' => '1293876000 ',
1320                 'usertimezone' => '2',
1321                 'timezone' => '99', // Take user timezone.
1322                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1323             ),
1324             array(
1325                 'time' => '1293876000 ',
1326                 'usertimezone' => '-2',
1327                 'timezone' => '99', // Take user timezone.
1328                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1329             ),
1330             array(
1331                 'time' => '1293876000 ',
1332                 'usertimezone' => '-10',
1333                 'timezone' => '2', // Take this timezone.
1334                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1335             ),
1336             array(
1337                 'time' => '1293876000 ',
1338                 'usertimezone' => '-10',
1339                 'timezone' => '-2', // Take this timezone.
1340                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1341             ),
1342             array(
1343                 'time' => '1293876000 ',
1344                 'usertimezone' => '-10',
1345                 'timezone' => 'random/time', // This should show server time.
1346                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1347             ),
1348             array(
1349                 'time' => '1293876000 ',
1350                 'usertimezone' => '14', // Server time zone.
1351                 'timezone' => '99',     // This should show user time.
1352                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1353             ),
1354         );
1356         // Check if forcetimezone is set then save it and set it to use user timezone.
1357         $cfgforcetimezone = null;
1358         if (isset($CFG->forcetimezone)) {
1359             $cfgforcetimezone = $CFG->forcetimezone;
1360             $CFG->forcetimezone = 99; // Get user default timezone.
1361         }
1362         // Store user default timezone to restore later.
1363         $userstimezone = $USER->timezone;
1365         // The string version of date comes from server locale setting and does
1366         // not respect user language, so it is necessary to reset that.
1367         $oldlocale = setlocale(LC_TIME, '0');
1368         setlocale(LC_TIME, 'en_AU.UTF-8');
1370         // Set default timezone to Australia/Perth, else time calculated
1371         // will not match expected values. Before that save system defaults.
1372         $systemdefaulttimezone = date_default_timezone_get();
1373         date_default_timezone_set('Australia/Perth');
1375         foreach ($testvalues as $vals) {
1376             $USER->timezone = $vals['usertimezone'];
1377             $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1379             // On different systems case of AM PM changes so compare case insensitive.
1380             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1381             $actualoutput = core_text::strtolower($actualoutput);
1383             $this->assertSame($vals['expectedoutput'], $actualoutput,
1384                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1385                 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1386         }
1388         // Restore user timezone back to what it was.
1389         $USER->timezone = $userstimezone;
1391         // Restore forcetimezone.
1392         if (!is_null($cfgforcetimezone)) {
1393             $CFG->forcetimezone = $cfgforcetimezone;
1394         }
1396         // Restore system default values.
1397         date_default_timezone_set($systemdefaulttimezone);
1398         setlocale(LC_TIME, $oldlocale);
1399     }
1401     public function test_make_timestamp() {
1402         global $USER, $CFG, $DB;
1403         $this->resetAfterTest();
1405         $this->setAdminUser();
1407         $testvalues = array(
1408             array(
1409                 'usertimezone' => 'America/Moncton',
1410                 'year' => '2011',
1411                 'month' => '7',
1412                 'day' => '1',
1413                 'hour' => '10',
1414                 'minutes' => '00',
1415                 'seconds' => '00',
1416                 'timezone' => '0.0',
1417                 'applydst' => false, // No dst offset.
1418                 'expectedoutput' => '1309514400' // 6pm at UTC+0.
1419             ),
1420             array(
1421                 'usertimezone' => 'America/Moncton',
1422                 'year' => '2011',
1423                 'month' => '7',
1424                 'day' => '1',
1425                 'hour' => '10',
1426                 'minutes' => '00',
1427                 'seconds' => '00',
1428                 'timezone' => '99',  // User default timezone.
1429                 'applydst' => false, // Don't apply dst.
1430                 'expectedoutput' => '1309528800'
1431             ),
1432             array(
1433                 'usertimezone' => 'America/Moncton',
1434                 'year' => '2011',
1435                 'month' => '7',
1436                 'day' => '1',
1437                 'hour' => '10',
1438                 'minutes' => '00',
1439                 'seconds' => '00',
1440                 'timezone' => '99', // User default timezone.
1441                 'applydst' => true, // Apply dst.
1442                 'expectedoutput' => '1309525200'
1443             ),
1444             array(
1445                 'usertimezone' => 'America/Moncton',
1446                 'year' => '2011',
1447                 'month' => '7',
1448                 'day' => '1',
1449                 'hour' => '10',
1450                 'minutes' => '00',
1451                 'seconds' => '00',
1452                 'timezone' => 'America/Moncton', // String timezone.
1453                 'applydst' => true, // Apply dst.
1454                 'expectedoutput' => '1309525200'
1455             ),
1456             array(
1457                 'usertimezone' => '2', // No dst applyed.
1458                 'year' => '2011',
1459                 'month' => '7',
1460                 'day' => '1',
1461                 'hour' => '10',
1462                 'minutes' => '00',
1463                 'seconds' => '00',
1464                 'timezone' => '99', // Take user timezone.
1465                 'applydst' => true, // Apply dst.
1466                 'expectedoutput' => '1309507200'
1467             ),
1468             array(
1469                 'usertimezone' => '-2', // No dst applyed.
1470                 'year' => '2011',
1471                 'month' => '7',
1472                 'day' => '1',
1473                 'hour' => '10',
1474                 'minutes' => '00',
1475                 'seconds' => '00',
1476                 'timezone' => '99', // Take usertimezone.
1477                 'applydst' => true, // Apply dst.
1478                 'expectedoutput' => '1309521600'
1479             ),
1480             array(
1481                 'usertimezone' => '-10', // No dst applyed.
1482                 'year' => '2011',
1483                 'month' => '7',
1484                 'day' => '1',
1485                 'hour' => '10',
1486                 'minutes' => '00',
1487                 'seconds' => '00',
1488                 'timezone' => '2',  // Take this timezone.
1489                 'applydst' => true, // Apply dst.
1490                 'expectedoutput' => '1309507200'
1491             ),
1492             array(
1493                 'usertimezone' => '-10', // No dst applyed.
1494                 'year' => '2011',
1495                 'month' => '7',
1496                 'day' => '1',
1497                 'hour' => '10',
1498                 'minutes' => '00',
1499                 'seconds' => '00',
1500                 'timezone' => '-2', // Take this timezone.
1501                 'applydst' => true, // Apply dst.
1502                 'expectedoutput' => '1309521600'
1503             ),
1504             array(
1505                 'usertimezone' => '-10', // No dst applyed.
1506                 'year' => '2011',
1507                 'month' => '7',
1508                 'day' => '1',
1509                 'hour' => '10',
1510                 'minutes' => '00',
1511                 'seconds' => '00',
1512                 'timezone' => 'random/time', // This should show server time.
1513                 'applydst' => true,          // Apply dst.
1514                 'expectedoutput' => '1309485600'
1515             ),
1516             array(
1517                 'usertimezone' => '14', // Server time.
1518                 'year' => '2011',
1519                 'month' => '7',
1520                 'day' => '1',
1521                 'hour' => '10',
1522                 'minutes' => '00',
1523                 'seconds' => '00',
1524                 'timezone' => '99', // Get user time.
1525                 'applydst' => true, // Apply dst.
1526                 'expectedoutput' => '1309485600'
1527             )
1528         );
1530         // Check if forcetimezone is set then save it and set it to use user timezone.
1531         $cfgforcetimezone = null;
1532         if (isset($CFG->forcetimezone)) {
1533             $cfgforcetimezone = $CFG->forcetimezone;
1534             $CFG->forcetimezone = 99; // Get user default timezone.
1535         }
1537         // Store user default timezone to restore later.
1538         $userstimezone = $USER->timezone;
1540         // The string version of date comes from server locale setting and does
1541         // not respect user language, so it is necessary to reset that.
1542         $oldlocale = setlocale(LC_TIME, '0');
1543         setlocale(LC_TIME, 'en_AU.UTF-8');
1545         // Set default timezone to Australia/Perth, else time calculated
1546         // Will not match expected values. Before that save system defaults.
1547         $systemdefaulttimezone = date_default_timezone_get();
1548         date_default_timezone_set('Australia/Perth');
1550         // Test make_timestamp with all testvals and assert if anything wrong.
1551         foreach ($testvalues as $vals) {
1552             $USER->timezone = $vals['usertimezone'];
1553             $actualoutput = make_timestamp(
1554                 $vals['year'],
1555                 $vals['month'],
1556                 $vals['day'],
1557                 $vals['hour'],
1558                 $vals['minutes'],
1559                 $vals['seconds'],
1560                 $vals['timezone'],
1561                 $vals['applydst']
1562             );
1564             // On different systems case of AM PM changes so compare case insensitive.
1565             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1566             $actualoutput = core_text::strtolower($actualoutput);
1568             $this->assertSame($vals['expectedoutput'], $actualoutput,
1569                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1570                 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1571         }
1573         // Restore user timezone back to what it was.
1574         $USER->timezone = $userstimezone;
1576         // Restore forcetimezone.
1577         if (!is_null($cfgforcetimezone)) {
1578             $CFG->forcetimezone = $cfgforcetimezone;
1579         }
1581         // Restore system default values.
1582         date_default_timezone_set($systemdefaulttimezone);
1583         setlocale(LC_TIME, $oldlocale);
1584     }
1586     /**
1587      * Test get_string and most importantly the implementation of the lang_string
1588      * object.
1589      */
1590     public function test_get_string() {
1591         global $COURSE;
1593         // Make sure we are using English.
1594         $originallang = $COURSE->lang;
1595         $COURSE->lang = 'en';
1597         $yes = get_string('yes');
1598         $yesexpected = 'Yes';
1599         $this->assertInternalType('string', $yes);
1600         $this->assertSame($yesexpected, $yes);
1602         $yes = get_string('yes', 'moodle');
1603         $this->assertInternalType('string', $yes);
1604         $this->assertSame($yesexpected, $yes);
1606         $yes = get_string('yes', 'core');
1607         $this->assertInternalType('string', $yes);
1608         $this->assertSame($yesexpected, $yes);
1610         $yes = get_string('yes', '');
1611         $this->assertInternalType('string', $yes);
1612         $this->assertSame($yesexpected, $yes);
1614         $yes = get_string('yes', null);
1615         $this->assertInternalType('string', $yes);
1616         $this->assertSame($yesexpected, $yes);
1618         $yes = get_string('yes', null, 1);
1619         $this->assertInternalType('string', $yes);
1620         $this->assertSame($yesexpected, $yes);
1622         $days = 1;
1623         $numdays = get_string('numdays', 'core', '1');
1624         $numdaysexpected = $days.' days';
1625         $this->assertInternalType('string', $numdays);
1626         $this->assertSame($numdaysexpected, $numdays);
1628         $yes = get_string('yes', null, null, true);
1629         $this->assertInstanceOf('lang_string', $yes);
1630         $this->assertSame($yesexpected, (string)$yes);
1632         // Test using a lang_string object as the $a argument for a normal
1633         // get_string call (returning string).
1634         $test = new lang_string('yes', null, null, true);
1635         $testexpected = get_string('numdays', 'core', get_string('yes'));
1636         $testresult = get_string('numdays', null, $test);
1637         $this->assertInternalType('string', $testresult);
1638         $this->assertSame($testexpected, $testresult);
1640         // Test using a lang_string object as the $a argument for an object
1641         // get_string call (returning lang_string).
1642         $test = new lang_string('yes', null, null, true);
1643         $testexpected = get_string('numdays', 'core', get_string('yes'));
1644         $testresult = get_string('numdays', null, $test, true);
1645         $this->assertInstanceOf('lang_string', $testresult);
1646         $this->assertSame($testexpected, "$testresult");
1648         // Make sure that object properties that can't be converted don't cause
1649         // errors.
1650         // Level one: This is as deep as current language processing goes.
1651         $test = new stdClass;
1652         $test->one = 'here';
1653         $string = get_string('yes', null, $test, true);
1654         $this->assertEquals($yesexpected, $string);
1656         // Make sure that object properties that can't be converted don't cause
1657         // errors.
1658         // Level two: Language processing doesn't currently reach this deep.
1659         // only immediate scalar properties are worked with.
1660         $test = new stdClass;
1661         $test->one = new stdClass;
1662         $test->one->two = 'here';
1663         $string = get_string('yes', null, $test, true);
1664         $this->assertEquals($yesexpected, $string);
1666         // Make sure that object properties that can't be converted don't cause
1667         // errors.
1668         // Level three: It should never ever go this deep, but we're making sure
1669         // it doesn't cause any probs anyway.
1670         $test = new stdClass;
1671         $test->one = new stdClass;
1672         $test->one->two = new stdClass;
1673         $test->one->two->three = 'here';
1674         $string = get_string('yes', null, $test, true);
1675         $this->assertEquals($yesexpected, $string);
1677         // Make sure that object properties that can't be converted don't cause
1678         // errors and check lang_string properties.
1679         // Level one: This is as deep as current language processing goes.
1680         $test = new stdClass;
1681         $test->one = new lang_string('yes');
1682         $string = get_string('yes', null, $test, true);
1683         $this->assertEquals($yesexpected, $string);
1685         // Make sure that object properties that can't be converted don't cause
1686         // errors and check lang_string properties.
1687         // Level two: Language processing doesn't currently reach this deep.
1688         // only immediate scalar properties are worked with.
1689         $test = new stdClass;
1690         $test->one = new stdClass;
1691         $test->one->two = new lang_string('yes');
1692         $string = get_string('yes', null, $test, true);
1693         $this->assertEquals($yesexpected, $string);
1695         // Make sure that object properties that can't be converted don't cause
1696         // errors and check lang_string properties.
1697         // Level three: It should never ever go this deep, but we're making sure
1698         // it doesn't cause any probs anyway.
1699         $test = new stdClass;
1700         $test->one = new stdClass;
1701         $test->one->two = new stdClass;
1702         $test->one->two->three = new lang_string('yes');
1703         $string = get_string('yes', null, $test, true);
1704         $this->assertEquals($yesexpected, $string);
1706         // Make sure that array properties that can't be converted don't cause
1707         // errors.
1708         $test = array();
1709         $test['one'] = new stdClass;
1710         $test['one']->two = 'here';
1711         $string = get_string('yes', null, $test, true);
1712         $this->assertEquals($yesexpected, $string);
1714         // Same thing but as above except using an object... this is allowed :P.
1715         $string = get_string('yes', null, null, true);
1716         $object = new stdClass;
1717         $object->$string = 'Yes';
1718         $this->assertEquals($yesexpected, $string);
1719         $this->assertEquals($yesexpected, $object->$string);
1721         // Reset the language.
1722         $COURSE->lang = $originallang;
1723     }
1725     /**
1726      * @expectedException PHPUnit_Framework_Error_Warning
1727      */
1728     public function test_get_string_limitation() {
1729         // This is one of the limitations to the lang_string class. It can't be
1730         // used as a key.
1731         $array = array(get_string('yes', null, null, true) => 'yes');
1732     }
1734     /**
1735      * Test localised float formatting.
1736      */
1737     public function test_format_float() {
1739         // Special case for null.
1740         $this->assertEquals('', format_float(null));
1742         // Default 1 decimal place.
1743         $this->assertEquals('5.4', format_float(5.43));
1744         $this->assertEquals('5.0', format_float(5.001));
1746         // Custom number of decimal places.
1747         $this->assertEquals('5.43000', format_float(5.43, 5));
1749         // Option to strip ending zeros after rounding.
1750         $this->assertEquals('5.43', format_float(5.43, 5, true, true));
1751         $this->assertEquals('5', format_float(5.0001, 3, true, true));
1753         // Tests with a localised decimal separator.
1754         $this->define_local_decimal_separator();
1756         // Localisation on (default).
1757         $this->assertEquals('5X43000', format_float(5.43, 5));
1758         $this->assertEquals('5X43', format_float(5.43, 5, true, true));
1760         // Localisation off.
1761         $this->assertEquals('5.43000', format_float(5.43, 5, false));
1762         $this->assertEquals('5.43', format_float(5.43, 5, false, true));
1763     }
1765     /**
1766      * Test localised float unformatting.
1767      */
1768     public function test_unformat_float() {
1770         // Tests without the localised decimal separator.
1772         // Special case for null, empty or white spaces only strings.
1773         $this->assertEquals(null, unformat_float(null));
1774         $this->assertEquals(null, unformat_float(''));
1775         $this->assertEquals(null, unformat_float('    '));
1777         // Regular use.
1778         $this->assertEquals(5.4, unformat_float('5.4'));
1779         $this->assertEquals(5.4, unformat_float('5.4', true));
1781         // No decimal.
1782         $this->assertEquals(5.0, unformat_float('5'));
1784         // Custom number of decimal.
1785         $this->assertEquals(5.43267, unformat_float('5.43267'));
1787         // Empty decimal.
1788         $this->assertEquals(100.0, unformat_float('100.00'));
1790         // With the thousand separator.
1791         $this->assertEquals(1000.0, unformat_float('1 000'));
1792         $this->assertEquals(1000.32, unformat_float('1 000.32'));
1794         // Negative number.
1795         $this->assertEquals(-100.0, unformat_float('-100'));
1797         // Wrong value.
1798         $this->assertEquals(0.0, unformat_float('Wrong value'));
1799         // Wrong value in strict mode.
1800         $this->assertFalse(unformat_float('Wrong value', true));
1802         // Combining options.
1803         $this->assertEquals(-1023.862567, unformat_float('   -1 023.862567     '));
1805         // Bad decimal separator (should crop the decimal).
1806         $this->assertEquals(50.0, unformat_float('50,57'));
1807         // Bad decimal separator in strict mode (should return false).
1808         $this->assertFalse(unformat_float('50,57', true));
1810         // Tests with a localised decimal separator.
1811         $this->define_local_decimal_separator();
1813         // We repeat the tests above but with the current decimal separator.
1815         // Regular use without and with the localised separator.
1816         $this->assertEquals (5.4, unformat_float('5.4'));
1817         $this->assertEquals (5.4, unformat_float('5X4'));
1819         // Custom number of decimal.
1820         $this->assertEquals (5.43267, unformat_float('5X43267'));
1822         // Empty decimal.
1823         $this->assertEquals (100.0, unformat_float('100X00'));
1825         // With the thousand separator.
1826         $this->assertEquals (1000.32, unformat_float('1 000X32'));
1828         // Bad different separator (should crop the decimal).
1829         $this->assertEquals (50.0, unformat_float('50Y57'));
1830         // Bad different separator in strict mode (should return false).
1831         $this->assertFalse (unformat_float('50Y57', true));
1833         // Combining options.
1834         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     '));
1835         // Combining options in strict mode.
1836         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     ', true));
1837     }
1839     /**
1840      * Test deleting of users.
1841      */
1842     public function test_delete_user() {
1843         global $DB, $CFG;
1845         $this->resetAfterTest();
1847         $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
1848         $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
1849         $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
1851         $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
1852         $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
1854         // Delete user and capture event.
1855         $sink = $this->redirectEvents();
1856         $result = delete_user($user);
1857         $events = $sink->get_events();
1858         $sink->close();
1859         $event = array_pop($events);
1861         // Test user is deleted in DB.
1862         $this->assertTrue($result);
1863         $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
1864         $this->assertEquals(1, $deluser->deleted);
1865         $this->assertEquals(0, $deluser->picture);
1866         $this->assertSame('', $deluser->idnumber);
1867         $this->assertSame(md5($user->username), $deluser->email);
1868         $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
1870         $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
1872         // Test Event.
1873         $this->assertInstanceOf('\core\event\user_deleted', $event);
1874         $this->assertSame($user->id, $event->objectid);
1875         $this->assertSame('user_deleted', $event->get_legacy_eventname());
1876         $this->assertEventLegacyData($user, $event);
1877         $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
1878         $this->assertEventLegacyLogData($expectedlogdata, $event);
1880         // Try invalid params.
1881         $record = new stdClass();
1882         $record->grrr = 1;
1883         try {
1884             delete_user($record);
1885             $this->fail('Expecting exception for invalid delete_user() $user parameter');
1886         } catch (moodle_exception $ex) {
1887             $this->assertInstanceOf('coding_exception', $ex);
1888         }
1889         $record->id = 1;
1890         try {
1891             delete_user($record);
1892             $this->fail('Expecting exception for invalid delete_user() $user parameter');
1893         } catch (moodle_exception $ex) {
1894             $this->assertInstanceOf('coding_exception', $ex);
1895         }
1897         $record = new stdClass();
1898         $record->id = 666;
1899         $record->username = 'xx';
1900         $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
1901         $result = delete_user($record);
1902         $this->assertFalse($result);
1904         $result = delete_user($guest);
1905         $this->assertFalse($result);
1907         $result = delete_user($admin);
1908         $this->assertFalse($result);
1910         $this->resetDebugging();
1911     }
1913     /**
1914      * Test function convert_to_array()
1915      */
1916     public function test_convert_to_array() {
1917         // Check that normal classes are converted to arrays the same way as (array) would do.
1918         $obj = new stdClass();
1919         $obj->prop1 = 'hello';
1920         $obj->prop2 = array('first', 'second', 13);
1921         $obj->prop3 = 15;
1922         $this->assertEquals(convert_to_array($obj), (array)$obj);
1924         // Check that context object (with iterator) is converted to array properly.
1925         $obj = context_system::instance();
1926         $ar = array(
1927             'id'           => $obj->id,
1928             'contextlevel' => $obj->contextlevel,
1929             'instanceid'   => $obj->instanceid,
1930             'path'         => $obj->path,
1931             'depth'        => $obj->depth
1932         );
1933         $this->assertEquals(convert_to_array($obj), $ar);
1934     }
1936     /**
1937      * Test the function date_format_string().
1938      */
1939     public function test_date_format_string() {
1940         global $CFG;
1942         // Forcing locale and timezone.
1943         $oldlocale = setlocale(LC_TIME, '0');
1944         if ($CFG->ostype == 'WINDOWS') {
1945             setlocale(LC_TIME, 'English_Australia.1252');
1946         } else {
1947             setlocale(LC_TIME, 'en_AU.UTF-8');
1948         }
1949         $systemdefaulttimezone = date_default_timezone_get();
1950         date_default_timezone_set('Australia/Perth');
1952         $tests = array(
1953             array(
1954                 'tz' => 99,
1955                 'str' => '%A, %d %B %Y, %I:%M %p',
1956                 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
1957             ),
1958             array(
1959                 'tz' => 0,
1960                 'str' => '%A, %d %B %Y, %I:%M %p',
1961                 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
1962             ),
1963             array(
1964                 'tz' => -12,
1965                 'str' => '%A, %d %B %Y, %I:%M %p',
1966                 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
1967             ),
1968             // Following tests pass on Windows only because en lang pack does
1969             // not contain localewincharset, in real life lang pack maintainers
1970             // may use only characters that are present in localewincharset
1971             // in format strings!
1972             array(
1973                 'tz' => 99,
1974                 'str' => 'Žluťoučký koníček %A',
1975                 'expected' => 'Žluťoučký koníček Saturday'
1976             ),
1977             array(
1978                 'tz' => 99,
1979                 'str' => '言語設定言語 %A',
1980                 'expected' => '言語設定言語 Saturday'
1981             ),
1982             array(
1983                 'tz' => 99,
1984                 'str' => '简体中文简体 %A',
1985                 'expected' => '简体中文简体 Saturday'
1986             ),
1987         );
1989         // Note: date_format_string() uses the timezone only to differenciate
1990         // the server time from the UTC time. It does not modify the timestamp.
1991         // Hence similar results for timezones <= 13.
1992         // On different systems case of AM PM changes so compare case insensitive.
1993         foreach ($tests as $test) {
1994             $str = date_format_string(1293876000, $test['str'], $test['tz']);
1995             $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
1996         }
1998         // Restore system default values.
1999         date_default_timezone_set($systemdefaulttimezone);
2000         setlocale(LC_TIME, $oldlocale);
2001     }
2003     public function test_get_config() {
2004         global $CFG;
2006         $this->resetAfterTest();
2008         // Preparation.
2009         set_config('phpunit_test_get_config_1', 'test 1');
2010         set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2011         if (!is_array($CFG->config_php_settings)) {
2012             $CFG->config_php_settings = array();
2013         }
2014         $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
2016         if (!is_array($CFG->forced_plugin_settings)) {
2017             $CFG->forced_plugin_settings = array();
2018         }
2019         if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
2020             $CFG->forced_plugin_settings['mod_forum'] = array();
2021         }
2022         $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2023         $CFG->phpunit_test_get_config_5 = 'test 5';
2025         // Testing.
2026         $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
2027         $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2028         $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
2029         $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2030         $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2031         $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2032         $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2034         // Test config we know to exist.
2035         $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
2036         $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2037         $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2038         $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2040         // Test setting a config var that already exists.
2041         set_config('phpunit_test_get_config_1', 'test a');
2042         $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
2043         $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
2045         // Test cache invalidation.
2046         $cache = cache::make('core', 'config');
2047         $this->assertInternalType('array', $cache->get('core'));
2048         $this->assertInternalType('array', $cache->get('mod_forum'));
2049         set_config('phpunit_test_get_config_1', 'test b');
2050         $this->assertFalse($cache->get('core'));
2051         set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2052         $this->assertFalse($cache->get('mod_forum'));
2053     }
2055     public function test_get_max_upload_sizes() {
2056         // Test with very low limits so we are not affected by php upload limits.
2057         // Test activity limit smallest.
2058         $sitebytes = 102400;
2059         $coursebytes = 51200;
2060         $modulebytes = 10240;
2061         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2063         $this->assertSame('Activity upload limit (10KB)', $result['0']);
2064         $this->assertCount(2, $result);
2066         // Test course limit smallest.
2067         $sitebytes = 102400;
2068         $coursebytes = 10240;
2069         $modulebytes = 51200;
2070         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2072         $this->assertSame('Course upload limit (10KB)', $result['0']);
2073         $this->assertCount(2, $result);
2075         // Test site limit smallest.
2076         $sitebytes = 10240;
2077         $coursebytes = 102400;
2078         $modulebytes = 51200;
2079         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2081         $this->assertSame('Site upload limit (10KB)', $result['0']);
2082         $this->assertCount(2, $result);
2084         // Test site limit not set.
2085         $sitebytes = 0;
2086         $coursebytes = 102400;
2087         $modulebytes = 51200;
2088         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2090         $this->assertSame('Activity upload limit (50KB)', $result['0']);
2091         $this->assertCount(3, $result);
2093         $sitebytes = 0;
2094         $coursebytes = 51200;
2095         $modulebytes = 102400;
2096         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2098         $this->assertSame('Course upload limit (50KB)', $result['0']);
2099         $this->assertCount(3, $result);
2101         // Test custom bytes in range.
2102         $sitebytes = 102400;
2103         $coursebytes = 51200;
2104         $modulebytes = 51200;
2105         $custombytes = 10240;
2106         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2108         $this->assertCount(3, $result);
2110         // Test custom bytes in range but non-standard.
2111         $sitebytes = 102400;
2112         $coursebytes = 51200;
2113         $modulebytes = 51200;
2114         $custombytes = 25600;
2115         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2117         $this->assertCount(4, $result);
2119         // Test custom bytes out of range.
2120         $sitebytes = 102400;
2121         $coursebytes = 51200;
2122         $modulebytes = 51200;
2123         $custombytes = 102400;
2124         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2126         $this->assertCount(3, $result);
2128         // Test custom bytes out of range and non-standard.
2129         $sitebytes = 102400;
2130         $coursebytes = 51200;
2131         $modulebytes = 51200;
2132         $custombytes = 256000;
2133         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2135         $this->assertCount(3, $result);
2137         // Test site limit only.
2138         $sitebytes = 51200;
2139         $result = get_max_upload_sizes($sitebytes);
2141         $this->assertSame('Site upload limit (50KB)', $result['0']);
2142         $this->assertSame('50KB', $result['51200']);
2143         $this->assertSame('10KB', $result['10240']);
2144         $this->assertCount(3, $result);
2146         // Test no limit.
2147         $result = get_max_upload_sizes();
2148         $this->assertArrayHasKey('0', $result);
2149         $this->assertArrayHasKey(get_max_upload_file_size(), $result);
2150     }
2152     /**
2153      * Test function password_is_legacy_hash().
2154      */
2155     public function test_password_is_legacy_hash() {
2156         // Well formed md5s should be matched.
2157         foreach (array('some', 'strings', 'to_check!') as $string) {
2158             $md5 = md5($string);
2159             $this->assertTrue(password_is_legacy_hash($md5));
2160         }
2161         // Strings that are not md5s should not be matched.
2162         foreach (array('', AUTH_PASSWORD_NOT_CACHED, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
2163             $this->assertFalse(password_is_legacy_hash($notmd5));
2164         }
2165     }
2167     /**
2168      * Test function validate_internal_user_password().
2169      */
2170     public function test_validate_internal_user_password() {
2171         if (password_compat_not_supported()) {
2172             // If bcrypt is not properly supported test legacy md5 hashes instead.
2173             // Can't hardcode these as we don't know the site's password salt.
2174             $validhashes = array(
2175                 'pw' => hash_internal_user_password('pw'),
2176                 'abc' => hash_internal_user_password('abc'),
2177                 'C0mP1eX_&}<?@*&%` |\"' => hash_internal_user_password('C0mP1eX_&}<?@*&%` |\"'),
2178                 'ĩńťėŕňăţĩōŋāĹ' => hash_internal_user_password('ĩńťėŕňăţĩōŋāĹ')
2179             );
2180         } else {
2181             // Otherwise test bcrypt hashes.
2182             $validhashes = array(
2183                 'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2184                 'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2185                 'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2186                 'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
2187             );
2188         }
2190         foreach ($validhashes as $password => $hash) {
2191             $user = new stdClass();
2192             $user->auth = 'manual';
2193             $user->password = $hash;
2194             // The correct password should be validated.
2195             $this->assertTrue(validate_internal_user_password($user, $password));
2196             // An incorrect password should not be validated.
2197             $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2198         }
2199     }
2201     /**
2202      * Test function hash_internal_user_password().
2203      */
2204     public function test_hash_internal_user_password() {
2205         $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2207         // Check that some passwords that we convert to hashes can
2208         // be validated.
2209         foreach ($passwords as $password) {
2210             $hash = hash_internal_user_password($password);
2211             $fasthash = hash_internal_user_password($password, true);
2212             $user = new stdClass();
2213             $user->auth = 'manual';
2214             $user->password = $hash;
2215             $this->assertTrue(validate_internal_user_password($user, $password));
2217             if (password_compat_not_supported()) {
2218                 // If bcrypt is not properly supported make sure the passwords are in md5 format.
2219                 $this->assertTrue(password_is_legacy_hash($hash));
2220             } else {
2221                 // Otherwise they should not be in md5 format.
2222                 $this->assertFalse(password_is_legacy_hash($hash));
2224                 // Check that cost factor in hash is correctly set.
2225                 $this->assertRegExp('/\$10\$/', $hash);
2226                 $this->assertRegExp('/\$04\$/', $fasthash);
2227             }
2228         }
2229     }
2231     /**
2232      * Test function update_internal_user_password().
2233      */
2234     public function test_update_internal_user_password() {
2235         global $DB;
2236         $this->resetAfterTest();
2237         $passwords = array('password', '1234', 'changeme', '****');
2238         foreach ($passwords as $password) {
2239             $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2240             update_internal_user_password($user, $password);
2241             // The user object should have been updated.
2242             $this->assertTrue(validate_internal_user_password($user, $password));
2243             // The database field for the user should also have been updated to the
2244             // same value.
2245             $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
2246         }
2248         $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2249         // Manually set the user's password to the md5 of the string 'password'.
2250         $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
2252         // Update the password.
2253         update_internal_user_password($user, 'password');
2255         if (password_compat_not_supported()) {
2256             // If bcrypt not properly supported the password should remain as an md5 hash.
2257             $expected_hash = hash_internal_user_password('password', true);
2258             $this->assertSame($user->password, $expected_hash);
2259             $this->assertTrue(password_is_legacy_hash($user->password));
2260         } else {
2261             // Otherwise password should have been updated to a bcrypt hash.
2262             $this->assertFalse(password_is_legacy_hash($user->password));
2263         }
2264     }
2266     public function test_fullname() {
2267         global $CFG;
2269         $this->resetAfterTest();
2271         // Create a user to test the name display on.
2272         $record = array();
2273         $record['firstname'] = 'Scott';
2274         $record['lastname'] = 'Fletcher';
2275         $record['firstnamephonetic'] = 'スコット';
2276         $record['lastnamephonetic'] = 'フレチャー';
2277         $record['alternatename'] = 'No friends';
2278         $user = $this->getDataGenerator()->create_user($record);
2280         // Back up config settings for restore later.
2281         $originalcfg = new stdClass();
2282         $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
2284         // Testing existing fullnamedisplay settings.
2285         $CFG->fullnamedisplay = 'firstname';
2286         $testname = fullname($user);
2287         $this->assertSame($user->firstname, $testname);
2289         $CFG->fullnamedisplay = 'firstname lastname';
2290         $expectedname = "$user->firstname $user->lastname";
2291         $testname = fullname($user);
2292         $this->assertSame($expectedname, $testname);
2294         $CFG->fullnamedisplay = 'lastname firstname';
2295         $expectedname = "$user->lastname $user->firstname";
2296         $testname = fullname($user);
2297         $this->assertSame($expectedname, $testname);
2299         $expectedname = get_string('fullnamedisplay', null, $user);
2300         $CFG->fullnamedisplay = 'language';
2301         $testname = fullname($user);
2302         $this->assertSame($expectedname, $testname);
2304         // Test override parameter.
2305         $CFG->fullnamedisplay = 'firstname';
2306         $expectedname = "$user->firstname $user->lastname";
2307         $testname = fullname($user, true);
2308         $this->assertSame($expectedname, $testname);
2310         // Test additional name fields.
2311         $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
2312         $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
2313         $testname = fullname($user);
2314         $this->assertSame($expectedname, $testname);
2316         // Test for handling missing data.
2317         $user->middlename = null;
2318         // Parenthesis with no data.
2319         $CFG->fullnamedisplay = 'firstname (middlename) lastname';
2320         $expectedname = "$user->firstname $user->lastname";
2321         $testname = fullname($user);
2322         $this->assertSame($expectedname, $testname);
2324         // Extra spaces due to no data.
2325         $CFG->fullnamedisplay = 'firstname middlename lastname';
2326         $expectedname = "$user->firstname $user->lastname";
2327         $testname = fullname($user);
2328         $this->assertSame($expectedname, $testname);
2330         // Regular expression testing.
2331         // Remove some data from the user fields.
2332         $user->firstnamephonetic = '';
2333         $user->lastnamephonetic = '';
2335         // Removing empty brackets and excess whitespace.
2336         // All of these configurations should resolve to just firstname lastname.
2337         $configarray = array();
2338         $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
2339         $configarray[] = 'firstname lastname \'middlename\'';
2340         $configarray[] = 'firstname "firstnamephonetic" lastname';
2341         $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
2343         foreach ($configarray as $config) {
2344             $CFG->fullnamedisplay = $config;
2345             $expectedname = "$user->firstname $user->lastname";
2346             $testname = fullname($user);
2347             $this->assertSame($expectedname, $testname);
2348         }
2350         // Check to make sure that other characters are left in place.
2351         $configarray = array();
2352         $configarray['0'] = new stdClass();
2353         $configarray['0']->config = 'lastname firstname, middlename';
2354         $configarray['0']->expectedname = "$user->lastname $user->firstname,";
2355         $configarray['1'] = new stdClass();
2356         $configarray['1']->config = 'lastname firstname + alternatename';
2357         $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
2358         $configarray['2'] = new stdClass();
2359         $configarray['2']->config = 'firstname aka: alternatename';
2360         $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
2361         $configarray['3'] = new stdClass();
2362         $configarray['3']->config = 'firstname (alternatename)';
2363         $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
2364         $configarray['4'] = new stdClass();
2365         $configarray['4']->config = 'firstname [alternatename]';
2366         $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
2367         $configarray['5'] = new stdClass();
2368         $configarray['5']->config = 'firstname "lastname"';
2369         $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
2371         foreach ($configarray as $config) {
2372             $CFG->fullnamedisplay = $config->config;
2373             $expectedname = $config->expectedname;
2374             $testname = fullname($user);
2375             $this->assertSame($expectedname, $testname);
2376         }
2378         // Tidy up after we finish testing.
2379         $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
2380     }
2382     public function test_get_all_user_name_fields() {
2383         $this->resetAfterTest();
2385         // Additional names in an array.
2386         $testarray = array('firstnamephonetic',
2387                            'lastnamephonetic',
2388                            'middlename',
2389                            'alternatename',
2390                            'firstname',
2391                            'lastname');
2392         $this->assertEquals($testarray, get_all_user_name_fields());
2394         // Additional names as a string.
2395         $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
2396         $this->assertEquals($teststring, get_all_user_name_fields(true));
2398         // Additional names as a string with an alias.
2399         $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
2400         $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
2401     }
2403     public function test_order_in_string() {
2404         $this->resetAfterTest();
2406         // Return an array in an order as they are encountered in a string.
2407         $valuearray = array('second', 'firsthalf', 'first');
2408         $formatstring = 'first firsthalf some other text (second)';
2409         $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
2410         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2412         // Try again with a different order for the format.
2413         $valuearray = array('second', 'firsthalf', 'first');
2414         $formatstring = 'firsthalf first second';
2415         $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
2416         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2418         // Try again with yet another different order for the format.
2419         $valuearray = array('second', 'firsthalf', 'first');
2420         $formatstring = 'start seconds away second firstquater first firsthalf';
2421         $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
2422         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2423     }
2425     public function test_complete_user_login() {
2426         global $USER;
2428         $this->resetAfterTest();
2429         $user = $this->getDataGenerator()->create_user();
2430         $this->setUser(0);
2432         $sink = $this->redirectEvents();
2433         @complete_user_login($user); // Hide session header errors.
2434         $this->assertEquals($user->id, $USER->id);
2435         $events = $sink->get_events();
2436         $sink->close();
2438         $this->assertCount(2, $events);
2439         $event = $events[0];
2440         $this->assertInstanceOf('\core\event\user_updated', $event);
2441         $event = $events[1];
2442         $this->assertInstanceOf('\core\event\user_loggedin', $event);
2443         $this->assertEquals('user', $event->objecttable);
2444         $this->assertEquals($user->id, $event->objectid);
2445         $this->assertEquals(context_system::instance()->id, $event->contextid);
2446         $this->assertEquals($user, $event->get_record_snapshot('user', $user->id));
2447     }
2449     /**
2450      * Test require_logout.
2451      */
2452     public function test_require_logout() {
2453         $this->resetAfterTest();
2454         $user = $this->getDataGenerator()->create_user();
2455         $this->setUser($user);
2457         $this->assertTrue(isloggedin());
2459         // Logout user and capture event.
2460         $sink = $this->redirectEvents();
2461         require_logout();
2462         $events = $sink->get_events();
2463         $sink->close();
2464         $event = array_pop($events);
2466         // Check if user is logged out.
2467         $this->assertFalse(isloggedin());
2469         // Test Event.
2470         $this->assertInstanceOf('\core\event\user_loggedout', $event);
2471         $this->assertSame($user->id, $event->objectid);
2472         $this->assertSame('user_logout', $event->get_legacy_eventname());
2473         $this->assertEventLegacyData($user, $event);
2474         $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
2475             $event->objectid);
2476         $this->assertEventLegacyLogData($expectedlogdata, $event);
2477     }