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