MDL-43669 messaging Enable sending email only from no-reply address
[moodle.git] / lib / tests / moodlelib_test.php
CommitLineData
a3d5830a
PS
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/>.
16
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 */
26
27defined('MOODLE_INTERNAL') || die();
28
be6ce11c 29class core_moodlelib_testcase extends advanced_testcase {
a3d5830a
PS
30
31 public static $includecoverage = array('lib/moodlelib.php');
32
d381fb77
GPL
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.
d381fb77
GPL
42 */
43 protected function define_local_decimal_separator() {
44 global $SESSION, $CFG;
45
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 }
52
be6ce11c
PS
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 '));
a3d5830a 57
be6ce11c
PS
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));
a3d5830a
PS
70 }
71
be6ce11c
PS
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).
a3d5830a
PS
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'));
90
be6ce11c 91 // Fixed input.
a3d5830a
PS
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'));
94
be6ce11c 95 // Incorrect input.
a3d5830a
PS
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'));
106
be6ce11c 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).
a3d5830a
PS
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'));
122
be6ce11c 123 // Fixed input.
a3d5830a
PS
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 '));
126
be6ce11c 127 // Incorrect input.
a3d5830a
PS
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'));
131
be6ce11c 132 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-).
a3d5830a
PS
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:'));
146
be6ce11c 147 // Multiple subnets.
a3d5830a
PS
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'));
152
be6ce11c 153 // Other incorrect input.
a3d5830a
PS
154 $this->assertFalse(address_in_subnet('123.123.123.123', ''));
155 }
156
be6ce11c
PS
157 public function test_fix_utf8() {
158 // Make sure valid data including other types is not changed.
a3d5830a
PS
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(''));
0aff15c2 164 $this->assertSame('abc', fix_utf8('abc'));
a3d5830a
PS
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));
171
bff1d60c
PS
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"));
a3d5830a 174
be6ce11c 175 // Invalid utf8 string.
0aff15c2 176 $this->assertSame('aš', fix_utf8('a'.chr(130).'š'), 'This fails with buggy iconv() when mbstring extenstion is not available as fallback.');
a3d5830a
PS
177 }
178
be6ce11c 179 public function test_optional_param() {
a3d5830a
PS
180 global $CFG;
181
182 $_POST['username'] = 'post_user';
183 $_GET['username'] = 'get_user';
be6ce11c 184 $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
a3d5830a
PS
185
186 unset($_POST['username']);
be6ce11c 187 $this->assertSame($_GET['username'], optional_param('username', 'default_user', PARAM_RAW));
a3d5830a
PS
188
189 unset($_GET['username']);
be6ce11c 190 $this->assertSame('default_user', optional_param('username', 'default_user', PARAM_RAW));
a3d5830a 191
be6ce11c 192 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
a3d5830a
PS
193 $_POST['username'] = 'post_user';
194 try {
195 optional_param('username', 'default_user', null);
196 $this->fail('coding_exception expected');
be6ce11c
PS
197 } catch (moodle_exception $ex) {
198 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
199 }
200 try {
201 @optional_param('username', 'default_user');
202 $this->fail('coding_exception expected');
be6ce11c
PS
203 } catch (moodle_exception $ex) {
204 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
205 }
206 try {
207 @optional_param('username');
208 $this->fail('coding_exception expected');
be6ce11c
PS
209 } catch (moodle_exception $ex) {
210 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
211 }
212 try {
213 optional_param('', 'default_user', PARAM_RAW);
214 $this->fail('coding_exception expected');
be6ce11c
PS
215 } catch (moodle_exception $ex) {
216 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
217 }
218
be6ce11c 219 // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
c8bc6c15 220 $_POST['username'] = array('a'=>'a');
be6ce11c 221 $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
c8bc6c15 222 $this->assertDebuggingCalled();
a3d5830a
PS
223 }
224
be6ce11c 225 public function test_optional_param_array() {
a3d5830a
PS
226 global $CFG;
227
228 $_POST['username'] = array('a'=>'post_user');
229 $_GET['username'] = array('a'=>'get_user');
be6ce11c 230 $this->assertSame($_POST['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
a3d5830a
PS
231
232 unset($_POST['username']);
be6ce11c 233 $this->assertSame($_GET['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
a3d5830a
PS
234
235 unset($_GET['username']);
be6ce11c 236 $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
a3d5830a 237
be6ce11c 238 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
a3d5830a
PS
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');
be6ce11c
PS
243 } catch (moodle_exception $ex) {
244 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
245 }
246 try {
247 @optional_param_array('username', array('a'=>'default_user'));
248 $this->fail('coding_exception expected');
be6ce11c
PS
249 } catch (moodle_exception $ex) {
250 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
251 }
252 try {
253 @optional_param_array('username');
254 $this->fail('coding_exception expected');
be6ce11c
PS
255 } catch (moodle_exception $ex) {
256 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
257 }
258 try {
259 optional_param_array('', array('a'=>'default_user'), PARAM_RAW);
260 $this->fail('coding_exception expected');
be6ce11c
PS
261 } catch (moodle_exception $ex) {
262 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
263 }
264
be6ce11c 265 // Do not allow nested arrays.
a3d5830a
PS
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 }
273
be6ce11c 274 // Do not allow non-arrays.
a3d5830a 275 $_POST['username'] = 'post_user';
be6ce11c 276 $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
c8bc6c15 277 $this->assertDebuggingCalled();
a3d5830a 278
be6ce11c 279 // Make sure array keys are sanitised.
a3d5830a 280 $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
be6ce11c 281 $this->assertSame(array('a1_-'=>'post_user'), optional_param_array('username', array(), PARAM_RAW));
c8bc6c15 282 $this->assertDebuggingCalled();
a3d5830a
PS
283 }
284
be6ce11c 285 public function test_required_param() {
a3d5830a
PS
286 $_POST['username'] = 'post_user';
287 $_GET['username'] = 'get_user';
be6ce11c 288 $this->assertSame('post_user', required_param('username', PARAM_RAW));
a3d5830a
PS
289
290 unset($_POST['username']);
be6ce11c 291 $this->assertSame('get_user', required_param('username', PARAM_RAW));
a3d5830a
PS
292
293 unset($_GET['username']);
294 try {
be6ce11c 295 $this->assertSame('default_user', required_param('username', PARAM_RAW));
a3d5830a
PS
296 $this->fail('moodle_exception expected');
297 } catch (moodle_exception $ex) {
be6ce11c 298 $this->assertInstanceOf('moodle_exception', $ex);
a3d5830a
PS
299 }
300
be6ce11c 301 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
a3d5830a
PS
302 $_POST['username'] = 'post_user';
303 try {
304 @required_param('username');
305 $this->fail('coding_exception expected');
be6ce11c
PS
306 } catch (moodle_exception $ex) {
307 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
308 }
309 try {
310 required_param('username', '');
311 $this->fail('coding_exception expected');
be6ce11c
PS
312 } catch (moodle_exception $ex) {
313 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
314 }
315 try {
316 required_param('', PARAM_RAW);
317 $this->fail('coding_exception expected');
be6ce11c
PS
318 } catch (moodle_exception $ex) {
319 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
320 }
321
be6ce11c 322 // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
c8bc6c15 323 $_POST['username'] = array('a'=>'a');
be6ce11c 324 $this->assertSame($_POST['username'], required_param('username', PARAM_RAW));
c8bc6c15 325 $this->assertDebuggingCalled();
a3d5830a
PS
326 }
327
be6ce11c 328 public function test_required_param_array() {
a3d5830a
PS
329 global $CFG;
330
331 $_POST['username'] = array('a'=>'post_user');
332 $_GET['username'] = array('a'=>'get_user');
be6ce11c 333 $this->assertSame($_POST['username'], required_param_array('username', PARAM_RAW));
a3d5830a
PS
334
335 unset($_POST['username']);
be6ce11c 336 $this->assertSame($_GET['username'], required_param_array('username', PARAM_RAW));
a3d5830a 337
be6ce11c 338 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
a3d5830a
PS
339 $_POST['username'] = array('a'=>'post_user');
340 try {
341 required_param_array('username', null);
342 $this->fail('coding_exception expected');
be6ce11c
PS
343 } catch (moodle_exception $ex) {
344 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
345 }
346 try {
347 @required_param_array('username');
348 $this->fail('coding_exception expected');
be6ce11c
PS
349 } catch (moodle_exception $ex) {
350 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
351 }
352 try {
353 required_param_array('', PARAM_RAW);
354 $this->fail('coding_exception expected');
be6ce11c
PS
355 } catch (moodle_exception $ex) {
356 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
357 }
358
be6ce11c 359 // Do not allow nested arrays.
a3d5830a
PS
360 try {
361 $_POST['username'] = array('a'=>array('b'=>'post_user'));
362 required_param_array('username', PARAM_RAW);
363 $this->fail('coding_exception expected');
be6ce11c
PS
364 } catch (moodle_exception $ex) {
365 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
366 }
367
be6ce11c 368 // Do not allow non-arrays.
a3d5830a
PS
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) {
be6ce11c 374 $this->assertInstanceOf('moodle_exception', $ex);
a3d5830a
PS
375 }
376
be6ce11c 377 // Make sure array keys are sanitised.
a3d5830a 378 $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
be6ce11c 379 $this->assertSame(array('a1_-'=>'post_user'), required_param_array('username', PARAM_RAW));
c8bc6c15 380 $this->assertDebuggingCalled();
a3d5830a
PS
381 }
382
be6ce11c
PS
383 public function test_clean_param() {
384 // Forbid objects and arrays.
a3d5830a
PS
385 try {
386 clean_param(array('x', 'y'), PARAM_RAW);
387 $this->fail('coding_exception expected');
be6ce11c
PS
388 } catch (moodle_exception $ex) {
389 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
390 }
391 try {
392 $param = new stdClass();
393 $param->id = 1;
394 clean_param($param, PARAM_RAW);
395 $this->fail('coding_exception expected');
be6ce11c
PS
396 } catch (moodle_exception $ex) {
397 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
398 }
399
be6ce11c 400 // Require correct type.
a3d5830a
PS
401 try {
402 clean_param('x', 'xxxxxx');
403 $this->fail('moodle_exception expected');
404 } catch (moodle_exception $ex) {
be6ce11c 405 $this->assertInstanceOf('moodle_exception', $ex);
a3d5830a
PS
406 }
407 try {
408 @clean_param('x');
409 $this->fail('moodle_exception expected');
410 } catch (moodle_exception $ex) {
be6ce11c 411 $this->assertInstanceOf('moodle_exception', $ex);
a3d5830a 412 }
a3d5830a
PS
413 }
414
be6ce11c
PS
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));
a3d5830a 419
be6ce11c 420 // Require correct type.
a3d5830a
PS
421 try {
422 clean_param_array(array('x'), 'xxxxxx');
423 $this->fail('moodle_exception expected');
424 } catch (moodle_exception $ex) {
be6ce11c 425 $this->assertInstanceOf('moodle_exception', $ex);
a3d5830a
PS
426 }
427 try {
428 @clean_param_array(array('x'));
429 $this->fail('moodle_exception expected');
430 } catch (moodle_exception $ex) {
be6ce11c 431 $this->assertInstanceOf('moodle_exception', $ex);
a3d5830a
PS
432 }
433
434 try {
435 clean_param_array(array('x', array('y')), PARAM_RAW);
436 $this->fail('coding_exception expected');
be6ce11c
PS
437 } catch (moodle_exception $ex) {
438 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
439 }
440
be6ce11c 441 // Test recursive.
a3d5830a
PS
442 }
443
be6ce11c
PS
444 public function test_clean_param_raw() {
445 $this->assertSame(
446 '#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)',
447 clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_RAW));
a3d5830a
PS
448 }
449
be6ce11c
PS
450 public function test_clean_param_trim() {
451 $this->assertSame('Frog toad', clean_param(" Frog toad \r\n ", PARAM_RAW_TRIMMED));
a3d5830a
PS
452 }
453
be6ce11c
PS
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));
a3d5830a
PS
458 }
459
be6ce11c
PS
460 public function test_clean_param_alpha() {
461 $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHA));
a3d5830a
PS
462 }
463
be6ce11c
PS
464 public function test_clean_param_alphanum() {
465 $this->assertSame('978942897DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHANUM));
a3d5830a
PS
466 }
467
be6ce11c
PS
468 public function test_clean_param_alphaext() {
469 $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHAEXT));
a3d5830a
PS
470 }
471
be6ce11c
PS
472 public function test_clean_param_sequence() {
473 $this->assertSame(',9789,42897', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_SEQUENCE));
a3d5830a
PS
474 }
475
be6ce11c
PS
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));
a41d1ca0
PS
485 $this->assertSame('feedback360', clean_param('feedback360', PARAM_COMPONENT));
486 $this->assertSame('mod_feedback360', clean_param('mod_feedback360', PARAM_COMPONENT));
be6ce11c
PS
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));
b5486ce8 493 $this->assertSame('', clean_param('mod__something', PARAM_COMPONENT));
be6ce11c
PS
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));
a3d5830a
PS
502 }
503
be6ce11c 504 public function test_is_valid_plugin_name() {
5f850735
TH
505 $this->assertTrue(is_valid_plugin_name('forum'));
506 $this->assertTrue(is_valid_plugin_name('forum2'));
a41d1ca0 507 $this->assertTrue(is_valid_plugin_name('feedback360'));
5f850735
TH
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 }
519
be6ce11c
PS
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));
a41d1ca0 524 $this->assertSame('feedback360', clean_param('feedback360', PARAM_PLUGIN));
be6ce11c
PS
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 }
536
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));
a41d1ca0 543 $this->assertSame('feedback360', clean_param('feedback360', PARAM_AREA));
be6ce11c
PS
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 }
552
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 }
573
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 }
583
584 public function test_clean_param_localurl() {
a3d5830a 585 global $CFG;
be6ce11c
PS
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 }
593
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));
616
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 }
624
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 }
644
645 public function test_clean_param_username() {
a3d5830a
PS
646 global $CFG;
647 $currentstatus = $CFG->extendedusernamechars;
648
be6ce11c
PS
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');
662
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));
a3d5830a
PS
672
673 $CFG->extendedusernamechars = $currentstatus;
674 }
675
be6ce11c
PS
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 }
691
692 public function test_clean_param_timezone() {
693 // Test timezone validation.
a3d5830a
PS
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',
8158ce79
JM
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',
a3d5830a
PS
716 '-12.5' => '-12.5',
717 '+12.5' => '+12.5',
8158ce79
JM
718 '13.0' => '13.0',
719 '-13.0' => '-13.0',
720 '+13.0' => '+13.0',
a3d5830a 721 '13.5' => '',
8158ce79 722 '+13.5' => '',
a3d5830a
PS
723 '-13.5' => '',
724 '0.2' => '');
725
726 foreach ($testvalues as $testvalue => $expectedvalue) {
727 $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
be6ce11c 728 $this->assertEquals($expectedvalue, $actualvalue);
a3d5830a
PS
729 }
730 }
731
be6ce11c 732 public function test_validate_param() {
a3d5830a
PS
733 try {
734 $param = validate_param('11a', PARAM_INT);
735 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
736 } catch (moodle_exception $ex) {
737 $this->assertInstanceOf('invalid_parameter_exception', $ex);
a3d5830a 738 }
be6ce11c
PS
739
740 $param = validate_param('11', PARAM_INT);
741 $this->assertSame(11, $param);
742
a3d5830a
PS
743 try {
744 $param = validate_param(null, PARAM_INT, false);
745 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
746 } catch (moodle_exception $ex) {
747 $this->assertInstanceOf('invalid_parameter_exception', $ex);
a3d5830a 748 }
be6ce11c
PS
749
750 $param = validate_param(null, PARAM_INT, true);
751 $this->assertSame(null, $param);
752
a3d5830a
PS
753 try {
754 $param = validate_param(array(), PARAM_INT);
755 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
756 } catch (moodle_exception $ex) {
757 $this->assertInstanceOf('invalid_parameter_exception', $ex);
a3d5830a
PS
758 }
759 try {
760 $param = validate_param(new stdClass, PARAM_INT);
761 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
762 } catch (moodle_exception $ex) {
763 $this->assertInstanceOf('invalid_parameter_exception', $ex);
9a97fa5a 764 }
be6ce11c
PS
765
766 $param = validate_param('1.0', PARAM_FLOAT);
767 $this->assertSame(1.0, $param);
768
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);
781
9a97fa5a
PS
782 try {
783 $param = validate_param('1,2', PARAM_FLOAT);
784 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
785 } catch (moodle_exception $ex) {
786 $this->assertInstanceOf('invalid_parameter_exception', $ex);
9a97fa5a
PS
787 }
788 try {
789 $param = validate_param('', PARAM_FLOAT);
790 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
791 } catch (moodle_exception $ex) {
792 $this->assertInstanceOf('invalid_parameter_exception', $ex);
9a97fa5a
PS
793 }
794 try {
795 $param = validate_param('.', PARAM_FLOAT);
796 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
797 } catch (moodle_exception $ex) {
798 $this->assertInstanceOf('invalid_parameter_exception', $ex);
9a97fa5a
PS
799 }
800 try {
801 $param = validate_param('e10', PARAM_FLOAT);
802 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
803 } catch (moodle_exception $ex) {
804 $this->assertInstanceOf('invalid_parameter_exception', $ex);
9a97fa5a
PS
805 }
806 try {
807 $param = validate_param('abc', PARAM_FLOAT);
808 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
809 } catch (moodle_exception $ex) {
810 $this->assertInstanceOf('invalid_parameter_exception', $ex);
9a97fa5a 811 }
a3d5830a
PS
812 }
813
be6ce11c 814 public function test_shorten_text_no_tags_already_short_enough() {
4a7cc248 815 // ......12345678901234567890123456.
a3d5830a 816 $text = "short text already no tags";
be6ce11c 817 $this->assertSame($text, shorten_text($text));
4a7cc248 818 }
a3d5830a 819
be6ce11c 820 public function test_shorten_text_with_tags_already_short_enough() {
4a7cc248 821 // .........123456...7890....12345678.......901234567.
a3d5830a 822 $text = "<p>short <b>text</b> already</p><p>with tags</p>";
be6ce11c 823 $this->assertSame($text, shorten_text($text));
4a7cc248 824 }
a3d5830a 825
be6ce11c 826 public function test_shorten_text_no_tags_needs_shortening() {
4a7cc248
TH
827 // Default truncation is after 30 chars, but allowing 3 for the final '...'.
828 // ......12345678901234567890123456789023456789012345678901234.
a3d5830a 829 $text = "long text without any tags blah de blah blah blah what";
be6ce11c 830 $this->assertSame('long text without any tags ...', shorten_text($text));
4a7cc248 831 }
a3d5830a 832
be6ce11c 833 public function test_shorten_text_with_tags_needs_shortening() {
4a7cc248 834 // .......................................123456789012345678901234567890...
a3d5830a
PS
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));
4a7cc248 839 }
a3d5830a 840
be6ce11c 841 public function test_shorten_text_with_entities() {
4a7cc248
TH
842 // Remember to allow 3 chars for the final '...'.
843 // ......123456789012345678901234567_____890...
a3d5830a 844 $text = "some text which shouldn't &nbsp; break there";
be6ce11c
PS
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));
4a7cc248 848 }
a3d5830a 849
be6ce11c 850 public function test_shorten_text_known_tricky_case() {
a3d5830a 851 // This case caused a bug up to 1.9.5
4a7cc248 852 // ..........123456789012345678901234567890123456789.....0_____1___2___...
a3d5830a 853 $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
be6ce11c 854 $this->assertSame("<h3>standard 'break-out' sub groups in ...</h3>",
4a7cc248 855 shorten_text($text, 41));
be6ce11c 856 $this->assertSame("<h3>standard 'break-out' sub groups in TGs?...</h3>",
4a7cc248 857 shorten_text($text, 42));
be6ce11c 858 $this->assertSame("<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;...",
a3d5830a 859 shorten_text($text, 43));
4a7cc248 860 }
a3d5830a 861
be6ce11c 862 public function test_shorten_text_no_spaces() {
4a7cc248
TH
863 // ..........123456789.
864 $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
be6ce11c 865 $this->assertSame("<h1>12345...</h1>", shorten_text($text, 8));
4a7cc248 866 }
a3d5830a 867
be6ce11c 868 public function test_shorten_text_utf8_european() {
4a7cc248
TH
869 // Text without tags.
870 // ......123456789012345678901234567.
a3d5830a 871 $text = "Žluťoučký koníček přeskočil";
be6ce11c
PS
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));
4a7cc248 875 // And try it with 2-less (that are, in bytes, the middle of a sequence).
be6ce11c
PS
876 $this->assertSame("Žluťoučký koní...", shorten_text($text, 17, true));
877 $this->assertSame("Žluťoučký ...", shorten_text($text, 17, false));
a3d5830a 878
4a7cc248 879 // .........123456789012345678...901234567....89012345.
a3d5830a 880 $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
be6ce11c
PS
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));
4a7cc248 885 // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
be6ce11c
PS
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));
4a7cc248 888 // And try over one tag (start/end), it does proper text len.
be6ce11c
PS
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));
4a7cc248 891 // And in the middle of one tag.
be6ce11c 892 $this->assertSame("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
4a7cc248 893 }
a3d5830a 894
be6ce11c 895 public function test_shorten_text_utf8_oriental() {
a3d5830a 896 // Japanese
4a7cc248
TH
897 // text without tags
898 // ......123456789012345678901234.
a3d5830a 899 $text = '言語設定言語設定abcdefghijkl';
be6ce11c
PS
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));
a3d5830a
PS
905
906 // Chinese
4a7cc248
TH
907 // text without tags
908 // ......123456789012345678901234.
a3d5830a 909 $text = '简体中文简体中文abcdefghijkl';
be6ce11c
PS
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));
4a7cc248 915 }
a3d5830a 916
be6ce11c 917 public function test_shorten_text_multilang() {
4a7cc248
TH
918 // This is not necessaryily specific to multilang. The issue is really
919 // tags with attributes, where before we were generating invalid HTML
be6ce11c 920 // output like shorten_text('<span id="x" class="y">A</span> B', 1)
4a7cc248
TH
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>';
be6ce11c 926 $this->assertSame('<span lang="en" class="multilang">...</span>',
4a7cc248 927 shorten_text($text, 1));
a3d5830a
PS
928 }
929
be6ce11c 930 public function test_usergetdate() {
a3d5830a 931 global $USER, $CFG, $DB;
be6ce11c 932 $this->resetAfterTest();
a3d5830a 933
be6ce11c 934 // Check if forcetimezone is set then save it and set it to use user timezone.
a3d5830a
PS
935 $cfgforcetimezone = null;
936 if (isset($CFG->forcetimezone)) {
937 $cfgforcetimezone = $CFG->forcetimezone;
be6ce11c 938 $CFG->forcetimezone = 99; // Get user default timezone.
a3d5830a
PS
939 }
940
be6ce11c 941 $this->setAdminUser();
a3d5830a
PS
942
943 $userstimezone = $USER->timezone;
be6ce11c 944 $USER->timezone = 2;// Set the timezone to a known state.
a3d5830a
PS
945
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');
950
be6ce11c 951 $ts = 1261540267; // The time this function was created.
a3d5830a 952
be6ce11c 953 $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
a3d5830a
PS
954 $arr = array_values($arr);
955
be6ce11c
PS
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.
a3d5830a
PS
968 $arr = array_values($arr);
969
be6ce11c
PS
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.
a3d5830a
PS
982 $USER->timezone = $userstimezone;
983
be6ce11c 984 // Restore forcetimezone if changed.
a3d5830a
PS
985 if (!is_null($cfgforcetimezone)) {
986 $CFG->forcetimezone = $cfgforcetimezone;
987 }
988
989 setlocale(LC_TIME, $oldlocale);
a3d5830a
PS
990 }
991
992 public function test_mark_user_preferences_changed() {
be6ce11c
PS
993 $this->resetAfterTest();
994 $otheruser = $this->getDataGenerator()->create_user();
995 $otheruserid = $otheruser->id;
a3d5830a 996
be6ce11c 997 set_cache_flag('userpreferenceschanged', $otheruserid, null);
a3d5830a
PS
998 mark_user_preferences_changed($otheruserid);
999
1000 $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
be6ce11c 1001 set_cache_flag('userpreferenceschanged', $otheruserid, null);
a3d5830a
PS
1002 }
1003
1004 public function test_check_user_preferences_loaded() {
1005 global $DB;
be6ce11c 1006 $this->resetAfterTest();
a3d5830a 1007
be6ce11c
PS
1008 $otheruser = $this->getDataGenerator()->create_user();
1009 $otheruserid = $otheruser->id;
a3d5830a
PS
1010
1011 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
be6ce11c 1012 set_cache_flag('userpreferenceschanged', $otheruserid, null);
a3d5830a
PS
1013
1014 $user = new stdClass();
1015 $user->id = $otheruserid;
1016
be6ce11c 1017 // Load.
a3d5830a
PS
1018 check_user_preferences_loaded($user);
1019 $this->assertTrue(isset($user->preference));
1020 $this->assertTrue(is_array($user->preference));
be6ce11c
PS
1021 $this->assertArrayHasKey('_lastloaded', $user->preference);
1022 $this->assertCount(1, $user->preference);
a3d5830a 1023
be6ce11c 1024 // Add preference via direct call.
a3d5830a
PS
1025 $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1026
be6ce11c 1027 // No cache reload yet.
a3d5830a 1028 check_user_preferences_loaded($user);
be6ce11c 1029 $this->assertCount(1, $user->preference);
a3d5830a 1030
be6ce11c 1031 // Forced reloading of cache.
a3d5830a
PS
1032 unset($user->preference);
1033 check_user_preferences_loaded($user);
be6ce11c
PS
1034 $this->assertCount(2, $user->preference);
1035 $this->assertSame('yyy', $user->preference['xxx']);
a3d5830a 1036
be6ce11c 1037 // Add preference via direct call.
a3d5830a
PS
1038 $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1039
be6ce11c 1040 // Test timeouts and modifications from different session.
a3d5830a
PS
1041 set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1042 $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1043 check_user_preferences_loaded($user);
be6ce11c 1044 $this->assertCount(2, $user->preference);
a3d5830a 1045 check_user_preferences_loaded($user, 10);
be6ce11c
PS
1046 $this->assertCount(3, $user->preference);
1047 $this->assertSame('bbb', $user->preference['aaa']);
a3d5830a
PS
1048 set_cache_flag('userpreferenceschanged', $user->id, null);
1049 }
1050
1051 public function test_set_user_preference() {
1052 global $DB, $USER;
be6ce11c 1053 $this->resetAfterTest();
a3d5830a 1054
be6ce11c 1055 $this->setAdminUser();
a3d5830a 1056
be6ce11c
PS
1057 $otheruser = $this->getDataGenerator()->create_user();
1058 $otheruserid = $otheruser->id;
a3d5830a
PS
1059
1060 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1061 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1062
1063 $user = new stdClass();
1064 $user->id = $otheruserid;
1065
1066 set_user_preference('aaa', 'bbb', $otheruserid);
be6ce11c
PS
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));
a3d5830a
PS
1069
1070 set_user_preference('xxx', 'yyy', $user);
be6ce11c
PS
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));
a3d5830a 1073 $this->assertTrue(is_array($user->preference));
be6ce11c
PS
1074 $this->assertSame('bbb', $user->preference['aaa']);
1075 $this->assertSame('yyy', $user->preference['xxx']);
a3d5830a 1076
be6ce11c
PS
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));
a3d5830a
PS
1080
1081 set_user_preference('ooo', true, $user);
1082 $prefs = get_user_preferences(null, null, $otheruserid);
be6ce11c
PS
1083 $this->assertSame($user->preference['aaa'], $prefs['aaa']);
1084 $this->assertSame($user->preference['ooo'], $prefs['ooo']);
1085 $this->assertSame('1', $prefs['ooo']);
a3d5830a
PS
1086
1087 set_user_preference('null', 0, $user);
1088 $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1089
1090 $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1091
1092 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1093 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1094
be6ce11c 1095 // Test $USER default.
a3d5830a
PS
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']));
1100
be6ce11c 1101 // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
a3d5830a
PS
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')));
1107
be6ce11c 1108 // Test > 1333 char values, coding_exception expected.
a3d5830a
PS
1109 $longvalue = str_repeat('a', 1334);
1110 try {
1111 set_user_preference('_test_long_user_preference', $longvalue);
17222a4a 1112 $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
be6ce11c
PS
1113 } catch (moodle_exception $ex) {
1114 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
1115 }
1116
be6ce11c 1117 // Test invalid params.
a3d5830a
PS
1118 try {
1119 set_user_preference('_test_user_preferences_pref', array());
17222a4a 1120 $this->fail('Exception expected - array not valid preference value');
be6ce11c
PS
1121 } catch (moodle_exception $ex) {
1122 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
1123 }
1124 try {
1125 set_user_preference('_test_user_preferences_pref', new stdClass);
17222a4a 1126 $this->fail('Exception expected - class not valid preference value');
be6ce11c
PS
1127 } catch (moodle_exception $ex) {
1128 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
1129 }
1130 try {
17222a4a
MN
1131 set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1132 $this->fail('Exception expected - user instance expected');
be6ce11c
PS
1133 } catch (moodle_exception $ex) {
1134 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
1135 }
1136 try {
1137 set_user_preference('_test_user_preferences_pref', 1, 'abc');
17222a4a 1138 $this->fail('Exception expected - user instance expected');
be6ce11c
PS
1139 } catch (moodle_exception $ex) {
1140 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
1141 }
1142 try {
1143 set_user_preference('', 1);
17222a4a 1144 $this->fail('Exception expected - invalid name accepted');
be6ce11c
PS
1145 } catch (moodle_exception $ex) {
1146 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
1147 }
1148 try {
1149 set_user_preference('1', 1);
17222a4a 1150 $this->fail('Exception expected - invalid name accepted');
be6ce11c
PS
1151 } catch (moodle_exception $ex) {
1152 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a 1153 }
a3d5830a
PS
1154 }
1155
1156 public function test_get_extra_user_fields() {
1157 global $CFG, $USER, $DB;
be6ce11c 1158 $this->resetAfterTest();
a3d5830a 1159
be6ce11c 1160 $this->setAdminUser();
a3d5830a
PS
1161
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();
1167
be6ce11c 1168 // No fields.
a3d5830a
PS
1169 $CFG->showuseridentity = '';
1170 $this->assertEquals(array(), get_extra_user_fields($context));
1171
be6ce11c 1172 // One field.
a3d5830a
PS
1173 $CFG->showuseridentity = 'frog';
1174 $this->assertEquals(array('frog'), get_extra_user_fields($context));
1175
be6ce11c 1176 // Two fields.
a3d5830a
PS
1177 $CFG->showuseridentity = 'frog,zombie';
1178 $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1179
be6ce11c 1180 // No fields, except.
a3d5830a
PS
1181 $CFG->showuseridentity = '';
1182 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1183
be6ce11c 1184 // One field.
a3d5830a
PS
1185 $CFG->showuseridentity = 'frog';
1186 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1187
be6ce11c 1188 // Two fields.
a3d5830a
PS
1189 $CFG->showuseridentity = 'frog,zombie';
1190 $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
a3d5830a
PS
1191 }
1192
1193 public function test_get_extra_user_fields_sql() {
1194 global $CFG, $USER, $DB;
be6ce11c 1195 $this->resetAfterTest();
a3d5830a 1196
be6ce11c 1197 $this->setAdminUser();
a3d5830a 1198
a3d5830a
PS
1199 $context = context_system::instance();
1200
be6ce11c 1201 // No fields.
a3d5830a 1202 $CFG->showuseridentity = '';
be6ce11c 1203 $this->assertSame('', get_extra_user_fields_sql($context));
a3d5830a 1204
be6ce11c 1205 // One field.
a3d5830a 1206 $CFG->showuseridentity = 'frog';
be6ce11c 1207 $this->assertSame(', frog', get_extra_user_fields_sql($context));
a3d5830a 1208
be6ce11c 1209 // Two fields with table prefix.
a3d5830a 1210 $CFG->showuseridentity = 'frog,zombie';
be6ce11c 1211 $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
a3d5830a 1212
be6ce11c 1213 // Two fields with field prefix.
a3d5830a 1214 $CFG->showuseridentity = 'frog,zombie';
be6ce11c 1215 $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
a3d5830a
PS
1216 get_extra_user_fields_sql($context, '', 'u_'));
1217
be6ce11c 1218 // One field excluded.
a3d5830a 1219 $CFG->showuseridentity = 'frog';
be6ce11c 1220 $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
a3d5830a 1221
be6ce11c 1222 // Two fields, one excluded, table+field prefix.
a3d5830a
PS
1223 $CFG->showuseridentity = 'frog,zombie';
1224 $this->assertEquals(', u1.zombie AS u_zombie',
1225 get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
a3d5830a
PS
1226 }
1227
d506f422
EL
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.
1241
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);
1250
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);
1259
1260 $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1261
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);
1270
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 }
1280
a3d5830a
PS
1281 public function test_userdate() {
1282 global $USER, $CFG, $DB;
be6ce11c 1283 $this->resetAfterTest();
a3d5830a 1284
be6ce11c 1285 $this->setAdminUser();
a3d5830a
PS
1286
1287 $testvalues = array(
1288 array(
1289 'time' => '1309514400',
1290 'usertimezone' => 'America/Moncton',
be6ce11c 1291 'timezone' => '0.0', // No dst offset.
a3d5830a
PS
1292 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1293 ),
1294 array(
1295 'time' => '1309514400',
1296 'usertimezone' => 'America/Moncton',
be6ce11c 1297 'timezone' => '99', // Dst offset and timezone offset.
a3d5830a
PS
1298 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1299 ),
1300 array(
1301 'time' => '1309514400',
1302 'usertimezone' => 'America/Moncton',
be6ce11c 1303 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
a3d5830a
PS
1304 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1305 ),
1306 array(
1307 'time' => '1293876000 ',
1308 'usertimezone' => 'America/Moncton',
be6ce11c 1309 'timezone' => '0.0', // No dst offset.
a3d5830a
PS
1310 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1311 ),
1312 array(
1313 'time' => '1293876000 ',
1314 'usertimezone' => 'America/Moncton',
be6ce11c 1315 'timezone' => '99', // No dst offset in jan, so just timezone offset.
a3d5830a
PS
1316 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1317 ),
1318 array(
1319 'time' => '1293876000 ',
1320 'usertimezone' => 'America/Moncton',
be6ce11c 1321 'timezone' => 'America/Moncton', // No dst offset in jan.
a3d5830a
PS
1322 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1323 ),
1324 array(
1325 'time' => '1293876000 ',
1326 'usertimezone' => '2',
be6ce11c 1327 'timezone' => '99', // Take user timezone.
a3d5830a
PS
1328 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1329 ),
1330 array(
1331 'time' => '1293876000 ',
1332 'usertimezone' => '-2',
be6ce11c 1333 'timezone' => '99', // Take user timezone.
a3d5830a
PS
1334 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1335 ),
1336 array(
1337 'time' => '1293876000 ',
1338 'usertimezone' => '-10',
be6ce11c 1339 'timezone' => '2', // Take this timezone.
a3d5830a
PS
1340 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1341 ),
1342 array(
1343 'time' => '1293876000 ',
1344 'usertimezone' => '-10',
be6ce11c 1345 'timezone' => '-2', // Take this timezone.
a3d5830a
PS
1346 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1347 ),
1348 array(
1349 'time' => '1293876000 ',
1350 'usertimezone' => '-10',
be6ce11c 1351 'timezone' => 'random/time', // This should show server time.
a3d5830a
PS
1352 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1353 ),
1354 array(
1355 'time' => '1293876000 ',
be6ce11c
PS
1356 'usertimezone' => '14', // Server time zone.
1357 'timezone' => '99', // This should show user time.
a3d5830a
PS
1358 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1359 ),
1360 );
1361
be6ce11c 1362 // Check if forcetimezone is set then save it and set it to use user timezone.
a3d5830a
PS
1363 $cfgforcetimezone = null;
1364 if (isset($CFG->forcetimezone)) {
1365 $cfgforcetimezone = $CFG->forcetimezone;
be6ce11c 1366 $CFG->forcetimezone = 99; // Get user default timezone.
a3d5830a 1367 }
be6ce11c 1368 // Store user default timezone to restore later.
a3d5830a
PS
1369 $userstimezone = $USER->timezone;
1370
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');
1375
be6ce11c
PS
1376 // Set default timezone to Australia/Perth, else time calculated
1377 // will not match expected values. Before that save system defaults.
a3d5830a
PS
1378 $systemdefaulttimezone = date_default_timezone_get();
1379 date_default_timezone_set('Australia/Perth');
1380
1381 foreach ($testvalues as $vals) {
1382 $USER->timezone = $vals['usertimezone'];
1383 $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1384
be6ce11c 1385 // On different systems case of AM PM changes so compare case insensitive.
2f1e464a
PS
1386 $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1387 $actualoutput = core_text::strtolower($actualoutput);
a3d5830a 1388
be6ce11c 1389 $this->assertSame($vals['expectedoutput'], $actualoutput,
a3d5830a
PS
1390 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1391 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1392 }
1393
be6ce11c 1394 // Restore user timezone back to what it was.
a3d5830a
PS
1395 $USER->timezone = $userstimezone;
1396
be6ce11c 1397 // Restore forcetimezone.
a3d5830a
PS
1398 if (!is_null($cfgforcetimezone)) {
1399 $CFG->forcetimezone = $cfgforcetimezone;
1400 }
1401
be6ce11c 1402 // Restore system default values.
a3d5830a
PS
1403 date_default_timezone_set($systemdefaulttimezone);
1404 setlocale(LC_TIME, $oldlocale);
a3d5830a
PS
1405 }
1406
1407 public function test_make_timestamp() {
1408 global $USER, $CFG, $DB;
be6ce11c 1409 $this->resetAfterTest();
a3d5830a 1410
be6ce11c 1411 $this->setAdminUser();
a3d5830a
PS
1412
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',
7b05e146 1422 'timezone' => '0.0',
be6ce11c
PS
1423 'applydst' => false, // No dst offset.
1424 'expectedoutput' => '1309514400' // 6pm at UTC+0.
a3d5830a
PS
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',
be6ce11c
PS
1434 'timezone' => '99', // User default timezone.
1435 'applydst' => false, // Don't apply dst.
a3d5830a
PS
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',
be6ce11c
PS
1446 'timezone' => '99', // User default timezone.
1447 'applydst' => true, // Apply dst.
a3d5830a
PS
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',
be6ce11c
PS
1458 'timezone' => 'America/Moncton', // String timezone.
1459 'applydst' => true, // Apply dst.
a3d5830a
PS
1460 'expectedoutput' => '1309525200'
1461 ),
1462 array(
be6ce11c 1463 'usertimezone' => '2', // No dst applyed.
a3d5830a
PS
1464 'year' => '2011',
1465 'month' => '7',
1466 'day' => '1',
1467 'hour' => '10',
1468 'minutes' => '00',
1469 'seconds' => '00',
be6ce11c
PS
1470 'timezone' => '99', // Take user timezone.
1471 'applydst' => true, // Apply dst.
a3d5830a
PS
1472 'expectedoutput' => '1309507200'
1473 ),
1474 array(
be6ce11c 1475 'usertimezone' => '-2', // No dst applyed.
a3d5830a
PS
1476 'year' => '2011',
1477 'month' => '7',
1478 'day' => '1',
1479 'hour' => '10',
1480 'minutes' => '00',
1481 'seconds' => '00',
be6ce11c
PS
1482 'timezone' => '99', // Take usertimezone.
1483 'applydst' => true, // Apply dst.
a3d5830a
PS
1484 'expectedoutput' => '1309521600'
1485 ),
1486 array(
be6ce11c 1487 'usertimezone' => '-10', // No dst applyed.
a3d5830a
PS
1488 'year' => '2011',
1489 'month' => '7',
1490 'day' => '1',
1491 'hour' => '10',
1492 'minutes' => '00',
1493 'seconds' => '00',
be6ce11c
PS
1494 'timezone' => '2', // Take this timezone.
1495 'applydst' => true, // Apply dst.
a3d5830a
PS
1496 'expectedoutput' => '1309507200'
1497 ),
1498 array(
be6ce11c 1499 'usertimezone' => '-10', // No dst applyed.
a3d5830a
PS
1500 'year' => '2011',
1501 'month' => '7',
1502 'day' => '1',
1503 'hour' => '10',
1504 'minutes' => '00',
1505 'seconds' => '00',
be6ce11c
PS
1506 'timezone' => '-2', // Take this timezone.
1507 'applydst' => true, // Apply dst.
a3d5830a
PS
1508 'expectedoutput' => '1309521600'
1509 ),
1510 array(
be6ce11c 1511 'usertimezone' => '-10', // No dst applyed.
a3d5830a
PS
1512 'year' => '2011',
1513 'month' => '7',
1514 'day' => '1',
1515 'hour' => '10',
1516 'minutes' => '00',
1517 'seconds' => '00',
be6ce11c
PS
1518 'timezone' => 'random/time', // This should show server time.
1519 'applydst' => true, // Apply dst.
a3d5830a
PS
1520 'expectedoutput' => '1309485600'
1521 ),
1522 array(
be6ce11c 1523 'usertimezone' => '14', // Server time.
a3d5830a
PS
1524 'year' => '2011',
1525 'month' => '7',
1526 'day' => '1',
1527 'hour' => '10',
1528 'minutes' => '00',
1529 'seconds' => '00',
be6ce11c
PS
1530 'timezone' => '99', // Get user time.
1531 'applydst' => true, // Apply dst.
a3d5830a
PS
1532 'expectedoutput' => '1309485600'
1533 )
1534 );
1535
be6ce11c 1536 // Check if forcetimezone is set then save it and set it to use user timezone.
a3d5830a
PS
1537 $cfgforcetimezone = null;
1538 if (isset($CFG->forcetimezone)) {
1539 $cfgforcetimezone = $CFG->forcetimezone;
be6ce11c 1540 $CFG->forcetimezone = 99; // Get user default timezone.
a3d5830a
PS
1541 }
1542
be6ce11c 1543 // Store user default timezone to restore later.
a3d5830a
PS
1544 $userstimezone = $USER->timezone;
1545
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');
1550
be6ce11c
PS
1551 // Set default timezone to Australia/Perth, else time calculated
1552 // Will not match expected values. Before that save system defaults.
a3d5830a
PS
1553 $systemdefaulttimezone = date_default_timezone_get();
1554 date_default_timezone_set('Australia/Perth');
1555
be6ce11c 1556 // Test make_timestamp with all testvals and assert if anything wrong.
a3d5830a
PS
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 );
1569
be6ce11c 1570 // On different systems case of AM PM changes so compare case insensitive.
2f1e464a
PS
1571 $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1572 $actualoutput = core_text::strtolower($actualoutput);
a3d5830a 1573
be6ce11c 1574 $this->assertSame($vals['expectedoutput'], $actualoutput,
a3d5830a
PS
1575 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1576 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1577 }
1578
be6ce11c 1579 // Restore user timezone back to what it was.
a3d5830a
PS
1580 $USER->timezone = $userstimezone;
1581
be6ce11c 1582 // Restore forcetimezone.
a3d5830a
PS
1583 if (!is_null($cfgforcetimezone)) {
1584 $CFG->forcetimezone = $cfgforcetimezone;
1585 }
1586
be6ce11c 1587 // Restore system default values.
a3d5830a
PS
1588 date_default_timezone_set($systemdefaulttimezone);
1589 setlocale(LC_TIME, $oldlocale);
a3d5830a
PS
1590 }
1591
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;
1598
be6ce11c 1599 // Make sure we are using English.
a3d5830a
PS
1600 $originallang = $COURSE->lang;
1601 $COURSE->lang = 'en';
1602
1603 $yes = get_string('yes');
1604 $yesexpected = 'Yes';
aed2b9ba 1605 $this->assertInternalType('string', $yes);
be6ce11c 1606 $this->assertSame($yesexpected, $yes);
a3d5830a
PS
1607
1608 $yes = get_string('yes', 'moodle');
aed2b9ba 1609 $this->assertInternalType('string', $yes);
be6ce11c 1610 $this->assertSame($yesexpected, $yes);
a3d5830a
PS
1611
1612 $yes = get_string('yes', 'core');
aed2b9ba 1613 $this->assertInternalType('string', $yes);
be6ce11c 1614 $this->assertSame($yesexpected, $yes);
a3d5830a
PS
1615
1616 $yes = get_string('yes', '');
aed2b9ba 1617 $this->assertInternalType('string', $yes);
be6ce11c 1618 $this->assertSame($yesexpected, $yes);
a3d5830a
PS
1619
1620 $yes = get_string('yes', null);
aed2b9ba 1621 $this->assertInternalType('string', $yes);
be6ce11c 1622 $this->assertSame($yesexpected, $yes);
a3d5830a
PS
1623
1624 $yes = get_string('yes', null, 1);
aed2b9ba 1625 $this->assertInternalType('string', $yes);
be6ce11c 1626 $this->assertSame($yesexpected, $yes);
a3d5830a
PS
1627
1628 $days = 1;
1629 $numdays = get_string('numdays', 'core', '1');
1630 $numdaysexpected = $days.' days';
aed2b9ba 1631 $this->assertInternalType('string', $numdays);
be6ce11c 1632 $this->assertSame($numdaysexpected, $numdays);
a3d5830a
PS
1633
1634 $yes = get_string('yes', null, null, true);
aed2b9ba 1635 $this->assertInstanceOf('lang_string', $yes);
be6ce11c 1636 $this->assertSame($yesexpected, (string)$yes);
a3d5830a
PS
1637
1638 // Test using a lang_string object as the $a argument for a normal
be6ce11c 1639 // get_string call (returning string).
a3d5830a
PS
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);
aed2b9ba 1643 $this->assertInternalType('string', $testresult);
be6ce11c 1644 $this->assertSame($testexpected, $testresult);
a3d5830a
PS
1645
1646 // Test using a lang_string object as the $a argument for an object
be6ce11c 1647 // get_string call (returning lang_string).
a3d5830a
PS
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);
aed2b9ba 1651 $this->assertInstanceOf('lang_string', $testresult);
be6ce11c 1652 $this->assertSame($testexpected, "$testresult");
a3d5830a
PS
1653
1654 // Make sure that object properties that can't be converted don't cause
be6ce11c
PS
1655 // errors.
1656 // Level one: This is as deep as current language processing goes.
a3d5830a
PS
1657 $test = new stdClass;
1658 $test->one = 'here';
1659 $string = get_string('yes', null, $test, true);
be6ce11c 1660 $this->assertEquals($yesexpected, $string);
a3d5830a
PS
1661
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);
be6ce11c 1670 $this->assertEquals($yesexpected, $string);
a3d5830a
PS
1671
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);
be6ce11c 1681 $this->assertEquals($yesexpected, $string);
a3d5830a
PS
1682
1683 // Make sure that object properties that can't be converted don't cause
1684 // errors and check lang_string properties.
be6ce11c 1685 // Level one: This is as deep as current language processing goes.
a3d5830a
PS
1686 $test = new stdClass;
1687 $test->one = new lang_string('yes');
1688 $string = get_string('yes', null, $test, true);
be6ce11c 1689 $this->assertEquals($yesexpected, $string);
a3d5830a
PS
1690
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);
be6ce11c 1699 $this->assertEquals($yesexpected, $string);
a3d5830a
PS
1700
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);
be6ce11c 1710 $this->assertEquals($yesexpected, $string);
a3d5830a
PS
1711
1712 // Make sure that array properties that can't be converted don't cause
be6ce11c 1713 // errors.
a3d5830a
PS
1714 $test = array();
1715 $test['one'] = new stdClass;
1716 $test['one']->two = 'here';
1717 $string = get_string('yes', null, $test, true);
be6ce11c 1718 $this->assertEquals($yesexpected, $string);
a3d5830a 1719
be6ce11c 1720 // Same thing but as above except using an object... this is allowed :P.
a3d5830a
PS
1721 $string = get_string('yes', null, null, true);
1722 $object = new stdClass;
1723 $object->$string = 'Yes';
be6ce11c
PS
1724 $this->assertEquals($yesexpected, $string);
1725 $this->assertEquals($yesexpected, $object->$string);
a3d5830a 1726
be6ce11c 1727 // Reset the language.
a3d5830a
PS
1728 $COURSE->lang = $originallang;
1729 }
1730
1731 /**
1732 * @expectedException PHPUnit_Framework_Error_Warning
a3d5830a
PS
1733 */
1734 public function test_get_string_limitation() {
1735 // This is one of the limitations to the lang_string class. It can't be
be6ce11c 1736 // used as a key.
a3d5830a
PS
1737 $array = array(get_string('yes', null, null, true) => 'yes');
1738 }
637da99e 1739
1740 /**
1741 * Test localised float formatting.
1742 */
1743 public function test_format_float() {
637da99e 1744
be6ce11c 1745 // Special case for null.
637da99e 1746 $this->assertEquals('', format_float(null));
1747
be6ce11c 1748 // Default 1 decimal place.
637da99e 1749 $this->assertEquals('5.4', format_float(5.43));
1750 $this->assertEquals('5.0', format_float(5.001));
1751
be6ce11c 1752 // Custom number of decimal places.
637da99e 1753 $this->assertEquals('5.43000', format_float(5.43, 5));
1754
be6ce11c 1755 // Option to strip ending zeros after rounding.
637da99e 1756 $this->assertEquals('5.43', format_float(5.43, 5, true, true));
1757 $this->assertEquals('5', format_float(5.0001, 3, true, true));
1758
d381fb77
GPL
1759 // Tests with a localised decimal separator.
1760 $this->define_local_decimal_separator();
637da99e 1761
be6ce11c 1762 // Localisation on (default).
637da99e 1763 $this->assertEquals('5X43000', format_float(5.43, 5));
1764 $this->assertEquals('5X43', format_float(5.43, 5, true, true));
1765
be6ce11c 1766 // Localisation off.
637da99e 1767 $this->assertEquals('5.43000', format_float(5.43, 5, false));
1768 $this->assertEquals('5.43', format_float(5.43, 5, false, true));
1769 }
4366ce80 1770
d381fb77
GPL
1771 /**
1772 * Test localised float unformatting.
1773 */
1774 public function test_unformat_float() {
1775
1776 // Tests without the localised decimal separator.
1777
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(' '));
1782
1783 // Regular use.
1784 $this->assertEquals(5.4, unformat_float('5.4'));
1785 $this->assertEquals(5.4, unformat_float('5.4', true));
1786
1787 // No decimal.
1788 $this->assertEquals(5.0, unformat_float('5'));
1789
1790 // Custom number of decimal.
1791 $this->assertEquals(5.43267, unformat_float('5.43267'));
1792
1793 // Empty decimal.
1794 $this->assertEquals(100.0, unformat_float('100.00'));
1795
1796 // With the thousand separator.
1797 $this->assertEquals(1000.0, unformat_float('1 000'));
1798 $this->assertEquals(1000.32, unformat_float('1 000.32'));
1799
1800 // Negative number.
1801 $this->assertEquals(-100.0, unformat_float('-100'));
1802
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));
1807
1808 // Combining options.
1809 $this->assertEquals(-1023.862567, unformat_float(' -1 023.862567 '));
1810
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));
1815
1816 // Tests with a localised decimal separator.
1817 $this->define_local_decimal_separator();
1818
1819 // We repeat the tests above but with the current decimal separator.
1820
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'));
1824
1825 // Custom number of decimal.
1826 $this->assertEquals (5.43267, unformat_float('5X43267'));
1827
1828 // Empty decimal.
1829 $this->assertEquals (100.0, unformat_float('100X00'));
1830
1831 // With the thousand separator.
1832 $this->assertEquals (1000.32, unformat_float('1 000X32'));
1833
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));
1838
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 }
1844
4366ce80
PS
1845 /**
1846 * Test deleting of users.
1847 */
1848 public function test_delete_user() {
1849 global $DB, $CFG;
1850
1851 $this->resetAfterTest();
1852
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)));
1856
1857 $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
1858 $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
1859
bb78e249
RT
1860 // Delete user and capture event.
1861 $sink = $this->redirectEvents();
4366ce80 1862 $result = delete_user($user);
bb78e249
RT
1863 $events = $sink->get_events();
1864 $sink->close();
1865 $event = array_pop($events);
1866
1867 // Test user is deleted in DB.
4366ce80
PS
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);
1875
1876 $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
1877
bb78e249
RT
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);
abedc1a8
RT
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));
623a32e5 1892 $this->assertEventContextNotUsed($event);
4366ce80 1893
bb78e249 1894 // Try invalid params.
4366ce80
PS
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');
be6ce11c
PS
1900 } catch (moodle_exception $ex) {
1901 $this->assertInstanceOf('coding_exception', $ex);
4366ce80
PS
1902 }
1903 $record->id = 1;
1904 try {
1905 delete_user($record);
1906 $this->fail('Expecting exception for invalid delete_user() $user parameter');
be6ce11c
PS
1907 } catch (moodle_exception $ex) {
1908 $this->assertInstanceOf('coding_exception', $ex);
4366ce80
PS
1909 }
1910
4366ce80
PS
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);
1917
1918 $result = delete_user($guest);
1919 $this->assertFalse($result);
1920
1921 $result = delete_user($admin);
1922 $this->assertFalse($result);
a3b6e311
PS
1923
1924 $this->resetDebugging();
4366ce80 1925 }
7b444a96
MG
1926
1927 /**
1928 * Test function convert_to_array()
1929 */
1930 public function test_convert_to_array() {
be6ce11c 1931 // Check that normal classes are converted to arrays the same way as (array) would do.
7b444a96
MG
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);
1937
be6ce11c 1938 // Check that context object (with iterator) is converted to array properly.
0601e0ee 1939 $obj = context_system::instance();
7b444a96
MG
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 }
15396bba
FM
1949
1950 /**
1951 * Test the function date_format_string().
1952 */
be6ce11c 1953 public function test_date_format_string() {
73d20f36
PS
1954 global $CFG;
1955
15396bba
FM
1956 // Forcing locale and timezone.
1957 $oldlocale = setlocale(LC_TIME, '0');
73d20f36
PS
1958 if ($CFG->ostype == 'WINDOWS') {
1959 setlocale(LC_TIME, 'English_Australia.1252');
1960 } else {
1961 setlocale(LC_TIME, 'en_AU.UTF-8');
1962 }
15396bba
FM
1963 $systemdefaulttimezone = date_default_timezone_get();
1964 date_default_timezone_set('Australia/Perth');
1965
a8397303
FM
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 ),
73d20f36
PS
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!
a8397303
FM
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 );
2002
15396bba
FM
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.
a8397303
FM
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']);
2f1e464a 2009 $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
a8397303 2010 }
15396bba
FM
2011
2012 // Restore system default values.
2013 date_default_timezone_set($systemdefaulttimezone);
2014 setlocale(LC_TIME, $oldlocale);
2015 }
7f30a644
SH
2016
2017 public function test_get_config() {
2018 global $CFG;
2019
2020 $this->resetAfterTest();
2021
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';
2029
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';
2038
2039 // Testing.
be6ce11c
PS
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'));
7f30a644
SH
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'));
2047
2048 // Test config we know to exist.
be6ce11c
PS
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'));
7f30a644
SH
2053
2054 // Test setting a config var that already exists.
2055 set_config('phpunit_test_get_config_1', 'test a');
be6ce11c
PS
2056 $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
2057 $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
7f30a644
SH
2058
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 }
6b219310 2068
be6ce11c 2069 public function test_get_max_upload_sizes() {
6b219310
DW
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);
2076
be6ce11c
PS
2077 $this->assertSame('Activity upload limit (10KB)', $result['0']);
2078 $this->assertCount(2, $result);
6b219310
DW
2079
2080 // Test course limit smallest.
2081 $sitebytes = 102400;
2082 $coursebytes = 10240;
2083 $modulebytes = 51200;
2084 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2085
be6ce11c
PS
2086 $this->assertSame('Course upload limit (10KB)', $result['0']);
2087 $this->assertCount(2, $result);
6b219310
DW
2088
2089 // Test site limit smallest.
2090 $sitebytes = 10240;
2091 $coursebytes = 102400;
2092 $modulebytes = 51200;
2093 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2094
be6ce11c
PS
2095 $this->assertSame('Site upload limit (10KB)', $result['0']);
2096 $this->assertCount(2, $result);
6b219310
DW
2097
2098 // Test site limit not set.
2099 $sitebytes = 0;
2100 $coursebytes = 102400;
2101 $modulebytes = 51200;
2102 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2103
be6ce11c
PS
2104 $this->assertSame('Activity upload limit (50KB)', $result['0']);
2105 $this->assertCount(3, $result);
6b219310
DW
2106
2107 $sitebytes = 0;
2108 $coursebytes = 51200;
2109 $modulebytes = 102400;
2110 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2111
be6ce11c
PS
2112 $this->assertSame('Course upload limit (50KB)', $result['0']);
2113 $this->assertCount(3, $result);
6b219310 2114
6b219310
DW
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);
2121
be6ce11c 2122 $this->assertCount(3, $result);
6b219310
DW
2123
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);
2130
be6ce11c 2131 $this->assertCount(4, $result);
6b219310
DW
2132
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);
2139
be6ce11c 2140 $this->assertCount(3, $result);
6b219310
DW
2141
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);
2148
be6ce11c 2149 $this->assertCount(3, $result);
f869cb23
PS
2150
2151 // Test site limit only.
2152 $sitebytes = 51200;
2153 $result = get_max_upload_sizes($sitebytes);
2154
be6ce11c
PS
2155 $this->assertSame('Site upload limit (50KB)', $result['0']);
2156 $this->assertSame('50KB', $result['51200']);
2157 $this->assertSame('10KB', $result['10240']);
f869cb23
PS
2158 $this->assertCount(3, $result);
2159
2160 // Test no limit.
2161 $result = get_max_upload_sizes();
2162 $this->assertArrayHasKey('0', $result);
2163 $this->assertArrayHasKey(get_max_upload_file_size(), $result);
6b219310 2164 }
1e7db9fe 2165
ec2d8ceb
SC
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 }
2180
2181 /**
2182 * Test function validate_internal_user_password().
2183 */
2184 public function test_validate_internal_user_password() {
25294dd4 2185 // Test bcrypt hashes.
6780a1d3
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 );
ec2d8ceb
SC
2192
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 }
2203
2204 /**
2205 * Test function hash_internal_user_password().
2206 */
2207 public function test_hash_internal_user_password() {
2208 $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2209
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));
2219
25294dd4 2220 // They should not be in md5 format.
6780a1d3
2221 $this->assertFalse(password_is_legacy_hash($hash));
2222
2223 // Check that cost factor in hash is correctly set.
2224 $this->assertRegExp('/\$10\$/', $hash);
2225 $this->assertRegExp('/\$04\$/', $fasthash);
ec2d8ceb
SC
2226 }
2227 }
2228
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.
be6ce11c 2243 $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
ec2d8ceb
SC
2244 }
2245
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));
2249
2250 // Update the password.
2251 update_internal_user_password($user, 'password');
2252
25294dd4 2253 // Password should have been updated to a bcrypt hash.
6780a1d3 2254 $this->assertFalse(password_is_legacy_hash($user->password));
ec2d8ceb 2255 }
a327f25e
AG
2256
2257 public function test_fullname() {
2258 global $CFG;
2259
2260 $this->resetAfterTest();
2261
2262 // Create a user to test the name display on.
2263 $record = array();
2264 $record['firstname'] = 'Scott';
2265 $record['lastname'] = 'Fletcher';
2266 $record['firstnamephonetic'] = 'スコット';
2267 $record['lastnamephonetic'] = 'フレチャー';
2268 $record['alternatename'] = 'No friends';
2269 $user = $this->getDataGenerator()->create_user($record);
2270
be6ce11c 2271 // Back up config settings for restore later.
a327f25e
AG
2272 $originalcfg = new stdClass();
2273 $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
2274
2275 // Testing existing fullnamedisplay settings.
2276 $CFG->fullnamedisplay = 'firstname';
2277 $testname = fullname($user);
be6ce11c 2278 $this->assertSame($user->firstname, $testname);
a327f25e
AG
2279
2280 $CFG->fullnamedisplay = 'firstname lastname';
2281 $expectedname = "$user->firstname $user->lastname";
2282 $testname = fullname($user);
be6ce11c 2283 $this->assertSame($expectedname, $testname);
a327f25e
AG
2284
2285 $CFG->fullnamedisplay = 'lastname firstname';
2286 $expectedname = "$user->lastname $user->firstname";
2287 $testname = fullname($user);
be6ce11c 2288 $this->assertSame($expectedname, $testname);
a327f25e
AG
2289
2290 $expectedname = get_string('fullnamedisplay', null, $user);
2291 $CFG->fullnamedisplay = 'language';
2292 $testname = fullname($user);
be6ce11c 2293 $this->assertSame($expectedname, $testname);
a327f25e
AG
2294
2295 // Test override parameter.
2296 $CFG->fullnamedisplay = 'firstname';
2297 $expectedname = "$user->firstname $user->lastname";
2298 $testname = fullname($user, true);
be6ce11c 2299 $this->assertSame($expectedname, $testname);
a327f25e
AG
2300
2301 // Test additional name fields.
2302 $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
2303 $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
2304 $testname = fullname($user);
be6ce11c 2305 $this->assertSame($expectedname, $testname);
a327f25e
AG
2306
2307 // Test for handling missing data.
2308 $user->middlename = null;
2309 // Parenthesis with no data.
2310 $CFG->fullnamedisplay = 'firstname (middlename) lastname';
2311 $expectedname = "$user->firstname $user->lastname";
2312 $testname = fullname($user);
be6ce11c 2313 $this->assertSame($expectedname, $testname);
a327f25e
AG
2314
2315 // Extra spaces due to no data.
2316 $CFG->fullnamedisplay = 'firstname middlename lastname';
2317 $expectedname = "$user->firstname $user->lastname";
2318 $testname = fullname($user);
be6ce11c 2319 $this->assertSame($expectedname, $testname);
a327f25e
AG
2320
2321 // Regular expression testing.
be6ce11c 2322 // Remove some data from the user fields.
a327f25e
AG
2323 $user->firstnamephonetic = '';
2324 $user->lastnamephonetic = '';
2325
2326 // Removing empty brackets and excess whitespace.
2327 // All of these configurations should resolve to just firstname lastname.
2328 $configarray = array();
2329 $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
2330 $configarray[] = 'firstname lastname \'middlename\'';
2331 $configarray[] = 'firstname "firstnamephonetic" lastname';
2332 $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
2333
2334 foreach ($configarray as $config) {
2335 $CFG->fullnamedisplay = $config;
2336 $expectedname = "$user->firstname $user->lastname";
2337 $testname = fullname($user);
be6ce11c 2338 $this->assertSame($expectedname, $testname);
a327f25e
AG
2339 }
2340
2341 // Check to make sure that other characters are left in place.
2342 $configarray = array();
2343 $configarray['0'] = new stdClass();
2344 $configarray['0']->config = 'lastname firstname, middlename';
2345 $configarray['0']->expectedname = "$user->lastname $user->firstname,";
2346 $configarray['1'] = new stdClass();
2347 $configarray['1']->config = 'lastname firstname + alternatename';
2348 $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
2349 $configarray['2'] = new stdClass();
2350 $configarray['2']->config = 'firstname aka: alternatename';
2351 $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
2352 $configarray['3'] = new stdClass();
2353 $configarray['3']->config = 'firstname (alternatename)';
2354 $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
2355 $configarray['4'] = new stdClass();
2356 $configarray['4']->config = 'firstname [alternatename]';
2357 $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
2358 $configarray['5'] = new stdClass();
2359 $configarray['5']->config = 'firstname "lastname"';
2360 $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
2361
2362 foreach ($configarray as $config) {
2363 $CFG->fullnamedisplay = $config->config;
2364 $expectedname = $config->expectedname;
2365 $testname = fullname($user);
be6ce11c 2366 $this->assertSame($expectedname, $testname);
a327f25e
AG
2367 }
2368
73d363f0
AG
2369 // Test debugging message displays when
2370 // fullnamedisplay setting is "normal".
2371 $CFG->fullnamedisplay = 'firstname lastname';
2372 unset($user);
2373 $user = new stdClass();
2374 $user->firstname = 'Stan';
2375 $user->lastname = 'Lee';
2376 $namedisplay = fullname($user);
2377 $this->assertDebuggingCalled();
2378
be6ce11c 2379 // Tidy up after we finish testing.
a327f25e
AG
2380 $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
2381 }
2382
2383 public function test_get_all_user_name_fields() {
2384 $this->resetAfterTest();
2385
2386 // Additional names in an array.
f490f988
AG
2387 $testarray = array('firstnamephonetic' => 'firstnamephonetic',
2388 'lastnamephonetic' => 'lastnamephonetic',
2389 'middlename' => 'middlename',
2390 'alternatename' => 'alternatename',
2391 'firstname' => 'firstname',
2392 'lastname' => 'lastname');
a327f25e
AG
2393 $this->assertEquals($testarray, get_all_user_name_fields());
2394
2395 // Additional names as a string.
2396 $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
2397 $this->assertEquals($teststring, get_all_user_name_fields(true));
2398
2399 // Additional names as a string with an alias.
2400 $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
2401 $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
f490f988 2402
5b1944bb 2403 // Additional name fields with a prefix - object.
f490f988
AG
2404 $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
2405 'lastnamephonetic' => 'authorlastnamephonetic',
2406 'middlename' => 'authormiddlename',
2407 'alternatename' => 'authoralternatename',
2408 'firstname' => 'authorfirstname',
2409 'lastname' => 'authorlastname');
2410 $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
2411
5b1944bb 2412 // Additional name fields with an alias and a title - string.
f490f988
AG
2413 $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';
2414 $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
a327f25e
AG
2415 }
2416
2417 public function test_order_in_string() {
2418 $this->resetAfterTest();
2419
2420 // Return an array in an order as they are encountered in a string.
2421 $valuearray = array('second', 'firsthalf', 'first');
2422 $formatstring = 'first firsthalf some other text (second)';
2423 $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
2424 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2425
2426 // Try again with a different order for the format.
2427 $valuearray = array('second', 'firsthalf', 'first');
2428 $formatstring = 'firsthalf first second';
2429 $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
2430 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2431
2432 // Try again with yet another different order for the format.
2433 $valuearray = array('second', 'firsthalf', 'first');
2434 $formatstring = 'start seconds away second firstquater first firsthalf';
2435 $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
2436 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2437 }
bb78e249 2438
d79d5ac2 2439 public function test_complete_user_login() {
93b3aaf4 2440 global $USER, $DB;
d79d5ac2
PS
2441
2442 $this->resetAfterTest();
2443 $user = $this->getDataGenerator()->create_user();
2444 $this->setUser(0);
2445
2446 $sink = $this->redirectEvents();
93b3aaf4
PS
2447 $loginuser = clone($user);
2448 $this->setCurrentTimeStart();
2449 @complete_user_login($loginuser); // Hide session header errors.
2450 $this->assertSame($loginuser, $USER);
d79d5ac2
PS
2451 $this->assertEquals($user->id, $USER->id);
2452 $events = $sink->get_events();
2453 $sink->close();
2454
54b1e040
2455 $this->assertCount(1, $events);
2456 $event = reset($events);
d79d5ac2
PS
2457 $this->assertInstanceOf('\core\event\user_loggedin', $event);
2458 $this->assertEquals('user', $event->objecttable);
2459 $this->assertEquals($user->id, $event->objectid);
2460 $this->assertEquals(context_system::instance()->id, $event->contextid);
623a32e5 2461 $this->assertEventContextNotUsed($event);
93b3aaf4
PS
2462
2463 $user = $DB->get_record('user', array('id'=>$user->id));
2464
2465 $this->assertTimeCurrent($user->firstaccess);
2466 $this->assertTimeCurrent($user->lastaccess);
93b3aaf4
PS
2467
2468 $this->assertTimeCurrent($USER->firstaccess);
2469 $this->assertTimeCurrent($USER->lastaccess);
93b3aaf4
PS
2470 $this->assertTimeCurrent($USER->currentlogin);
2471 $this->assertSame(sesskey(), $USER->sesskey);
2472 $this->assertTimeCurrent($USER->preference['_lastloaded']);
2473 $this->assertObjectNotHasAttribute('password', $USER);
2474 $this->assertObjectNotHasAttribute('description', $USER);
d79d5ac2
PS
2475 }
2476
bb78e249
RT
2477 /**
2478 * Test require_logout.
2479 */
2480 public function test_require_logout() {
2481 $this->resetAfterTest();
2482 $user = $this->getDataGenerator()->create_user();
2483 $this->setUser($user);
bb78e249
RT
2484
2485 $this->assertTrue(isloggedin());
2486
2487 // Logout user and capture event.
2488 $sink = $this->redirectEvents();
2489 require_logout();
2490 $events = $sink->get_events();
2491 $sink->close();
2492 $event = array_pop($events);
2493
2494 // Check if user is logged out.
2495 $this->assertFalse(isloggedin());
2496
2497 // Test Event.
2498 $this->assertInstanceOf('\core\event\user_loggedout', $event);
2499 $this->assertSame($user->id, $event->objectid);
2500 $this->assertSame('user_logout', $event->get_legacy_eventname());
2501 $this->assertEventLegacyData($user, $event);
2502 $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
2503 $event->objectid);
2504 $this->assertEventLegacyLogData($expectedlogdata, $event);
623a32e5 2505 $this->assertEventContextNotUsed($event);
bb78e249 2506 }
90930acf
PS
2507
2508 public function test_email_to_user() {
f007e899
PS
2509 global $CFG;
2510
90930acf
PS
2511 $this->resetAfterTest();
2512
2513 $user1 = $this->getDataGenerator()->create_user();
2514 $user2 = $this->getDataGenerator()->create_user();
2515
2516 $subject = 'subject';
2517 $messagetext = 'message text';
2518 $subject2 = 'subject 2';
2519 $messagetext2 = 'message text 2';
2520
f007e899
PS
2521 $this->assertNotEmpty($CFG->noemailever);
2522 email_to_user($user1, $user2, $subject, $messagetext);
2523 $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
2524
90930acf
PS
2525 unset_config('noemailever');
2526
f007e899
PS
2527 email_to_user($user1, $user2, $subject, $messagetext);
2528 $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2529
90930acf
PS
2530 $sink = $this->redirectEmails();
2531 email_to_user($user1, $user2, $subject, $messagetext);
2532 email_to_user($user2, $user1, $subject2, $messagetext2);
2533 $this->assertSame(2, $sink->count());
2534 $result = $sink->get_messages();
2535 $this->assertCount(2, $result);
2536 $sink->close();
2537
2538 $this->assertSame($subject, $result[0]->subject);
2539 $this->assertSame($messagetext, trim($result[0]->body));
2540 $this->assertSame($user1->email, $result[0]->to);
2541 $this->assertSame($user2->email, $result[0]->from);
2542
2543 $this->assertSame($subject2, $result[1]->subject);
2544 $this->assertSame($messagetext2, trim($result[1]->body));
2545 $this->assertSame($user2->email, $result[1]->to);
2546 $this->assertSame($user1->email, $result[1]->from);
f007e899
PS
2547
2548 email_to_user($user1, $user2, $subject, $messagetext);
2549 $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
85614920
MA
2550
2551 // Test $CFG->emailonlyfromnoreplyaddress.
2552 set_config('emailonlyfromnoreplyaddress', 1);
2553 $this->assertNotEmpty($CFG->emailonlyfromnoreplyaddress);
2554 $sink = $this->redirectEmails();
2555 email_to_user($user1, $user2, $subject, $messagetext);
2556 unset_config('emailonlyfromnoreplyaddress');
2557 email_to_user($user1, $user2, $subject, $messagetext);
2558 $result = $sink->get_messages();
2559 $this->assertEquals($CFG->noreplyaddress, $result[0]->from);
2560 $this->assertNotEquals($CFG->noreplyaddress, $result[1]->from);
2561 $sink->close();
90930acf 2562 }
6c679d15
AA
2563
2564 /**
2565 * Test user_updated event trigger by various apis.
2566 */
2567 public function test_user_updated_event() {
2568 global $DB, $CFG;
2569
2570 $this->resetAfterTest();
2571
2572 $user = $this->getDataGenerator()->create_user();
2573
2574 // Set config to allow email_to_user() to be called.
2575 $CFG->noemailever = false;
2576
2577 // Update user password.
2578 $sink = $this->redirectEvents();
2579 $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
2580 setnew_password_and_mail($user);
2581 update_internal_user_password($user, 'randompass');
2582 $events = $sink->get_events();
2583 $sink->close();
2584 $sink2->close();
2585
2586 // Test updated value.
2587 $dbuser = $DB->get_record('user', array('id' => $user->id));
2588 $this->assertSame($user->firstname, $dbuser->firstname);
2589 $this->assertNotSame('M00dLe@T', $dbuser->password);
2590
2591 // Test event.
2592 foreach ($events as $event) {
2593 $this->assertInstanceOf('\core\event\user_updated', $event);
2594 $this->assertSame($user->id, $event->objectid);
2595 $this->assertSame('user_updated', $event->get_legacy_eventname());
2596 $this->assertEventLegacyData($user, $event);
2597 $this->assertEquals(context_user::instance($user->id), $event->get_context());
2598 $expectedlogdata = array(SITEID, 'user', 'update', 'view.php?id='.$user->id, '');
2599 $this->assertEventLegacyLogData($expectedlogdata, $event);
623a32e5 2600 $this->assertEventContextNotUsed($event);
6c679d15
AA
2601 }
2602 }
2603
cc49a6f7
AA
2604 /**
2605 * Test remove_course_content deletes course contents
2606 * TODO Add asserts to verify other data related to course is deleted as well.
2607 */
2608 public function test_remove_course_contents() {
2609
2610 $this->resetAfterTest();
2611
2612 $course = $this->getDataGenerator()->create_course();
2613 $user = $this->getDataGenerator()->create_user();
2614 $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
2615 $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id));
2616
2617 $this->assertNotEquals(false, note_load($note->id));
2618 remove_course_contents($course->id, false);
2619 $this->assertFalse(note_load($note->id));
2620 }
2621
f490f988
AG
2622 /**
2623 * Test function username_load_fields_from_object().
2624 */
2625 public function test_username_load_fields_from_object() {
2626 $this->resetAfterTest();
2627
2628 // This object represents the information returned from an sql query.
2629 $userinfo = new stdClass();
2630 $userinfo->userid = 1;
2631 $userinfo->username = 'loosebruce';
2632 $userinfo->firstname = 'Bruce';
2633 $userinfo->lastname = 'Campbell';
2634 $userinfo->firstnamephonetic = 'ブルース';
2635 $userinfo->lastnamephonetic = 'カンベッル';
2636 $userinfo->middlename = '';
2637 $userinfo->alternatename = '';
2638 $userinfo->email = '';
2639 $userinfo->picture = 23;
5b1944bb 2640 $userinfo->imagealt = 'Michael Jordan draining another basket.';
f490f988
AG
2641 $userinfo->idnumber = 3982;
2642
f490f988
AG
2643 // Just user name fields.
2644 $user = new stdClass();
2645 $user = username_load_fields_from_object($user, $userinfo);
2646 $expectedarray = new stdClass();
2647 $expectedarray->firstname = 'Bruce';
2648 $expectedarray->lastname = 'Campbell';
2649 $expectedarray->firstnamephonetic = 'ブルース';
2650 $expectedarray->lastnamephonetic = 'カンベッル';
2651 $expectedarray->middlename = '';
2652 $expectedarray->alternatename = '';
2653 $this->assertEquals($user, $expectedarray);
2654
2655 // User information for showing a picture.
2656 $user = new stdClass();
e351bed5 2657 $additionalfields = explode(',', user_picture::fields());
f490f988 2658 $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
e351bed5 2659 $user->id = $userinfo->userid;
f490f988
AG
2660 $expectedarray = new stdClass();
2661 $expectedarray->id = 1;
2662 $expectedarray->firstname = 'Bruce';
2663 $expectedarray->lastname = 'Campbell';
2664 $expectedarray->firstnamephonetic = 'ブルース';
2665 $expectedarray->lastnamephonetic = 'カンベッル';
2666 $expectedarray->middlename = '';
2667 $expectedarray->alternatename = '';
2668 $expectedarray->email = '';
2669 $expectedarray->picture = 23;
5b1944bb 2670 $expectedarray->imagealt = 'Michael Jordan draining another basket.';
f490f988
AG
2671 $this->assertEquals($user, $expectedarray);
2672
2673 // Alter the userinfo object to have a prefix.
2674 $userinfo->authorfirstname = 'Bruce';
2675 $userinfo->authorlastname = 'Campbell';
2676 $userinfo->authorfirstnamephonetic = 'ブルース';
2677 $userinfo->authorlastnamephonetic = 'カンベッル';
2678 $userinfo->authormiddlename = '';
e351bed5
AG
2679 $userinfo->authorpicture = 23;
2680 $userinfo->authorimagealt = 'Michael Jordan draining another basket.';
2681 $userinfo->authoremail = 'test@testing.net';
2682
f490f988
AG
2683
2684 // Return an object with user picture information.
2685 $user = new stdClass();
e351bed5 2686 $additionalfields = explode(',', user_picture::fields());
f490f988 2687 $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
e351bed5 2688 $user->id = $userinfo->userid;
f490f988
AG
2689 $expectedarray = new stdClass();
2690 $expectedarray->id = 1;
2691 $expectedarray->firstname = 'Bruce';
2692 $expectedarray->lastname = 'Campbell';
2693 $expectedarray->firstnamephonetic = 'ブルース';
2694 $expectedarray->lastnamephonetic = 'カンベッル';
2695 $expectedarray->middlename = '';
2696 $expectedarray->alternatename = '';
e351bed5 2697 $expectedarray->email = 'test@testing.net';
f490f988 2698 $expectedarray->picture = 23;
5b1944bb 2699 $expectedarray->imagealt = 'Michael Jordan draining another basket.';
f490f988
AG
2700 $this->assertEquals($user, $expectedarray);
2701 }
1da7d44a
TB
2702
2703 /**
2704 * Test function count_words().
2705 */
2706 public function test_count_words() {
2707 $count = count_words("one two three'four");
2708 $this->assertEquals(3, $count);
2709
2710 $count = count_words('one+two three’four');
2711 $this->assertEquals(3, $count);
2712
2713 $count = count_words('one"two three-four');
2714 $this->assertEquals(3, $count);
2715
2716 $count = count_words('one@two three_four');
2717 $this->assertEquals(4, $count);
2718
2719 $count = count_words('one\two three/four');
2720 $this->assertEquals(4, $count);
2721
2722 $count = count_words(' one ... two &nbsp; three...four ');
2723 $this->assertEquals(4, $count);
2724
2725 $count = count_words('one.2 3,four');
2726 $this->assertEquals(4, $count);
2727
2728 $count = count_words('1³ £2 €3.45 $6,789');
2729 $this->assertEquals(4, $count);
2730
2731 $count = count_words('one—two ブルース カンベッル');
2732 $this->assertEquals(4, $count);
2733
2734 $count = count_words('one…two ブルース … カンベッル');
2735 $this->assertEquals(4, $count);
2736 }
a3d5830a 2737}