MDL-56602 themes: Use version number as base themerev
[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);
308ce5b4
MG
205 } catch (Error $error) {
206 // PHP 7.1 throws Error even earlier.
207 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
a3d5830a
PS
208 }
209 try {
210 @optional_param('username');
211 $this->fail('coding_exception expected');
be6ce11c
PS
212 } catch (moodle_exception $ex) {
213 $this->assertInstanceOf('coding_exception', $ex);
308ce5b4
MG
214 } catch (Error $error) {
215 // PHP 7.1 throws Error even earlier.
216 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
a3d5830a
PS
217 }
218 try {
219 optional_param('', 'default_user', PARAM_RAW);
220 $this->fail('coding_exception expected');
be6ce11c
PS
221 } catch (moodle_exception $ex) {
222 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
223 }
224
be6ce11c 225 // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
c8bc6c15 226 $_POST['username'] = array('a'=>'a');
be6ce11c 227 $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
c8bc6c15 228 $this->assertDebuggingCalled();
a3d5830a
PS
229 }
230
be6ce11c 231 public function test_optional_param_array() {
a3d5830a
PS
232 global $CFG;
233
234 $_POST['username'] = array('a'=>'post_user');
235 $_GET['username'] = array('a'=>'get_user');
be6ce11c 236 $this->assertSame($_POST['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
a3d5830a
PS
237
238 unset($_POST['username']);
be6ce11c 239 $this->assertSame($_GET['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
a3d5830a
PS
240
241 unset($_GET['username']);
be6ce11c 242 $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
a3d5830a 243
be6ce11c 244 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
a3d5830a
PS
245 $_POST['username'] = array('a'=>'post_user');
246 try {
247 optional_param_array('username', array('a'=>'default_user'), null);
248 $this->fail('coding_exception expected');
be6ce11c
PS
249 } catch (moodle_exception $ex) {
250 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
251 }
252 try {
253 @optional_param_array('username', array('a'=>'default_user'));
254 $this->fail('coding_exception expected');
be6ce11c
PS
255 } catch (moodle_exception $ex) {
256 $this->assertInstanceOf('coding_exception', $ex);
308ce5b4
MG
257 } catch (Error $error) {
258 // PHP 7.1 throws Error even earlier.
259 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
a3d5830a
PS
260 }
261 try {
262 @optional_param_array('username');
263 $this->fail('coding_exception expected');
be6ce11c
PS
264 } catch (moodle_exception $ex) {
265 $this->assertInstanceOf('coding_exception', $ex);
308ce5b4
MG
266 } catch (Error $error) {
267 // PHP 7.1 throws Error even earlier.
268 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
a3d5830a
PS
269 }
270 try {
271 optional_param_array('', array('a'=>'default_user'), PARAM_RAW);
272 $this->fail('coding_exception expected');
be6ce11c
PS
273 } catch (moodle_exception $ex) {
274 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
275 }
276
be6ce11c 277 // Do not allow nested arrays.
a3d5830a
PS
278 try {
279 $_POST['username'] = array('a'=>array('b'=>'post_user'));
280 optional_param_array('username', array('a'=>'default_user'), PARAM_RAW);
281 $this->fail('coding_exception expected');
282 } catch (coding_exception $ex) {
283 $this->assertTrue(true);
284 }
285
be6ce11c 286 // Do not allow non-arrays.
a3d5830a 287 $_POST['username'] = 'post_user';
be6ce11c 288 $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
c8bc6c15 289 $this->assertDebuggingCalled();
a3d5830a 290
be6ce11c 291 // Make sure array keys are sanitised.
a3d5830a 292 $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
be6ce11c 293 $this->assertSame(array('a1_-'=>'post_user'), optional_param_array('username', array(), PARAM_RAW));
c8bc6c15 294 $this->assertDebuggingCalled();
a3d5830a
PS
295 }
296
be6ce11c 297 public function test_required_param() {
a3d5830a
PS
298 $_POST['username'] = 'post_user';
299 $_GET['username'] = 'get_user';
be6ce11c 300 $this->assertSame('post_user', required_param('username', PARAM_RAW));
a3d5830a
PS
301
302 unset($_POST['username']);
be6ce11c 303 $this->assertSame('get_user', required_param('username', PARAM_RAW));
a3d5830a
PS
304
305 unset($_GET['username']);
306 try {
be6ce11c 307 $this->assertSame('default_user', required_param('username', PARAM_RAW));
a3d5830a
PS
308 $this->fail('moodle_exception expected');
309 } catch (moodle_exception $ex) {
be6ce11c 310 $this->assertInstanceOf('moodle_exception', $ex);
a3d5830a
PS
311 }
312
be6ce11c 313 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
a3d5830a
PS
314 $_POST['username'] = 'post_user';
315 try {
316 @required_param('username');
317 $this->fail('coding_exception expected');
be6ce11c
PS
318 } catch (moodle_exception $ex) {
319 $this->assertInstanceOf('coding_exception', $ex);
308ce5b4
MG
320 } catch (Error $error) {
321 // PHP 7.1 throws Error even earlier.
322 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
a3d5830a
PS
323 }
324 try {
325 required_param('username', '');
326 $this->fail('coding_exception expected');
be6ce11c
PS
327 } catch (moodle_exception $ex) {
328 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
329 }
330 try {
331 required_param('', PARAM_RAW);
332 $this->fail('coding_exception expected');
be6ce11c
PS
333 } catch (moodle_exception $ex) {
334 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
335 }
336
be6ce11c 337 // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
c8bc6c15 338 $_POST['username'] = array('a'=>'a');
be6ce11c 339 $this->assertSame($_POST['username'], required_param('username', PARAM_RAW));
c8bc6c15 340 $this->assertDebuggingCalled();
a3d5830a
PS
341 }
342
be6ce11c 343 public function test_required_param_array() {
a3d5830a
PS
344 global $CFG;
345
346 $_POST['username'] = array('a'=>'post_user');
347 $_GET['username'] = array('a'=>'get_user');
be6ce11c 348 $this->assertSame($_POST['username'], required_param_array('username', PARAM_RAW));
a3d5830a
PS
349
350 unset($_POST['username']);
be6ce11c 351 $this->assertSame($_GET['username'], required_param_array('username', PARAM_RAW));
a3d5830a 352
be6ce11c 353 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
a3d5830a
PS
354 $_POST['username'] = array('a'=>'post_user');
355 try {
356 required_param_array('username', null);
357 $this->fail('coding_exception expected');
be6ce11c
PS
358 } catch (moodle_exception $ex) {
359 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
360 }
361 try {
362 @required_param_array('username');
363 $this->fail('coding_exception expected');
be6ce11c
PS
364 } catch (moodle_exception $ex) {
365 $this->assertInstanceOf('coding_exception', $ex);
308ce5b4
MG
366 } catch (Error $error) {
367 // PHP 7.1 throws Error.
368 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
a3d5830a
PS
369 }
370 try {
371 required_param_array('', PARAM_RAW);
372 $this->fail('coding_exception expected');
be6ce11c
PS
373 } catch (moodle_exception $ex) {
374 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
375 }
376
be6ce11c 377 // Do not allow nested arrays.
a3d5830a
PS
378 try {
379 $_POST['username'] = array('a'=>array('b'=>'post_user'));
380 required_param_array('username', PARAM_RAW);
381 $this->fail('coding_exception expected');
be6ce11c
PS
382 } catch (moodle_exception $ex) {
383 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
384 }
385
be6ce11c 386 // Do not allow non-arrays.
a3d5830a
PS
387 try {
388 $_POST['username'] = 'post_user';
389 required_param_array('username', PARAM_RAW);
390 $this->fail('moodle_exception expected');
391 } catch (moodle_exception $ex) {
be6ce11c 392 $this->assertInstanceOf('moodle_exception', $ex);
a3d5830a
PS
393 }
394
be6ce11c 395 // Make sure array keys are sanitised.
a3d5830a 396 $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
be6ce11c 397 $this->assertSame(array('a1_-'=>'post_user'), required_param_array('username', PARAM_RAW));
c8bc6c15 398 $this->assertDebuggingCalled();
a3d5830a
PS
399 }
400
be6ce11c
PS
401 public function test_clean_param() {
402 // Forbid objects and arrays.
a3d5830a
PS
403 try {
404 clean_param(array('x', 'y'), PARAM_RAW);
405 $this->fail('coding_exception expected');
be6ce11c
PS
406 } catch (moodle_exception $ex) {
407 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
408 }
409 try {
410 $param = new stdClass();
411 $param->id = 1;
412 clean_param($param, PARAM_RAW);
413 $this->fail('coding_exception expected');
be6ce11c
PS
414 } catch (moodle_exception $ex) {
415 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
416 }
417
be6ce11c 418 // Require correct type.
a3d5830a
PS
419 try {
420 clean_param('x', 'xxxxxx');
421 $this->fail('moodle_exception expected');
422 } catch (moodle_exception $ex) {
be6ce11c 423 $this->assertInstanceOf('moodle_exception', $ex);
a3d5830a
PS
424 }
425 try {
426 @clean_param('x');
427 $this->fail('moodle_exception expected');
428 } catch (moodle_exception $ex) {
be6ce11c 429 $this->assertInstanceOf('moodle_exception', $ex);
308ce5b4
MG
430 } catch (Error $error) {
431 // PHP 7.1 throws Error even earlier.
432 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
a3d5830a 433 }
a3d5830a
PS
434 }
435
be6ce11c
PS
436 public function test_clean_param_array() {
437 $this->assertSame(array(), clean_param_array(null, PARAM_RAW));
438 $this->assertSame(array('a', 'b'), clean_param_array(array('a', 'b'), PARAM_RAW));
439 $this->assertSame(array('a', array('b')), clean_param_array(array('a', array('b')), PARAM_RAW, true));
a3d5830a 440
be6ce11c 441 // Require correct type.
a3d5830a
PS
442 try {
443 clean_param_array(array('x'), 'xxxxxx');
444 $this->fail('moodle_exception expected');
445 } catch (moodle_exception $ex) {
be6ce11c 446 $this->assertInstanceOf('moodle_exception', $ex);
a3d5830a
PS
447 }
448 try {
449 @clean_param_array(array('x'));
450 $this->fail('moodle_exception expected');
451 } catch (moodle_exception $ex) {
be6ce11c 452 $this->assertInstanceOf('moodle_exception', $ex);
308ce5b4
MG
453 } catch (Error $error) {
454 // PHP 7.1 throws Error even earlier.
455 $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
a3d5830a
PS
456 }
457
458 try {
459 clean_param_array(array('x', array('y')), PARAM_RAW);
460 $this->fail('coding_exception expected');
be6ce11c
PS
461 } catch (moodle_exception $ex) {
462 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
463 }
464
be6ce11c 465 // Test recursive.
a3d5830a
PS
466 }
467
be6ce11c
PS
468 public function test_clean_param_raw() {
469 $this->assertSame(
470 '#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)',
471 clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_RAW));
a3d5830a
PS
472 }
473
be6ce11c
PS
474 public function test_clean_param_trim() {
475 $this->assertSame('Frog toad', clean_param(" Frog toad \r\n ", PARAM_RAW_TRIMMED));
a3d5830a
PS
476 }
477
be6ce11c
PS
478 public function test_clean_param_clean() {
479 // PARAM_CLEAN is an ugly hack, do not use in new code (skodak),
480 // instead use more specific type, or submit sothing that can be verified properly.
481 $this->assertSame('xx', clean_param('xx<script>', PARAM_CLEAN));
a3d5830a
PS
482 }
483
be6ce11c
PS
484 public function test_clean_param_alpha() {
485 $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHA));
a3d5830a
PS
486 }
487
be6ce11c
PS
488 public function test_clean_param_alphanum() {
489 $this->assertSame('978942897DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHANUM));
a3d5830a
PS
490 }
491
be6ce11c
PS
492 public function test_clean_param_alphaext() {
493 $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHAEXT));
a3d5830a
PS
494 }
495
be6ce11c
PS
496 public function test_clean_param_sequence() {
497 $this->assertSame(',9789,42897', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_SEQUENCE));
a3d5830a
PS
498 }
499
be6ce11c
PS
500 public function test_clean_param_component() {
501 // Please note the cleaning of component names is very strict, no guessing here.
502 $this->assertSame('mod_forum', clean_param('mod_forum', PARAM_COMPONENT));
503 $this->assertSame('block_online_users', clean_param('block_online_users', PARAM_COMPONENT));
504 $this->assertSame('block_blond_online_users', clean_param('block_blond_online_users', PARAM_COMPONENT));
505 $this->assertSame('mod_something2', clean_param('mod_something2', PARAM_COMPONENT));
506 $this->assertSame('forum', clean_param('forum', PARAM_COMPONENT));
507 $this->assertSame('user', clean_param('user', PARAM_COMPONENT));
508 $this->assertSame('rating', clean_param('rating', PARAM_COMPONENT));
a41d1ca0
PS
509 $this->assertSame('feedback360', clean_param('feedback360', PARAM_COMPONENT));
510 $this->assertSame('mod_feedback360', clean_param('mod_feedback360', PARAM_COMPONENT));
be6ce11c
PS
511 $this->assertSame('', clean_param('mod_2something', PARAM_COMPONENT));
512 $this->assertSame('', clean_param('2mod_something', PARAM_COMPONENT));
513 $this->assertSame('', clean_param('mod_something_xx', PARAM_COMPONENT));
514 $this->assertSame('', clean_param('auth_something__xx', PARAM_COMPONENT));
515 $this->assertSame('', clean_param('mod_Something', PARAM_COMPONENT));
516 $this->assertSame('', clean_param('mod_somethíng', PARAM_COMPONENT));
b5486ce8 517 $this->assertSame('', clean_param('mod__something', PARAM_COMPONENT));
be6ce11c
PS
518 $this->assertSame('', clean_param('auth_xx-yy', PARAM_COMPONENT));
519 $this->assertSame('', clean_param('_auth_xx', PARAM_COMPONENT));
520 $this->assertSame('', clean_param('a2uth_xx', PARAM_COMPONENT));
521 $this->assertSame('', clean_param('auth_xx_', PARAM_COMPONENT));
522 $this->assertSame('', clean_param('auth_xx.old', PARAM_COMPONENT));
523 $this->assertSame('', clean_param('_user', PARAM_COMPONENT));
524 $this->assertSame('', clean_param('2rating', PARAM_COMPONENT));
525 $this->assertSame('', clean_param('user_', PARAM_COMPONENT));
a3d5830a
PS
526 }
527
be6ce11c 528 public function test_is_valid_plugin_name() {
5f850735
TH
529 $this->assertTrue(is_valid_plugin_name('forum'));
530 $this->assertTrue(is_valid_plugin_name('forum2'));
a41d1ca0 531 $this->assertTrue(is_valid_plugin_name('feedback360'));
5f850735
TH
532 $this->assertTrue(is_valid_plugin_name('online_users'));
533 $this->assertTrue(is_valid_plugin_name('blond_online_users'));
534 $this->assertFalse(is_valid_plugin_name('online__users'));
535 $this->assertFalse(is_valid_plugin_name('forum '));
536 $this->assertFalse(is_valid_plugin_name('forum.old'));
537 $this->assertFalse(is_valid_plugin_name('xx-yy'));
538 $this->assertFalse(is_valid_plugin_name('2xx'));
539 $this->assertFalse(is_valid_plugin_name('Xx'));
540 $this->assertFalse(is_valid_plugin_name('_xx'));
541 $this->assertFalse(is_valid_plugin_name('xx_'));
542 }
543
be6ce11c
PS
544 public function test_clean_param_plugin() {
545 // Please note the cleaning of plugin names is very strict, no guessing here.
546 $this->assertSame('forum', clean_param('forum', PARAM_PLUGIN));
547 $this->assertSame('forum2', clean_param('forum2', PARAM_PLUGIN));
a41d1ca0 548 $this->assertSame('feedback360', clean_param('feedback360', PARAM_PLUGIN));
be6ce11c
PS
549 $this->assertSame('online_users', clean_param('online_users', PARAM_PLUGIN));
550 $this->assertSame('blond_online_users', clean_param('blond_online_users', PARAM_PLUGIN));
551 $this->assertSame('', clean_param('online__users', PARAM_PLUGIN));
552 $this->assertSame('', clean_param('forum ', PARAM_PLUGIN));
553 $this->assertSame('', clean_param('forum.old', PARAM_PLUGIN));
554 $this->assertSame('', clean_param('xx-yy', PARAM_PLUGIN));
555 $this->assertSame('', clean_param('2xx', PARAM_PLUGIN));
556 $this->assertSame('', clean_param('Xx', PARAM_PLUGIN));
557 $this->assertSame('', clean_param('_xx', PARAM_PLUGIN));
558 $this->assertSame('', clean_param('xx_', PARAM_PLUGIN));
559 }
560
561 public function test_clean_param_area() {
562 // Please note the cleaning of area names is very strict, no guessing here.
563 $this->assertSame('something', clean_param('something', PARAM_AREA));
564 $this->assertSame('something2', clean_param('something2', PARAM_AREA));
565 $this->assertSame('some_thing', clean_param('some_thing', PARAM_AREA));
566 $this->assertSame('some_thing_xx', clean_param('some_thing_xx', PARAM_AREA));
a41d1ca0 567 $this->assertSame('feedback360', clean_param('feedback360', PARAM_AREA));
be6ce11c
PS
568 $this->assertSame('', clean_param('_something', PARAM_AREA));
569 $this->assertSame('', clean_param('something_', PARAM_AREA));
570 $this->assertSame('', clean_param('2something', PARAM_AREA));
571 $this->assertSame('', clean_param('Something', PARAM_AREA));
572 $this->assertSame('', clean_param('some-thing', PARAM_AREA));
573 $this->assertSame('', clean_param('somethííng', PARAM_AREA));
574 $this->assertSame('', clean_param('something.x', PARAM_AREA));
575 }
576
577 public function test_clean_param_text() {
578 $this->assertSame(PARAM_TEXT, PARAM_MULTILANG);
579 // Standard.
580 $this->assertSame('xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>', clean_param('xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>', PARAM_TEXT));
581 $this->assertSame('<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>', clean_param('<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>', PARAM_TEXT));
582 $this->assertSame('xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>', clean_param('xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>', PARAM_TEXT));
583 // Malformed.
584 $this->assertSame('<span lang="en" class="multilang">aa</span>', clean_param('<span lang="en" class="multilang">aa</span>', PARAM_TEXT));
585 $this->assertSame('aa', clean_param('<span lang="en" class="nothing" class="multilang">aa</span>', PARAM_TEXT));
586 $this->assertSame('aa', clean_param('<lang lang="en" class="multilang">aa</lang>', PARAM_TEXT));
587 $this->assertSame('aa', clean_param('<lang lang="en!!">aa</lang>', PARAM_TEXT));
588 $this->assertSame('aa', clean_param('<span lang="en==" class="multilang">aa</span>', PARAM_TEXT));
589 $this->assertSame('abc', clean_param('a<em>b</em>c', PARAM_TEXT));
590 $this->assertSame('a>c>', clean_param('a><xx >c>', PARAM_TEXT)); // Standard strip_tags() behaviour.
591 $this->assertSame('a', clean_param('a<b', PARAM_TEXT));
592 $this->assertSame('a>b', clean_param('a>b', PARAM_TEXT));
593 $this->assertSame('<lang lang="en">a>a</lang>', clean_param('<lang lang="en">a>a</lang>', PARAM_TEXT)); // Standard strip_tags() behaviour.
594 $this->assertSame('a', clean_param('<lang lang="en">a<a</lang>', PARAM_TEXT));
595 $this->assertSame('<lang lang="en">aa</lang>', clean_param('<lang lang="en">a<br>a</lang>', PARAM_TEXT));
596 }
597
598 public function test_clean_param_url() {
599 // Test PARAM_URL and PARAM_LOCALURL a bit.
600 $this->assertSame('http://google.com/', clean_param('http://google.com/', PARAM_URL));
601 $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));
602 $this->assertSame('http://localhost/', clean_param('http://localhost/', PARAM_URL));
603 $this->assertSame('http://0.255.1.1/numericip.php', clean_param('http://0.255.1.1/numericip.php', PARAM_URL));
604 $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_URL));
605 $this->assertSame('', clean_param('funny:thing', PARAM_URL));
606 }
607
608 public function test_clean_param_localurl() {
a3d5830a 609 global $CFG;
0339f2c4
EL
610
611 $this->resetAfterTest();
612
d031c2dc
FM
613 // External, invalid.
614 $this->assertSame('', clean_param('funny:thing', PARAM_LOCALURL));
be6ce11c 615 $this->assertSame('', clean_param('http://google.com/', PARAM_LOCALURL));
d031c2dc 616 $this->assertSame('', clean_param('https://google.com/?test=true', PARAM_LOCALURL));
be6ce11c 617 $this->assertSame('', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL));
d031c2dc
FM
618
619 // Local absolute.
be6ce11c 620 $this->assertSame(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
d031c2dc
FM
621 $this->assertSame($CFG->wwwroot . '/with/something?else=true',
622 clean_param($CFG->wwwroot . '/with/something?else=true', PARAM_LOCALURL));
623
624 // Local relative.
be6ce11c 625 $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_LOCALURL));
be6ce11c 626 $this->assertSame('course/view.php?id=3', clean_param('course/view.php?id=3', PARAM_LOCALURL));
d031c2dc
FM
627
628 // Local absolute HTTPS.
629 $httpsroot = str_replace('http:', 'https:', $CFG->wwwroot);
d031c2dc
FM
630 $CFG->loginhttps = false;
631 $this->assertSame('', clean_param($httpsroot, PARAM_LOCALURL));
632 $this->assertSame('', clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL));
633 $CFG->loginhttps = true;
634 $this->assertSame($httpsroot, clean_param($httpsroot, PARAM_LOCALURL));
635 $this->assertSame($httpsroot . '/with/something?else=true',
636 clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL));
0339f2c4
EL
637
638 // Test open redirects are not possible.
639 $CFG->loginhttps = false;
640 $CFG->wwwroot = 'http://www.example.com';
641 $this->assertSame('', clean_param('http://www.example.com.evil.net/hack.php', PARAM_LOCALURL));
642 $CFG->loginhttps = true;
643 $this->assertSame('', clean_param('https://www.example.com.evil.net/hack.php', PARAM_LOCALURL));
be6ce11c
PS
644 }
645
646 public function test_clean_param_file() {
647 $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_FILE));
648 $this->assertSame('badfile.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE));
649 $this->assertSame('..parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_FILE));
650 $this->assertSame('....grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_FILE));
651 $this->assertSame('..winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_FILE));
652 $this->assertSame('....wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_FILE));
653 $this->assertSame('myfile.a.b.txt', clean_param('myfile.a.b.txt', PARAM_FILE));
654 $this->assertSame('myfile..a..b.txt', clean_param('myfile..a..b.txt', PARAM_FILE));
655 $this->assertSame('myfile.a..b...txt', clean_param('myfile.a..b...txt', PARAM_FILE));
656 $this->assertSame('myfile.a.txt', clean_param('myfile.a.txt', PARAM_FILE));
657 $this->assertSame('myfile...txt', clean_param('myfile...txt', PARAM_FILE));
658 $this->assertSame('...jpg', clean_param('...jpg', PARAM_FILE));
659 $this->assertSame('.a.b.', clean_param('.a.b.', PARAM_FILE));
660 $this->assertSame('', clean_param('.', PARAM_FILE));
661 $this->assertSame('', clean_param('..', PARAM_FILE));
662 $this->assertSame('...', clean_param('...', PARAM_FILE));
663 $this->assertSame('. . . .', clean_param('. . . .', PARAM_FILE));
664 $this->assertSame('dontrtrim.me. .. .. . ', clean_param('dontrtrim.me. .. .. . ', PARAM_FILE));
665 $this->assertSame(' . .dontltrim.me', clean_param(' . .dontltrim.me', PARAM_FILE));
666 $this->assertSame('here is a tab.txt', clean_param("here is a tab\t.txt", PARAM_FILE));
667 $this->assertSame('here is a linebreak.txt', clean_param("here is a line\r\nbreak.txt", PARAM_FILE));
668
669 // The following behaviours have been maintained although they seem a little odd.
670 $this->assertSame('funnything', clean_param('funny:thing', PARAM_FILE));
671 $this->assertSame('.currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_FILE));
672 $this->assertSame('ctempwindowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_FILE));
673 $this->assertSame('homeuserlinuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_FILE));
674 $this->assertSame('~myfile.txt', clean_param('~/myfile.txt', PARAM_FILE));
675 }
676
677 public function test_clean_param_path() {
678 $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_PATH));
679 $this->assertSame('bad/file.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH));
680 $this->assertSame('/parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_PATH));
681 $this->assertSame('/grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_PATH));
682 $this->assertSame('/winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_PATH));
683 $this->assertSame('/wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_PATH));
684 $this->assertSame('funnything', clean_param('funny:thing', PARAM_PATH));
685 $this->assertSame('./here', clean_param('./././here', PARAM_PATH));
686 $this->assertSame('./currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_PATH));
687 $this->assertSame('c/temp/windowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_PATH));
688 $this->assertSame('/home/user/linuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_PATH));
689 $this->assertSame('/home../user ./.linuxfile.txt', clean_param('/home../user ./.linuxfile.txt', PARAM_PATH));
690 $this->assertSame('~/myfile.txt', clean_param('~/myfile.txt', PARAM_PATH));
691 $this->assertSame('~/myfile.txt', clean_param('~/../myfile.txt', PARAM_PATH));
692 $this->assertSame('/..b../.../myfile.txt', clean_param('/..b../.../myfile.txt', PARAM_PATH));
693 $this->assertSame('..b../.../myfile.txt', clean_param('..b../.../myfile.txt', PARAM_PATH));
694 $this->assertSame('/super/slashes/', clean_param('/super//slashes///', PARAM_PATH));
695 }
696
697 public function test_clean_param_username() {
a3d5830a
PS
698 global $CFG;
699 $currentstatus = $CFG->extendedusernamechars;
700
be6ce11c
PS
701 // Run tests with extended character == false;.
702 $CFG->extendedusernamechars = false;
703 $this->assertSame('johndoe123', clean_param('johndoe123', PARAM_USERNAME) );
704 $this->assertSame('john.doe', clean_param('john.doe', PARAM_USERNAME));
705 $this->assertSame('john-doe', clean_param('john-doe', PARAM_USERNAME));
706 $this->assertSame('john-doe', clean_param('john- doe', PARAM_USERNAME));
707 $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
708 $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
709 $this->assertSame('johndoe', clean_param('john~doe', PARAM_USERNAME));
710 $this->assertSame('johndoe', clean_param('john´doe', PARAM_USERNAME));
77218e4a 711 $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john_');
712 $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john_');
be6ce11c
PS
713 $this->assertSame(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
714 $this->assertSame('johnd', clean_param('JOHNdóé ', PARAM_USERNAME));
715 $this->assertSame(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýá\9e?\9eý??\9adoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
716
717 // Test success condition, if extendedusernamechars == ENABLE;.
718 $CFG->extendedusernamechars = true;
719 $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
720 $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
77218e4a 721 $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john# $%&()+_^');
722 $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john# $%&()+_^');
be6ce11c
PS
723 $this->assertSame('john~doe', clean_param('john~doe', PARAM_USERNAME));
724 $this->assertSame('john´doe', clean_param('joHN´doe', PARAM_USERNAME));
725 $this->assertSame('johndoe', clean_param('johnDOE', PARAM_USERNAME));
726 $this->assertSame('johndóé', clean_param('johndóé ', PARAM_USERNAME));
a3d5830a
PS
727
728 $CFG->extendedusernamechars = $currentstatus;
729 }
730
be6ce11c
PS
731 public function test_clean_param_stringid() {
732 // Test string identifiers validation.
733 // Valid strings.
734 $this->assertSame('validstring', clean_param('validstring', PARAM_STRINGID));
735 $this->assertSame('mod/foobar:valid_capability', clean_param('mod/foobar:valid_capability', PARAM_STRINGID));
736 $this->assertSame('CZ', clean_param('CZ', PARAM_STRINGID));
737 $this->assertSame('application/vnd.ms-powerpoint', clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID));
738 $this->assertSame('grade2', clean_param('grade2', PARAM_STRINGID));
739 // Invalid strings.
740 $this->assertSame('', clean_param('trailing ', PARAM_STRINGID));
741 $this->assertSame('', clean_param('space bar', PARAM_STRINGID));
742 $this->assertSame('', clean_param('0numeric', PARAM_STRINGID));
743 $this->assertSame('', clean_param('*', PARAM_STRINGID));
744 $this->assertSame('', clean_param(' ', PARAM_STRINGID));
745 }
746
747 public function test_clean_param_timezone() {
748 // Test timezone validation.
a3d5830a
PS
749 $testvalues = array (
750 'America/Jamaica' => 'America/Jamaica',
751 'America/Argentina/Cordoba' => 'America/Argentina/Cordoba',
752 'America/Port-au-Prince' => 'America/Port-au-Prince',
753 'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
754 'PST8PDT' => 'PST8PDT',
755 'Wrong.Value' => '',
756 'Wrong/.Value' => '',
757 'Wrong(Value)' => '',
758 '0' => '0',
759 '0.0' => '0.0',
760 '0.5' => '0.5',
8158ce79
JM
761 '9.0' => '9.0',
762 '-9.0' => '-9.0',
763 '+9.0' => '+9.0',
764 '9.5' => '9.5',
765 '-9.5' => '-9.5',
766 '+9.5' => '+9.5',
767 '12.0' => '12.0',
768 '-12.0' => '-12.0',
769 '+12.0' => '+12.0',
770 '12.5' => '12.5',
a3d5830a
PS
771 '-12.5' => '-12.5',
772 '+12.5' => '+12.5',
8158ce79
JM
773 '13.0' => '13.0',
774 '-13.0' => '-13.0',
775 '+13.0' => '+13.0',
a3d5830a 776 '13.5' => '',
8158ce79 777 '+13.5' => '',
a3d5830a
PS
778 '-13.5' => '',
779 '0.2' => '');
780
781 foreach ($testvalues as $testvalue => $expectedvalue) {
782 $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
be6ce11c 783 $this->assertEquals($expectedvalue, $actualvalue);
a3d5830a
PS
784 }
785 }
786
be6ce11c 787 public function test_validate_param() {
a3d5830a
PS
788 try {
789 $param = validate_param('11a', PARAM_INT);
790 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
791 } catch (moodle_exception $ex) {
792 $this->assertInstanceOf('invalid_parameter_exception', $ex);
a3d5830a 793 }
be6ce11c
PS
794
795 $param = validate_param('11', PARAM_INT);
796 $this->assertSame(11, $param);
797
a3d5830a
PS
798 try {
799 $param = validate_param(null, PARAM_INT, false);
800 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
801 } catch (moodle_exception $ex) {
802 $this->assertInstanceOf('invalid_parameter_exception', $ex);
a3d5830a 803 }
be6ce11c
PS
804
805 $param = validate_param(null, PARAM_INT, true);
806 $this->assertSame(null, $param);
807
a3d5830a
PS
808 try {
809 $param = validate_param(array(), PARAM_INT);
810 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
811 } catch (moodle_exception $ex) {
812 $this->assertInstanceOf('invalid_parameter_exception', $ex);
a3d5830a
PS
813 }
814 try {
815 $param = validate_param(new stdClass, PARAM_INT);
816 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
817 } catch (moodle_exception $ex) {
818 $this->assertInstanceOf('invalid_parameter_exception', $ex);
9a97fa5a 819 }
be6ce11c
PS
820
821 $param = validate_param('1.0', PARAM_FLOAT);
822 $this->assertSame(1.0, $param);
823
824 // Make sure valid floats do not cause exception.
825 validate_param(1.0, PARAM_FLOAT);
826 validate_param(10, PARAM_FLOAT);
827 validate_param('0', PARAM_FLOAT);
828 validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
829 validate_param('011.1', PARAM_FLOAT);
830 validate_param('11', PARAM_FLOAT);
831 validate_param('+.1', PARAM_FLOAT);
832 validate_param('-.1', PARAM_FLOAT);
833 validate_param('1e10', PARAM_FLOAT);
834 validate_param('.1e+10', PARAM_FLOAT);
835 validate_param('1E-1', PARAM_FLOAT);
836
9a97fa5a
PS
837 try {
838 $param = validate_param('1,2', PARAM_FLOAT);
839 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
840 } catch (moodle_exception $ex) {
841 $this->assertInstanceOf('invalid_parameter_exception', $ex);
9a97fa5a
PS
842 }
843 try {
844 $param = validate_param('', PARAM_FLOAT);
845 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
846 } catch (moodle_exception $ex) {
847 $this->assertInstanceOf('invalid_parameter_exception', $ex);
9a97fa5a
PS
848 }
849 try {
850 $param = validate_param('.', PARAM_FLOAT);
851 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
852 } catch (moodle_exception $ex) {
853 $this->assertInstanceOf('invalid_parameter_exception', $ex);
9a97fa5a
PS
854 }
855 try {
856 $param = validate_param('e10', PARAM_FLOAT);
857 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
858 } catch (moodle_exception $ex) {
859 $this->assertInstanceOf('invalid_parameter_exception', $ex);
9a97fa5a
PS
860 }
861 try {
862 $param = validate_param('abc', PARAM_FLOAT);
863 $this->fail('invalid_parameter_exception expected');
be6ce11c
PS
864 } catch (moodle_exception $ex) {
865 $this->assertInstanceOf('invalid_parameter_exception', $ex);
9a97fa5a 866 }
a3d5830a
PS
867 }
868
be6ce11c 869 public function test_shorten_text_no_tags_already_short_enough() {
4a7cc248 870 // ......12345678901234567890123456.
a3d5830a 871 $text = "short text already no tags";
be6ce11c 872 $this->assertSame($text, shorten_text($text));
4a7cc248 873 }
a3d5830a 874
be6ce11c 875 public function test_shorten_text_with_tags_already_short_enough() {
4a7cc248 876 // .........123456...7890....12345678.......901234567.
a3d5830a 877 $text = "<p>short <b>text</b> already</p><p>with tags</p>";
be6ce11c 878 $this->assertSame($text, shorten_text($text));
4a7cc248 879 }
a3d5830a 880
be6ce11c 881 public function test_shorten_text_no_tags_needs_shortening() {
4a7cc248
TH
882 // Default truncation is after 30 chars, but allowing 3 for the final '...'.
883 // ......12345678901234567890123456789023456789012345678901234.
a3d5830a 884 $text = "long text without any tags blah de blah blah blah what";
be6ce11c 885 $this->assertSame('long text without any tags ...', shorten_text($text));
4a7cc248 886 }
a3d5830a 887
be6ce11c 888 public function test_shorten_text_with_tags_needs_shortening() {
4a7cc248 889 // .......................................123456789012345678901234567890...
a3d5830a
PS
890 $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
891 "be chopped off but <b>should be added back again</b></blockquote></p></div>";
892 $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
893 "tags that ...</blockquote></p></div>", shorten_text($text));
4a7cc248 894 }
a3d5830a 895
4ebdd154 896 public function test_shorten_text_with_tags_and_html_comment() {
897 $text = "<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with ".
898 "tags that will<!--<![endif]--> ".
899 "be chopped off but <b>should be added back again</b></blockquote></p></div>";
900 $this->assertEquals("<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with " .
901 "tags that ...<!--<![endif]--></blockquote></p></div>", shorten_text($text));
902 }
903
be6ce11c 904 public function test_shorten_text_with_entities() {
4a7cc248
TH
905 // Remember to allow 3 chars for the final '...'.
906 // ......123456789012345678901234567_____890...
a3d5830a 907 $text = "some text which shouldn't &nbsp; break there";
be6ce11c
PS
908 $this->assertSame("some text which shouldn't &nbsp; ...", shorten_text($text, 31));
909 $this->assertSame("some text which shouldn't &nbsp;...", shorten_text($text, 30));
910 $this->assertSame("some text which shouldn't ...", shorten_text($text, 29));
4a7cc248 911 }
a3d5830a 912
be6ce11c 913 public function test_shorten_text_known_tricky_case() {
a3d5830a 914 // This case caused a bug up to 1.9.5
4a7cc248 915 // ..........123456789012345678901234567890123456789.....0_____1___2___...
a3d5830a 916 $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
be6ce11c 917 $this->assertSame("<h3>standard 'break-out' sub groups in ...</h3>",
4a7cc248 918 shorten_text($text, 41));
be6ce11c 919 $this->assertSame("<h3>standard 'break-out' sub groups in TGs?...</h3>",
4a7cc248 920 shorten_text($text, 42));
be6ce11c 921 $this->assertSame("<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;...",
a3d5830a 922 shorten_text($text, 43));
4a7cc248 923 }
a3d5830a 924
be6ce11c 925 public function test_shorten_text_no_spaces() {
4a7cc248
TH
926 // ..........123456789.
927 $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
be6ce11c 928 $this->assertSame("<h1>12345...</h1>", shorten_text($text, 8));
4a7cc248 929 }
a3d5830a 930
be6ce11c 931 public function test_shorten_text_utf8_european() {
4a7cc248
TH
932 // Text without tags.
933 // ......123456789012345678901234567.
a3d5830a 934 $text = "Žluťoučký koníček přeskočil";
be6ce11c
PS
935 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
936 $this->assertSame("Žluťoučký koníče...", shorten_text($text, 19, true));
937 $this->assertSame("Žluťoučký ...", shorten_text($text, 19, false));
4a7cc248 938 // And try it with 2-less (that are, in bytes, the middle of a sequence).
be6ce11c
PS
939 $this->assertSame("Žluťoučký koní...", shorten_text($text, 17, true));
940 $this->assertSame("Žluťoučký ...", shorten_text($text, 17, false));
a3d5830a 941
4a7cc248 942 // .........123456789012345678...901234567....89012345.
a3d5830a 943 $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
be6ce11c
PS
944 $this->assertSame($text, shorten_text($text, 60));
945 $this->assertSame("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
946 $this->assertSame("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
947 $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
4a7cc248 948 // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
be6ce11c
PS
949 $this->assertSame("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
950 $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
4a7cc248 951 // And try over one tag (start/end), it does proper text len.
be6ce11c
PS
952 $this->assertSame("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
953 $this->assertSame("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
4a7cc248 954 // And in the middle of one tag.
be6ce11c 955 $this->assertSame("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
4a7cc248 956 }
a3d5830a 957
be6ce11c 958 public function test_shorten_text_utf8_oriental() {
a3d5830a 959 // Japanese
4a7cc248
TH
960 // text without tags
961 // ......123456789012345678901234.
a3d5830a 962 $text = '言語設定言語設定abcdefghijkl';
be6ce11c
PS
963 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
964 $this->assertSame("言語設定言語...", shorten_text($text, 9, true));
965 $this->assertSame("言語設定言語...", shorten_text($text, 9, false));
966 $this->assertSame("言語設定言語設定ab...", shorten_text($text, 13, true));
967 $this->assertSame("言語設定言語設定...", shorten_text($text, 13, false));
a3d5830a
PS
968
969 // Chinese
4a7cc248
TH
970 // text without tags
971 // ......123456789012345678901234.
a3d5830a 972 $text = '简体中文简体中文abcdefghijkl';
be6ce11c
PS
973 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
974 $this->assertSame("简体中文简体...", shorten_text($text, 9, true));
975 $this->assertSame("简体中文简体...", shorten_text($text, 9, false));
976 $this->assertSame("简体中文简体中文ab...", shorten_text($text, 13, true));
977 $this->assertSame("简体中文简体中文...", shorten_text($text, 13, false));
4a7cc248 978 }
a3d5830a 979
be6ce11c 980 public function test_shorten_text_multilang() {
4a7cc248
TH
981 // This is not necessaryily specific to multilang. The issue is really
982 // tags with attributes, where before we were generating invalid HTML
be6ce11c 983 // output like shorten_text('<span id="x" class="y">A</span> B', 1)
4a7cc248
TH
984 // returning '<span id="x" ...</span>'. It is just that multilang
985 // requires the sort of HTML that is quite likely to trigger this.
986 // ........................................1...
987 $text = '<span lang="en" class="multilang">A</span>' .
988 '<span lang="fr" class="multilang">B</span>';
be6ce11c 989 $this->assertSame('<span lang="en" class="multilang">...</span>',
4a7cc248 990 shorten_text($text, 1));
a3d5830a
PS
991 }
992
be6ce11c 993 public function test_usergetdate() {
a3d5830a 994 global $USER, $CFG, $DB;
be6ce11c 995 $this->resetAfterTest();
a3d5830a 996
be6ce11c 997 $this->setAdminUser();
a3d5830a 998
be6ce11c 999 $USER->timezone = 2;// Set the timezone to a known state.
a3d5830a 1000
be6ce11c 1001 $ts = 1261540267; // The time this function was created.
a3d5830a 1002
be6ce11c 1003 $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
a3d5830a
PS
1004 $arr = array_values($arr);
1005
be6ce11c
PS
1006 list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1007 $this->assertSame(7, $seconds);
1008 $this->assertSame(51, $minutes);
1009 $this->assertSame(4, $hours);
1010 $this->assertSame(23, $mday);
1011 $this->assertSame(3, $wday);
1012 $this->assertSame(12, $mon);
1013 $this->assertSame(2009, $year);
1014 $this->assertSame(356, $yday);
1015 $this->assertSame('Wednesday', $weekday);
1016 $this->assertSame('December', $month);
1017 $arr = usergetdate($ts); // Gets the timezone from the $USER object.
a3d5830a
PS
1018 $arr = array_values($arr);
1019
be6ce11c
PS
1020 list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1021 $this->assertSame(7, $seconds);
1022 $this->assertSame(51, $minutes);
1023 $this->assertSame(5, $hours);
1024 $this->assertSame(23, $mday);
1025 $this->assertSame(3, $wday);
1026 $this->assertSame(12, $mon);
1027 $this->assertSame(2009, $year);
1028 $this->assertSame(356, $yday);
1029 $this->assertSame('Wednesday', $weekday);
1030 $this->assertSame('December', $month);
a3d5830a
PS
1031 }
1032
1033 public function test_mark_user_preferences_changed() {
be6ce11c
PS
1034 $this->resetAfterTest();
1035 $otheruser = $this->getDataGenerator()->create_user();
1036 $otheruserid = $otheruser->id;
a3d5830a 1037
be6ce11c 1038 set_cache_flag('userpreferenceschanged', $otheruserid, null);
a3d5830a
PS
1039 mark_user_preferences_changed($otheruserid);
1040
1041 $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
be6ce11c 1042 set_cache_flag('userpreferenceschanged', $otheruserid, null);
a3d5830a
PS
1043 }
1044
1045 public function test_check_user_preferences_loaded() {
1046 global $DB;
be6ce11c 1047 $this->resetAfterTest();
a3d5830a 1048
be6ce11c
PS
1049 $otheruser = $this->getDataGenerator()->create_user();
1050 $otheruserid = $otheruser->id;
a3d5830a
PS
1051
1052 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
be6ce11c 1053 set_cache_flag('userpreferenceschanged', $otheruserid, null);
a3d5830a
PS
1054
1055 $user = new stdClass();
1056 $user->id = $otheruserid;
1057
be6ce11c 1058 // Load.
a3d5830a
PS
1059 check_user_preferences_loaded($user);
1060 $this->assertTrue(isset($user->preference));
1061 $this->assertTrue(is_array($user->preference));
be6ce11c
PS
1062 $this->assertArrayHasKey('_lastloaded', $user->preference);
1063 $this->assertCount(1, $user->preference);
a3d5830a 1064
be6ce11c 1065 // Add preference via direct call.
a3d5830a
PS
1066 $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1067
be6ce11c 1068 // No cache reload yet.
a3d5830a 1069 check_user_preferences_loaded($user);
be6ce11c 1070 $this->assertCount(1, $user->preference);
a3d5830a 1071
be6ce11c 1072 // Forced reloading of cache.
a3d5830a
PS
1073 unset($user->preference);
1074 check_user_preferences_loaded($user);
be6ce11c
PS
1075 $this->assertCount(2, $user->preference);
1076 $this->assertSame('yyy', $user->preference['xxx']);
a3d5830a 1077
be6ce11c 1078 // Add preference via direct call.
a3d5830a
PS
1079 $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1080
be6ce11c 1081 // Test timeouts and modifications from different session.
a3d5830a
PS
1082 set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1083 $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1084 check_user_preferences_loaded($user);
be6ce11c 1085 $this->assertCount(2, $user->preference);
a3d5830a 1086 check_user_preferences_loaded($user, 10);
be6ce11c
PS
1087 $this->assertCount(3, $user->preference);
1088 $this->assertSame('bbb', $user->preference['aaa']);
a3d5830a
PS
1089 set_cache_flag('userpreferenceschanged', $user->id, null);
1090 }
1091
1092 public function test_set_user_preference() {
1093 global $DB, $USER;
be6ce11c 1094 $this->resetAfterTest();
a3d5830a 1095
be6ce11c 1096 $this->setAdminUser();
a3d5830a 1097
be6ce11c
PS
1098 $otheruser = $this->getDataGenerator()->create_user();
1099 $otheruserid = $otheruser->id;
a3d5830a
PS
1100
1101 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1102 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1103
1104 $user = new stdClass();
1105 $user->id = $otheruserid;
1106
1107 set_user_preference('aaa', 'bbb', $otheruserid);
be6ce11c
PS
1108 $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1109 $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
a3d5830a
PS
1110
1111 set_user_preference('xxx', 'yyy', $user);
be6ce11c
PS
1112 $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1113 $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
a3d5830a 1114 $this->assertTrue(is_array($user->preference));
be6ce11c
PS
1115 $this->assertSame('bbb', $user->preference['aaa']);
1116 $this->assertSame('yyy', $user->preference['xxx']);
a3d5830a 1117
be6ce11c
PS
1118 set_user_preference('xxx', null, $user);
1119 $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1120 $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
a3d5830a
PS
1121
1122 set_user_preference('ooo', true, $user);
1123 $prefs = get_user_preferences(null, null, $otheruserid);
be6ce11c
PS
1124 $this->assertSame($user->preference['aaa'], $prefs['aaa']);
1125 $this->assertSame($user->preference['ooo'], $prefs['ooo']);
1126 $this->assertSame('1', $prefs['ooo']);
a3d5830a
PS
1127
1128 set_user_preference('null', 0, $user);
1129 $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1130
1131 $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1132
1133 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1134 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1135
be6ce11c 1136 // Test $USER default.
a3d5830a
PS
1137 set_user_preference('_test_user_preferences_pref', 'ok');
1138 $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1139 unset_user_preference('_test_user_preferences_pref');
1140 $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1141
be6ce11c 1142 // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
a3d5830a
PS
1143 $longvalue = str_repeat('a', 1333);
1144 set_user_preference('_test_long_user_preference', $longvalue);
1145 $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1146 $this->assertEquals($longvalue,
1147 $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1148
be6ce11c 1149 // Test > 1333 char values, coding_exception expected.
a3d5830a
PS
1150 $longvalue = str_repeat('a', 1334);
1151 try {
1152 set_user_preference('_test_long_user_preference', $longvalue);
17222a4a 1153 $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
be6ce11c
PS
1154 } catch (moodle_exception $ex) {
1155 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
1156 }
1157
be6ce11c 1158 // Test invalid params.
a3d5830a
PS
1159 try {
1160 set_user_preference('_test_user_preferences_pref', array());
17222a4a 1161 $this->fail('Exception expected - array not valid preference value');
be6ce11c
PS
1162 } catch (moodle_exception $ex) {
1163 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
1164 }
1165 try {
1166 set_user_preference('_test_user_preferences_pref', new stdClass);
17222a4a 1167 $this->fail('Exception expected - class not valid preference value');
be6ce11c
PS
1168 } catch (moodle_exception $ex) {
1169 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
1170 }
1171 try {
17222a4a
MN
1172 set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1173 $this->fail('Exception expected - user instance expected');
be6ce11c
PS
1174 } catch (moodle_exception $ex) {
1175 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
1176 }
1177 try {
1178 set_user_preference('_test_user_preferences_pref', 1, 'abc');
17222a4a 1179 $this->fail('Exception expected - user instance expected');
be6ce11c
PS
1180 } catch (moodle_exception $ex) {
1181 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
1182 }
1183 try {
1184 set_user_preference('', 1);
17222a4a 1185 $this->fail('Exception expected - invalid name accepted');
be6ce11c
PS
1186 } catch (moodle_exception $ex) {
1187 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a
PS
1188 }
1189 try {
1190 set_user_preference('1', 1);
17222a4a 1191 $this->fail('Exception expected - invalid name accepted');
be6ce11c
PS
1192 } catch (moodle_exception $ex) {
1193 $this->assertInstanceOf('coding_exception', $ex);
a3d5830a 1194 }
a3d5830a
PS
1195 }
1196
1197 public function test_get_extra_user_fields() {
1198 global $CFG, $USER, $DB;
be6ce11c 1199 $this->resetAfterTest();
a3d5830a 1200
be6ce11c 1201 $this->setAdminUser();
a3d5830a
PS
1202
1203 // It would be really nice if there were a way to 'mock' has_capability
1204 // checks (either to return true or false) but as there is not, this
1205 // test doesn't test the capability check. Presumably, anyone running
1206 // unit tests will have the capability.
1207 $context = context_system::instance();
1208
be6ce11c 1209 // No fields.
a3d5830a
PS
1210 $CFG->showuseridentity = '';
1211 $this->assertEquals(array(), get_extra_user_fields($context));
1212
be6ce11c 1213 // One field.
a3d5830a
PS
1214 $CFG->showuseridentity = 'frog';
1215 $this->assertEquals(array('frog'), get_extra_user_fields($context));
1216
be6ce11c 1217 // Two fields.
a3d5830a
PS
1218 $CFG->showuseridentity = 'frog,zombie';
1219 $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1220
be6ce11c 1221 // No fields, except.
a3d5830a
PS
1222 $CFG->showuseridentity = '';
1223 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1224
be6ce11c 1225 // One field.
a3d5830a
PS
1226 $CFG->showuseridentity = 'frog';
1227 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1228
be6ce11c 1229 // Two fields.
a3d5830a
PS
1230 $CFG->showuseridentity = 'frog,zombie';
1231 $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
a3d5830a
PS
1232 }
1233
1234 public function test_get_extra_user_fields_sql() {
1235 global $CFG, $USER, $DB;
be6ce11c 1236 $this->resetAfterTest();
a3d5830a 1237
be6ce11c 1238 $this->setAdminUser();
a3d5830a 1239
a3d5830a
PS
1240 $context = context_system::instance();
1241
be6ce11c 1242 // No fields.
a3d5830a 1243 $CFG->showuseridentity = '';
be6ce11c 1244 $this->assertSame('', get_extra_user_fields_sql($context));
a3d5830a 1245
be6ce11c 1246 // One field.
a3d5830a 1247 $CFG->showuseridentity = 'frog';
be6ce11c 1248 $this->assertSame(', frog', get_extra_user_fields_sql($context));
a3d5830a 1249
be6ce11c 1250 // Two fields with table prefix.
a3d5830a 1251 $CFG->showuseridentity = 'frog,zombie';
be6ce11c 1252 $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
a3d5830a 1253
be6ce11c 1254 // Two fields with field prefix.
a3d5830a 1255 $CFG->showuseridentity = 'frog,zombie';
be6ce11c 1256 $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
a3d5830a
PS
1257 get_extra_user_fields_sql($context, '', 'u_'));
1258
be6ce11c 1259 // One field excluded.
a3d5830a 1260 $CFG->showuseridentity = 'frog';
be6ce11c 1261 $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
a3d5830a 1262
be6ce11c 1263 // Two fields, one excluded, table+field prefix.
a3d5830a
PS
1264 $CFG->showuseridentity = 'frog,zombie';
1265 $this->assertEquals(', u1.zombie AS u_zombie',
1266 get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
a3d5830a
PS
1267 }
1268
d506f422
EL
1269 /**
1270 * Test some critical TZ/DST.
1271 *
1272 * This method tests some special TZ/DST combinations that were fixed
1273 * by MDL-38999. The tests are done by comparing the results of the
1274 * output using Moodle TZ/DST support and PHP native one.
1275 *
1276 * Note: If you don't trust PHP TZ/DST support, can verify the
1277 * harcoded expectations below with:
1278 * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
1279 */
1280 public function test_some_moodle_special_dst() {
1281 $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
1282
1283 // In Europe/Tallinn it was 2013/04/08 05:00:00.
1284 $expectation = '2013/04/08 05:00:00';
1285 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1286 $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1287 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1288 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1289 $this->assertSame($expectation, $phpres);
1290 $this->assertSame($expectation, $moodleres);
1291
1292 // In St. Johns it was 2013/04/07 23:30:00.
1293 $expectation = '2013/04/07 23:30:00';
1294 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1295 $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1296 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1297 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1298 $this->assertSame($expectation, $phpres);
1299 $this->assertSame($expectation, $moodleres);
1300
1301 $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1302
1303 // In Europe/Tallinn it was 2013/11/08 04:00:00.
1304 $expectation = '2013/11/08 04:00:00';
1305 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1306 $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1307 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1308 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1309 $this->assertSame($expectation, $phpres);
1310 $this->assertSame($expectation, $moodleres);
1311
1312 // In St. Johns it was 2013/11/07 22:30:00.
1313 $expectation = '2013/11/07 22:30:00';
1314 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1315 $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1316 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1317 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1318 $this->assertSame($expectation, $phpres);
1319 $this->assertSame($expectation, $moodleres);
1320 }
1321
a3d5830a
PS
1322 public function test_userdate() {
1323 global $USER, $CFG, $DB;
be6ce11c 1324 $this->resetAfterTest();
a3d5830a 1325
be6ce11c 1326 $this->setAdminUser();
a3d5830a
PS
1327
1328 $testvalues = array(
1329 array(
1330 'time' => '1309514400',
1331 'usertimezone' => 'America/Moncton',
be6ce11c 1332 'timezone' => '0.0', // No dst offset.
a3d5830a
PS
1333 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1334 ),
1335 array(
1336 'time' => '1309514400',
1337 'usertimezone' => 'America/Moncton',
be6ce11c 1338 'timezone' => '99', // Dst offset and timezone offset.
a3d5830a
PS
1339 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1340 ),
1341 array(
1342 'time' => '1309514400',
1343 'usertimezone' => 'America/Moncton',
be6ce11c 1344 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
a3d5830a
PS
1345 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1346 ),
1347 array(
1348 'time' => '1293876000 ',
1349 'usertimezone' => 'America/Moncton',
be6ce11c 1350 'timezone' => '0.0', // No dst offset.
a3d5830a
PS
1351 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1352 ),
1353 array(
1354 'time' => '1293876000 ',
1355 'usertimezone' => 'America/Moncton',
be6ce11c 1356 'timezone' => '99', // No dst offset in jan, so just timezone offset.
a3d5830a
PS
1357 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1358 ),
1359 array(
1360 'time' => '1293876000 ',
1361 'usertimezone' => 'America/Moncton',
be6ce11c 1362 'timezone' => 'America/Moncton', // No dst offset in jan.
a3d5830a
PS
1363 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1364 ),
1365 array(
1366 'time' => '1293876000 ',
1367 'usertimezone' => '2',
be6ce11c 1368 'timezone' => '99', // Take user timezone.
a3d5830a
PS
1369 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1370 ),
1371 array(
1372 'time' => '1293876000 ',
1373 'usertimezone' => '-2',
be6ce11c 1374 'timezone' => '99', // Take user timezone.
a3d5830a
PS
1375 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1376 ),
1377 array(
1378 'time' => '1293876000 ',
1379 'usertimezone' => '-10',
be6ce11c 1380 'timezone' => '2', // Take this timezone.
a3d5830a
PS
1381 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1382 ),
1383 array(
1384 'time' => '1293876000 ',
1385 'usertimezone' => '-10',
be6ce11c 1386 'timezone' => '-2', // Take this timezone.
a3d5830a
PS
1387 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1388 ),
1389 array(
1390 'time' => '1293876000 ',
1391 'usertimezone' => '-10',
be6ce11c 1392 'timezone' => 'random/time', // This should show server time.
a3d5830a
PS
1393 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1394 ),
1395 array(
1396 'time' => '1293876000 ',
d6e7a63d 1397 'usertimezone' => '20', // Fallback to server time zone.
be6ce11c 1398 'timezone' => '99', // This should show user time.
a3d5830a
PS
1399 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1400 ),
1401 );
1402
be6ce11c 1403 // Set default timezone to Australia/Perth, else time calculated
d6e7a63d
PS
1404 // will not match expected values.
1405 $this->setTimezone(99, 'Australia/Perth');
a3d5830a
PS
1406
1407 foreach ($testvalues as $vals) {
1408 $USER->timezone = $vals['usertimezone'];
1409 $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1410
be6ce11c 1411 // On different systems case of AM PM changes so compare case insensitive.
2f1e464a
PS
1412 $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1413 $actualoutput = core_text::strtolower($actualoutput);
a3d5830a 1414
be6ce11c 1415 $this->assertSame($vals['expectedoutput'], $actualoutput,
d6e7a63d 1416 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput} \ndata: " . var_export($vals, true));
a3d5830a 1417 }
a3d5830a
PS
1418 }
1419
980a3a12
PS
1420 /**
1421 * Make sure the DST changes happen at the right time in Moodle.
1422 */
1423 public function test_dst_changes() {
1424 // DST switching in Prague.
1425 // From 2AM to 3AM in 1989.
1426 $date = new DateTime('1989-03-26T01:59:00+01:00');
b6e98dc8 1427 $this->assertSame('Sunday, 26 March 1989, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
980a3a12 1428 $date = new DateTime('1989-03-26T02:01:00+01:00');
b6e98dc8 1429 $this->assertSame('Sunday, 26 March 1989, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
980a3a12
PS
1430 // From 3AM to 2AM in 1989 - not the same as the west Europe.
1431 $date = new DateTime('1989-09-24T01:59:00+01:00');
b6e98dc8 1432 $this->assertSame('Sunday, 24 September 1989, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
980a3a12 1433 $date = new DateTime('1989-09-24T02:01:00+01:00');
b6e98dc8 1434 $this->assertSame('Sunday, 24 September 1989, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
980a3a12
PS
1435 // From 2AM to 3AM in 2014.
1436 $date = new DateTime('2014-03-30T01:59:00+01:00');
b6e98dc8 1437 $this->assertSame('Sunday, 30 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
980a3a12 1438 $date = new DateTime('2014-03-30T02:01:00+01:00');
b6e98dc8 1439 $this->assertSame('Sunday, 30 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
980a3a12
PS
1440 // From 3AM to 2AM in 2014.
1441 $date = new DateTime('2014-10-26T01:59:00+01:00');
b6e98dc8 1442 $this->assertSame('Sunday, 26 October 2014, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
980a3a12 1443 $date = new DateTime('2014-10-26T02:01:00+01:00');
b6e98dc8 1444 $this->assertSame('Sunday, 26 October 2014, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
980a3a12
PS
1445 // From 2AM to 3AM in 2020.
1446 $date = new DateTime('2020-03-29T01:59:00+01:00');
b6e98dc8 1447 $this->assertSame('Sunday, 29 March 2020, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
980a3a12 1448 $date = new DateTime('2020-03-29T02:01:00+01:00');
b6e98dc8 1449 $this->assertSame('Sunday, 29 March 2020, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
980a3a12
PS
1450 // From 3AM to 2AM in 2020.
1451 $date = new DateTime('2020-10-25T01:59:00+01:00');
b6e98dc8 1452 $this->assertSame('Sunday, 25 October 2020, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
980a3a12 1453 $date = new DateTime('2020-10-25T02:01:00+01:00');
b6e98dc8 1454 $this->assertSame('Sunday, 25 October 2020, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
980a3a12
PS
1455
1456 // DST switching in NZ.
1457 // From 3AM to 2AM in 2015.
1458 $date = new DateTime('2015-04-05T02:59:00+13:00');
b6e98dc8 1459 $this->assertSame('Sunday, 5 April 2015, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
980a3a12 1460 $date = new DateTime('2015-04-05T03:01:00+13:00');
b6e98dc8 1461 $this->assertSame('Sunday, 5 April 2015, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
980a3a12
PS
1462 // From 2AM to 3AM in 2009.
1463 $date = new DateTime('2015-09-27T01:59:00+12:00');
b6e98dc8 1464 $this->assertSame('Sunday, 27 September 2015, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
980a3a12 1465 $date = new DateTime('2015-09-27T02:01:00+12:00');
b6e98dc8 1466 $this->assertSame('Sunday, 27 September 2015, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
980a3a12
PS
1467
1468 // DST switching in Perth.
1469 // From 3AM to 2AM in 2009.
1470 $date = new DateTime('2008-03-30T01:59:00+08:00');
b6e98dc8 1471 $this->assertSame('Sunday, 30 March 2008, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
980a3a12 1472 $date = new DateTime('2008-03-30T02:01:00+08:00');
b6e98dc8 1473 $this->assertSame('Sunday, 30 March 2008, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
980a3a12
PS
1474 // From 2AM to 3AM in 2009.
1475 $date = new DateTime('2008-10-26T01:59:00+08:00');
b6e98dc8 1476 $this->assertSame('Sunday, 26 October 2008, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
980a3a12 1477 $date = new DateTime('2008-10-26T02:01:00+08:00');
b6e98dc8 1478 $this->assertSame('Sunday, 26 October 2008, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
980a3a12
PS
1479
1480 // DST switching in US.
1481 // From 2AM to 3AM in 2014.
1482 $date = new DateTime('2014-03-09T01:59:00-05:00');
b6e98dc8 1483 $this->assertSame('Sunday, 9 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
980a3a12 1484 $date = new DateTime('2014-03-09T02:01:00-05:00');
b6e98dc8 1485 $this->assertSame('Sunday, 9 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
980a3a12
PS
1486 // From 3AM to 2AM in 2014.
1487 $date = new DateTime('2014-11-02T01:59:00-04:00');
b6e98dc8 1488 $this->assertSame('Sunday, 2 November 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
980a3a12 1489 $date = new DateTime('2014-11-02T02:01:00-04:00');
b6e98dc8 1490 $this->assertSame('Sunday, 2 November 2014, 01:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
980a3a12
PS
1491 }
1492
a3d5830a
PS
1493 public function test_make_timestamp() {
1494 global $USER, $CFG, $DB;
be6ce11c 1495 $this->resetAfterTest();
a3d5830a 1496
be6ce11c 1497 $this->setAdminUser();
a3d5830a
PS
1498
1499 $testvalues = array(
1500 array(
1501 'usertimezone' => 'America/Moncton',
1502 'year' => '2011',
1503 'month' => '7',
1504 'day' => '1',
1505 'hour' => '10',
1506 'minutes' => '00',
1507 'seconds' => '00',
7b05e146 1508 'timezone' => '0.0',
be6ce11c
PS
1509 'applydst' => false, // No dst offset.
1510 'expectedoutput' => '1309514400' // 6pm at UTC+0.
a3d5830a
PS
1511 ),
1512 array(
1513 'usertimezone' => 'America/Moncton',
1514 'year' => '2011',
1515 'month' => '7',
1516 'day' => '1',
1517 'hour' => '10',
1518 'minutes' => '00',
1519 'seconds' => '00',
be6ce11c
PS
1520 'timezone' => '99', // User default timezone.
1521 'applydst' => false, // Don't apply dst.
a3d5830a
PS
1522 'expectedoutput' => '1309528800'
1523 ),
1524 array(
1525 'usertimezone' => 'America/Moncton',
1526 'year' => '2011',
1527 'month' => '7',
1528 'day' => '1',
1529 'hour' => '10',
1530 'minutes' => '00',
1531 'seconds' => '00',
be6ce11c
PS
1532 'timezone' => '99', // User default timezone.
1533 'applydst' => true, // Apply dst.
a3d5830a
PS
1534 'expectedoutput' => '1309525200'
1535 ),
1536 array(
1537 'usertimezone' => 'America/Moncton',
1538 'year' => '2011',
1539 'month' => '7',
1540 'day' => '1',
1541 'hour' => '10',
1542 'minutes' => '00',
1543 'seconds' => '00',
be6ce11c
PS
1544 'timezone' => 'America/Moncton', // String timezone.
1545 'applydst' => true, // Apply dst.
a3d5830a
PS
1546 'expectedoutput' => '1309525200'
1547 ),
1548 array(
be6ce11c 1549 'usertimezone' => '2', // No dst applyed.
a3d5830a
PS
1550 'year' => '2011',
1551 'month' => '7',
1552 'day' => '1',
1553 'hour' => '10',
1554 'minutes' => '00',
1555 'seconds' => '00',
be6ce11c
PS
1556 'timezone' => '99', // Take user timezone.
1557 'applydst' => true, // Apply dst.
a3d5830a
PS
1558 'expectedoutput' => '1309507200'
1559 ),
1560 array(
be6ce11c 1561 'usertimezone' => '-2', // No dst applyed.
a3d5830a
PS
1562 'year' => '2011',
1563 'month' => '7',
1564 'day' => '1',
1565 'hour' => '10',
1566 'minutes' => '00',
1567 'seconds' => '00',
be6ce11c
PS
1568 'timezone' => '99', // Take usertimezone.
1569 'applydst' => true, // Apply dst.
a3d5830a
PS
1570 'expectedoutput' => '1309521600'
1571 ),
1572 array(
be6ce11c 1573 'usertimezone' => '-10', // No dst applyed.
a3d5830a
PS
1574 'year' => '2011',
1575 'month' => '7',
1576 'day' => '1',
1577 'hour' => '10',
1578 'minutes' => '00',
1579 'seconds' => '00',
be6ce11c
PS
1580 'timezone' => '2', // Take this timezone.
1581 'applydst' => true, // Apply dst.
a3d5830a
PS
1582 'expectedoutput' => '1309507200'
1583 ),
1584 array(
be6ce11c 1585 'usertimezone' => '-10', // No dst applyed.
a3d5830a
PS
1586 'year' => '2011',
1587 'month' => '7',
1588 'day' => '1',
1589 'hour' => '10',
1590 'minutes' => '00',
1591 'seconds' => '00',
be6ce11c
PS
1592 'timezone' => '-2', // Take this timezone.
1593 'applydst' => true, // Apply dst.
a3d5830a
PS
1594 'expectedoutput' => '1309521600'
1595 ),
1596 array(
be6ce11c 1597 'usertimezone' => '-10', // No dst applyed.
a3d5830a
PS
1598 'year' => '2011',
1599 'month' => '7',
1600 'day' => '1',
1601 'hour' => '10',
1602 'minutes' => '00',
1603 'seconds' => '00',
be6ce11c
PS
1604 'timezone' => 'random/time', // This should show server time.
1605 'applydst' => true, // Apply dst.
a3d5830a
PS
1606 'expectedoutput' => '1309485600'
1607 ),
1608 array(
88474db2 1609 'usertimezone' => '-14', // Server time.
a3d5830a
PS
1610 'year' => '2011',
1611 'month' => '7',
1612 'day' => '1',
1613 'hour' => '10',
1614 'minutes' => '00',
1615 'seconds' => '00',
be6ce11c
PS
1616 'timezone' => '99', // Get user time.
1617 'applydst' => true, // Apply dst.
a3d5830a
PS
1618 'expectedoutput' => '1309485600'
1619 )
1620 );
1621
be6ce11c 1622 // Set default timezone to Australia/Perth, else time calculated
d6e7a63d
PS
1623 // will not match expected values.
1624 $this->setTimezone(99, 'Australia/Perth');
a3d5830a 1625
be6ce11c 1626 // Test make_timestamp with all testvals and assert if anything wrong.
a3d5830a
PS
1627 foreach ($testvalues as $vals) {
1628 $USER->timezone = $vals['usertimezone'];
1629 $actualoutput = make_timestamp(
1630 $vals['year'],
1631 $vals['month'],
1632 $vals['day'],
1633 $vals['hour'],
1634 $vals['minutes'],
1635 $vals['seconds'],
1636 $vals['timezone'],
1637 $vals['applydst']
1638 );
1639
be6ce11c 1640 // On different systems case of AM PM changes so compare case insensitive.
2f1e464a
PS
1641 $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1642 $actualoutput = core_text::strtolower($actualoutput);
a3d5830a 1643
be6ce11c 1644 $this->assertSame($vals['expectedoutput'], $actualoutput,
a3d5830a
PS
1645 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1646 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1647 }
a3d5830a
PS
1648 }
1649
1650 /**
1651 * Test get_string and most importantly the implementation of the lang_string
1652 * object.
1653 */
1654 public function test_get_string() {
1655 global $COURSE;
1656
be6ce11c 1657 // Make sure we are using English.
a3d5830a
PS
1658 $originallang = $COURSE->lang;
1659 $COURSE->lang = 'en';
1660
1661 $yes = get_string('yes');
1662 $yesexpected = 'Yes';
aed2b9ba 1663 $this->assertInternalType('string', $yes);
be6ce11c 1664 $this->assertSame($yesexpected, $yes);
a3d5830a
PS
1665
1666 $yes = get_string('yes', 'moodle');
aed2b9ba 1667 $this->assertInternalType('string', $yes);
be6ce11c 1668 $this->assertSame($yesexpected, $yes);
a3d5830a
PS
1669
1670 $yes = get_string('yes', 'core');
aed2b9ba 1671 $this->assertInternalType('string', $yes);
be6ce11c 1672 $this->assertSame($yesexpected, $yes);
a3d5830a
PS
1673
1674 $yes = get_string('yes', '');
aed2b9ba 1675 $this->assertInternalType('string', $yes);
be6ce11c 1676 $this->assertSame($yesexpected, $yes);
a3d5830a
PS
1677
1678 $yes = get_string('yes', null);
aed2b9ba 1679 $this->assertInternalType('string', $yes);
be6ce11c 1680 $this->assertSame($yesexpected, $yes);
a3d5830a
PS
1681
1682 $yes = get_string('yes', null, 1);
aed2b9ba 1683 $this->assertInternalType('string', $yes);
be6ce11c 1684 $this->assertSame($yesexpected, $yes);
a3d5830a
PS
1685
1686 $days = 1;
1687 $numdays = get_string('numdays', 'core', '1');
1688 $numdaysexpected = $days.' days';
aed2b9ba 1689 $this->assertInternalType('string', $numdays);
be6ce11c 1690 $this->assertSame($numdaysexpected, $numdays);
a3d5830a
PS
1691
1692 $yes = get_string('yes', null, null, true);
aed2b9ba 1693 $this->assertInstanceOf('lang_string', $yes);
be6ce11c 1694 $this->assertSame($yesexpected, (string)$yes);
a3d5830a
PS
1695
1696 // Test using a lang_string object as the $a argument for a normal
be6ce11c 1697 // get_string call (returning string).
a3d5830a
PS
1698 $test = new lang_string('yes', null, null, true);
1699 $testexpected = get_string('numdays', 'core', get_string('yes'));
1700 $testresult = get_string('numdays', null, $test);
aed2b9ba 1701 $this->assertInternalType('string', $testresult);
be6ce11c 1702 $this->assertSame($testexpected, $testresult);
a3d5830a
PS
1703
1704 // Test using a lang_string object as the $a argument for an object
be6ce11c 1705 // get_string call (returning lang_string).
a3d5830a
PS
1706 $test = new lang_string('yes', null, null, true);
1707 $testexpected = get_string('numdays', 'core', get_string('yes'));
1708 $testresult = get_string('numdays', null, $test, true);
aed2b9ba 1709 $this->assertInstanceOf('lang_string', $testresult);
be6ce11c 1710 $this->assertSame($testexpected, "$testresult");
a3d5830a
PS
1711
1712 // Make sure that object properties that can't be converted don't cause
be6ce11c
PS
1713 // errors.
1714 // Level one: This is as deep as current language processing goes.
a3d5830a
PS
1715 $test = new stdClass;
1716 $test->one = 'here';
1717 $string = get_string('yes', null, $test, true);
be6ce11c 1718 $this->assertEquals($yesexpected, $string);
a3d5830a
PS
1719
1720 // Make sure that object properties that can't be converted don't cause
1721 // errors.
1722 // Level two: Language processing doesn't currently reach this deep.
1723 // only immediate scalar properties are worked with.
1724 $test = new stdClass;
1725 $test->one = new stdClass;
1726 $test->one->two = 'here';
1727 $string = get_string('yes', null, $test, true);
be6ce11c 1728 $this->assertEquals($yesexpected, $string);
a3d5830a
PS
1729
1730 // Make sure that object properties that can't be converted don't cause
1731 // errors.
1732 // Level three: It should never ever go this deep, but we're making sure
1733 // it doesn't cause any probs anyway.
1734 $test = new stdClass;
1735 $test->one = new stdClass;
1736 $test->one->two = new stdClass;
1737 $test->one->two->three = 'here';
1738 $string = get_string('yes', null, $test, true);
be6ce11c 1739 $this->assertEquals($yesexpected, $string);
a3d5830a
PS
1740
1741 // Make sure that object properties that can't be converted don't cause
1742 // errors and check lang_string properties.
be6ce11c 1743 // Level one: This is as deep as current language processing goes.
a3d5830a
PS
1744 $test = new stdClass;
1745 $test->one = new lang_string('yes');
1746 $string = get_string('yes', null, $test, true);
be6ce11c 1747 $this->assertEquals($yesexpected, $string);
a3d5830a
PS
1748
1749 // Make sure that object properties that can't be converted don't cause
1750 // errors and check lang_string properties.
1751 // Level two: Language processing doesn't currently reach this deep.
1752 // only immediate scalar properties are worked with.
1753 $test = new stdClass;
1754 $test->one = new stdClass;
1755 $test->one->two = new lang_string('yes');
1756 $string = get_string('yes', null, $test, true);
be6ce11c 1757 $this->assertEquals($yesexpected, $string);
a3d5830a
PS
1758
1759 // Make sure that object properties that can't be converted don't cause
1760 // errors and check lang_string properties.
1761 // Level three: It should never ever go this deep, but we're making sure
1762 // it doesn't cause any probs anyway.
1763 $test = new stdClass;
1764 $test->one = new stdClass;
1765 $test->one->two = new stdClass;
1766 $test->one->two->three = new lang_string('yes');
1767 $string = get_string('yes', null, $test, true);
be6ce11c 1768 $this->assertEquals($yesexpected, $string);
a3d5830a
PS
1769
1770 // Make sure that array properties that can't be converted don't cause
be6ce11c 1771 // errors.
a3d5830a
PS
1772 $test = array();
1773 $test['one'] = new stdClass;
1774 $test['one']->two = 'here';
1775 $string = get_string('yes', null, $test, true);
be6ce11c 1776 $this->assertEquals($yesexpected, $string);
a3d5830a 1777
be6ce11c 1778 // Same thing but as above except using an object... this is allowed :P.
a3d5830a
PS
1779 $string = get_string('yes', null, null, true);
1780 $object = new stdClass;
1781 $object->$string = 'Yes';
be6ce11c
PS
1782 $this->assertEquals($yesexpected, $string);
1783 $this->assertEquals($yesexpected, $object->$string);
a3d5830a 1784
be6ce11c 1785 // Reset the language.
a3d5830a
PS
1786 $COURSE->lang = $originallang;
1787 }
1788
1789 /**
1790 * @expectedException PHPUnit_Framework_Error_Warning
a3d5830a
PS
1791 */
1792 public function test_get_string_limitation() {
1793 // This is one of the limitations to the lang_string class. It can't be
be6ce11c 1794 // used as a key.
a3d5830a
PS
1795 $array = array(get_string('yes', null, null, true) => 'yes');
1796 }
637da99e 1797
1798 /**
1799 * Test localised float formatting.
1800 */
1801 public function test_format_float() {
637da99e 1802
be6ce11c 1803 // Special case for null.
637da99e 1804 $this->assertEquals('', format_float(null));
1805
be6ce11c 1806 // Default 1 decimal place.
637da99e 1807 $this->assertEquals('5.4', format_float(5.43));
1808 $this->assertEquals('5.0', format_float(5.001));
1809
be6ce11c 1810 // Custom number of decimal places.
637da99e 1811 $this->assertEquals('5.43000', format_float(5.43, 5));
1812
be6ce11c 1813 // Option to strip ending zeros after rounding.
637da99e 1814 $this->assertEquals('5.43', format_float(5.43, 5, true, true));
1815 $this->assertEquals('5', format_float(5.0001, 3, true, true));
1816
d381fb77
GPL
1817 // Tests with a localised decimal separator.
1818 $this->define_local_decimal_separator();
637da99e 1819
be6ce11c 1820 // Localisation on (default).
637da99e 1821 $this->assertEquals('5X43000', format_float(5.43, 5));
1822 $this->assertEquals('5X43', format_float(5.43, 5, true, true));
1823
be6ce11c 1824 // Localisation off.
637da99e 1825 $this->assertEquals('5.43000', format_float(5.43, 5, false));
1826 $this->assertEquals('5.43', format_float(5.43, 5, false, true));
1827 }
4366ce80 1828
d381fb77
GPL
1829 /**
1830 * Test localised float unformatting.
1831 */
1832 public function test_unformat_float() {
1833
1834 // Tests without the localised decimal separator.
1835
1836 // Special case for null, empty or white spaces only strings.
1837 $this->assertEquals(null, unformat_float(null));
1838 $this->assertEquals(null, unformat_float(''));
1839 $this->assertEquals(null, unformat_float(' '));
1840
1841 // Regular use.
1842 $this->assertEquals(5.4, unformat_float('5.4'));
1843 $this->assertEquals(5.4, unformat_float('5.4', true));
1844
1845 // No decimal.
1846 $this->assertEquals(5.0, unformat_float('5'));
1847
1848 // Custom number of decimal.
1849 $this->assertEquals(5.43267, unformat_float('5.43267'));
1850
1851 // Empty decimal.
1852 $this->assertEquals(100.0, unformat_float('100.00'));
1853
1854 // With the thousand separator.
1855 $this->assertEquals(1000.0, unformat_float('1 000'));
1856 $this->assertEquals(1000.32, unformat_float('1 000.32'));
1857
1858 // Negative number.
1859 $this->assertEquals(-100.0, unformat_float('-100'));
1860
1861 // Wrong value.
1862 $this->assertEquals(0.0, unformat_float('Wrong value'));
1863 // Wrong value in strict mode.
1864 $this->assertFalse(unformat_float('Wrong value', true));
1865
1866 // Combining options.
1867 $this->assertEquals(-1023.862567, unformat_float(' -1 023.862567 '));
1868
1869 // Bad decimal separator (should crop the decimal).
1870 $this->assertEquals(50.0, unformat_float('50,57'));
1871 // Bad decimal separator in strict mode (should return false).
1872 $this->assertFalse(unformat_float('50,57', true));
1873
1874 // Tests with a localised decimal separator.
1875 $this->define_local_decimal_separator();
1876
1877 // We repeat the tests above but with the current decimal separator.
1878
1879 // Regular use without and with the localised separator.
1880 $this->assertEquals (5.4, unformat_float('5.4'));
1881 $this->assertEquals (5.4, unformat_float('5X4'));
1882
1883 // Custom number of decimal.
1884 $this->assertEquals (5.43267, unformat_float('5X43267'));
1885
1886 // Empty decimal.
1887 $this->assertEquals (100.0, unformat_float('100X00'));
1888
1889 // With the thousand separator.
1890 $this->assertEquals (1000.32, unformat_float('1 000X32'));
1891
1892 // Bad different separator (should crop the decimal).
1893 $this->assertEquals (50.0, unformat_float('50Y57'));
1894 // Bad different separator in strict mode (should return false).
1895 $this->assertFalse (unformat_float('50Y57', true));
1896
1897 // Combining options.
1898 $this->assertEquals (-1023.862567, unformat_float(' -1 023X862567 '));
1899 // Combining options in strict mode.
1900 $this->assertEquals (-1023.862567, unformat_float(' -1 023X862567 ', true));
1901 }
1902
4366ce80
PS
1903 /**
1904 * Test deleting of users.
1905 */
1906 public function test_delete_user() {
1907 global $DB, $CFG;
1908
1909 $this->resetAfterTest();
1910
1911 $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
1912 $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
1913 $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
1914
1915 $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
1916 $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
a180d06c
FM
1917 $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
1918 $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
1919 $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => ''));
1920 $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => ''));
4366ce80 1921
bb78e249
RT
1922 // Delete user and capture event.
1923 $sink = $this->redirectEvents();
4366ce80 1924 $result = delete_user($user);
bb78e249
RT
1925 $events = $sink->get_events();
1926 $sink->close();
1927 $event = array_pop($events);
1928
1929 // Test user is deleted in DB.
4366ce80
PS
1930 $this->assertTrue($result);
1931 $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
1932 $this->assertEquals(1, $deluser->deleted);
1933 $this->assertEquals(0, $deluser->picture);
1934 $this->assertSame('', $deluser->idnumber);
1935 $this->assertSame(md5($user->username), $deluser->email);
1936 $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
1937
1938 $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
1939
bb78e249
RT
1940 // Test Event.
1941 $this->assertInstanceOf('\core\event\user_deleted', $event);
1942 $this->assertSame($user->id, $event->objectid);
1943 $this->assertSame('user_deleted', $event->get_legacy_eventname());
1944 $this->assertEventLegacyData($user, $event);
1945 $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
1946 $this->assertEventLegacyLogData($expectedlogdata, $event);
abedc1a8
RT
1947 $eventdata = $event->get_data();
1948 $this->assertSame($eventdata['other']['username'], $user->username);
1949 $this->assertSame($eventdata['other']['email'], $user->email);
1950 $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
1951 $this->assertSame($eventdata['other']['picture'], $user->picture);
1952 $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
1953 $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
623a32e5 1954 $this->assertEventContextNotUsed($event);
4366ce80 1955
bb78e249 1956 // Try invalid params.
4366ce80
PS
1957 $record = new stdClass();
1958 $record->grrr = 1;
1959 try {
1960 delete_user($record);
1961 $this->fail('Expecting exception for invalid delete_user() $user parameter');
be6ce11c
PS
1962 } catch (moodle_exception $ex) {
1963 $this->assertInstanceOf('coding_exception', $ex);
4366ce80
PS
1964 }
1965 $record->id = 1;
1966 try {
1967 delete_user($record);
1968 $this->fail('Expecting exception for invalid delete_user() $user parameter');
be6ce11c
PS
1969 } catch (moodle_exception $ex) {
1970 $this->assertInstanceOf('coding_exception', $ex);
4366ce80
PS
1971 }
1972
4366ce80
PS
1973 $record = new stdClass();
1974 $record->id = 666;
1975 $record->username = 'xx';
1976 $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
1977 $result = delete_user($record);
1978 $this->assertFalse($result);
1979
1980 $result = delete_user($guest);
1981 $this->assertFalse($result);
1982
1983 $result = delete_user($admin);
1984 $this->assertFalse($result);
a3b6e311 1985
a180d06c
FM
1986 // Simultaneously deleting users with identical email addresses.
1987 $result1 = delete_user($usersharedemail1);
1988 $result2 = delete_user($usersharedemail2);
1989
1990 $usersharedemail1after = $DB->get_record('user', array('id' => $usersharedemail1->id));
1991 $usersharedemail2after = $DB->get_record('user', array('id' => $usersharedemail2->id));
1992 $this->assertTrue($result1);
1993 $this->assertTrue($result2);
1994 $this->assertStringStartsWith($usersharedemail1->email . '.', $usersharedemail1after->username);
1995 $this->assertStringStartsWith($usersharedemail2->email . '.', $usersharedemail2after->username);
1996
1997 // Simultaneously deleting users without email addresses.
1998 $result1 = delete_user($useremptyemail1);
1999 $result2 = delete_user($useremptyemail2);
2000
2001 $useremptyemail1after = $DB->get_record('user', array('id' => $useremptyemail1->id));
2002 $useremptyemail2after = $DB->get_record('user', array('id' => $useremptyemail2->id));
2003 $this->assertTrue($result1);
2004 $this->assertTrue($result2);
2005 $this->assertStringStartsWith($useremptyemail1->username . '.' . $useremptyemail1->id . '@unknownemail.invalid.',
2006 $useremptyemail1after->username);
2007 $this->assertStringStartsWith($useremptyemail2->username . '.' . $useremptyemail2->id . '@unknownemail.invalid.',
2008 $useremptyemail2after->username);
2009
a3b6e311 2010 $this->resetDebugging();
4366ce80 2011 }
7b444a96
MG
2012
2013 /**
2014 * Test function convert_to_array()
2015 */
2016 public function test_convert_to_array() {
be6ce11c 2017 // Check that normal classes are converted to arrays the same way as (array) would do.
7b444a96
MG
2018 $obj = new stdClass();
2019 $obj->prop1 = 'hello';
2020 $obj->prop2 = array('first', 'second', 13);
2021 $obj->prop3 = 15;
2022 $this->assertEquals(convert_to_array($obj), (array)$obj);
2023
be6ce11c 2024 // Check that context object (with iterator) is converted to array properly.
0601e0ee 2025 $obj = context_system::instance();
7b444a96
MG
2026 $ar = array(
2027 'id' => $obj->id,
2028 'contextlevel' => $obj->contextlevel,
2029 'instanceid' => $obj->instanceid,
2030 'path' => $obj->path,
2031 'depth' => $obj->depth
2032 );
2033 $this->assertEquals(convert_to_array($obj), $ar);
2034 }
15396bba
FM
2035
2036 /**
2037 * Test the function date_format_string().
2038 */
be6ce11c 2039 public function test_date_format_string() {
73d20f36
PS
2040 global $CFG;
2041
d6e7a63d
PS
2042 $this->resetAfterTest();
2043 $this->setTimezone(99, 'Australia/Perth');
15396bba 2044
a8397303
FM
2045 $tests = array(
2046 array(
2047 'tz' => 99,
2048 'str' => '%A, %d %B %Y, %I:%M %p',
2049 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
2050 ),
2051 array(
2052 'tz' => 0,
2053 'str' => '%A, %d %B %Y, %I:%M %p',
2054 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2055 ),
2056 array(
d6e7a63d
PS
2057 // Note: this function expected the timestamp in weird format before,
2058 // since 2.9 it uses UTC.
2059 'tz' => 'Pacific/Auckland',
a8397303 2060 'str' => '%A, %d %B %Y, %I:%M %p',
d6e7a63d 2061 'expected' => 'Saturday, 01 January 2011, 11:00 PM'
a8397303 2062 ),
73d20f36
PS
2063 // Following tests pass on Windows only because en lang pack does
2064 // not contain localewincharset, in real life lang pack maintainers
2065 // may use only characters that are present in localewincharset
2066 // in format strings!
a8397303
FM
2067 array(
2068 'tz' => 99,
2069 'str' => 'Žluťoučký koníček %A',
2070 'expected' => 'Žluťoučký koníček Saturday'
2071 ),
2072 array(
2073 'tz' => 99,
2074 'str' => '言語設定言語 %A',
2075 'expected' => '言語設定言語 Saturday'
2076 ),
2077 array(
2078 'tz' => 99,
2079 'str' => '简体中文简体 %A',
2080 'expected' => '简体中文简体 Saturday'
2081 ),
2082 );
2083
15396bba
FM
2084 // Note: date_format_string() uses the timezone only to differenciate
2085 // the server time from the UTC time. It does not modify the timestamp.
2086 // Hence similar results for timezones <= 13.
a8397303
FM
2087 // On different systems case of AM PM changes so compare case insensitive.
2088 foreach ($tests as $test) {
2089 $str = date_format_string(1293876000, $test['str'], $test['tz']);
2f1e464a 2090 $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
a8397303 2091 }
15396bba 2092 }
7f30a644
SH
2093
2094 public function test_get_config() {
2095 global $CFG;
2096
2097 $this->resetAfterTest();
2098
2099 // Preparation.
2100 set_config('phpunit_test_get_config_1', 'test 1');
2101 set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2102 if (!is_array($CFG->config_php_settings)) {
2103 $CFG->config_php_settings = array();
2104 }
2105 $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
2106
2107 if (!is_array($CFG->forced_plugin_settings)) {
2108 $CFG->forced_plugin_settings = array();
2109 }
2110 if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
2111 $CFG->forced_plugin_settings['mod_forum'] = array();
2112 }
2113 $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2114 $CFG->phpunit_test_get_config_5 = 'test 5';
2115
2116 // Testing.
be6ce11c
PS
2117 $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
2118 $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2119 $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
2120 $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
7f30a644
SH
2121 $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2122 $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2123 $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2124
2125 // Test config we know to exist.
be6ce11c
PS
2126 $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
2127 $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2128 $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2129 $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
7f30a644
SH
2130
2131 // Test setting a config var that already exists.
2132 set_config('phpunit_test_get_config_1', 'test a');
be6ce11c
PS
2133 $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
2134 $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
7f30a644
SH
2135
2136 // Test cache invalidation.
2137 $cache = cache::make('core', 'config');
2138 $this->assertInternalType('array', $cache->get('core'));
2139 $this->assertInternalType('array', $cache->get('mod_forum'));
2140 set_config('phpunit_test_get_config_1', 'test b');
2141 $this->assertFalse($cache->get('core'));
2142 set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2143 $this->assertFalse($cache->get('mod_forum'));
2144 }
6b219310 2145
be6ce11c 2146 public function test_get_max_upload_sizes() {
6b219310
DW
2147 // Test with very low limits so we are not affected by php upload limits.
2148 // Test activity limit smallest.
2149 $sitebytes = 102400;
2150 $coursebytes = 51200;
2151 $modulebytes = 10240;
2152 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2153
be6ce11c
PS
2154 $this->assertSame('Activity upload limit (10KB)', $result['0']);
2155 $this->assertCount(2, $result);
6b219310
DW
2156
2157 // Test course limit smallest.
2158 $sitebytes = 102400;
2159 $coursebytes = 10240;
2160 $modulebytes = 51200;
2161 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2162
be6ce11c
PS
2163 $this->assertSame('Course upload limit (10KB)', $result['0']);
2164 $this->assertCount(2, $result);
6b219310
DW
2165
2166 // Test site limit smallest.
2167 $sitebytes = 10240;
2168 $coursebytes = 102400;
2169 $modulebytes = 51200;
2170 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2171
be6ce11c
PS
2172 $this->assertSame('Site upload limit (10KB)', $result['0']);
2173 $this->assertCount(2, $result);
6b219310
DW
2174
2175 // Test site limit not set.
2176 $sitebytes = 0;
2177 $coursebytes = 102400;
2178 $modulebytes = 51200;
2179 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2180
be6ce11c
PS
2181 $this->assertSame('Activity upload limit (50KB)', $result['0']);
2182 $this->assertCount(3, $result);
6b219310
DW
2183
2184 $sitebytes = 0;
2185 $coursebytes = 51200;
2186 $modulebytes = 102400;
2187 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2188
be6ce11c
PS
2189 $this->assertSame('Course upload limit (50KB)', $result['0']);
2190 $this->assertCount(3, $result);
6b219310 2191
6b219310
DW
2192 // Test custom bytes in range.
2193 $sitebytes = 102400;
2194 $coursebytes = 51200;
2195 $modulebytes = 51200;
2196 $custombytes = 10240;
2197 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2198
be6ce11c 2199 $this->assertCount(3, $result);
6b219310
DW
2200
2201 // Test custom bytes in range but non-standard.
2202 $sitebytes = 102400;
2203 $coursebytes = 51200;
2204 $modulebytes = 51200;
2205 $custombytes = 25600;
2206 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2207
be6ce11c 2208 $this->assertCount(4, $result);
6b219310
DW
2209
2210 // Test custom bytes out of range.
2211 $sitebytes = 102400;
2212 $coursebytes = 51200;
2213 $modulebytes = 51200;
2214 $custombytes = 102400;
2215 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2216
be6ce11c 2217 $this->assertCount(3, $result);
6b219310
DW
2218
2219 // Test custom bytes out of range and non-standard.
2220 $sitebytes = 102400;
2221 $coursebytes = 51200;
2222 $modulebytes = 51200;
2223 $custombytes = 256000;
2224 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2225
be6ce11c 2226 $this->assertCount(3, $result);
f869cb23
PS
2227
2228 // Test site limit only.
2229 $sitebytes = 51200;
2230 $result = get_max_upload_sizes($sitebytes);
2231
be6ce11c
PS
2232 $this->assertSame('Site upload limit (50KB)', $result['0']);
2233 $this->assertSame('50KB', $result['51200']);
2234 $this->assertSame('10KB', $result['10240']);
f869cb23
PS
2235 $this->assertCount(3, $result);
2236
2237 // Test no limit.
2238 $result = get_max_upload_sizes();
2239 $this->assertArrayHasKey('0', $result);
2240 $this->assertArrayHasKey(get_max_upload_file_size(), $result);
6b219310 2241 }
1e7db9fe 2242
ec2d8ceb
SC
2243 /**
2244 * Test function password_is_legacy_hash().
2245 */
2246 public function test_password_is_legacy_hash() {
2247 // Well formed md5s should be matched.
2248 foreach (array('some', 'strings', 'to_check!') as $string) {
2249 $md5 = md5($string);
2250 $this->assertTrue(password_is_legacy_hash($md5));
2251 }
2252 // Strings that are not md5s should not be matched.
2253 foreach (array('', AUTH_PASSWORD_NOT_CACHED, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
2254 $this->assertFalse(password_is_legacy_hash($notmd5));
2255 }
2256 }
2257
2258 /**
2259 * Test function validate_internal_user_password().
2260 */
2261 public function test_validate_internal_user_password() {
25294dd4 2262 // Test bcrypt hashes.
6780a1d3
2263 $validhashes = array(
2264 'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2265 'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2266 'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2267 'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
2268 );
ec2d8ceb
SC
2269
2270 foreach ($validhashes as $password => $hash) {
2271 $user = new stdClass();
2272 $user->auth = 'manual';
2273 $user->password = $hash;
2274 // The correct password should be validated.
2275 $this->assertTrue(validate_internal_user_password($user, $password));
2276 // An incorrect password should not be validated.
2277 $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2278 }
2279 }
2280
2281 /**
2282 * Test function hash_internal_user_password().
2283 */
2284 public function test_hash_internal_user_password() {
2285 $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2286
2287 // Check that some passwords that we convert to hashes can
2288 // be validated.
2289 foreach ($passwords as $password) {
2290 $hash = hash_internal_user_password($password);
2291 $fasthash = hash_internal_user_password($password, true);
2292 $user = new stdClass();
2293 $user->auth = 'manual';
2294 $user->password = $hash;
2295 $this->assertTrue(validate_internal_user_password($user, $password));
2296
25294dd4 2297 // They should not be in md5 format.
6780a1d3
2298 $this->assertFalse(password_is_legacy_hash($hash));
2299
2300 // Check that cost factor in hash is correctly set.
2301 $this->assertRegExp('/\$10\$/', $hash);
2302 $this->assertRegExp('/\$04\$/', $fasthash);
ec2d8ceb
SC
2303 }
2304 }
2305
2306 /**
2307 * Test function update_internal_user_password().
2308 */
2309 public function test_update_internal_user_password() {
2310 global $DB;
2311 $this->resetAfterTest();
2312 $passwords = array('password', '1234', 'changeme', '****');
2313 foreach ($passwords as $password) {
2314 $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2315 update_internal_user_password($user, $password);
2316 // The user object should have been updated.
2317 $this->assertTrue(validate_internal_user_password($user, $password));
2318 // The database field for the user should also have been updated to the
2319 // same value.
be6ce11c 2320 $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
ec2d8ceb
SC
2321 }
2322
2323 $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2324 // Manually set the user's password to the md5 of the string 'password'.
2325 $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
2326
a7466eb4 2327 $sink = $this->redirectEvents();
ec2d8ceb
SC
2328 // Update the password.
2329 update_internal_user_password($user, 'password');
a7466eb4
RT
2330 $events = $sink->get_events();
2331 $sink->close();
2332 $event = array_pop($events);
ec2d8ceb 2333
25294dd4 2334 // Password should have been updated to a bcrypt hash.
6780a1d3 2335 $this->assertFalse(password_is_legacy_hash($user->password));
a7466eb4
RT
2336
2337 // Verify event information.
2338 $this->assertInstanceOf('\core\event\user_password_updated', $event);
2339 $this->assertSame($user->id, $event->relateduserid);
2340 $this->assertEquals(context_user::instance($user->id), $event->get_context());
2341 $this->assertEventContextNotUsed($event);
fb71171f
MG
2342
2343 // Verify recovery of property 'auth'.
2344 unset($user->auth);
2345 update_internal_user_password($user, 'newpassword');
2346 $this->assertDebuggingCalled('User record in update_internal_user_password() must include field auth',
2347 DEBUG_DEVELOPER);
2348 $this->assertEquals('manual', $user->auth);
ec2d8ceb 2349 }
a327f25e 2350
b5bad169
MN
2351 /**
2352 * Testing that if the password is not cached, that it does not update
2353 * the user table and fire event.
2354 */
2355 public function test_update_internal_user_password_no_cache() {
2356 $this->resetAfterTest();
2357
2358 $user = $this->getDataGenerator()->create_user(array('auth' => 'cas'));
2359 $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2360
2361 $sink = $this->redirectEvents();
2362 update_internal_user_password($user, 'wonkawonka');
2363 $this->assertEquals(0, $sink->count(), 'User updated event should not fire');
2364 }
2365
2366 /**
2367 * Test if the user has a password hash, but now their auth method
2368 * says not to cache it. Then it should update.
2369 */
2370 public function test_update_internal_user_password_update_no_cache() {
2371 $this->resetAfterTest();
2372
2373 $user = $this->getDataGenerator()->create_user(array('password' => 'test'));
2374 $this->assertNotEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2375 $user->auth = 'cas'; // Change to a auth that does not store passwords.
2376
2377 $sink = $this->redirectEvents();
2378 update_internal_user_password($user, 'wonkawonka');
2379 $this->assertGreaterThanOrEqual(1, $sink->count(), 'User updated event should fire');
2380
2381 $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2382 }
2383
a327f25e
AG
2384 public function test_fullname() {
2385 global $CFG;
2386
2387 $this->resetAfterTest();
2388
2389 // Create a user to test the name display on.
2390 $record = array();
2391 $record['firstname'] = 'Scott';
2392 $record['lastname'] = 'Fletcher';
2393 $record['firstnamephonetic'] = 'スコット';
2394 $record['lastnamephonetic'] = 'フレチャー';
2395 $record['alternatename'] = 'No friends';
2396 $user = $this->getDataGenerator()->create_user($record);
2397
be6ce11c 2398 // Back up config settings for restore later.
a327f25e
AG
2399 $originalcfg = new stdClass();
2400 $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
795c5881 2401 $originalcfg->alternativefullnameformat = $CFG->alternativefullnameformat;
a327f25e
AG
2402
2403 // Testing existing fullnamedisplay settings.
2404 $CFG->fullnamedisplay = 'firstname';
2405 $testname = fullname($user);
be6ce11c 2406 $this->assertSame($user->firstname, $testname);
a327f25e
AG
2407
2408 $CFG->fullnamedisplay = 'firstname lastname';
2409 $expectedname = "$user->firstname $user->lastname";
2410 $testname = fullname($user);
be6ce11c 2411 $this->assertSame($expectedname, $testname);
a327f25e
AG
2412
2413 $CFG->fullnamedisplay = 'lastname firstname';
2414 $expectedname = "$user->lastname $user->firstname";
2415 $testname = fullname($user);
be6ce11c 2416 $this->assertSame($expectedname, $testname);
a327f25e
AG
2417
2418 $expectedname = get_string('fullnamedisplay', null, $user);
2419 $CFG->fullnamedisplay = 'language';
2420 $testname = fullname($user);
be6ce11c 2421 $this->assertSame($expectedname, $testname);
a327f25e
AG
2422
2423 // Test override parameter.
2424 $CFG->fullnamedisplay = 'firstname';
2425 $expectedname = "$user->firstname $user->lastname";
2426 $testname = fullname($user, true);
be6ce11c 2427 $this->assertSame($expectedname, $testname);
a327f25e 2428
795c5881
AG
2429 // Test alternativefullnameformat setting.
2430 // Test alternativefullnameformat that has been set to nothing.
2431 $CFG->alternativefullnameformat = '';
2432 $expectedname = "$user->firstname $user->lastname";
2433 $testname = fullname($user, true);
2434 $this->assertSame($expectedname, $testname);
2435
2436 // Test alternativefullnameformat that has been set to 'language'.
2437 $CFG->alternativefullnameformat = 'language';
2438 $expectedname = "$user->firstname $user->lastname";
2439 $testname = fullname($user, true);
2440 $this->assertSame($expectedname, $testname);
2441
2442 // Test customising the alternativefullnameformat setting with all additional name fields.
2443 $CFG->alternativefullnameformat = 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename';
2444 $expectedname = "$user->firstname $user->lastname $user->firstnamephonetic $user->lastnamephonetic $user->middlename $user->alternatename";
2445 $testname = fullname($user, true);
2446 $this->assertSame($expectedname, $testname);
2447
a327f25e
AG
2448 // Test additional name fields.
2449 $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
2450 $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
2451 $testname = fullname($user);
be6ce11c 2452 $this->assertSame($expectedname, $testname);
a327f25e
AG
2453
2454 // Test for handling missing data.
2455 $user->middlename = null;
2456 // Parenthesis with no data.
2457 $CFG->fullnamedisplay = 'firstname (middlename) lastname';
2458 $expectedname = "$user->firstname $user->lastname";
2459 $testname = fullname($user);
be6ce11c 2460 $this->assertSame($expectedname, $testname);
a327f25e
AG
2461
2462 // Extra spaces due to no data.
2463 $CFG->fullnamedisplay = 'firstname middlename lastname';
2464 $expectedname = "$user->firstname $user->lastname";
2465 $testname = fullname($user);
be6ce11c 2466 $this->assertSame($expectedname, $testname);
a327f25e
AG
2467
2468 // Regular expression testing.
be6ce11c 2469 // Remove some data from the user fields.
a327f25e
AG
2470 $user->firstnamephonetic = '';
2471 $user->lastnamephonetic = '';
2472
2473 // Removing empty brackets and excess whitespace.
2474 // All of these configurations should resolve to just firstname lastname.
2475 $configarray = array();
2476 $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
2477 $configarray[] = 'firstname lastname \'middlename\'';
2478 $configarray[] = 'firstname "firstnamephonetic" lastname';
2479 $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
2480
2481 foreach ($configarray as $config) {
2482 $CFG->fullnamedisplay = $config;
2483 $expectedname = "$user->firstname $user->lastname";
2484 $testname = fullname($user);
be6ce11c 2485 $this->assertSame($expectedname, $testname);
a327f25e
AG
2486 }
2487
2488 // Check to make sure that other characters are left in place.
2489 $configarray = array();
2490 $configarray['0'] = new stdClass();
2491 $configarray['0']->config = 'lastname firstname, middlename';
2492 $configarray['0']->expectedname = "$user->lastname $user->firstname,";
2493 $configarray['1'] = new stdClass();
2494 $configarray['1']->config = 'lastname firstname + alternatename';
2495 $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
2496 $configarray['2'] = new stdClass();
2497 $configarray['2']->config = 'firstname aka: alternatename';
2498 $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
2499 $configarray['3'] = new stdClass();
2500 $configarray['3']->config = 'firstname (alternatename)';
2501 $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
2502 $configarray['4'] = new stdClass();
2503 $configarray['4']->config = 'firstname [alternatename]';
2504 $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
2505 $configarray['5'] = new stdClass();
2506 $configarray['5']->config = 'firstname "lastname"';
2507 $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
2508
2509 foreach ($configarray as $config) {
2510 $CFG->fullnamedisplay = $config->config;
2511 $expectedname = $config->expectedname;
2512 $testname = fullname($user);
be6ce11c 2513 $this->assertSame($expectedname, $testname);
a327f25e
AG
2514 }
2515
73d363f0
AG
2516 // Test debugging message displays when
2517 // fullnamedisplay setting is "normal".
2518 $CFG->fullnamedisplay = 'firstname lastname';
2519 unset($user);
2520 $user = new stdClass();
2521 $user->firstname = 'Stan';
2522 $user->lastname = 'Lee';
2523 $namedisplay = fullname($user);
2524 $this->assertDebuggingCalled();
2525
be6ce11c 2526 // Tidy up after we finish testing.
a327f25e 2527 $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
795c5881 2528 $CFG->alternativefullnameformat = $originalcfg->alternativefullnameformat;
a327f25e
AG
2529 }
2530
2531 public function test_get_all_user_name_fields() {
2532 $this->resetAfterTest();
2533
2534 // Additional names in an array.
f490f988
AG
2535 $testarray = array('firstnamephonetic' => 'firstnamephonetic',
2536 'lastnamephonetic' => 'lastnamephonetic',
2537 'middlename' => 'middlename',
2538 'alternatename' => 'alternatename',
2539 'firstname' => 'firstname',
2540 'lastname' => 'lastname');
a327f25e
AG
2541 $this->assertEquals($testarray, get_all_user_name_fields());
2542
2543 // Additional names as a string.
2544 $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
2545 $this->assertEquals($teststring, get_all_user_name_fields(true));
2546
2547 // Additional names as a string with an alias.
2548 $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
2549 $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
f490f988 2550
5b1944bb 2551 // Additional name fields with a prefix - object.
f490f988
AG
2552 $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
2553 'lastnamephonetic' => 'authorlastnamephonetic',
2554 'middlename' => 'authormiddlename',
2555 'alternatename' => 'authoralternatename',
2556 'firstname' => 'authorfirstname',
2557 'lastname' => 'authorlastname');
2558 $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
2559
5b1944bb 2560 // Additional name fields with an alias and a title - string.
f490f988
AG
2561 $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';
2562 $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
e622b1a1
AG
2563
2564 // Test the order parameter of the function.
2565 // Returning an array.
2566 $testarray = array('firstname' => 'firstname',
2567 'lastname' => 'lastname',
2568 'firstnamephonetic' => 'firstnamephonetic',
2569 'lastnamephonetic' => 'lastnamephonetic',
2570 'middlename' => 'middlename',
2571 'alternatename' => 'alternatename'
2572 );
2573 $this->assertEquals($testarray, get_all_user_name_fields(false, null, null, null, true));
2574
2575 // Returning a string.
2576 $teststring = 'firstname,lastname,firstnamephonetic,lastnamephonetic,middlename,alternatename';
2577 $this->assertEquals($teststring, get_all_user_name_fields(true, null, null, null, true));
a327f25e
AG
2578 }
2579
2580 public function test_order_in_string() {
2581 $this->resetAfterTest();
2582
2583 // Return an array in an order as they are encountered in a string.
2584 $valuearray = array('second', 'firsthalf', 'first');
2585 $formatstring = 'first firsthalf some other text (second)';
2586 $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
2587 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2588
2589 // Try again with a different order for the format.
2590 $valuearray = array('second', 'firsthalf', 'first');
2591 $formatstring = 'firsthalf first second';
2592 $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
2593 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2594
2595 // Try again with yet another different order for the format.
2596 $valuearray = array('second', 'firsthalf', 'first');
2597 $formatstring = 'start seconds away second firstquater first firsthalf';
2598 $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
2599 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2600 }
bb78e249 2601
d79d5ac2 2602 public function test_complete_user_login() {
93b3aaf4 2603 global $USER, $DB;
d79d5ac2
PS
2604
2605 $this->resetAfterTest();
2606 $user = $this->getDataGenerator()->create_user();
2607 $this->setUser(0);
2608
2609 $sink = $this->redirectEvents();
93b3aaf4
PS
2610 $loginuser = clone($user);
2611 $this->setCurrentTimeStart();
2612 @complete_user_login($loginuser); // Hide session header errors.
2613 $this->assertSame($loginuser, $USER);
d79d5ac2
PS
2614 $this->assertEquals($user->id, $USER->id);
2615 $events = $sink->get_events();
2616 $sink->close();
2617
54b1e040
2618 $this->assertCount(1, $events);
2619 $event = reset($events);
d79d5ac2
PS
2620 $this->assertInstanceOf('\core\event\user_loggedin', $event);
2621 $this->assertEquals('user', $event->objecttable);
2622 $this->assertEquals($user->id, $event->objectid);
2623 $this->assertEquals(context_system::instance()->id, $event->contextid);
623a32e5 2624 $this->assertEventContextNotUsed($event);
93b3aaf4
PS
2625
2626 $user = $DB->get_record('user', array('id'=>$user->id));
2627
2628 $this->assertTimeCurrent($user->firstaccess);
2629 $this->assertTimeCurrent($user->lastaccess);
93b3aaf4
PS
2630
2631 $this->assertTimeCurrent($USER->firstaccess);
2632 $this->assertTimeCurrent($USER->lastaccess);
93b3aaf4
PS
2633 $this->assertTimeCurrent($USER->currentlogin);
2634 $this->assertSame(sesskey(), $USER->sesskey);
2635 $this->assertTimeCurrent($USER->preference['_lastloaded']);
2636 $this->assertObjectNotHasAttribute('password', $USER);
2637 $this->assertObjectNotHasAttribute('description', $USER);
d79d5ac2
PS
2638 }
2639
bb78e249
RT
2640 /**
2641 * Test require_logout.
2642 */
2643 public function test_require_logout() {
2644 $this->resetAfterTest();
2645 $user = $this->getDataGenerator()->create_user();
2646 $this->setUser($user);
bb78e249
RT
2647
2648 $this->assertTrue(isloggedin());
2649
2650 // Logout user and capture event.
2651 $sink = $this->redirectEvents();
2652 require_logout();
2653 $events = $sink->get_events();
2654 $sink->close();
2655 $event = array_pop($events);
2656
2657 // Check if user is logged out.
2658 $this->assertFalse(isloggedin());
2659
2660 // Test Event.
2661 $this->assertInstanceOf('\core\event\user_loggedout', $event);
2662 $this->assertSame($user->id, $event->objectid);
2663 $this->assertSame('user_logout', $event->get_legacy_eventname());
2664 $this->assertEventLegacyData($user, $event);
2665 $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
2666 $event->objectid);
2667 $this->assertEventLegacyLogData($expectedlogdata, $event);
623a32e5 2668 $this->assertEventContextNotUsed($event);
bb78e249 2669 }
90930acf 2670
54dceeed
BH
2671 /**
2672 * A data provider for testing email messageid
2673 */
2674 public function generate_email_messageid_provider() {
2675 return array(
2676 'nopath' => array(
2677 'wwwroot' => 'http://www.example.com',
2678 'ids' => array(
2679 'a-custom-id' => '<a-custom-id@www.example.com>',
2680 'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash@www.example.com>',
2681 ),
2682 ),
2683 'path' => array(
2684 'wwwroot' => 'http://www.example.com/path/subdir',
2685 'ids' => array(
2686 'a-custom-id' => '<a-custom-id/path/subdir@www.example.com>',
2687 'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash/path/subdir@www.example.com>',
2688 ),
2689 ),
2690 );
2691 }
2692
2693 /**
2694 * Test email message id generation
2695 *
2696 * @dataProvider generate_email_messageid_provider
2697 *
2698 * @param string $wwwroot The wwwroot
2699 * @param array $msgids An array of msgid local parts and the final result
2700 */
2701 public function test_generate_email_messageid($wwwroot, $msgids) {
2702 global $CFG;
2703
2704 $this->resetAfterTest();
2705 $CFG->wwwroot = $wwwroot;
2706
2707 foreach ($msgids as $local => $final) {
2708 $this->assertEquals($final, generate_email_messageid($local));
2709 }
2710 }
eca8cf67 2711
34417803
BH
2712 /**
2713 * A data provider for testing email diversion
2714 */
eca8cf67
BH
2715 public function diverted_emails_provider() {
2716 return array(
2717 'nodiverts' => array(
2718 'divertallemailsto' => null,
2719 'divertallemailsexcept' => null,
2720 array(
2721 'foo@example.com',
2722 'test@real.com',
2723 'fred.jones@example.com',
2724 'dev1@dev.com',
2725 'fred@example.com',
2726 'fred+verp@example.com',
2727 ),
2728 false,
2729 ),
2730 'alldiverts' => array(
2731 'divertallemailsto' => 'somewhere@elsewhere.com',
2732 'divertallemailsexcept' => null,
2733 array(
2734 'foo@example.com',
2735 'test@real.com',
2736 'fred.jones@example.com',
2737 'dev1@dev.com',
2738 'fred@example.com',
2739 'fred+verp@example.com',
2740 ),
2741 true,
2742 ),
2743 'alsodiverts' => array(
2744 'divertallemailsto' => 'somewhere@elsewhere.com',
2745 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
2746 array(
2747 'foo@example.com',
2748 'test@real.com',
2749 'fred.jones@example.com',
2750 ),
2751 true,
2752 ),
2753 'divertsexceptions' => array(
2754 'divertallemailsto' => 'somewhere@elsewhere.com',
2755 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
2756 array(
2757 'dev1@dev.com',
2758 'fred@example.com',
2759 'fred+verp@example.com',
2760 ),
2761 false,
2762 ),
2763 );
2764 }
2765
2766 /**
34417803
BH
2767 * Test email diversion
2768 *
eca8cf67 2769 * @dataProvider diverted_emails_provider
34417803
BH
2770 *
2771 * @param string $divertallemailsto An optional email address
2772 * @param string $divertallemailsexcept An optional exclusion list
2773 * @param array $addresses An array of test addresses
2774 * @param boolean $expected Expected result
eca8cf67
BH
2775 */
2776 public function test_email_should_be_diverted($divertallemailsto, $divertallemailsexcept, $addresses, $expected) {
2777 global $CFG;
2778
2779 $this->resetAfterTest();
2780 $CFG->divertallemailsto = $divertallemailsto;
2781 $CFG->divertallemailsexcept = $divertallemailsexcept;
2782
2783 foreach ($addresses as $address) {
2784 $this->assertEquals($expected, email_should_be_diverted($address));
2785 }
2786 }
2787
90930acf 2788 public function test_email_to_user() {
f007e899
PS
2789 global $CFG;
2790
90930acf
PS
2791 $this->resetAfterTest();
2792
e0789335
AG
2793 $user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
2794 $user2 = $this->getDataGenerator()->create_user(array('maildisplay' => 1));
2795 $user3 = $this->getDataGenerator()->create_user(array('maildisplay' => 0));
2796 set_config('allowedemaildomains', 'example.com');
90930acf
PS
2797
2798 $subject = 'subject';
2799 $messagetext = 'message text';
2800 $subject2 = 'subject 2';
2801 $messagetext2 = 'message text 2';
2802
fc05c1b8
AN
2803 // Close the default email sink.
2804 $sink = $this->redirectEmails();
2805 $sink->close();
2806
2807 $CFG->noemailever = true;
f007e899
PS
2808 $this->assertNotEmpty($CFG->noemailever);
2809 email_to_user($user1, $user2, $subject, $messagetext);
2810 $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
2811
90930acf
PS
2812 unset_config('noemailever');
2813
f007e899
PS
2814 email_to_user($user1, $user2, $subject, $messagetext);
2815 $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2816
90930acf
PS
2817 $sink = $this->redirectEmails();
2818 email_to_user($user1, $user2, $subject, $messagetext);
2819 email_to_user($user2, $user1, $subject2, $messagetext2);
2820 $this->assertSame(2, $sink->count());
2821 $result = $sink->get_messages();
2822 $this->assertCount(2, $result);
2823 $sink->close();
2824
2825 $this->assertSame($subject, $result[0]->subject);
2826 $this->assertSame($messagetext, trim($result[0]->body));
2827 $this->assertSame($user1->email, $result[0]->to);
2828 $this->assertSame($user2->email, $result[0]->from);
2829
2830 $this->assertSame($subject2, $result[1]->subject);
2831 $this->assertSame($messagetext2, trim($result[1]->body));
2832 $this->assertSame($user2->email, $result[1]->to);
2833 $this->assertSame($user1->email, $result[1]->from);
f007e899
PS
2834
2835 email_to_user($user1, $user2, $subject, $messagetext);
2836 $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
85614920 2837
e0789335
AG
2838 // Test that an empty noreplyaddress will default to a no-reply address.
2839 $sink = $this->redirectEmails();
2840 email_to_user($user1, $user3, $subject, $messagetext);
2841 $result = $sink->get_messages();
2842 $this->assertEquals($CFG->noreplyaddress, $result[0]->from);
2843 $sink->close();
2844 set_config('noreplyaddress', '');
2845 $sink = $this->redirectEmails();
2846 email_to_user($user1, $user3, $subject, $messagetext);
2847 $result = $sink->get_messages();
2848 $this->assertEquals('noreply@www.example.com', $result[0]->from);
2849 $sink->close();
2850
2851 // Test $CFG->allowedemaildomains.
2852 set_config('noreplyaddress', 'noreply@www.example.com');
2853 $this->assertNotEmpty($CFG->allowedemaildomains);
85614920
MA
2854 $sink = $this->redirectEmails();
2855 email_to_user($user1, $user2, $subject, $messagetext);
e0789335 2856 unset_config('allowedemaildomains');
85614920
MA
2857 email_to_user($user1, $user2, $subject, $messagetext);
2858 $result = $sink->get_messages();
e0789335
AG
2859 $this->assertNotEquals($CFG->noreplyaddress, $result[0]->from);
2860 $this->assertEquals($CFG->noreplyaddress, $result[1]->from);
85614920 2861 $sink->close();
90930acf 2862 }
6c679d15
AA
2863
2864 /**
a7466eb4 2865 * Test setnew_password_and_mail.
6c679d15 2866 */
a7466eb4 2867 public function test_setnew_password_and_mail() {
6c679d15
AA
2868 global $DB, $CFG;
2869
2870 $this->resetAfterTest();
2871
2872 $user = $this->getDataGenerator()->create_user();
2873
6c679d15
AA
2874 // Update user password.
2875 $sink = $this->redirectEvents();
2876 $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
2877 setnew_password_and_mail($user);
6c679d15
AA
2878 $events = $sink->get_events();
2879 $sink->close();
2880 $sink2->close();
a7466eb4 2881 $event = array_pop($events);
6c679d15
AA
2882
2883 // Test updated value.
2884 $dbuser = $DB->get_record('user', array('id' => $user->id));
2885 $this->assertSame($user->firstname, $dbuser->firstname);
a7466eb4 2886 $this->assertNotEmpty($dbuser->password);
6c679d15
AA
2887
2888 // Test event.
a7466eb4
RT
2889 $this->assertInstanceOf('\core\event\user_password_updated', $event);
2890 $this->assertSame($user->id, $event->relateduserid);
2891 $this->assertEquals(context_user::instance($user->id), $event->get_context());
2892 $this->assertEventContextNotUsed($event);
6c679d15
AA
2893 }
2894
cc49a6f7
AA
2895 /**
2896 * Test remove_course_content deletes course contents
2897 * TODO Add asserts to verify other data related to course is deleted as well.
2898 */
2899 public function test_remove_course_contents() {
2900
2901 $this->resetAfterTest();
2902
2903 $course = $this->getDataGenerator()->create_course();
2904 $user = $this->getDataGenerator()->create_user();
2905 $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
2906 $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id));
2907
2908 $this->assertNotEquals(false, note_load($note->id));
2909 remove_course_contents($course->id, false);
2910 $this->assertFalse(note_load($note->id));
2911 }
2912
f490f988
AG
2913 /**
2914 * Test function username_load_fields_from_object().
2915 */
2916 public function test_username_load_fields_from_object() {
2917 $this->resetAfterTest();
2918
2919 // This object represents the information returned from an sql query.
2920 $userinfo = new stdClass();
2921 $userinfo->userid = 1;
2922 $userinfo->username = 'loosebruce';
2923 $userinfo->firstname = 'Bruce';
2924 $userinfo->lastname = 'Campbell';
2925 $userinfo->firstnamephonetic = 'ブルース';
2926 $userinfo->lastnamephonetic = 'カンベッル';
2927 $userinfo->middlename = '';
2928 $userinfo->alternatename = '';
2929 $userinfo->email = '';
2930 $userinfo->picture = 23;
5b1944bb 2931 $userinfo->imagealt = 'Michael Jordan draining another basket.';
f490f988
AG
2932 $userinfo->idnumber = 3982;
2933
f490f988
AG
2934 // Just user name fields.
2935 $user = new stdClass();
2936 $user = username_load_fields_from_object($user, $userinfo);
2937 $expectedarray = new stdClass();
2938 $expectedarray->firstname = 'Bruce';
2939 $expectedarray->lastname = 'Campbell';
2940 $expectedarray->firstnamephonetic = 'ブルース';
2941 $expectedarray->lastnamephonetic = 'カンベッル';
2942 $expectedarray->middlename = '';
2943 $expectedarray->alternatename = '';
2944 $this->assertEquals($user, $expectedarray);
2945
2946 // User information for showing a picture.
2947 $user = new stdClass();
e351bed5 2948 $additionalfields = explode(',', user_picture::fields());
f490f988 2949 $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
e351bed5 2950 $user->id = $userinfo->userid;
f490f988
AG
2951 $expectedarray = new stdClass();
2952 $expectedarray->id = 1;
2953 $expectedarray->firstname = 'Bruce';
2954 $expectedarray->lastname = 'Campbell';
2955 $expectedarray->firstnamephonetic = 'ブルース';
2956 $expectedarray->lastnamephonetic = 'カンベッル';
2957 $expectedarray->middlename = '';
2958 $expectedarray->alternatename = '';
2959 $expectedarray->email = '';
2960 $expectedarray->picture = 23;
5b1944bb 2961 $expectedarray->imagealt = 'Michael Jordan draining another basket.';
f490f988
AG
2962 $this->assertEquals($user, $expectedarray);
2963
2964 // Alter the userinfo object to have a prefix.
2965 $userinfo->authorfirstname = 'Bruce';
2966 $userinfo->authorlastname = 'Campbell';
2967 $userinfo->authorfirstnamephonetic = 'ブルース';
2968 $userinfo->authorlastnamephonetic = 'カンベッル';
2969 $userinfo->authormiddlename = '';
e351bed5
AG
2970 $userinfo->authorpicture = 23;
2971 $userinfo->authorimagealt = 'Michael Jordan draining another basket.';
0fe86bbd 2972 $userinfo->authoremail = 'test@example.com';
e351bed5 2973
f490f988
AG
2974
2975 // Return an object with user picture information.
2976 $user = new stdClass();
e351bed5 2977 $additionalfields = explode(',', user_picture::fields());
f490f988 2978 $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
e351bed5 2979 $user->id = $userinfo->userid;
f490f988
AG
2980 $expectedarray = new stdClass();
2981 $expectedarray->id = 1;
2982 $expectedarray->firstname = 'Bruce';
2983 $expectedarray->lastname = 'Campbell';
2984 $expectedarray->firstnamephonetic = 'ブルース';
2985 $expectedarray->lastnamephonetic = 'カンベッル';
2986 $expectedarray->middlename = '';
2987 $expectedarray->alternatename = '';
0fe86bbd 2988 $expectedarray->email = 'test@example.com';
f490f988 2989 $expectedarray->picture = 23;
5b1944bb 2990 $expectedarray->imagealt = 'Michael Jordan draining another basket.';
f490f988
AG
2991 $this->assertEquals($user, $expectedarray);
2992 }
1da7d44a
TB
2993
2994 /**
2995 * Test function count_words().
2996 */
2997 public function test_count_words() {
2998 $count = count_words("one two three'four");
2999 $this->assertEquals(3, $count);
3000
3001 $count = count_words('one+two three’four');
3002 $this->assertEquals(3, $count);
3003
3004 $count = count_words('one"two three-four');
6e38f41d 3005 $this->assertEquals(2, $count);
1da7d44a
TB
3006
3007 $count = count_words('one@two three_four');
3008 $this->assertEquals(4, $count);
3009
3010 $count = count_words('one\two three/four');
3011 $this->assertEquals(4, $count);
3012
3013 $count = count_words(' one ... two &nbsp; three...four ');
3014 $this->assertEquals(4, $count);
3015
3016 $count = count_words('one.2 3,four');
3017 $this->assertEquals(4, $count);
3018
3019 $count = count_words('1³ £2 €3.45 $6,789');
3020 $this->assertEquals(4, $count);
3021
3022 $count = count_words('one—two ブルース カンベッル');
3023 $this->assertEquals(4, $count);
3024
3025 $count = count_words('one…two ブルース … カンベッル');
3026 $this->assertEquals(4, $count);
3027 }
ad2fc0d8
MH
3028 /**
3029 * Tests the getremoteaddr() function.
3030 */
3031 public function test_getremoteaddr() {
c2a9bb3a
JO
3032 $xforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null;
3033
ad2fc0d8
MH
3034 $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
3035 $noip = getremoteaddr('1.1.1.1');
3036 $this->assertEquals('1.1.1.1', $noip);
3037
3038 $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
3039 $noip = getremoteaddr();
3040 $this->assertEquals('0.0.0.0', $noip);
3041
3042 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1';
3043 $singleip = getremoteaddr();
3044 $this->assertEquals('127.0.0.1', $singleip);
3045
3046 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2';
3047 $twoip = getremoteaddr();
3048 $this->assertEquals('127.0.0.1', $twoip);
3049
3050 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2, 127.0.0.3';
3051 $threeip = getremoteaddr();
3052 $this->assertEquals('127.0.0.1', $threeip);
3053
c2a9bb3a
JO
3054 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1:65535,127.0.0.2';
3055 $portip = getremoteaddr();
3056 $this->assertEquals('127.0.0.1', $portip);
3057
3058 $_SERVER['HTTP_X_FORWARDED_FOR'] = '0:0:0:0:0:0:0:1,127.0.0.2';
3059 $portip = getremoteaddr();
3060 $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3061
3062 $_SERVER['HTTP_X_FORWARDED_FOR'] = '0::1,127.0.0.2';
3063 $portip = getremoteaddr();
3064 $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3065
3066 $_SERVER['HTTP_X_FORWARDED_FOR'] = '[0:0:0:0:0:0:0:1]:65535,127.0.0.2';
3067 $portip = getremoteaddr();
3068 $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
3069
3070 $_SERVER['HTTP_X_FORWARDED_FOR'] = $xforwardedfor;
3071
ad2fc0d8 3072 }
e4ac3879
PS
3073
3074 /*
3075 * Test emulation of random_bytes() function.
3076 */
3077 public function test_random_bytes_emulate() {
3078 $result = random_bytes_emulate(10);
3079 $this->assertSame(10, strlen($result));
3080 $this->assertnotSame($result, random_bytes_emulate(10));
3081
3082 $result = random_bytes_emulate(21);
3083 $this->assertSame(21, strlen($result));
3084 $this->assertnotSame($result, random_bytes_emulate(21));
3085
3086 $result = random_bytes_emulate(666);
3087 $this->assertSame(666, strlen($result));
3088
6a3acc84
RS
3089 $result = random_bytes_emulate(40);