Merge branch 'wip-MDL-40356-master' of git://github.com/abgreeve/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('feedback360', clean_param('feedback360', PARAM_COMPONENT));
486         $this->assertSame('mod_feedback360', clean_param('mod_feedback360', PARAM_COMPONENT));
487         $this->assertSame('', clean_param('mod_2something', PARAM_COMPONENT));
488         $this->assertSame('', clean_param('2mod_something', PARAM_COMPONENT));
489         $this->assertSame('', clean_param('mod_something_xx', PARAM_COMPONENT));
490         $this->assertSame('', clean_param('auth_something__xx', PARAM_COMPONENT));
491         $this->assertSame('', clean_param('mod_Something', PARAM_COMPONENT));
492         $this->assertSame('', clean_param('mod_somethíng', PARAM_COMPONENT));
493         $this->assertSame('', clean_param('mod__something', PARAM_COMPONENT));
494         $this->assertSame('', clean_param('auth_xx-yy', PARAM_COMPONENT));
495         $this->assertSame('', clean_param('_auth_xx', PARAM_COMPONENT));
496         $this->assertSame('', clean_param('a2uth_xx', PARAM_COMPONENT));
497         $this->assertSame('', clean_param('auth_xx_', PARAM_COMPONENT));
498         $this->assertSame('', clean_param('auth_xx.old', PARAM_COMPONENT));
499         $this->assertSame('', clean_param('_user', PARAM_COMPONENT));
500         $this->assertSame('', clean_param('2rating', PARAM_COMPONENT));
501         $this->assertSame('', clean_param('user_', PARAM_COMPONENT));
502     }
504     public function test_is_valid_plugin_name() {
505         $this->assertTrue(is_valid_plugin_name('forum'));
506         $this->assertTrue(is_valid_plugin_name('forum2'));
507         $this->assertTrue(is_valid_plugin_name('feedback360'));
508         $this->assertTrue(is_valid_plugin_name('online_users'));
509         $this->assertTrue(is_valid_plugin_name('blond_online_users'));
510         $this->assertFalse(is_valid_plugin_name('online__users'));
511         $this->assertFalse(is_valid_plugin_name('forum '));
512         $this->assertFalse(is_valid_plugin_name('forum.old'));
513         $this->assertFalse(is_valid_plugin_name('xx-yy'));
514         $this->assertFalse(is_valid_plugin_name('2xx'));
515         $this->assertFalse(is_valid_plugin_name('Xx'));
516         $this->assertFalse(is_valid_plugin_name('_xx'));
517         $this->assertFalse(is_valid_plugin_name('xx_'));
518     }
520     public function test_clean_param_plugin() {
521         // Please note the cleaning of plugin names is very strict, no guessing here.
522         $this->assertSame('forum', clean_param('forum', PARAM_PLUGIN));
523         $this->assertSame('forum2', clean_param('forum2', PARAM_PLUGIN));
524         $this->assertSame('feedback360', clean_param('feedback360', PARAM_PLUGIN));
525         $this->assertSame('online_users', clean_param('online_users', PARAM_PLUGIN));
526         $this->assertSame('blond_online_users', clean_param('blond_online_users', PARAM_PLUGIN));
527         $this->assertSame('', clean_param('online__users', PARAM_PLUGIN));
528         $this->assertSame('', clean_param('forum ', PARAM_PLUGIN));
529         $this->assertSame('', clean_param('forum.old', PARAM_PLUGIN));
530         $this->assertSame('', clean_param('xx-yy', PARAM_PLUGIN));
531         $this->assertSame('', clean_param('2xx', PARAM_PLUGIN));
532         $this->assertSame('', clean_param('Xx', PARAM_PLUGIN));
533         $this->assertSame('', clean_param('_xx', PARAM_PLUGIN));
534         $this->assertSame('', clean_param('xx_', PARAM_PLUGIN));
535     }
537     public function test_clean_param_area() {
538         // Please note the cleaning of area names is very strict, no guessing here.
539         $this->assertSame('something', clean_param('something', PARAM_AREA));
540         $this->assertSame('something2', clean_param('something2', PARAM_AREA));
541         $this->assertSame('some_thing', clean_param('some_thing', PARAM_AREA));
542         $this->assertSame('some_thing_xx', clean_param('some_thing_xx', PARAM_AREA));
543         $this->assertSame('feedback360', clean_param('feedback360', PARAM_AREA));
544         $this->assertSame('', clean_param('_something', PARAM_AREA));
545         $this->assertSame('', clean_param('something_', PARAM_AREA));
546         $this->assertSame('', clean_param('2something', PARAM_AREA));
547         $this->assertSame('', clean_param('Something', PARAM_AREA));
548         $this->assertSame('', clean_param('some-thing', PARAM_AREA));
549         $this->assertSame('', clean_param('somethííng', PARAM_AREA));
550         $this->assertSame('', clean_param('something.x', PARAM_AREA));
551     }
553     public function test_clean_param_text() {
554         $this->assertSame(PARAM_TEXT, PARAM_MULTILANG);
555         // Standard.
556         $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));
557         $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));
558         $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));
559         // Malformed.
560         $this->assertSame('<span lang="en" class="multilang">aa</span>', clean_param('<span lang="en" class="multilang">aa</span>', PARAM_TEXT));
561         $this->assertSame('aa', clean_param('<span lang="en" class="nothing" class="multilang">aa</span>', PARAM_TEXT));
562         $this->assertSame('aa', clean_param('<lang lang="en" class="multilang">aa</lang>', PARAM_TEXT));
563         $this->assertSame('aa', clean_param('<lang lang="en!!">aa</lang>', PARAM_TEXT));
564         $this->assertSame('aa', clean_param('<span lang="en==" class="multilang">aa</span>', PARAM_TEXT));
565         $this->assertSame('abc', clean_param('a<em>b</em>c', PARAM_TEXT));
566         $this->assertSame('a>c>', clean_param('a><xx >c>', PARAM_TEXT)); // Standard strip_tags() behaviour.
567         $this->assertSame('a', clean_param('a<b', PARAM_TEXT));
568         $this->assertSame('a>b', clean_param('a>b', PARAM_TEXT));
569         $this->assertSame('<lang lang="en">a>a</lang>', clean_param('<lang lang="en">a>a</lang>', PARAM_TEXT)); // Standard strip_tags() behaviour.
570         $this->assertSame('a', clean_param('<lang lang="en">a<a</lang>', PARAM_TEXT));
571         $this->assertSame('<lang lang="en">aa</lang>', clean_param('<lang lang="en">a<br>a</lang>', PARAM_TEXT));
572     }
574     public function test_clean_param_url() {
575         // Test PARAM_URL and PARAM_LOCALURL a bit.
576         $this->assertSame('http://google.com/', clean_param('http://google.com/', PARAM_URL));
577         $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));
578         $this->assertSame('http://localhost/', clean_param('http://localhost/', PARAM_URL));
579         $this->assertSame('http://0.255.1.1/numericip.php', clean_param('http://0.255.1.1/numericip.php', PARAM_URL));
580         $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_URL));
581         $this->assertSame('', clean_param('funny:thing', PARAM_URL));
582     }
584     public function test_clean_param_localurl() {
585         global $CFG;
586         $this->assertSame('', clean_param('http://google.com/', PARAM_LOCALURL));
587         $this->assertSame('', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL));
588         $this->assertSame(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
589         $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_LOCALURL));
590         $this->assertSame('', clean_param('funny:thing', PARAM_LOCALURL));
591         $this->assertSame('course/view.php?id=3', clean_param('course/view.php?id=3', PARAM_LOCALURL));
592     }
594     public function test_clean_param_file() {
595         $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_FILE));
596         $this->assertSame('badfile.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE));
597         $this->assertSame('..parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_FILE));
598         $this->assertSame('....grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_FILE));
599         $this->assertSame('..winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_FILE));
600         $this->assertSame('....wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_FILE));
601         $this->assertSame('myfile.a.b.txt', clean_param('myfile.a.b.txt', PARAM_FILE));
602         $this->assertSame('myfile..a..b.txt', clean_param('myfile..a..b.txt', PARAM_FILE));
603         $this->assertSame('myfile.a..b...txt', clean_param('myfile.a..b...txt', PARAM_FILE));
604         $this->assertSame('myfile.a.txt', clean_param('myfile.a.txt', PARAM_FILE));
605         $this->assertSame('myfile...txt', clean_param('myfile...txt', PARAM_FILE));
606         $this->assertSame('...jpg', clean_param('...jpg', PARAM_FILE));
607         $this->assertSame('.a.b.', clean_param('.a.b.', PARAM_FILE));
608         $this->assertSame('', clean_param('.', PARAM_FILE));
609         $this->assertSame('', clean_param('..', PARAM_FILE));
610         $this->assertSame('...', clean_param('...', PARAM_FILE));
611         $this->assertSame('. . . .', clean_param('. . . .', PARAM_FILE));
612         $this->assertSame('dontrtrim.me. .. .. . ', clean_param('dontrtrim.me. .. .. . ', PARAM_FILE));
613         $this->assertSame(' . .dontltrim.me', clean_param(' . .dontltrim.me', PARAM_FILE));
614         $this->assertSame('here is a tab.txt', clean_param("here is a tab\t.txt", PARAM_FILE));
615         $this->assertSame('here is a linebreak.txt', clean_param("here is a line\r\nbreak.txt", PARAM_FILE));
617         // The following behaviours have been maintained although they seem a little odd.
618         $this->assertSame('funnything', clean_param('funny:thing', PARAM_FILE));
619         $this->assertSame('.currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_FILE));
620         $this->assertSame('ctempwindowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_FILE));
621         $this->assertSame('homeuserlinuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_FILE));
622         $this->assertSame('~myfile.txt', clean_param('~/myfile.txt', PARAM_FILE));
623     }
625     public function test_clean_param_path() {
626         $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_PATH));
627         $this->assertSame('bad/file.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH));
628         $this->assertSame('/parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_PATH));
629         $this->assertSame('/grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_PATH));
630         $this->assertSame('/winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_PATH));
631         $this->assertSame('/wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_PATH));
632         $this->assertSame('funnything', clean_param('funny:thing', PARAM_PATH));
633         $this->assertSame('./here', clean_param('./././here', PARAM_PATH));
634         $this->assertSame('./currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_PATH));
635         $this->assertSame('c/temp/windowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_PATH));
636         $this->assertSame('/home/user/linuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_PATH));
637         $this->assertSame('/home../user ./.linuxfile.txt', clean_param('/home../user ./.linuxfile.txt', PARAM_PATH));
638         $this->assertSame('~/myfile.txt', clean_param('~/myfile.txt', PARAM_PATH));
639         $this->assertSame('~/myfile.txt', clean_param('~/../myfile.txt', PARAM_PATH));
640         $this->assertSame('/..b../.../myfile.txt', clean_param('/..b../.../myfile.txt', PARAM_PATH));
641         $this->assertSame('..b../.../myfile.txt', clean_param('..b../.../myfile.txt', PARAM_PATH));
642         $this->assertSame('/super/slashes/', clean_param('/super//slashes///', PARAM_PATH));
643     }
645     public function test_clean_param_username() {
646         global $CFG;
647         $currentstatus =  $CFG->extendedusernamechars;
649         // Run tests with extended character == false;.
650         $CFG->extendedusernamechars = false;
651         $this->assertSame('johndoe123', clean_param('johndoe123', PARAM_USERNAME) );
652         $this->assertSame('john.doe', clean_param('john.doe', PARAM_USERNAME));
653         $this->assertSame('john-doe', clean_param('john-doe', PARAM_USERNAME));
654         $this->assertSame('john-doe', clean_param('john- doe', PARAM_USERNAME));
655         $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
656         $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
657         $this->assertSame('johndoe', clean_param('john~doe', PARAM_USERNAME));
658         $this->assertSame('johndoe', clean_param('john´doe', PARAM_USERNAME));
659         $this->assertSame(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
660         $this->assertSame('johnd', clean_param('JOHNdóé ', PARAM_USERNAME));
661         $this->assertSame(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýá\9e?\9eý??\9adoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
663         // Test success condition, if extendedusernamechars == ENABLE;.
664         $CFG->extendedusernamechars = true;
665         $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
666         $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
667         $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john#$%&()+_^');
668         $this->assertSame('john~doe', clean_param('john~doe', PARAM_USERNAME));
669         $this->assertSame('john´doe', clean_param('joHN´doe', PARAM_USERNAME));
670         $this->assertSame('johndoe', clean_param('johnDOE', PARAM_USERNAME));
671         $this->assertSame('johndóé', clean_param('johndóé ', PARAM_USERNAME));
673         $CFG->extendedusernamechars = $currentstatus;
674     }
676     public function test_clean_param_stringid() {
677         // Test string identifiers validation.
678         // Valid strings.
679         $this->assertSame('validstring', clean_param('validstring', PARAM_STRINGID));
680         $this->assertSame('mod/foobar:valid_capability', clean_param('mod/foobar:valid_capability', PARAM_STRINGID));
681         $this->assertSame('CZ', clean_param('CZ', PARAM_STRINGID));
682         $this->assertSame('application/vnd.ms-powerpoint', clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID));
683         $this->assertSame('grade2', clean_param('grade2', PARAM_STRINGID));
684         // Invalid strings.
685         $this->assertSame('', clean_param('trailing ', PARAM_STRINGID));
686         $this->assertSame('', clean_param('space bar', PARAM_STRINGID));
687         $this->assertSame('', clean_param('0numeric', PARAM_STRINGID));
688         $this->assertSame('', clean_param('*', PARAM_STRINGID));
689         $this->assertSame('', clean_param(' ', PARAM_STRINGID));
690     }
692     public function test_clean_param_timezone() {
693         // Test timezone validation.
694         $testvalues = array (
695             'America/Jamaica'                => 'America/Jamaica',
696             'America/Argentina/Cordoba'      => 'America/Argentina/Cordoba',
697             'America/Port-au-Prince'         => 'America/Port-au-Prince',
698             'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
699             'PST8PDT'                        => 'PST8PDT',
700             'Wrong.Value'                    => '',
701             'Wrong/.Value'                   => '',
702             'Wrong(Value)'                   => '',
703             '0'                              => '0',
704             '0.0'                            => '0.0',
705             '0.5'                            => '0.5',
706             '9.0'                            => '9.0',
707             '-9.0'                           => '-9.0',
708             '+9.0'                           => '+9.0',
709             '9.5'                            => '9.5',
710             '-9.5'                           => '-9.5',
711             '+9.5'                           => '+9.5',
712             '12.0'                           => '12.0',
713             '-12.0'                          => '-12.0',
714             '+12.0'                          => '+12.0',
715             '12.5'                           => '12.5',
716             '-12.5'                          => '-12.5',
717             '+12.5'                          => '+12.5',
718             '13.0'                           => '13.0',
719             '-13.0'                          => '-13.0',
720             '+13.0'                          => '+13.0',
721             '13.5'                           => '',
722             '+13.5'                          => '',
723             '-13.5'                          => '',
724             '0.2'                            => '');
726         foreach ($testvalues as $testvalue => $expectedvalue) {
727             $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
728             $this->assertEquals($expectedvalue, $actualvalue);
729         }
730     }
732     public function test_validate_param() {
733         try {
734             $param = validate_param('11a', PARAM_INT);
735             $this->fail('invalid_parameter_exception expected');
736         } catch (moodle_exception $ex) {
737             $this->assertInstanceOf('invalid_parameter_exception', $ex);
738         }
740         $param = validate_param('11', PARAM_INT);
741         $this->assertSame(11, $param);
743         try {
744             $param = validate_param(null, PARAM_INT, false);
745             $this->fail('invalid_parameter_exception expected');
746         } catch (moodle_exception $ex) {
747             $this->assertInstanceOf('invalid_parameter_exception', $ex);
748         }
750         $param = validate_param(null, PARAM_INT, true);
751         $this->assertSame(null, $param);
753         try {
754             $param = validate_param(array(), PARAM_INT);
755             $this->fail('invalid_parameter_exception expected');
756         } catch (moodle_exception $ex) {
757             $this->assertInstanceOf('invalid_parameter_exception', $ex);
758         }
759         try {
760             $param = validate_param(new stdClass, PARAM_INT);
761             $this->fail('invalid_parameter_exception expected');
762         } catch (moodle_exception $ex) {
763             $this->assertInstanceOf('invalid_parameter_exception', $ex);
764         }
766         $param = validate_param('1.0', PARAM_FLOAT);
767         $this->assertSame(1.0, $param);
769         // Make sure valid floats do not cause exception.
770         validate_param(1.0, PARAM_FLOAT);
771         validate_param(10, PARAM_FLOAT);
772         validate_param('0', PARAM_FLOAT);
773         validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
774         validate_param('011.1', PARAM_FLOAT);
775         validate_param('11', PARAM_FLOAT);
776         validate_param('+.1', PARAM_FLOAT);
777         validate_param('-.1', PARAM_FLOAT);
778         validate_param('1e10', PARAM_FLOAT);
779         validate_param('.1e+10', PARAM_FLOAT);
780         validate_param('1E-1', PARAM_FLOAT);
782         try {
783             $param = validate_param('1,2', 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('.', 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('e10', PARAM_FLOAT);
802             $this->fail('invalid_parameter_exception expected');
803         } catch (moodle_exception $ex) {
804             $this->assertInstanceOf('invalid_parameter_exception', $ex);
805         }
806         try {
807             $param = validate_param('abc', PARAM_FLOAT);
808             $this->fail('invalid_parameter_exception expected');
809         } catch (moodle_exception $ex) {
810             $this->assertInstanceOf('invalid_parameter_exception', $ex);
811         }
812     }
814     public function test_shorten_text_no_tags_already_short_enough() {
815         // ......12345678901234567890123456.
816         $text = "short text already no tags";
817         $this->assertSame($text, shorten_text($text));
818     }
820     public function test_shorten_text_with_tags_already_short_enough() {
821         // .........123456...7890....12345678.......901234567.
822         $text = "<p>short <b>text</b> already</p><p>with tags</p>";
823         $this->assertSame($text, shorten_text($text));
824     }
826     public function test_shorten_text_no_tags_needs_shortening() {
827         // Default truncation is after 30 chars, but allowing 3 for the final '...'.
828         // ......12345678901234567890123456789023456789012345678901234.
829         $text = "long text without any tags blah de blah blah blah what";
830         $this->assertSame('long text without any tags ...', shorten_text($text));
831     }
833     public function test_shorten_text_with_tags_needs_shortening() {
834         // .......................................123456789012345678901234567890...
835         $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
836             "be chopped off but <b>should be added back again</b></blockquote></p></div>";
837         $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
838             "tags that ...</blockquote></p></div>", shorten_text($text));
839     }
841     public function test_shorten_text_with_entities() {
842         // Remember to allow 3 chars for the final '...'.
843         // ......123456789012345678901234567_____890...
844         $text = "some text which shouldn't &nbsp; break there";
845         $this->assertSame("some text which shouldn't &nbsp; ...", shorten_text($text, 31));
846         $this->assertSame("some text which shouldn't &nbsp;...", shorten_text($text, 30));
847         $this->assertSame("some text which shouldn't ...", shorten_text($text, 29));
848     }
850     public function test_shorten_text_known_tricky_case() {
851         // This case caused a bug up to 1.9.5
852         // ..........123456789012345678901234567890123456789.....0_____1___2___...
853         $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
854         $this->assertSame("<h3>standard 'break-out' sub groups in ...</h3>",
855             shorten_text($text, 41));
856         $this->assertSame("<h3>standard 'break-out' sub groups in TGs?...</h3>",
857             shorten_text($text, 42));
858         $this->assertSame("<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;...",
859             shorten_text($text, 43));
860     }
862     public function test_shorten_text_no_spaces() {
863         // ..........123456789.
864         $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
865         $this->assertSame("<h1>12345...</h1>", shorten_text($text, 8));
866     }
868     public function test_shorten_text_utf8_european() {
869         // Text without tags.
870         // ......123456789012345678901234567.
871         $text = "Žluťoučký koníček přeskočil";
872         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
873         $this->assertSame("Žluťoučký koníče...", shorten_text($text, 19, true));
874         $this->assertSame("Žluťoučký ...", shorten_text($text, 19, false));
875         // And try it with 2-less (that are, in bytes, the middle of a sequence).
876         $this->assertSame("Žluťoučký koní...", shorten_text($text, 17, true));
877         $this->assertSame("Žluťoučký ...", shorten_text($text, 17, false));
879         // .........123456789012345678...901234567....89012345.
880         $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
881         $this->assertSame($text, shorten_text($text, 60));
882         $this->assertSame("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
883         $this->assertSame("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
884         $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
885         // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
886         $this->assertSame("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
887         $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
888         // And try over one tag (start/end), it does proper text len.
889         $this->assertSame("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
890         $this->assertSame("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
891         // And in the middle of one tag.
892         $this->assertSame("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
893     }
895     public function test_shorten_text_utf8_oriental() {
896         // Japanese
897         // text without tags
898         // ......123456789012345678901234.
899         $text = '言語設定言語設定abcdefghijkl';
900         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
901         $this->assertSame("言語設定言語...", shorten_text($text, 9, true));
902         $this->assertSame("言語設定言語...", shorten_text($text, 9, false));
903         $this->assertSame("言語設定言語設定ab...", shorten_text($text, 13, true));
904         $this->assertSame("言語設定言語設定...", shorten_text($text, 13, false));
906         // Chinese
907         // text without tags
908         // ......123456789012345678901234.
909         $text = '简体中文简体中文abcdefghijkl';
910         $this->assertSame($text, shorten_text($text)); // 30 chars by default.
911         $this->assertSame("简体中文简体...", shorten_text($text, 9, true));
912         $this->assertSame("简体中文简体...", shorten_text($text, 9, false));
913         $this->assertSame("简体中文简体中文ab...", shorten_text($text, 13, true));
914         $this->assertSame("简体中文简体中文...", shorten_text($text, 13, false));
915     }
917     public function test_shorten_text_multilang() {
918         // This is not necessaryily specific to multilang. The issue is really
919         // tags with attributes, where before we were generating invalid HTML
920         // output like shorten_text('<span id="x" class="y">A</span> B', 1)
921         // returning '<span id="x" ...</span>'. It is just that multilang
922         // requires the sort of HTML that is quite likely to trigger this.
923         // ........................................1...
924         $text = '<span lang="en" class="multilang">A</span>' .
925                 '<span lang="fr" class="multilang">B</span>';
926         $this->assertSame('<span lang="en" class="multilang">...</span>',
927                 shorten_text($text, 1));
928     }
930     public function test_usergetdate() {
931         global $USER, $CFG, $DB;
932         $this->resetAfterTest();
934         // Check if forcetimezone is set then save it and set it to use user timezone.
935         $cfgforcetimezone = null;
936         if (isset($CFG->forcetimezone)) {
937             $cfgforcetimezone = $CFG->forcetimezone;
938             $CFG->forcetimezone = 99; // Get user default timezone.
939         }
941         $this->setAdminUser();
943         $userstimezone = $USER->timezone;
944         $USER->timezone = 2;// Set the timezone to a known state.
946         // The string version of date comes from server locale setting and does
947         // not respect user language, so it is necessary to reset that.
948         $oldlocale = setlocale(LC_TIME, '0');
949         setlocale(LC_TIME, 'en_AU.UTF-8');
951         $ts = 1261540267; // The time this function was created.
953         $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
954         $arr = array_values($arr);
956         list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
957         $this->assertSame(7, $seconds);
958         $this->assertSame(51, $minutes);
959         $this->assertSame(4, $hours);
960         $this->assertSame(23, $mday);
961         $this->assertSame(3, $wday);
962         $this->assertSame(12, $mon);
963         $this->assertSame(2009, $year);
964         $this->assertSame(356, $yday);
965         $this->assertSame('Wednesday', $weekday);
966         $this->assertSame('December', $month);
967         $arr = usergetdate($ts); // Gets the timezone from the $USER object.
968         $arr = array_values($arr);
970         list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
971         $this->assertSame(7, $seconds);
972         $this->assertSame(51, $minutes);
973         $this->assertSame(5, $hours);
974         $this->assertSame(23, $mday);
975         $this->assertSame(3, $wday);
976         $this->assertSame(12, $mon);
977         $this->assertSame(2009, $year);
978         $this->assertSame(356, $yday);
979         $this->assertSame('Wednesday', $weekday);
980         $this->assertSame('December', $month);
981         // Set the timezone back to what it was.
982         $USER->timezone = $userstimezone;
984         // Restore forcetimezone if changed.
985         if (!is_null($cfgforcetimezone)) {
986             $CFG->forcetimezone = $cfgforcetimezone;
987         }
989         setlocale(LC_TIME, $oldlocale);
990     }
992     public function test_mark_user_preferences_changed() {
993         $this->resetAfterTest();
994         $otheruser = $this->getDataGenerator()->create_user();
995         $otheruserid = $otheruser->id;
997         set_cache_flag('userpreferenceschanged', $otheruserid, null);
998         mark_user_preferences_changed($otheruserid);
1000         $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1001         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1002     }
1004     public function test_check_user_preferences_loaded() {
1005         global $DB;
1006         $this->resetAfterTest();
1008         $otheruser = $this->getDataGenerator()->create_user();
1009         $otheruserid = $otheruser->id;
1011         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1012         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1014         $user = new stdClass();
1015         $user->id = $otheruserid;
1017         // Load.
1018         check_user_preferences_loaded($user);
1019         $this->assertTrue(isset($user->preference));
1020         $this->assertTrue(is_array($user->preference));
1021         $this->assertArrayHasKey('_lastloaded', $user->preference);
1022         $this->assertCount(1, $user->preference);
1024         // Add preference via direct call.
1025         $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1027         // No cache reload yet.
1028         check_user_preferences_loaded($user);
1029         $this->assertCount(1, $user->preference);
1031         // Forced reloading of cache.
1032         unset($user->preference);
1033         check_user_preferences_loaded($user);
1034         $this->assertCount(2, $user->preference);
1035         $this->assertSame('yyy', $user->preference['xxx']);
1037         // Add preference via direct call.
1038         $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1040         // Test timeouts and modifications from different session.
1041         set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1042         $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1043         check_user_preferences_loaded($user);
1044         $this->assertCount(2, $user->preference);
1045         check_user_preferences_loaded($user, 10);
1046         $this->assertCount(3, $user->preference);
1047         $this->assertSame('bbb', $user->preference['aaa']);
1048         set_cache_flag('userpreferenceschanged', $user->id, null);
1049     }
1051     public function test_set_user_preference() {
1052         global $DB, $USER;
1053         $this->resetAfterTest();
1055         $this->setAdminUser();
1057         $otheruser = $this->getDataGenerator()->create_user();
1058         $otheruserid = $otheruser->id;
1060         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1061         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1063         $user = new stdClass();
1064         $user->id = $otheruserid;
1066         set_user_preference('aaa', 'bbb', $otheruserid);
1067         $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1068         $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
1070         set_user_preference('xxx', 'yyy', $user);
1071         $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1072         $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
1073         $this->assertTrue(is_array($user->preference));
1074         $this->assertSame('bbb', $user->preference['aaa']);
1075         $this->assertSame('yyy', $user->preference['xxx']);
1077         set_user_preference('xxx', null, $user);
1078         $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1079         $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
1081         set_user_preference('ooo', true, $user);
1082         $prefs = get_user_preferences(null, null, $otheruserid);
1083         $this->assertSame($user->preference['aaa'], $prefs['aaa']);
1084         $this->assertSame($user->preference['ooo'], $prefs['ooo']);
1085         $this->assertSame('1', $prefs['ooo']);
1087         set_user_preference('null', 0, $user);
1088         $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1090         $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1092         $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1093         set_cache_flag('userpreferenceschanged', $otheruserid, null);
1095         // Test $USER default.
1096         set_user_preference('_test_user_preferences_pref', 'ok');
1097         $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1098         unset_user_preference('_test_user_preferences_pref');
1099         $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1101         // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
1102         $longvalue = str_repeat('a', 1333);
1103         set_user_preference('_test_long_user_preference', $longvalue);
1104         $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1105         $this->assertEquals($longvalue,
1106             $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1108         // Test > 1333 char values, coding_exception expected.
1109         $longvalue = str_repeat('a', 1334);
1110         try {
1111             set_user_preference('_test_long_user_preference', $longvalue);
1112             $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1113         } catch (moodle_exception $ex) {
1114             $this->assertInstanceOf('coding_exception', $ex);
1115         }
1117         // Test invalid params.
1118         try {
1119             set_user_preference('_test_user_preferences_pref', array());
1120             $this->fail('Exception expected - array 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', new stdClass);
1126             $this->fail('Exception expected - class not valid preference value');
1127         } catch (moodle_exception $ex) {
1128             $this->assertInstanceOf('coding_exception', $ex);
1129         }
1130         try {
1131             set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
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('_test_user_preferences_pref', 1, 'abc');
1138             $this->fail('Exception expected - user instance expected');
1139         } catch (moodle_exception $ex) {
1140             $this->assertInstanceOf('coding_exception', $ex);
1141         }
1142         try {
1143             set_user_preference('', 1);
1144             $this->fail('Exception expected - invalid name accepted');
1145         } catch (moodle_exception $ex) {
1146             $this->assertInstanceOf('coding_exception', $ex);
1147         }
1148         try {
1149             set_user_preference('1', 1);
1150             $this->fail('Exception expected - invalid name accepted');
1151         } catch (moodle_exception $ex) {
1152             $this->assertInstanceOf('coding_exception', $ex);
1153         }
1154     }
1156     public function test_get_extra_user_fields() {
1157         global $CFG, $USER, $DB;
1158         $this->resetAfterTest();
1160         $this->setAdminUser();
1162         // It would be really nice if there were a way to 'mock' has_capability
1163         // checks (either to return true or false) but as there is not, this
1164         // test doesn't test the capability check. Presumably, anyone running
1165         // unit tests will have the capability.
1166         $context = context_system::instance();
1168         // No fields.
1169         $CFG->showuseridentity = '';
1170         $this->assertEquals(array(), get_extra_user_fields($context));
1172         // One field.
1173         $CFG->showuseridentity = 'frog';
1174         $this->assertEquals(array('frog'), get_extra_user_fields($context));
1176         // Two fields.
1177         $CFG->showuseridentity = 'frog,zombie';
1178         $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1180         // No fields, except.
1181         $CFG->showuseridentity = '';
1182         $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1184         // One field.
1185         $CFG->showuseridentity = 'frog';
1186         $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1188         // Two fields.
1189         $CFG->showuseridentity = 'frog,zombie';
1190         $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1191     }
1193     public function test_get_extra_user_fields_sql() {
1194         global $CFG, $USER, $DB;
1195         $this->resetAfterTest();
1197         $this->setAdminUser();
1199         $context = context_system::instance();
1201         // No fields.
1202         $CFG->showuseridentity = '';
1203         $this->assertSame('', get_extra_user_fields_sql($context));
1205         // One field.
1206         $CFG->showuseridentity = 'frog';
1207         $this->assertSame(', frog', get_extra_user_fields_sql($context));
1209         // Two fields with table prefix.
1210         $CFG->showuseridentity = 'frog,zombie';
1211         $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1213         // Two fields with field prefix.
1214         $CFG->showuseridentity = 'frog,zombie';
1215         $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
1216             get_extra_user_fields_sql($context, '', 'u_'));
1218         // One field excluded.
1219         $CFG->showuseridentity = 'frog';
1220         $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
1222         // Two fields, one excluded, table+field prefix.
1223         $CFG->showuseridentity = 'frog,zombie';
1224         $this->assertEquals(', u1.zombie AS u_zombie',
1225             get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1226     }
1228     /**
1229      * Test some critical TZ/DST.
1230      *
1231      * This method tests some special TZ/DST combinations that were fixed
1232      * by MDL-38999. The tests are done by comparing the results of the
1233      * output using Moodle TZ/DST support and PHP native one.
1234      *
1235      * Note: If you don't trust PHP TZ/DST support, can verify the
1236      * harcoded expectations below with:
1237      * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
1238      */
1239     public function test_some_moodle_special_dst() {
1240         $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
1242         // In Europe/Tallinn it was 2013/04/08 05:00:00.
1243         $expectation = '2013/04/08 05:00:00';
1244         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1245         $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1246         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1247         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1248         $this->assertSame($expectation, $phpres);
1249         $this->assertSame($expectation, $moodleres);
1251         // In St. Johns it was 2013/04/07 23:30:00.
1252         $expectation = '2013/04/07 23:30:00';
1253         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1254         $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1255         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1256         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1257         $this->assertSame($expectation, $phpres);
1258         $this->assertSame($expectation, $moodleres);
1260         $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1262         // In Europe/Tallinn it was 2013/11/08 04:00:00.
1263         $expectation = '2013/11/08 04:00:00';
1264         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1265         $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1266         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1267         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1268         $this->assertSame($expectation, $phpres);
1269         $this->assertSame($expectation, $moodleres);
1271         // In St. Johns it was 2013/11/07 22:30:00.
1272         $expectation = '2013/11/07 22:30:00';
1273         $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1274         $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1275         $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1276         $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1277         $this->assertSame($expectation, $phpres);
1278         $this->assertSame($expectation, $moodleres);
1279     }
1281     public function test_userdate() {
1282         global $USER, $CFG, $DB;
1283         $this->resetAfterTest();
1285         $this->setAdminUser();
1287         $testvalues = array(
1288             array(
1289                 'time' => '1309514400',
1290                 'usertimezone' => 'America/Moncton',
1291                 'timezone' => '0.0', // No dst offset.
1292                 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1293             ),
1294             array(
1295                 'time' => '1309514400',
1296                 'usertimezone' => 'America/Moncton',
1297                 'timezone' => '99', // Dst offset and timezone offset.
1298                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1299             ),
1300             array(
1301                 'time' => '1309514400',
1302                 'usertimezone' => 'America/Moncton',
1303                 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
1304                 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1305             ),
1306             array(
1307                 'time' => '1293876000 ',
1308                 'usertimezone' => 'America/Moncton',
1309                 'timezone' => '0.0', // No dst offset.
1310                 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1311             ),
1312             array(
1313                 'time' => '1293876000 ',
1314                 'usertimezone' => 'America/Moncton',
1315                 'timezone' => '99', // No dst offset in jan, so just timezone offset.
1316                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1317             ),
1318             array(
1319                 'time' => '1293876000 ',
1320                 'usertimezone' => 'America/Moncton',
1321                 'timezone' => 'America/Moncton', // No dst offset in jan.
1322                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1323             ),
1324             array(
1325                 'time' => '1293876000 ',
1326                 'usertimezone' => '2',
1327                 'timezone' => '99', // Take user timezone.
1328                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1329             ),
1330             array(
1331                 'time' => '1293876000 ',
1332                 'usertimezone' => '-2',
1333                 'timezone' => '99', // Take user timezone.
1334                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1335             ),
1336             array(
1337                 'time' => '1293876000 ',
1338                 'usertimezone' => '-10',
1339                 'timezone' => '2', // Take this timezone.
1340                 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1341             ),
1342             array(
1343                 'time' => '1293876000 ',
1344                 'usertimezone' => '-10',
1345                 'timezone' => '-2', // Take this timezone.
1346                 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1347             ),
1348             array(
1349                 'time' => '1293876000 ',
1350                 'usertimezone' => '-10',
1351                 'timezone' => 'random/time', // This should show server time.
1352                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1353             ),
1354             array(
1355                 'time' => '1293876000 ',
1356                 'usertimezone' => '14', // Server time zone.
1357                 'timezone' => '99',     // This should show user time.
1358                 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1359             ),
1360         );
1362         // Check if forcetimezone is set then save it and set it to use user timezone.
1363         $cfgforcetimezone = null;
1364         if (isset($CFG->forcetimezone)) {
1365             $cfgforcetimezone = $CFG->forcetimezone;
1366             $CFG->forcetimezone = 99; // Get user default timezone.
1367         }
1368         // Store user default timezone to restore later.
1369         $userstimezone = $USER->timezone;
1371         // The string version of date comes from server locale setting and does
1372         // not respect user language, so it is necessary to reset that.
1373         $oldlocale = setlocale(LC_TIME, '0');
1374         setlocale(LC_TIME, 'en_AU.UTF-8');
1376         // Set default timezone to Australia/Perth, else time calculated
1377         // will not match expected values. Before that save system defaults.
1378         $systemdefaulttimezone = date_default_timezone_get();
1379         date_default_timezone_set('Australia/Perth');
1381         foreach ($testvalues as $vals) {
1382             $USER->timezone = $vals['usertimezone'];
1383             $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1385             // On different systems case of AM PM changes so compare case insensitive.
1386             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1387             $actualoutput = core_text::strtolower($actualoutput);
1389             $this->assertSame($vals['expectedoutput'], $actualoutput,
1390                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1391                 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1392         }
1394         // Restore user timezone back to what it was.
1395         $USER->timezone = $userstimezone;
1397         // Restore forcetimezone.
1398         if (!is_null($cfgforcetimezone)) {
1399             $CFG->forcetimezone = $cfgforcetimezone;
1400         }
1402         // Restore system default values.
1403         date_default_timezone_set($systemdefaulttimezone);
1404         setlocale(LC_TIME, $oldlocale);
1405     }
1407     public function test_make_timestamp() {
1408         global $USER, $CFG, $DB;
1409         $this->resetAfterTest();
1411         $this->setAdminUser();
1413         $testvalues = array(
1414             array(
1415                 'usertimezone' => 'America/Moncton',
1416                 'year' => '2011',
1417                 'month' => '7',
1418                 'day' => '1',
1419                 'hour' => '10',
1420                 'minutes' => '00',
1421                 'seconds' => '00',
1422                 'timezone' => '0.0',
1423                 'applydst' => false, // No dst offset.
1424                 'expectedoutput' => '1309514400' // 6pm at UTC+0.
1425             ),
1426             array(
1427                 'usertimezone' => 'America/Moncton',
1428                 'year' => '2011',
1429                 'month' => '7',
1430                 'day' => '1',
1431                 'hour' => '10',
1432                 'minutes' => '00',
1433                 'seconds' => '00',
1434                 'timezone' => '99',  // User default timezone.
1435                 'applydst' => false, // Don't apply dst.
1436                 'expectedoutput' => '1309528800'
1437             ),
1438             array(
1439                 'usertimezone' => 'America/Moncton',
1440                 'year' => '2011',
1441                 'month' => '7',
1442                 'day' => '1',
1443                 'hour' => '10',
1444                 'minutes' => '00',
1445                 'seconds' => '00',
1446                 'timezone' => '99', // User default timezone.
1447                 'applydst' => true, // Apply dst.
1448                 'expectedoutput' => '1309525200'
1449             ),
1450             array(
1451                 'usertimezone' => 'America/Moncton',
1452                 'year' => '2011',
1453                 'month' => '7',
1454                 'day' => '1',
1455                 'hour' => '10',
1456                 'minutes' => '00',
1457                 'seconds' => '00',
1458                 'timezone' => 'America/Moncton', // String timezone.
1459                 'applydst' => true, // Apply dst.
1460                 'expectedoutput' => '1309525200'
1461             ),
1462             array(
1463                 'usertimezone' => '2', // No dst applyed.
1464                 'year' => '2011',
1465                 'month' => '7',
1466                 'day' => '1',
1467                 'hour' => '10',
1468                 'minutes' => '00',
1469                 'seconds' => '00',
1470                 'timezone' => '99', // Take user timezone.
1471                 'applydst' => true, // Apply dst.
1472                 'expectedoutput' => '1309507200'
1473             ),
1474             array(
1475                 'usertimezone' => '-2', // No dst applyed.
1476                 'year' => '2011',
1477                 'month' => '7',
1478                 'day' => '1',
1479                 'hour' => '10',
1480                 'minutes' => '00',
1481                 'seconds' => '00',
1482                 'timezone' => '99', // Take usertimezone.
1483                 'applydst' => true, // Apply dst.
1484                 'expectedoutput' => '1309521600'
1485             ),
1486             array(
1487                 'usertimezone' => '-10', // No dst applyed.
1488                 'year' => '2011',
1489                 'month' => '7',
1490                 'day' => '1',
1491                 'hour' => '10',
1492                 'minutes' => '00',
1493                 'seconds' => '00',
1494                 'timezone' => '2',  // Take this timezone.
1495                 'applydst' => true, // Apply dst.
1496                 'expectedoutput' => '1309507200'
1497             ),
1498             array(
1499                 'usertimezone' => '-10', // No dst applyed.
1500                 'year' => '2011',
1501                 'month' => '7',
1502                 'day' => '1',
1503                 'hour' => '10',
1504                 'minutes' => '00',
1505                 'seconds' => '00',
1506                 'timezone' => '-2', // Take this timezone.
1507                 'applydst' => true, // Apply dst.
1508                 'expectedoutput' => '1309521600'
1509             ),
1510             array(
1511                 'usertimezone' => '-10', // No dst applyed.
1512                 'year' => '2011',
1513                 'month' => '7',
1514                 'day' => '1',
1515                 'hour' => '10',
1516                 'minutes' => '00',
1517                 'seconds' => '00',
1518                 'timezone' => 'random/time', // This should show server time.
1519                 'applydst' => true,          // Apply dst.
1520                 'expectedoutput' => '1309485600'
1521             ),
1522             array(
1523                 'usertimezone' => '14', // Server time.
1524                 'year' => '2011',
1525                 'month' => '7',
1526                 'day' => '1',
1527                 'hour' => '10',
1528                 'minutes' => '00',
1529                 'seconds' => '00',
1530                 'timezone' => '99', // Get user time.
1531                 'applydst' => true, // Apply dst.
1532                 'expectedoutput' => '1309485600'
1533             )
1534         );
1536         // Check if forcetimezone is set then save it and set it to use user timezone.
1537         $cfgforcetimezone = null;
1538         if (isset($CFG->forcetimezone)) {
1539             $cfgforcetimezone = $CFG->forcetimezone;
1540             $CFG->forcetimezone = 99; // Get user default timezone.
1541         }
1543         // Store user default timezone to restore later.
1544         $userstimezone = $USER->timezone;
1546         // The string version of date comes from server locale setting and does
1547         // not respect user language, so it is necessary to reset that.
1548         $oldlocale = setlocale(LC_TIME, '0');
1549         setlocale(LC_TIME, 'en_AU.UTF-8');
1551         // Set default timezone to Australia/Perth, else time calculated
1552         // Will not match expected values. Before that save system defaults.
1553         $systemdefaulttimezone = date_default_timezone_get();
1554         date_default_timezone_set('Australia/Perth');
1556         // Test make_timestamp with all testvals and assert if anything wrong.
1557         foreach ($testvalues as $vals) {
1558             $USER->timezone = $vals['usertimezone'];
1559             $actualoutput = make_timestamp(
1560                 $vals['year'],
1561                 $vals['month'],
1562                 $vals['day'],
1563                 $vals['hour'],
1564                 $vals['minutes'],
1565                 $vals['seconds'],
1566                 $vals['timezone'],
1567                 $vals['applydst']
1568             );
1570             // On different systems case of AM PM changes so compare case insensitive.
1571             $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1572             $actualoutput = core_text::strtolower($actualoutput);
1574             $this->assertSame($vals['expectedoutput'], $actualoutput,
1575                 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1576                 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1577         }
1579         // Restore user timezone back to what it was.
1580         $USER->timezone = $userstimezone;
1582         // Restore forcetimezone.
1583         if (!is_null($cfgforcetimezone)) {
1584             $CFG->forcetimezone = $cfgforcetimezone;
1585         }
1587         // Restore system default values.
1588         date_default_timezone_set($systemdefaulttimezone);
1589         setlocale(LC_TIME, $oldlocale);
1590     }
1592     /**
1593      * Test get_string and most importantly the implementation of the lang_string
1594      * object.
1595      */
1596     public function test_get_string() {
1597         global $COURSE;
1599         // Make sure we are using English.
1600         $originallang = $COURSE->lang;
1601         $COURSE->lang = 'en';
1603         $yes = get_string('yes');
1604         $yesexpected = 'Yes';
1605         $this->assertInternalType('string', $yes);
1606         $this->assertSame($yesexpected, $yes);
1608         $yes = get_string('yes', 'moodle');
1609         $this->assertInternalType('string', $yes);
1610         $this->assertSame($yesexpected, $yes);
1612         $yes = get_string('yes', 'core');
1613         $this->assertInternalType('string', $yes);
1614         $this->assertSame($yesexpected, $yes);
1616         $yes = get_string('yes', '');
1617         $this->assertInternalType('string', $yes);
1618         $this->assertSame($yesexpected, $yes);
1620         $yes = get_string('yes', null);
1621         $this->assertInternalType('string', $yes);
1622         $this->assertSame($yesexpected, $yes);
1624         $yes = get_string('yes', null, 1);
1625         $this->assertInternalType('string', $yes);
1626         $this->assertSame($yesexpected, $yes);
1628         $days = 1;
1629         $numdays = get_string('numdays', 'core', '1');
1630         $numdaysexpected = $days.' days';
1631         $this->assertInternalType('string', $numdays);
1632         $this->assertSame($numdaysexpected, $numdays);
1634         $yes = get_string('yes', null, null, true);
1635         $this->assertInstanceOf('lang_string', $yes);
1636         $this->assertSame($yesexpected, (string)$yes);
1638         // Test using a lang_string object as the $a argument for a normal
1639         // get_string call (returning string).
1640         $test = new lang_string('yes', null, null, true);
1641         $testexpected = get_string('numdays', 'core', get_string('yes'));
1642         $testresult = get_string('numdays', null, $test);
1643         $this->assertInternalType('string', $testresult);
1644         $this->assertSame($testexpected, $testresult);
1646         // Test using a lang_string object as the $a argument for an object
1647         // get_string call (returning lang_string).
1648         $test = new lang_string('yes', null, null, true);
1649         $testexpected = get_string('numdays', 'core', get_string('yes'));
1650         $testresult = get_string('numdays', null, $test, true);
1651         $this->assertInstanceOf('lang_string', $testresult);
1652         $this->assertSame($testexpected, "$testresult");
1654         // Make sure that object properties that can't be converted don't cause
1655         // errors.
1656         // Level one: This is as deep as current language processing goes.
1657         $test = new stdClass;
1658         $test->one = 'here';
1659         $string = get_string('yes', null, $test, true);
1660         $this->assertEquals($yesexpected, $string);
1662         // Make sure that object properties that can't be converted don't cause
1663         // errors.
1664         // Level two: Language processing doesn't currently reach this deep.
1665         // only immediate scalar properties are worked with.
1666         $test = new stdClass;
1667         $test->one = new stdClass;
1668         $test->one->two = 'here';
1669         $string = get_string('yes', null, $test, true);
1670         $this->assertEquals($yesexpected, $string);
1672         // Make sure that object properties that can't be converted don't cause
1673         // errors.
1674         // Level three: It should never ever go this deep, but we're making sure
1675         // it doesn't cause any probs anyway.
1676         $test = new stdClass;
1677         $test->one = new stdClass;
1678         $test->one->two = new stdClass;
1679         $test->one->two->three = 'here';
1680         $string = get_string('yes', null, $test, true);
1681         $this->assertEquals($yesexpected, $string);
1683         // Make sure that object properties that can't be converted don't cause
1684         // errors and check lang_string properties.
1685         // Level one: This is as deep as current language processing goes.
1686         $test = new stdClass;
1687         $test->one = new lang_string('yes');
1688         $string = get_string('yes', null, $test, true);
1689         $this->assertEquals($yesexpected, $string);
1691         // Make sure that object properties that can't be converted don't cause
1692         // errors and check lang_string properties.
1693         // Level two: Language processing doesn't currently reach this deep.
1694         // only immediate scalar properties are worked with.
1695         $test = new stdClass;
1696         $test->one = new stdClass;
1697         $test->one->two = new lang_string('yes');
1698         $string = get_string('yes', null, $test, true);
1699         $this->assertEquals($yesexpected, $string);
1701         // Make sure that object properties that can't be converted don't cause
1702         // errors and check lang_string properties.
1703         // Level three: It should never ever go this deep, but we're making sure
1704         // it doesn't cause any probs anyway.
1705         $test = new stdClass;
1706         $test->one = new stdClass;
1707         $test->one->two = new stdClass;
1708         $test->one->two->three = new lang_string('yes');
1709         $string = get_string('yes', null, $test, true);
1710         $this->assertEquals($yesexpected, $string);
1712         // Make sure that array properties that can't be converted don't cause
1713         // errors.
1714         $test = array();
1715         $test['one'] = new stdClass;
1716         $test['one']->two = 'here';
1717         $string = get_string('yes', null, $test, true);
1718         $this->assertEquals($yesexpected, $string);
1720         // Same thing but as above except using an object... this is allowed :P.
1721         $string = get_string('yes', null, null, true);
1722         $object = new stdClass;
1723         $object->$string = 'Yes';
1724         $this->assertEquals($yesexpected, $string);
1725         $this->assertEquals($yesexpected, $object->$string);
1727         // Reset the language.
1728         $COURSE->lang = $originallang;
1729     }
1731     /**
1732      * @expectedException PHPUnit_Framework_Error_Warning
1733      */
1734     public function test_get_string_limitation() {
1735         // This is one of the limitations to the lang_string class. It can't be
1736         // used as a key.
1737         $array = array(get_string('yes', null, null, true) => 'yes');
1738     }
1740     /**
1741      * Test localised float formatting.
1742      */
1743     public function test_format_float() {
1745         // Special case for null.
1746         $this->assertEquals('', format_float(null));
1748         // Default 1 decimal place.
1749         $this->assertEquals('5.4', format_float(5.43));
1750         $this->assertEquals('5.0', format_float(5.001));
1752         // Custom number of decimal places.
1753         $this->assertEquals('5.43000', format_float(5.43, 5));
1755         // Option to strip ending zeros after rounding.
1756         $this->assertEquals('5.43', format_float(5.43, 5, true, true));
1757         $this->assertEquals('5', format_float(5.0001, 3, true, true));
1759         // Tests with a localised decimal separator.
1760         $this->define_local_decimal_separator();
1762         // Localisation on (default).
1763         $this->assertEquals('5X43000', format_float(5.43, 5));
1764         $this->assertEquals('5X43', format_float(5.43, 5, true, true));
1766         // Localisation off.
1767         $this->assertEquals('5.43000', format_float(5.43, 5, false));
1768         $this->assertEquals('5.43', format_float(5.43, 5, false, true));
1769     }
1771     /**
1772      * Test localised float unformatting.
1773      */
1774     public function test_unformat_float() {
1776         // Tests without the localised decimal separator.
1778         // Special case for null, empty or white spaces only strings.
1779         $this->assertEquals(null, unformat_float(null));
1780         $this->assertEquals(null, unformat_float(''));
1781         $this->assertEquals(null, unformat_float('    '));
1783         // Regular use.
1784         $this->assertEquals(5.4, unformat_float('5.4'));
1785         $this->assertEquals(5.4, unformat_float('5.4', true));
1787         // No decimal.
1788         $this->assertEquals(5.0, unformat_float('5'));
1790         // Custom number of decimal.
1791         $this->assertEquals(5.43267, unformat_float('5.43267'));
1793         // Empty decimal.
1794         $this->assertEquals(100.0, unformat_float('100.00'));
1796         // With the thousand separator.
1797         $this->assertEquals(1000.0, unformat_float('1 000'));
1798         $this->assertEquals(1000.32, unformat_float('1 000.32'));
1800         // Negative number.
1801         $this->assertEquals(-100.0, unformat_float('-100'));
1803         // Wrong value.
1804         $this->assertEquals(0.0, unformat_float('Wrong value'));
1805         // Wrong value in strict mode.
1806         $this->assertFalse(unformat_float('Wrong value', true));
1808         // Combining options.
1809         $this->assertEquals(-1023.862567, unformat_float('   -1 023.862567     '));
1811         // Bad decimal separator (should crop the decimal).
1812         $this->assertEquals(50.0, unformat_float('50,57'));
1813         // Bad decimal separator in strict mode (should return false).
1814         $this->assertFalse(unformat_float('50,57', true));
1816         // Tests with a localised decimal separator.
1817         $this->define_local_decimal_separator();
1819         // We repeat the tests above but with the current decimal separator.
1821         // Regular use without and with the localised separator.
1822         $this->assertEquals (5.4, unformat_float('5.4'));
1823         $this->assertEquals (5.4, unformat_float('5X4'));
1825         // Custom number of decimal.
1826         $this->assertEquals (5.43267, unformat_float('5X43267'));
1828         // Empty decimal.
1829         $this->assertEquals (100.0, unformat_float('100X00'));
1831         // With the thousand separator.
1832         $this->assertEquals (1000.32, unformat_float('1 000X32'));
1834         // Bad different separator (should crop the decimal).
1835         $this->assertEquals (50.0, unformat_float('50Y57'));
1836         // Bad different separator in strict mode (should return false).
1837         $this->assertFalse (unformat_float('50Y57', true));
1839         // Combining options.
1840         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     '));
1841         // Combining options in strict mode.
1842         $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     ', true));
1843     }
1845     /**
1846      * Test deleting of users.
1847      */
1848     public function test_delete_user() {
1849         global $DB, $CFG;
1851         $this->resetAfterTest();
1853         $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
1854         $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
1855         $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
1857         $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
1858         $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
1860         // Delete user and capture event.
1861         $sink = $this->redirectEvents();
1862         $result = delete_user($user);
1863         $events = $sink->get_events();
1864         $sink->close();
1865         $event = array_pop($events);
1867         // Test user is deleted in DB.
1868         $this->assertTrue($result);
1869         $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
1870         $this->assertEquals(1, $deluser->deleted);
1871         $this->assertEquals(0, $deluser->picture);
1872         $this->assertSame('', $deluser->idnumber);
1873         $this->assertSame(md5($user->username), $deluser->email);
1874         $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
1876         $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
1878         // Test Event.
1879         $this->assertInstanceOf('\core\event\user_deleted', $event);
1880         $this->assertSame($user->id, $event->objectid);
1881         $this->assertSame('user_deleted', $event->get_legacy_eventname());
1882         $this->assertEventLegacyData($user, $event);
1883         $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
1884         $this->assertEventLegacyLogData($expectedlogdata, $event);
1885         $eventdata = $event->get_data();
1886         $this->assertSame($eventdata['other']['username'], $user->username);
1887         $this->assertSame($eventdata['other']['email'], $user->email);
1888         $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
1889         $this->assertSame($eventdata['other']['picture'], $user->picture);
1890         $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
1891         $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
1892         $this->assertEventContextNotUsed($event);
1894         // Try invalid params.
1895         $record = new stdClass();
1896         $record->grrr = 1;
1897         try {
1898             delete_user($record);
1899             $this->fail('Expecting exception for invalid delete_user() $user parameter');
1900         } catch (moodle_exception $ex) {
1901             $this->assertInstanceOf('coding_exception', $ex);
1902         }
1903         $record->id = 1;
1904         try {
1905             delete_user($record);
1906             $this->fail('Expecting exception for invalid delete_user() $user parameter');
1907         } catch (moodle_exception $ex) {
1908             $this->assertInstanceOf('coding_exception', $ex);
1909         }
1911         $record = new stdClass();
1912         $record->id = 666;
1913         $record->username = 'xx';
1914         $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
1915         $result = delete_user($record);
1916         $this->assertFalse($result);
1918         $result = delete_user($guest);
1919         $this->assertFalse($result);
1921         $result = delete_user($admin);
1922         $this->assertFalse($result);
1924         $this->resetDebugging();
1925     }
1927     /**
1928      * Test function convert_to_array()
1929      */
1930     public function test_convert_to_array() {
1931         // Check that normal classes are converted to arrays the same way as (array) would do.
1932         $obj = new stdClass();
1933         $obj->prop1 = 'hello';
1934         $obj->prop2 = array('first', 'second', 13);
1935         $obj->prop3 = 15;
1936         $this->assertEquals(convert_to_array($obj), (array)$obj);
1938         // Check that context object (with iterator) is converted to array properly.
1939         $obj = context_system::instance();
1940         $ar = array(
1941             'id'           => $obj->id,
1942             'contextlevel' => $obj->contextlevel,
1943             'instanceid'   => $obj->instanceid,
1944             'path'         => $obj->path,
1945             'depth'        => $obj->depth
1946         );
1947         $this->assertEquals(convert_to_array($obj), $ar);
1948     }
1950     /**
1951      * Test the function date_format_string().
1952      */
1953     public function test_date_format_string() {
1954         global $CFG;
1956         // Forcing locale and timezone.
1957         $oldlocale = setlocale(LC_TIME, '0');
1958         if ($CFG->ostype == 'WINDOWS') {
1959             setlocale(LC_TIME, 'English_Australia.1252');
1960         } else {
1961             setlocale(LC_TIME, 'en_AU.UTF-8');
1962         }
1963         $systemdefaulttimezone = date_default_timezone_get();
1964         date_default_timezone_set('Australia/Perth');
1966         $tests = array(
1967             array(
1968                 'tz' => 99,
1969                 'str' => '%A, %d %B %Y, %I:%M %p',
1970                 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
1971             ),
1972             array(
1973                 'tz' => 0,
1974                 'str' => '%A, %d %B %Y, %I:%M %p',
1975                 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
1976             ),
1977             array(
1978                 'tz' => -12,
1979                 'str' => '%A, %d %B %Y, %I:%M %p',
1980                 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
1981             ),
1982             // Following tests pass on Windows only because en lang pack does
1983             // not contain localewincharset, in real life lang pack maintainers
1984             // may use only characters that are present in localewincharset
1985             // in format strings!
1986             array(
1987                 'tz' => 99,
1988                 'str' => 'Žluťoučký koníček %A',
1989                 'expected' => 'Žluťoučký koníček Saturday'
1990             ),
1991             array(
1992                 'tz' => 99,
1993                 'str' => '言語設定言語 %A',
1994                 'expected' => '言語設定言語 Saturday'
1995             ),
1996             array(
1997                 'tz' => 99,
1998                 'str' => '简体中文简体 %A',
1999                 'expected' => '简体中文简体 Saturday'
2000             ),
2001         );
2003         // Note: date_format_string() uses the timezone only to differenciate
2004         // the server time from the UTC time. It does not modify the timestamp.
2005         // Hence similar results for timezones <= 13.
2006         // On different systems case of AM PM changes so compare case insensitive.
2007         foreach ($tests as $test) {
2008             $str = date_format_string(1293876000, $test['str'], $test['tz']);
2009             $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
2010         }
2012         // Restore system default values.
2013         date_default_timezone_set($systemdefaulttimezone);
2014         setlocale(LC_TIME, $oldlocale);
2015     }
2017     public function test_get_config() {
2018         global $CFG;
2020         $this->resetAfterTest();
2022         // Preparation.
2023         set_config('phpunit_test_get_config_1', 'test 1');
2024         set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2025         if (!is_array($CFG->config_php_settings)) {
2026             $CFG->config_php_settings = array();
2027         }
2028         $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
2030         if (!is_array($CFG->forced_plugin_settings)) {
2031             $CFG->forced_plugin_settings = array();
2032         }
2033         if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
2034             $CFG->forced_plugin_settings['mod_forum'] = array();
2035         }
2036         $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2037         $CFG->phpunit_test_get_config_5 = 'test 5';
2039         // Testing.
2040         $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
2041         $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2042         $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
2043         $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2044         $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2045         $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2046         $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2048         // Test config we know to exist.
2049         $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
2050         $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2051         $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2052         $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2054         // Test setting a config var that already exists.
2055         set_config('phpunit_test_get_config_1', 'test a');
2056         $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
2057         $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
2059         // Test cache invalidation.
2060         $cache = cache::make('core', 'config');
2061         $this->assertInternalType('array', $cache->get('core'));
2062         $this->assertInternalType('array', $cache->get('mod_forum'));
2063         set_config('phpunit_test_get_config_1', 'test b');
2064         $this->assertFalse($cache->get('core'));
2065         set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2066         $this->assertFalse($cache->get('mod_forum'));
2067     }
2069     public function test_get_max_upload_sizes() {
2070         // Test with very low limits so we are not affected by php upload limits.
2071         // Test activity limit smallest.
2072         $sitebytes = 102400;
2073         $coursebytes = 51200;
2074         $modulebytes = 10240;
2075         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2077         $this->assertSame('Activity upload limit (10KB)', $result['0']);
2078         $this->assertCount(2, $result);
2080         // Test course limit smallest.
2081         $sitebytes = 102400;
2082         $coursebytes = 10240;
2083         $modulebytes = 51200;
2084         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2086         $this->assertSame('Course upload limit (10KB)', $result['0']);
2087         $this->assertCount(2, $result);
2089         // Test site limit smallest.
2090         $sitebytes = 10240;
2091         $coursebytes = 102400;
2092         $modulebytes = 51200;
2093         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2095         $this->assertSame('Site upload limit (10KB)', $result['0']);
2096         $this->assertCount(2, $result);
2098         // Test site limit not set.
2099         $sitebytes = 0;
2100         $coursebytes = 102400;
2101         $modulebytes = 51200;
2102         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2104         $this->assertSame('Activity upload limit (50KB)', $result['0']);
2105         $this->assertCount(3, $result);
2107         $sitebytes = 0;
2108         $coursebytes = 51200;
2109         $modulebytes = 102400;
2110         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2112         $this->assertSame('Course upload limit (50KB)', $result['0']);
2113         $this->assertCount(3, $result);
2115         // Test custom bytes in range.
2116         $sitebytes = 102400;
2117         $coursebytes = 51200;
2118         $modulebytes = 51200;
2119         $custombytes = 10240;
2120         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2122         $this->assertCount(3, $result);
2124         // Test custom bytes in range but non-standard.
2125         $sitebytes = 102400;
2126         $coursebytes = 51200;
2127         $modulebytes = 51200;
2128         $custombytes = 25600;
2129         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2131         $this->assertCount(4, $result);
2133         // Test custom bytes out of range.
2134         $sitebytes = 102400;
2135         $coursebytes = 51200;
2136         $modulebytes = 51200;
2137         $custombytes = 102400;
2138         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2140         $this->assertCount(3, $result);
2142         // Test custom bytes out of range and non-standard.
2143         $sitebytes = 102400;
2144         $coursebytes = 51200;
2145         $modulebytes = 51200;
2146         $custombytes = 256000;
2147         $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2149         $this->assertCount(3, $result);
2151         // Test site limit only.
2152         $sitebytes = 51200;
2153         $result = get_max_upload_sizes($sitebytes);
2155         $this->assertSame('Site upload limit (50KB)', $result['0']);
2156         $this->assertSame('50KB', $result['51200']);
2157         $this->assertSame('10KB', $result['10240']);
2158         $this->assertCount(3, $result);
2160         // Test no limit.
2161         $result = get_max_upload_sizes();
2162         $this->assertArrayHasKey('0', $result);
2163         $this->assertArrayHasKey(get_max_upload_file_size(), $result);
2164     }
2166     /**
2167      * Test function password_is_legacy_hash().
2168      */
2169     public function test_password_is_legacy_hash() {
2170         // Well formed md5s should be matched.
2171         foreach (array('some', 'strings', 'to_check!') as $string) {
2172             $md5 = md5($string);
2173             $this->assertTrue(password_is_legacy_hash($md5));
2174         }
2175         // Strings that are not md5s should not be matched.
2176         foreach (array('', AUTH_PASSWORD_NOT_CACHED, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
2177             $this->assertFalse(password_is_legacy_hash($notmd5));
2178         }
2179     }
2181     /**
2182      * Test function validate_internal_user_password().
2183      */
2184     public function test_validate_internal_user_password() {
2185         // Test bcrypt hashes.
2186         $validhashes = array(
2187             'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2188             'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2189             'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2190             'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
2191         );
2193         foreach ($validhashes as $password => $hash) {
2194             $user = new stdClass();
2195             $user->auth = 'manual';
2196             $user->password = $hash;
2197             // The correct password should be validated.
2198             $this->assertTrue(validate_internal_user_password($user, $password));
2199             // An incorrect password should not be validated.
2200             $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2201         }
2202     }
2204     /**
2205      * Test function hash_internal_user_password().
2206      */
2207     public function test_hash_internal_user_password() {
2208         $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2210         // Check that some passwords that we convert to hashes can
2211         // be validated.
2212         foreach ($passwords as $password) {
2213             $hash = hash_internal_user_password($password);
2214             $fasthash = hash_internal_user_password($password, true);
2215             $user = new stdClass();
2216             $user->auth = 'manual';
2217             $user->password = $hash;
2218             $this->assertTrue(validate_internal_user_password($user, $password));
2220             // They should not be in md5 format.
2221             $this->assertFalse(password_is_legacy_hash($hash));
2223             // Check that cost factor in hash is correctly set.
2224             $this->assertRegExp('/\$10\$/', $hash);
2225             $this->assertRegExp('/\$04\$/', $fasthash);
2226         }
2227     }
2229     /**
2230      * Test function update_internal_user_password().
2231      */
2232     public function test_update_internal_user_password() {
2233         global $DB;
2234         $this->resetAfterTest();
2235         $passwords = array('password', '1234', 'changeme', '****');
2236         foreach ($passwords as $password) {
2237             $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2238             update_internal_user_password($user, $password);
2239             // The user object should have been updated.
2240             $this->assertTrue(validate_internal_user_password($user, $password));
2241             // The database field for the user should also have been updated to the
2242             // same value.
2243             $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
2244         }
2246         $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2247         // Manually set the user's password to the md5 of the string 'password'.
2248         $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
2250         $sink = $this->redirectEvents();
2251         // Update the password.
2252         update_internal_user_password($user, 'password');
2253         $events = $sink->get_events();
2254         $sink->close();
2255         $event = array_pop($events);
2257         // Password should have been updated to a bcrypt hash.
2258         $this->assertFalse(password_is_legacy_hash($user->password));
2260         // Verify event information.
2261         $this->assertInstanceOf('\core\event\user_password_updated', $event);
2262         $this->assertSame($user->id, $event->relateduserid);
2263         $this->assertEquals(context_user::instance($user->id), $event->get_context());
2264         $this->assertEventContextNotUsed($event);
2266         // Verify recovery of property 'auth'.
2267         unset($user->auth);
2268         update_internal_user_password($user, 'newpassword');
2269         $this->assertDebuggingCalled('User record in update_internal_user_password() must include field auth',
2270                 DEBUG_DEVELOPER);
2271         $this->assertEquals('manual', $user->auth);
2272     }
2274     /**
2275      * Testing that if the password is not cached, that it does not update
2276      * the user table and fire event.
2277      */
2278     public function test_update_internal_user_password_no_cache() {
2279         $this->resetAfterTest();
2281         $user = $this->getDataGenerator()->create_user(array('auth' => 'cas'));
2282         $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2284         $sink = $this->redirectEvents();
2285         update_internal_user_password($user, 'wonkawonka');
2286         $this->assertEquals(0, $sink->count(), 'User updated event should not fire');
2287     }
2289     /**
2290      * Test if the user has a password hash, but now their auth method
2291      * says not to cache it.  Then it should update.
2292      */
2293     public function test_update_internal_user_password_update_no_cache() {
2294         $this->resetAfterTest();
2296         $user = $this->getDataGenerator()->create_user(array('password' => 'test'));
2297         $this->assertNotEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2298         $user->auth = 'cas'; // Change to a auth that does not store passwords.
2300         $sink = $this->redirectEvents();
2301         update_internal_user_password($user, 'wonkawonka');
2302         $this->assertGreaterThanOrEqual(1, $sink->count(), 'User updated event should fire');
2304         $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2305     }
2307     public function test_fullname() {
2308         global $CFG;
2310         $this->resetAfterTest();
2312         // Create a user to test the name display on.
2313         $record = array();
2314         $record['firstname'] = 'Scott';
2315         $record['lastname'] = 'Fletcher';
2316         $record['firstnamephonetic'] = 'スコット';
2317         $record['lastnamephonetic'] = 'フレチャー';
2318         $record['alternatename'] = 'No friends';
2319         $user = $this->getDataGenerator()->create_user($record);
2321         // Back up config settings for restore later.
2322         $originalcfg = new stdClass();
2323         $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
2324         $originalcfg->alternativefullnameformat = $CFG->alternativefullnameformat;
2326         // Testing existing fullnamedisplay settings.
2327         $CFG->fullnamedisplay = 'firstname';
2328         $testname = fullname($user);
2329         $this->assertSame($user->firstname, $testname);
2331         $CFG->fullnamedisplay = 'firstname lastname';
2332         $expectedname = "$user->firstname $user->lastname";
2333         $testname = fullname($user);
2334         $this->assertSame($expectedname, $testname);
2336         $CFG->fullnamedisplay = 'lastname firstname';
2337         $expectedname = "$user->lastname $user->firstname";
2338         $testname = fullname($user);
2339         $this->assertSame($expectedname, $testname);
2341         $expectedname = get_string('fullnamedisplay', null, $user);
2342         $CFG->fullnamedisplay = 'language';
2343         $testname = fullname($user);
2344         $this->assertSame($expectedname, $testname);
2346         // Test override parameter.
2347         $CFG->fullnamedisplay = 'firstname';
2348         $expectedname = "$user->firstname $user->lastname";
2349         $testname = fullname($user, true);
2350         $this->assertSame($expectedname, $testname);
2352         // Test alternativefullnameformat setting.
2353         // Test alternativefullnameformat that has been set to nothing.
2354         $CFG->alternativefullnameformat = '';
2355         $expectedname = "$user->firstname $user->lastname";
2356         $testname = fullname($user, true);
2357         $this->assertSame($expectedname, $testname);
2359         // Test alternativefullnameformat that has been set to 'language'.
2360         $CFG->alternativefullnameformat = 'language';
2361         $expectedname = "$user->firstname $user->lastname";
2362         $testname = fullname($user, true);
2363         $this->assertSame($expectedname, $testname);
2365         // Test customising the alternativefullnameformat setting with all additional name fields.
2366         $CFG->alternativefullnameformat = 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename';
2367         $expectedname = "$user->firstname $user->lastname $user->firstnamephonetic $user->lastnamephonetic $user->middlename $user->alternatename";
2368         $testname = fullname($user, true);
2369         $this->assertSame($expectedname, $testname);
2371         // Test additional name fields.
2372         $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
2373         $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
2374         $testname = fullname($user);
2375         $this->assertSame($expectedname, $testname);
2377         // Test for handling missing data.
2378         $user->middlename = null;
2379         // Parenthesis with no data.
2380         $CFG->fullnamedisplay = 'firstname (middlename) lastname';
2381         $expectedname = "$user->firstname $user->lastname";
2382         $testname = fullname($user);
2383         $this->assertSame($expectedname, $testname);
2385         // Extra spaces due to no data.
2386         $CFG->fullnamedisplay = 'firstname middlename lastname';
2387         $expectedname = "$user->firstname $user->lastname";
2388         $testname = fullname($user);
2389         $this->assertSame($expectedname, $testname);
2391         // Regular expression testing.
2392         // Remove some data from the user fields.
2393         $user->firstnamephonetic = '';
2394         $user->lastnamephonetic = '';
2396         // Removing empty brackets and excess whitespace.
2397         // All of these configurations should resolve to just firstname lastname.
2398         $configarray = array();
2399         $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
2400         $configarray[] = 'firstname lastname \'middlename\'';
2401         $configarray[] = 'firstname "firstnamephonetic" lastname';
2402         $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
2404         foreach ($configarray as $config) {
2405             $CFG->fullnamedisplay = $config;
2406             $expectedname = "$user->firstname $user->lastname";
2407             $testname = fullname($user);
2408             $this->assertSame($expectedname, $testname);
2409         }
2411         // Check to make sure that other characters are left in place.
2412         $configarray = array();
2413         $configarray['0'] = new stdClass();
2414         $configarray['0']->config = 'lastname firstname, middlename';
2415         $configarray['0']->expectedname = "$user->lastname $user->firstname,";
2416         $configarray['1'] = new stdClass();
2417         $configarray['1']->config = 'lastname firstname + alternatename';
2418         $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
2419         $configarray['2'] = new stdClass();
2420         $configarray['2']->config = 'firstname aka: alternatename';
2421         $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
2422         $configarray['3'] = new stdClass();
2423         $configarray['3']->config = 'firstname (alternatename)';
2424         $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
2425         $configarray['4'] = new stdClass();
2426         $configarray['4']->config = 'firstname [alternatename]';
2427         $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
2428         $configarray['5'] = new stdClass();
2429         $configarray['5']->config = 'firstname "lastname"';
2430         $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
2432         foreach ($configarray as $config) {
2433             $CFG->fullnamedisplay = $config->config;
2434             $expectedname = $config->expectedname;
2435             $testname = fullname($user);
2436             $this->assertSame($expectedname, $testname);
2437         }
2439         // Test debugging message displays when
2440         // fullnamedisplay setting is "normal".
2441         $CFG->fullnamedisplay = 'firstname lastname';
2442         unset($user);
2443         $user = new stdClass();
2444         $user->firstname = 'Stan';
2445         $user->lastname = 'Lee';
2446         $namedisplay = fullname($user);
2447         $this->assertDebuggingCalled();
2449         // Tidy up after we finish testing.
2450         $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
2451         $CFG->alternativefullnameformat = $originalcfg->alternativefullnameformat;
2452     }
2454     public function test_get_all_user_name_fields() {
2455         $this->resetAfterTest();
2457         // Additional names in an array.
2458         $testarray = array('firstnamephonetic' => 'firstnamephonetic',
2459                 'lastnamephonetic' => 'lastnamephonetic',
2460                 'middlename' => 'middlename',
2461                 'alternatename' => 'alternatename',
2462                 'firstname' => 'firstname',
2463                 'lastname' => 'lastname');
2464         $this->assertEquals($testarray, get_all_user_name_fields());
2466         // Additional names as a string.
2467         $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
2468         $this->assertEquals($teststring, get_all_user_name_fields(true));
2470         // Additional names as a string with an alias.
2471         $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
2472         $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
2474         // Additional name fields with a prefix - object.
2475         $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
2476                 'lastnamephonetic' => 'authorlastnamephonetic',
2477                 'middlename' => 'authormiddlename',
2478                 'alternatename' => 'authoralternatename',
2479                 'firstname' => 'authorfirstname',
2480                 'lastname' => 'authorlastname');
2481         $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
2483         // Additional name fields with an alias and a title - string.
2484         $teststring = 'u.firstnamephonetic AS authorfirstnamephonetic,u.lastnamephonetic AS authorlastnamephonetic,u.middlename AS authormiddlename,u.alternatename AS authoralternatename,u.firstname AS authorfirstname,u.lastname AS authorlastname';
2485         $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
2486     }
2488     public function test_order_in_string() {
2489         $this->resetAfterTest();
2491         // Return an array in an order as they are encountered in a string.
2492         $valuearray = array('second', 'firsthalf', 'first');
2493         $formatstring = 'first firsthalf some other text (second)';
2494         $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
2495         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2497         // Try again with a different order for the format.
2498         $valuearray = array('second', 'firsthalf', 'first');
2499         $formatstring = 'firsthalf first second';
2500         $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
2501         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2503         // Try again with yet another different order for the format.
2504         $valuearray = array('second', 'firsthalf', 'first');
2505         $formatstring = 'start seconds away second firstquater first firsthalf';
2506         $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
2507         $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2508     }
2510     public function test_complete_user_login() {
2511         global $USER, $DB;
2513         $this->resetAfterTest();
2514         $user = $this->getDataGenerator()->create_user();
2515         $this->setUser(0);
2517         $sink = $this->redirectEvents();
2518         $loginuser = clone($user);
2519         $this->setCurrentTimeStart();
2520         @complete_user_login($loginuser); // Hide session header errors.
2521         $this->assertSame($loginuser, $USER);
2522         $this->assertEquals($user->id, $USER->id);
2523         $events = $sink->get_events();
2524         $sink->close();
2526         $this->assertCount(1, $events);
2527         $event = reset($events);
2528         $this->assertInstanceOf('\core\event\user_loggedin', $event);
2529         $this->assertEquals('user', $event->objecttable);
2530         $this->assertEquals($user->id, $event->objectid);
2531         $this->assertEquals(context_system::instance()->id, $event->contextid);
2532         $this->assertEventContextNotUsed($event);
2534         $user = $DB->get_record('user', array('id'=>$user->id));
2536         $this->assertTimeCurrent($user->firstaccess);
2537         $this->assertTimeCurrent($user->lastaccess);
2539         $this->assertTimeCurrent($USER->firstaccess);
2540         $this->assertTimeCurrent($USER->lastaccess);
2541         $this->assertTimeCurrent($USER->currentlogin);
2542         $this->assertSame(sesskey(), $USER->sesskey);
2543         $this->assertTimeCurrent($USER->preference['_lastloaded']);
2544         $this->assertObjectNotHasAttribute('password', $USER);
2545         $this->assertObjectNotHasAttribute('description', $USER);
2546     }
2548     /**
2549      * Test require_logout.
2550      */
2551     public function test_require_logout() {
2552         $this->resetAfterTest();
2553         $user = $this->getDataGenerator()->create_user();
2554         $this->setUser($user);
2556         $this->assertTrue(isloggedin());
2558         // Logout user and capture event.
2559         $sink = $this->redirectEvents();
2560         require_logout();
2561         $events = $sink->get_events();
2562         $sink->close();
2563         $event = array_pop($events);
2565         // Check if user is logged out.
2566         $this->assertFalse(isloggedin());
2568         // Test Event.
2569         $this->assertInstanceOf('\core\event\user_loggedout', $event);
2570         $this->assertSame($user->id, $event->objectid);
2571         $this->assertSame('user_logout', $event->get_legacy_eventname());
2572         $this->assertEventLegacyData($user, $event);
2573         $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
2574             $event->objectid);
2575         $this->assertEventLegacyLogData($expectedlogdata, $event);
2576         $this->assertEventContextNotUsed($event);
2577     }
2579     public function test_email_to_user() {
2580         global $CFG;
2582         $this->resetAfterTest();
2584         $user1 = $this->getDataGenerator()->create_user();
2585         $user2 = $this->getDataGenerator()->create_user();
2587         $subject = 'subject';
2588         $messagetext = 'message text';
2589         $subject2 = 'subject 2';
2590         $messagetext2 = 'message text 2';
2592         $this->assertNotEmpty($CFG->noemailever);
2593         email_to_user($user1, $user2, $subject, $messagetext);
2594         $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
2596         unset_config('noemailever');
2598         email_to_user($user1, $user2, $subject, $messagetext);
2599         $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2601         $sink = $this->redirectEmails();
2602         email_to_user($user1, $user2, $subject, $messagetext);
2603         email_to_user($user2, $user1, $subject2, $messagetext2);
2604         $this->assertSame(2, $sink->count());
2605         $result = $sink->get_messages();
2606         $this->assertCount(2, $result);
2607         $sink->close();
2609         $this->assertSame($subject, $result[0]->subject);
2610         $this->assertSame($messagetext, trim($result[0]->body));
2611         $this->assertSame($user1->email, $result[0]->to);
2612         $this->assertSame($user2->email, $result[0]->from);
2614         $this->assertSame($subject2, $result[1]->subject);
2615         $this->assertSame($messagetext2, trim($result[1]->body));
2616         $this->assertSame($user2->email, $result[1]->to);
2617         $this->assertSame($user1->email, $result[1]->from);
2619         email_to_user($user1, $user2, $subject, $messagetext);
2620         $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2622         // Test $CFG->emailonlyfromnoreplyaddress.
2623         set_config('emailonlyfromnoreplyaddress', 1);
2624         $this->assertNotEmpty($CFG->emailonlyfromnoreplyaddress);
2625         $sink = $this->redirectEmails();
2626         email_to_user($user1, $user2, $subject, $messagetext);
2627         unset_config('emailonlyfromnoreplyaddress');
2628         email_to_user($user1, $user2, $subject, $messagetext);
2629         $result = $sink->get_messages();
2630         $this->assertEquals($CFG->noreplyaddress, $result[0]->from);
2631         $this->assertNotEquals($CFG->noreplyaddress, $result[1]->from);
2632         $sink->close();
2633     }
2635     /**
2636      * Test setnew_password_and_mail.
2637      */
2638     public function test_setnew_password_and_mail() {
2639         global $DB, $CFG;
2641         $this->resetAfterTest();
2643         $user = $this->getDataGenerator()->create_user();
2645         // Set config to allow email_to_user() to be called.
2646         $CFG->noemailever = false;
2648         // Update user password.
2649         $sink = $this->redirectEvents();
2650         $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
2651         setnew_password_and_mail($user);
2652         $events = $sink->get_events();
2653         $sink->close();
2654         $sink2->close();
2655         $event = array_pop($events);
2657         // Test updated value.
2658         $dbuser = $DB->get_record('user', array('id' => $user->id));
2659         $this->assertSame($user->firstname, $dbuser->firstname);
2660         $this->assertNotEmpty($dbuser->password);
2662         // Test event.
2663         $this->assertInstanceOf('\core\event\user_password_updated', $event);
2664         $this->assertSame($user->id, $event->relateduserid);
2665         $this->assertEquals(context_user::instance($user->id), $event->get_context());
2666         $this->assertEventContextNotUsed($event);
2667     }
2669     /**
2670      * Test remove_course_content deletes course contents
2671      * TODO Add asserts to verify other data related to course is deleted as well.
2672      */
2673     public function test_remove_course_contents() {
2675         $this->resetAfterTest();
2677         $course = $this->getDataGenerator()->create_course();
2678         $user = $this->getDataGenerator()->create_user();
2679         $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
2680         $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id));
2682         $this->assertNotEquals(false, note_load($note->id));
2683         remove_course_contents($course->id, false);
2684         $this->assertFalse(note_load($note->id));
2685     }
2687     /**
2688      * Test function username_load_fields_from_object().
2689      */
2690     public function test_username_load_fields_from_object() {
2691         $this->resetAfterTest();
2693         // This object represents the information returned from an sql query.
2694         $userinfo = new stdClass();
2695         $userinfo->userid = 1;
2696         $userinfo->username = 'loosebruce';
2697         $userinfo->firstname = 'Bruce';
2698         $userinfo->lastname = 'Campbell';
2699         $userinfo->firstnamephonetic = 'ブルース';
2700         $userinfo->lastnamephonetic = 'カンベッル';
2701         $userinfo->middlename = '';
2702         $userinfo->alternatename = '';
2703         $userinfo->email = '';
2704         $userinfo->picture = 23;
2705         $userinfo->imagealt = 'Michael Jordan draining another basket.';
2706         $userinfo->idnumber = 3982;
2708         // Just user name fields.
2709         $user = new stdClass();
2710         $user = username_load_fields_from_object($user, $userinfo);
2711         $expectedarray = new stdClass();
2712         $expectedarray->firstname = 'Bruce';
2713         $expectedarray->lastname = 'Campbell';
2714         $expectedarray->firstnamephonetic = 'ブルース';
2715         $expectedarray->lastnamephonetic = 'カンベッル';
2716         $expectedarray->middlename = '';
2717         $expectedarray->alternatename = '';
2718         $this->assertEquals($user, $expectedarray);
2720         // User information for showing a picture.
2721         $user = new stdClass();
2722         $additionalfields = explode(',', user_picture::fields());
2723         $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
2724         $user->id = $userinfo->userid;
2725         $expectedarray = new stdClass();
2726         $expectedarray->id = 1;
2727         $expectedarray->firstname = 'Bruce';
2728         $expectedarray->lastname = 'Campbell';
2729         $expectedarray->firstnamephonetic = 'ブルース';
2730         $expectedarray->lastnamephonetic = 'カンベッル';
2731         $expectedarray->middlename = '';
2732         $expectedarray->alternatename = '';
2733         $expectedarray->email = '';
2734         $expectedarray->picture = 23;
2735         $expectedarray->imagealt = 'Michael Jordan draining another basket.';
2736         $this->assertEquals($user, $expectedarray);
2738         // Alter the userinfo object to have a prefix.
2739         $userinfo->authorfirstname = 'Bruce';
2740         $userinfo->authorlastname = 'Campbell';
2741         $userinfo->authorfirstnamephonetic = 'ブルース';
2742         $userinfo->authorlastnamephonetic = 'カンベッル';
2743         $userinfo->authormiddlename = '';
2744         $userinfo->authorpicture = 23;
2745         $userinfo->authorimagealt = 'Michael Jordan draining another basket.';
2746         $userinfo->authoremail = 'test@testing.net';
2749         // Return an object with user picture information.
2750         $user = new stdClass();
2751         $additionalfields = explode(',', user_picture::fields());
2752         $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
2753         $user->id = $userinfo->userid;
2754         $expectedarray = new stdClass();
2755         $expectedarray->id = 1;
2756         $expectedarray->firstname = 'Bruce';
2757         $expectedarray->lastname = 'Campbell';
2758         $expectedarray->firstnamephonetic = 'ブルース';
2759         $expectedarray->lastnamephonetic = 'カンベッル';
2760         $expectedarray->middlename = '';
2761         $expectedarray->alternatename = '';
2762         $expectedarray->email = 'test@testing.net';
2763         $expectedarray->picture = 23;
2764         $expectedarray->imagealt = 'Michael Jordan draining another basket.';
2765         $this->assertEquals($user, $expectedarray);
2766     }
2768     /**
2769      * Test function count_words().
2770      */
2771     public function test_count_words() {
2772         $count = count_words("one two three'four");
2773         $this->assertEquals(3, $count);
2775         $count = count_words('one+two three’four');
2776         $this->assertEquals(3, $count);
2778         $count = count_words('one"two three-four');
2779         $this->assertEquals(3, $count);
2781         $count = count_words('one@two three_four');
2782         $this->assertEquals(4, $count);
2784         $count = count_words('one\two three/four');
2785         $this->assertEquals(4, $count);
2787         $count = count_words(' one ... two &nbsp; three...four ');
2788         $this->assertEquals(4, $count);
2790         $count = count_words('one.2 3,four');
2791         $this->assertEquals(4, $count);
2793         $count = count_words('1³ £2 €3.45 $6,789');
2794         $this->assertEquals(4, $count);
2796         $count = count_words('one—two ブルース カンベッル');
2797         $this->assertEquals(4, $count);
2799         $count = count_words('one…two ブルース … カンベッル');
2800         $this->assertEquals(4, $count);
2801     }