Merge branch 'MDL-51434-master' of git://github.com/jleyva/moodle
[moodle.git] / lib / tests / moodlelib_test.php
blob78b2a2d16bd2f4af4a91928d0c5056f4385eda8c
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.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Unit tests for (some of) ../moodlelib.php.
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
27 defined('MOODLE_INTERNAL') || die();
29 class core_moodlelib_testcase extends advanced_testcase {
31 public static $includecoverage = array('lib/moodlelib.php');
33 /**
34 * Define a local decimal separator.
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.
43 protected function define_local_decimal_separator() {
44 global $SESSION, $CFG;
46 $SESSION->lang = 'xx';
47 $langconfig = "<?php\n\$string['decsep'] = 'X';";
48 $langfolder = $CFG->dataroot . '/lang/xx';
49 check_dir_exists($langfolder);
50 file_put_contents($langfolder . '/langconfig.php', $langconfig);
53 public function test_cleanremoteaddr() {
54 // IPv4.
55 $this->assertNull(cleanremoteaddr('1023.121.234.1'));
56 $this->assertSame('123.121.234.1', cleanremoteaddr('123.121.234.01 '));
58 // IPv6.
59 $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:0:0'));
60 $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:abh'));
61 $this->assertNull(cleanremoteaddr('0:0:0:::0:0:1'));
62 $this->assertSame('::', cleanremoteaddr('0:0:0:0:0:0:0:0', true));
63 $this->assertSame('::1:1', cleanremoteaddr('0:0:0:0:0:0:1:1', true));
64 $this->assertSame('abcd:ef::', cleanremoteaddr('abcd:00ef:0:0:0:0:0:0', true));
65 $this->assertSame('1::1', cleanremoteaddr('1:0:0:0:0:0:0:1', true));
66 $this->assertSame('0:0:0:0:0:0:10:1', cleanremoteaddr('::10:1', false));
67 $this->assertSame('1:1:0:0:0:0:0:0', cleanremoteaddr('01:1::', false));
68 $this->assertSame('10:0:0:0:0:0:0:10', cleanremoteaddr('10::10', false));
69 $this->assertSame('::ffff:c0a8:11', cleanremoteaddr('::ffff:192.168.1.1', true));
72 public function test_address_in_subnet() {
73 // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask).
74 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.1/32'));
75 $this->assertFalse(address_in_subnet('123.121.23.1', '123.121.23.0/32'));
76 $this->assertTrue(address_in_subnet('10.10.10.100', '123.121.23.45/0'));
77 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/24'));
78 $this->assertFalse(address_in_subnet('123.121.34.1', '123.121.234.0/24'));
79 $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/30'));
80 $this->assertFalse(address_in_subnet('123.121.23.8', '123.121.23.0/30'));
81 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
82 $this->assertFalse(address_in_subnet('bab:baba::baba', 'bab:baba::cece/128'));
83 $this->assertTrue(address_in_subnet('baba:baba::baba', 'cece:cece::cece/0'));
84 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
85 $this->assertTrue(address_in_subnet('baba:baba::00ba', 'baba:baba::/120'));
86 $this->assertFalse(address_in_subnet('baba:baba::aba', 'baba:baba::/120'));
87 $this->assertTrue(address_in_subnet('baba::baba:00ba', 'baba::baba:0/112'));
88 $this->assertFalse(address_in_subnet('baba::aba:00ba', 'baba::baba:0/112'));
89 $this->assertFalse(address_in_subnet('aba::baba:0000', 'baba::baba:0/112'));
91 // Fixed input.
92 $this->assertTrue(address_in_subnet('123.121.23.1 ', ' 123.121.23.0 / 24'));
93 $this->assertTrue(address_in_subnet('::ffff:10.1.1.1', ' 0:0:0:000:0:ffff:a1:10 / 126'));
95 // Incorrect input.
96 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/-2'));
97 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/64'));
98 $this->assertFalse(address_in_subnet('123.121.234.x', '123.121.234.1/24'));
99 $this->assertFalse(address_in_subnet('123.121.234.0', '123.121.234.xx/24'));
100 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/xx0'));
101 $this->assertFalse(address_in_subnet('::1', '::aa:0/xx0'));
102 $this->assertFalse(address_in_subnet('::1', '::aa:0/-5'));
103 $this->assertFalse(address_in_subnet('::1', '::aa:0/130'));
104 $this->assertFalse(address_in_subnet('x:1', '::aa:0/130'));
105 $this->assertFalse(address_in_subnet('::1', '::ax:0/130'));
107 // 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy (a range of IP addresses in the last group).
108 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12-14'));
109 $this->assertTrue(address_in_subnet('123.121.234.13', '123.121.234.12-14'));
110 $this->assertTrue(address_in_subnet('123.121.234.14', '123.121.234.12-14'));
111 $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.12-14'));
112 $this->assertFalse(address_in_subnet('123.121.234.20', '123.121.234.12-14'));
113 $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.234.12-14'));
114 $this->assertFalse(address_in_subnet('123.12.234.12', '123.121.234.12-14'));
115 $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba-babe'));
116 $this->assertTrue(address_in_subnet('baba:baba::babc', 'baba:baba::baba-babe'));
117 $this->assertTrue(address_in_subnet('baba:baba::babe', 'baba:baba::baba-babe'));
118 $this->assertFalse(address_in_subnet('bab:baba::bab0', 'bab:baba::baba-babe'));
119 $this->assertFalse(address_in_subnet('bab:baba::babf', 'bab:baba::baba-babe'));
120 $this->assertFalse(address_in_subnet('bab:baba::bfbe', 'bab:baba::baba-babe'));
121 $this->assertFalse(address_in_subnet('bfb:baba::babe', 'bab:baba::baba-babe'));
123 // Fixed input.
124 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12 - 14 '));
125 $this->assertTrue(address_in_subnet('bab:baba::babe', 'bab:baba::baba - babe '));
127 // Incorrect input.
128 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-234.14'));
129 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-256'));
130 $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12--256'));
132 // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-).
133 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12'));
134 $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.23.13'));
135 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.'));
136 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234'));
137 $this->assertTrue(address_in_subnet('123.121.234.12', '123.121'));
138 $this->assertTrue(address_in_subnet('123.121.234.12', '123'));
139 $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234.'));
140 $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234'));
141 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba::bab'));
142 $this->assertFalse(address_in_subnet('baba:baba::ba', 'baba:baba::bc'));
143 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba'));
144 $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:'));
145 $this->assertFalse(address_in_subnet('bab:baba::bab', 'baba:'));
147 // Multiple subnets.
148 $this->assertTrue(address_in_subnet('123.121.234.12', '::1/64, 124., 123.121.234.10-30'));
149 $this->assertTrue(address_in_subnet('124.121.234.12', '::1/64, 124., 123.121.234.10-30'));
150 $this->assertTrue(address_in_subnet('::2', '::1/64, 124., 123.121.234.10-30'));
151 $this->assertFalse(address_in_subnet('12.121.234.12', '::1/64, 124., 123.121.234.10-30'));
153 // Other incorrect input.
154 $this->assertFalse(address_in_subnet('123.123.123.123', ''));
157 public function test_fix_utf8() {
158 // Make sure valid data including other types is not changed.
159 $this->assertSame(null, fix_utf8(null));
160 $this->assertSame(1, fix_utf8(1));
161 $this->assertSame(1.1, fix_utf8(1.1));
162 $this->assertSame(true, fix_utf8(true));
163 $this->assertSame('', fix_utf8(''));
164 $this->assertSame('abc', fix_utf8('abc'));
165 $array = array('do', 're', 'mi');
166 $this->assertSame($array, fix_utf8($array));
167 $object = new stdClass();
168 $object->a = 'aa';
169 $object->b = 'bb';
170 $this->assertEquals($object, fix_utf8($object));
172 // valid utf8 string
173 $this->assertSame("žlutý koníček přeskočil potůček \n\t\r", fix_utf8("žlutý koníček přeskočil potůček \n\t\r\0"));
175 // Invalid utf8 string.
176 $this->assertSame('aš', fix_utf8('a'.chr(130).'š'), 'This fails with buggy iconv() when mbstring extenstion is not available as fallback.');
179 public function test_optional_param() {
180 global $CFG;
182 $_POST['username'] = 'post_user';
183 $_GET['username'] = 'get_user';
184 $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
186 unset($_POST['username']);
187 $this->assertSame($_GET['username'], optional_param('username', 'default_user', PARAM_RAW));
189 unset($_GET['username']);
190 $this->assertSame('default_user', optional_param('username', 'default_user', PARAM_RAW));
192 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
193 $_POST['username'] = 'post_user';
194 try {
195 optional_param('username', 'default_user', null);
196 $this->fail('coding_exception expected');
197 } catch (moodle_exception $ex) {
198 $this->assertInstanceOf('coding_exception', $ex);
200 try {
201 @optional_param('username', 'default_user');
202 $this->fail('coding_exception expected');
203 } catch (moodle_exception $ex) {
204 $this->assertInstanceOf('coding_exception', $ex);
206 try {
207 @optional_param('username');
208 $this->fail('coding_exception expected');
209 } catch (moodle_exception $ex) {
210 $this->assertInstanceOf('coding_exception', $ex);
212 try {
213 optional_param('', 'default_user', PARAM_RAW);
214 $this->fail('coding_exception expected');
215 } catch (moodle_exception $ex) {
216 $this->assertInstanceOf('coding_exception', $ex);
219 // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
220 $_POST['username'] = array('a'=>'a');
221 $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
222 $this->assertDebuggingCalled();
225 public function test_optional_param_array() {
226 global $CFG;
228 $_POST['username'] = array('a'=>'post_user');
229 $_GET['username'] = array('a'=>'get_user');
230 $this->assertSame($_POST['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
232 unset($_POST['username']);
233 $this->assertSame($_GET['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
235 unset($_GET['username']);
236 $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
238 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
239 $_POST['username'] = array('a'=>'post_user');
240 try {
241 optional_param_array('username', array('a'=>'default_user'), null);
242 $this->fail('coding_exception expected');
243 } catch (moodle_exception $ex) {
244 $this->assertInstanceOf('coding_exception', $ex);
246 try {
247 @optional_param_array('username', array('a'=>'default_user'));
248 $this->fail('coding_exception expected');
249 } catch (moodle_exception $ex) {
250 $this->assertInstanceOf('coding_exception', $ex);
252 try {
253 @optional_param_array('username');
254 $this->fail('coding_exception expected');
255 } catch (moodle_exception $ex) {
256 $this->assertInstanceOf('coding_exception', $ex);
258 try {
259 optional_param_array('', array('a'=>'default_user'), PARAM_RAW);
260 $this->fail('coding_exception expected');
261 } catch (moodle_exception $ex) {
262 $this->assertInstanceOf('coding_exception', $ex);
265 // Do not allow nested arrays.
266 try {
267 $_POST['username'] = array('a'=>array('b'=>'post_user'));
268 optional_param_array('username', array('a'=>'default_user'), PARAM_RAW);
269 $this->fail('coding_exception expected');
270 } catch (coding_exception $ex) {
271 $this->assertTrue(true);
274 // Do not allow non-arrays.
275 $_POST['username'] = 'post_user';
276 $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
277 $this->assertDebuggingCalled();
279 // Make sure array keys are sanitised.
280 $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
281 $this->assertSame(array('a1_-'=>'post_user'), optional_param_array('username', array(), PARAM_RAW));
282 $this->assertDebuggingCalled();
285 public function test_required_param() {
286 $_POST['username'] = 'post_user';
287 $_GET['username'] = 'get_user';
288 $this->assertSame('post_user', required_param('username', PARAM_RAW));
290 unset($_POST['username']);
291 $this->assertSame('get_user', required_param('username', PARAM_RAW));
293 unset($_GET['username']);
294 try {
295 $this->assertSame('default_user', required_param('username', PARAM_RAW));
296 $this->fail('moodle_exception expected');
297 } catch (moodle_exception $ex) {
298 $this->assertInstanceOf('moodle_exception', $ex);
301 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
302 $_POST['username'] = 'post_user';
303 try {
304 @required_param('username');
305 $this->fail('coding_exception expected');
306 } catch (moodle_exception $ex) {
307 $this->assertInstanceOf('coding_exception', $ex);
309 try {
310 required_param('username', '');
311 $this->fail('coding_exception expected');
312 } catch (moodle_exception $ex) {
313 $this->assertInstanceOf('coding_exception', $ex);
315 try {
316 required_param('', PARAM_RAW);
317 $this->fail('coding_exception expected');
318 } catch (moodle_exception $ex) {
319 $this->assertInstanceOf('coding_exception', $ex);
322 // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
323 $_POST['username'] = array('a'=>'a');
324 $this->assertSame($_POST['username'], required_param('username', PARAM_RAW));
325 $this->assertDebuggingCalled();
328 public function test_required_param_array() {
329 global $CFG;
331 $_POST['username'] = array('a'=>'post_user');
332 $_GET['username'] = array('a'=>'get_user');
333 $this->assertSame($_POST['username'], required_param_array('username', PARAM_RAW));
335 unset($_POST['username']);
336 $this->assertSame($_GET['username'], required_param_array('username', PARAM_RAW));
338 // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
339 $_POST['username'] = array('a'=>'post_user');
340 try {
341 required_param_array('username', null);
342 $this->fail('coding_exception expected');
343 } catch (moodle_exception $ex) {
344 $this->assertInstanceOf('coding_exception', $ex);
346 try {
347 @required_param_array('username');
348 $this->fail('coding_exception expected');
349 } catch (moodle_exception $ex) {
350 $this->assertInstanceOf('coding_exception', $ex);
352 try {
353 required_param_array('', PARAM_RAW);
354 $this->fail('coding_exception expected');
355 } catch (moodle_exception $ex) {
356 $this->assertInstanceOf('coding_exception', $ex);
359 // Do not allow nested arrays.
360 try {
361 $_POST['username'] = array('a'=>array('b'=>'post_user'));
362 required_param_array('username', PARAM_RAW);
363 $this->fail('coding_exception expected');
364 } catch (moodle_exception $ex) {
365 $this->assertInstanceOf('coding_exception', $ex);
368 // Do not allow non-arrays.
369 try {
370 $_POST['username'] = 'post_user';
371 required_param_array('username', PARAM_RAW);
372 $this->fail('moodle_exception expected');
373 } catch (moodle_exception $ex) {
374 $this->assertInstanceOf('moodle_exception', $ex);
377 // Make sure array keys are sanitised.
378 $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
379 $this->assertSame(array('a1_-'=>'post_user'), required_param_array('username', PARAM_RAW));
380 $this->assertDebuggingCalled();
383 public function test_clean_param() {
384 // Forbid objects and arrays.
385 try {
386 clean_param(array('x', 'y'), PARAM_RAW);
387 $this->fail('coding_exception expected');
388 } catch (moodle_exception $ex) {
389 $this->assertInstanceOf('coding_exception', $ex);
391 try {
392 $param = new stdClass();
393 $param->id = 1;
394 clean_param($param, PARAM_RAW);
395 $this->fail('coding_exception expected');
396 } catch (moodle_exception $ex) {
397 $this->assertInstanceOf('coding_exception', $ex);
400 // Require correct type.
401 try {
402 clean_param('x', 'xxxxxx');
403 $this->fail('moodle_exception expected');
404 } catch (moodle_exception $ex) {
405 $this->assertInstanceOf('moodle_exception', $ex);
407 try {
408 @clean_param('x');
409 $this->fail('moodle_exception expected');
410 } catch (moodle_exception $ex) {
411 $this->assertInstanceOf('moodle_exception', $ex);
415 public function test_clean_param_array() {
416 $this->assertSame(array(), clean_param_array(null, PARAM_RAW));
417 $this->assertSame(array('a', 'b'), clean_param_array(array('a', 'b'), PARAM_RAW));
418 $this->assertSame(array('a', array('b')), clean_param_array(array('a', array('b')), PARAM_RAW, true));
420 // Require correct type.
421 try {
422 clean_param_array(array('x'), 'xxxxxx');
423 $this->fail('moodle_exception expected');
424 } catch (moodle_exception $ex) {
425 $this->assertInstanceOf('moodle_exception', $ex);
427 try {
428 @clean_param_array(array('x'));
429 $this->fail('moodle_exception expected');
430 } catch (moodle_exception $ex) {
431 $this->assertInstanceOf('moodle_exception', $ex);
434 try {
435 clean_param_array(array('x', array('y')), PARAM_RAW);
436 $this->fail('coding_exception expected');
437 } catch (moodle_exception $ex) {
438 $this->assertInstanceOf('coding_exception', $ex);
441 // Test recursive.
444 public function test_clean_param_raw() {
445 $this->assertSame(
446 '#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)',
447 clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_RAW));
450 public function test_clean_param_trim() {
451 $this->assertSame('Frog toad', clean_param(" Frog toad \r\n ", PARAM_RAW_TRIMMED));
454 public function test_clean_param_clean() {
455 // PARAM_CLEAN is an ugly hack, do not use in new code (skodak),
456 // instead use more specific type, or submit sothing that can be verified properly.
457 $this->assertSame('xx', clean_param('xx<script>', PARAM_CLEAN));
460 public function test_clean_param_alpha() {
461 $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHA));
464 public function test_clean_param_alphanum() {
465 $this->assertSame('978942897DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHANUM));
468 public function test_clean_param_alphaext() {
469 $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHAEXT));
472 public function test_clean_param_sequence() {
473 $this->assertSame(',9789,42897', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_SEQUENCE));
476 public function test_clean_param_component() {
477 // Please note the cleaning of component names is very strict, no guessing here.
478 $this->assertSame('mod_forum', clean_param('mod_forum', PARAM_COMPONENT));
479 $this->assertSame('block_online_users', clean_param('block_online_users', PARAM_COMPONENT));
480 $this->assertSame('block_blond_online_users', clean_param('block_blond_online_users', PARAM_COMPONENT));
481 $this->assertSame('mod_something2', clean_param('mod_something2', PARAM_COMPONENT));
482 $this->assertSame('forum', clean_param('forum', PARAM_COMPONENT));
483 $this->assertSame('user', clean_param('user', PARAM_COMPONENT));
484 $this->assertSame('rating', clean_param('rating', PARAM_COMPONENT));
485 $this->assertSame('feedback360', clean_param('feedback360', PARAM_COMPONENT));
486 $this->assertSame('mod_feedback360', clean_param('mod_feedback360', PARAM_COMPONENT));
487 $this->assertSame('', clean_param('mod_2something', PARAM_COMPONENT));
488 $this->assertSame('', clean_param('2mod_something', PARAM_COMPONENT));
489 $this->assertSame('', clean_param('mod_something_xx', PARAM_COMPONENT));
490 $this->assertSame('', clean_param('auth_something__xx', PARAM_COMPONENT));
491 $this->assertSame('', clean_param('mod_Something', PARAM_COMPONENT));
492 $this->assertSame('', clean_param('mod_somethíng', PARAM_COMPONENT));
493 $this->assertSame('', clean_param('mod__something', PARAM_COMPONENT));
494 $this->assertSame('', clean_param('auth_xx-yy', PARAM_COMPONENT));
495 $this->assertSame('', clean_param('_auth_xx', PARAM_COMPONENT));
496 $this->assertSame('', clean_param('a2uth_xx', PARAM_COMPONENT));
497 $this->assertSame('', clean_param('auth_xx_', PARAM_COMPONENT));
498 $this->assertSame('', clean_param('auth_xx.old', PARAM_COMPONENT));
499 $this->assertSame('', clean_param('_user', PARAM_COMPONENT));
500 $this->assertSame('', clean_param('2rating', PARAM_COMPONENT));
501 $this->assertSame('', clean_param('user_', PARAM_COMPONENT));
504 public function test_is_valid_plugin_name() {
505 $this->assertTrue(is_valid_plugin_name('forum'));
506 $this->assertTrue(is_valid_plugin_name('forum2'));
507 $this->assertTrue(is_valid_plugin_name('feedback360'));
508 $this->assertTrue(is_valid_plugin_name('online_users'));
509 $this->assertTrue(is_valid_plugin_name('blond_online_users'));
510 $this->assertFalse(is_valid_plugin_name('online__users'));
511 $this->assertFalse(is_valid_plugin_name('forum '));
512 $this->assertFalse(is_valid_plugin_name('forum.old'));
513 $this->assertFalse(is_valid_plugin_name('xx-yy'));
514 $this->assertFalse(is_valid_plugin_name('2xx'));
515 $this->assertFalse(is_valid_plugin_name('Xx'));
516 $this->assertFalse(is_valid_plugin_name('_xx'));
517 $this->assertFalse(is_valid_plugin_name('xx_'));
520 public function test_clean_param_plugin() {
521 // Please note the cleaning of plugin names is very strict, no guessing here.
522 $this->assertSame('forum', clean_param('forum', PARAM_PLUGIN));
523 $this->assertSame('forum2', clean_param('forum2', PARAM_PLUGIN));
524 $this->assertSame('feedback360', clean_param('feedback360', PARAM_PLUGIN));
525 $this->assertSame('online_users', clean_param('online_users', PARAM_PLUGIN));
526 $this->assertSame('blond_online_users', clean_param('blond_online_users', PARAM_PLUGIN));
527 $this->assertSame('', clean_param('online__users', PARAM_PLUGIN));
528 $this->assertSame('', clean_param('forum ', PARAM_PLUGIN));
529 $this->assertSame('', clean_param('forum.old', PARAM_PLUGIN));
530 $this->assertSame('', clean_param('xx-yy', PARAM_PLUGIN));
531 $this->assertSame('', clean_param('2xx', PARAM_PLUGIN));
532 $this->assertSame('', clean_param('Xx', PARAM_PLUGIN));
533 $this->assertSame('', clean_param('_xx', PARAM_PLUGIN));
534 $this->assertSame('', clean_param('xx_', PARAM_PLUGIN));
537 public function test_clean_param_area() {
538 // Please note the cleaning of area names is very strict, no guessing here.
539 $this->assertSame('something', clean_param('something', PARAM_AREA));
540 $this->assertSame('something2', clean_param('something2', PARAM_AREA));
541 $this->assertSame('some_thing', clean_param('some_thing', PARAM_AREA));
542 $this->assertSame('some_thing_xx', clean_param('some_thing_xx', PARAM_AREA));
543 $this->assertSame('feedback360', clean_param('feedback360', PARAM_AREA));
544 $this->assertSame('', clean_param('_something', PARAM_AREA));
545 $this->assertSame('', clean_param('something_', PARAM_AREA));
546 $this->assertSame('', clean_param('2something', PARAM_AREA));
547 $this->assertSame('', clean_param('Something', PARAM_AREA));
548 $this->assertSame('', clean_param('some-thing', PARAM_AREA));
549 $this->assertSame('', clean_param('somethííng', PARAM_AREA));
550 $this->assertSame('', clean_param('something.x', PARAM_AREA));
553 public function test_clean_param_text() {
554 $this->assertSame(PARAM_TEXT, PARAM_MULTILANG);
555 // Standard.
556 $this->assertSame('xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>', clean_param('xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>', PARAM_TEXT));
557 $this->assertSame('<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>', clean_param('<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>', PARAM_TEXT));
558 $this->assertSame('xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>', clean_param('xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>', PARAM_TEXT));
559 // Malformed.
560 $this->assertSame('<span lang="en" class="multilang">aa</span>', clean_param('<span lang="en" class="multilang">aa</span>', PARAM_TEXT));
561 $this->assertSame('aa', clean_param('<span lang="en" class="nothing" class="multilang">aa</span>', PARAM_TEXT));
562 $this->assertSame('aa', clean_param('<lang lang="en" class="multilang">aa</lang>', PARAM_TEXT));
563 $this->assertSame('aa', clean_param('<lang lang="en!!">aa</lang>', PARAM_TEXT));
564 $this->assertSame('aa', clean_param('<span lang="en==" class="multilang">aa</span>', PARAM_TEXT));
565 $this->assertSame('abc', clean_param('a<em>b</em>c', PARAM_TEXT));
566 $this->assertSame('a>c>', clean_param('a><xx >c>', PARAM_TEXT)); // Standard strip_tags() behaviour.
567 $this->assertSame('a', clean_param('a<b', PARAM_TEXT));
568 $this->assertSame('a>b', clean_param('a>b', PARAM_TEXT));
569 $this->assertSame('<lang lang="en">a>a</lang>', clean_param('<lang lang="en">a>a</lang>', PARAM_TEXT)); // Standard strip_tags() behaviour.
570 $this->assertSame('a', clean_param('<lang lang="en">a<a</lang>', PARAM_TEXT));
571 $this->assertSame('<lang lang="en">aa</lang>', clean_param('<lang lang="en">a<br>a</lang>', PARAM_TEXT));
574 public function test_clean_param_url() {
575 // Test PARAM_URL and PARAM_LOCALURL a bit.
576 $this->assertSame('http://google.com/', clean_param('http://google.com/', PARAM_URL));
577 $this->assertSame('http://some.very.long.and.silly.domain/with/a/path/', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_URL));
578 $this->assertSame('http://localhost/', clean_param('http://localhost/', PARAM_URL));
579 $this->assertSame('http://0.255.1.1/numericip.php', clean_param('http://0.255.1.1/numericip.php', PARAM_URL));
580 $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_URL));
581 $this->assertSame('', clean_param('funny:thing', PARAM_URL));
584 public function test_clean_param_localurl() {
585 global $CFG;
587 $this->resetAfterTest();
589 // External, invalid.
590 $this->assertSame('', clean_param('funny:thing', PARAM_LOCALURL));
591 $this->assertSame('', clean_param('http://google.com/', PARAM_LOCALURL));
592 $this->assertSame('', clean_param('https://google.com/?test=true', PARAM_LOCALURL));
593 $this->assertSame('', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL));
595 // Local absolute.
596 $this->assertSame(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
597 $this->assertSame($CFG->wwwroot . '/with/something?else=true',
598 clean_param($CFG->wwwroot . '/with/something?else=true', PARAM_LOCALURL));
600 // Local relative.
601 $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_LOCALURL));
602 $this->assertSame('course/view.php?id=3', clean_param('course/view.php?id=3', PARAM_LOCALURL));
604 // Local absolute HTTPS.
605 $httpsroot = str_replace('http:', 'https:', $CFG->wwwroot);
606 $CFG->loginhttps = false;
607 $this->assertSame('', clean_param($httpsroot, PARAM_LOCALURL));
608 $this->assertSame('', clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL));
609 $CFG->loginhttps = true;
610 $this->assertSame($httpsroot, clean_param($httpsroot, PARAM_LOCALURL));
611 $this->assertSame($httpsroot . '/with/something?else=true',
612 clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL));
614 // Test open redirects are not possible.
615 $CFG->loginhttps = false;
616 $CFG->wwwroot = 'http://www.example.com';
617 $this->assertSame('', clean_param('http://www.example.com.evil.net/hack.php', PARAM_LOCALURL));
618 $CFG->loginhttps = true;
619 $this->assertSame('', clean_param('https://www.example.com.evil.net/hack.php', PARAM_LOCALURL));
622 public function test_clean_param_file() {
623 $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_FILE));
624 $this->assertSame('badfile.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE));
625 $this->assertSame('..parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_FILE));
626 $this->assertSame('....grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_FILE));
627 $this->assertSame('..winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_FILE));
628 $this->assertSame('....wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_FILE));
629 $this->assertSame('myfile.a.b.txt', clean_param('myfile.a.b.txt', PARAM_FILE));
630 $this->assertSame('myfile..a..b.txt', clean_param('myfile..a..b.txt', PARAM_FILE));
631 $this->assertSame('myfile.a..b...txt', clean_param('myfile.a..b...txt', PARAM_FILE));
632 $this->assertSame('myfile.a.txt', clean_param('myfile.a.txt', PARAM_FILE));
633 $this->assertSame('myfile...txt', clean_param('myfile...txt', PARAM_FILE));
634 $this->assertSame('...jpg', clean_param('...jpg', PARAM_FILE));
635 $this->assertSame('.a.b.', clean_param('.a.b.', PARAM_FILE));
636 $this->assertSame('', clean_param('.', PARAM_FILE));
637 $this->assertSame('', clean_param('..', PARAM_FILE));
638 $this->assertSame('...', clean_param('...', PARAM_FILE));
639 $this->assertSame('. . . .', clean_param('. . . .', PARAM_FILE));
640 $this->assertSame('dontrtrim.me. .. .. . ', clean_param('dontrtrim.me. .. .. . ', PARAM_FILE));
641 $this->assertSame(' . .dontltrim.me', clean_param(' . .dontltrim.me', PARAM_FILE));
642 $this->assertSame('here is a tab.txt', clean_param("here is a tab\t.txt", PARAM_FILE));
643 $this->assertSame('here is a linebreak.txt', clean_param("here is a line\r\nbreak.txt", PARAM_FILE));
645 // The following behaviours have been maintained although they seem a little odd.
646 $this->assertSame('funnything', clean_param('funny:thing', PARAM_FILE));
647 $this->assertSame('.currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_FILE));
648 $this->assertSame('ctempwindowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_FILE));
649 $this->assertSame('homeuserlinuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_FILE));
650 $this->assertSame('~myfile.txt', clean_param('~/myfile.txt', PARAM_FILE));
653 public function test_clean_param_path() {
654 $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_PATH));
655 $this->assertSame('bad/file.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH));
656 $this->assertSame('/parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_PATH));
657 $this->assertSame('/grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_PATH));
658 $this->assertSame('/winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_PATH));
659 $this->assertSame('/wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_PATH));
660 $this->assertSame('funnything', clean_param('funny:thing', PARAM_PATH));
661 $this->assertSame('./here', clean_param('./././here', PARAM_PATH));
662 $this->assertSame('./currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_PATH));
663 $this->assertSame('c/temp/windowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_PATH));
664 $this->assertSame('/home/user/linuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_PATH));
665 $this->assertSame('/home../user ./.linuxfile.txt', clean_param('/home../user ./.linuxfile.txt', PARAM_PATH));
666 $this->assertSame('~/myfile.txt', clean_param('~/myfile.txt', PARAM_PATH));
667 $this->assertSame('~/myfile.txt', clean_param('~/../myfile.txt', PARAM_PATH));
668 $this->assertSame('/..b../.../myfile.txt', clean_param('/..b../.../myfile.txt', PARAM_PATH));
669 $this->assertSame('..b../.../myfile.txt', clean_param('..b../.../myfile.txt', PARAM_PATH));
670 $this->assertSame('/super/slashes/', clean_param('/super//slashes///', PARAM_PATH));
673 public function test_clean_param_username() {
674 global $CFG;
675 $currentstatus = $CFG->extendedusernamechars;
677 // Run tests with extended character == false;.
678 $CFG->extendedusernamechars = false;
679 $this->assertSame('johndoe123', clean_param('johndoe123', PARAM_USERNAME) );
680 $this->assertSame('john.doe', clean_param('john.doe', PARAM_USERNAME));
681 $this->assertSame('john-doe', clean_param('john-doe', PARAM_USERNAME));
682 $this->assertSame('john-doe', clean_param('john- doe', PARAM_USERNAME));
683 $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
684 $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
685 $this->assertSame('johndoe', clean_param('john~doe', PARAM_USERNAME));
686 $this->assertSame('johndoe', clean_param('john´doe', PARAM_USERNAME));
687 $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john_');
688 $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john_');
689 $this->assertSame(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
690 $this->assertSame('johnd', clean_param('JOHNdóé ', PARAM_USERNAME));
691 $this->assertSame(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýáž?žý??šdoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
693 // Test success condition, if extendedusernamechars == ENABLE;.
694 $CFG->extendedusernamechars = true;
695 $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
696 $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
697 $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john# $%&()+_^');
698 $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john# $%&()+_^');
699 $this->assertSame('john~doe', clean_param('john~doe', PARAM_USERNAME));
700 $this->assertSame('john´doe', clean_param('joHN´doe', PARAM_USERNAME));
701 $this->assertSame('johndoe', clean_param('johnDOE', PARAM_USERNAME));
702 $this->assertSame('johndóé', clean_param('johndóé ', PARAM_USERNAME));
704 $CFG->extendedusernamechars = $currentstatus;
707 public function test_clean_param_stringid() {
708 // Test string identifiers validation.
709 // Valid strings.
710 $this->assertSame('validstring', clean_param('validstring', PARAM_STRINGID));
711 $this->assertSame('mod/foobar:valid_capability', clean_param('mod/foobar:valid_capability', PARAM_STRINGID));
712 $this->assertSame('CZ', clean_param('CZ', PARAM_STRINGID));
713 $this->assertSame('application/vnd.ms-powerpoint', clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID));
714 $this->assertSame('grade2', clean_param('grade2', PARAM_STRINGID));
715 // Invalid strings.
716 $this->assertSame('', clean_param('trailing ', PARAM_STRINGID));
717 $this->assertSame('', clean_param('space bar', PARAM_STRINGID));
718 $this->assertSame('', clean_param('0numeric', PARAM_STRINGID));
719 $this->assertSame('', clean_param('*', PARAM_STRINGID));
720 $this->assertSame('', clean_param(' ', PARAM_STRINGID));
723 public function test_clean_param_timezone() {
724 // Test timezone validation.
725 $testvalues = array (
726 'America/Jamaica' => 'America/Jamaica',
727 'America/Argentina/Cordoba' => 'America/Argentina/Cordoba',
728 'America/Port-au-Prince' => 'America/Port-au-Prince',
729 'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
730 'PST8PDT' => 'PST8PDT',
731 'Wrong.Value' => '',
732 'Wrong/.Value' => '',
733 'Wrong(Value)' => '',
734 '0' => '0',
735 '0.0' => '0.0',
736 '0.5' => '0.5',
737 '9.0' => '9.0',
738 '-9.0' => '-9.0',
739 '+9.0' => '+9.0',
740 '9.5' => '9.5',
741 '-9.5' => '-9.5',
742 '+9.5' => '+9.5',
743 '12.0' => '12.0',
744 '-12.0' => '-12.0',
745 '+12.0' => '+12.0',
746 '12.5' => '12.5',
747 '-12.5' => '-12.5',
748 '+12.5' => '+12.5',
749 '13.0' => '13.0',
750 '-13.0' => '-13.0',
751 '+13.0' => '+13.0',
752 '13.5' => '',
753 '+13.5' => '',
754 '-13.5' => '',
755 '0.2' => '');
757 foreach ($testvalues as $testvalue => $expectedvalue) {
758 $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
759 $this->assertEquals($expectedvalue, $actualvalue);
763 public function test_validate_param() {
764 try {
765 $param = validate_param('11a', PARAM_INT);
766 $this->fail('invalid_parameter_exception expected');
767 } catch (moodle_exception $ex) {
768 $this->assertInstanceOf('invalid_parameter_exception', $ex);
771 $param = validate_param('11', PARAM_INT);
772 $this->assertSame(11, $param);
774 try {
775 $param = validate_param(null, PARAM_INT, false);
776 $this->fail('invalid_parameter_exception expected');
777 } catch (moodle_exception $ex) {
778 $this->assertInstanceOf('invalid_parameter_exception', $ex);
781 $param = validate_param(null, PARAM_INT, true);
782 $this->assertSame(null, $param);
784 try {
785 $param = validate_param(array(), PARAM_INT);
786 $this->fail('invalid_parameter_exception expected');
787 } catch (moodle_exception $ex) {
788 $this->assertInstanceOf('invalid_parameter_exception', $ex);
790 try {
791 $param = validate_param(new stdClass, PARAM_INT);
792 $this->fail('invalid_parameter_exception expected');
793 } catch (moodle_exception $ex) {
794 $this->assertInstanceOf('invalid_parameter_exception', $ex);
797 $param = validate_param('1.0', PARAM_FLOAT);
798 $this->assertSame(1.0, $param);
800 // Make sure valid floats do not cause exception.
801 validate_param(1.0, PARAM_FLOAT);
802 validate_param(10, PARAM_FLOAT);
803 validate_param('0', PARAM_FLOAT);
804 validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
805 validate_param('011.1', PARAM_FLOAT);
806 validate_param('11', PARAM_FLOAT);
807 validate_param('+.1', PARAM_FLOAT);
808 validate_param('-.1', PARAM_FLOAT);
809 validate_param('1e10', PARAM_FLOAT);
810 validate_param('.1e+10', PARAM_FLOAT);
811 validate_param('1E-1', PARAM_FLOAT);
813 try {
814 $param = validate_param('1,2', PARAM_FLOAT);
815 $this->fail('invalid_parameter_exception expected');
816 } catch (moodle_exception $ex) {
817 $this->assertInstanceOf('invalid_parameter_exception', $ex);
819 try {
820 $param = validate_param('', PARAM_FLOAT);
821 $this->fail('invalid_parameter_exception expected');
822 } catch (moodle_exception $ex) {
823 $this->assertInstanceOf('invalid_parameter_exception', $ex);
825 try {
826 $param = validate_param('.', PARAM_FLOAT);
827 $this->fail('invalid_parameter_exception expected');
828 } catch (moodle_exception $ex) {
829 $this->assertInstanceOf('invalid_parameter_exception', $ex);
831 try {
832 $param = validate_param('e10', PARAM_FLOAT);
833 $this->fail('invalid_parameter_exception expected');
834 } catch (moodle_exception $ex) {
835 $this->assertInstanceOf('invalid_parameter_exception', $ex);
837 try {
838 $param = validate_param('abc', PARAM_FLOAT);
839 $this->fail('invalid_parameter_exception expected');
840 } catch (moodle_exception $ex) {
841 $this->assertInstanceOf('invalid_parameter_exception', $ex);
845 public function test_shorten_text_no_tags_already_short_enough() {
846 // ......12345678901234567890123456.
847 $text = "short text already no tags";
848 $this->assertSame($text, shorten_text($text));
851 public function test_shorten_text_with_tags_already_short_enough() {
852 // .........123456...7890....12345678.......901234567.
853 $text = "<p>short <b>text</b> already</p><p>with tags</p>";
854 $this->assertSame($text, shorten_text($text));
857 public function test_shorten_text_no_tags_needs_shortening() {
858 // Default truncation is after 30 chars, but allowing 3 for the final '...'.
859 // ......12345678901234567890123456789023456789012345678901234.
860 $text = "long text without any tags blah de blah blah blah what";
861 $this->assertSame('long text without any tags ...', shorten_text($text));
864 public function test_shorten_text_with_tags_needs_shortening() {
865 // .......................................123456789012345678901234567890...
866 $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
867 "be chopped off but <b>should be added back again</b></blockquote></p></div>";
868 $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
869 "tags that ...</blockquote></p></div>", shorten_text($text));
872 public function test_shorten_text_with_entities() {
873 // Remember to allow 3 chars for the final '...'.
874 // ......123456789012345678901234567_____890...
875 $text = "some text which shouldn't &nbsp; break there";
876 $this->assertSame("some text which shouldn't &nbsp; ...", shorten_text($text, 31));
877 $this->assertSame("some text which shouldn't &nbsp;...", shorten_text($text, 30));
878 $this->assertSame("some text which shouldn't ...", shorten_text($text, 29));
881 public function test_shorten_text_known_tricky_case() {
882 // This case caused a bug up to 1.9.5
883 // ..........123456789012345678901234567890123456789.....0_____1___2___...
884 $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
885 $this->assertSame("<h3>standard 'break-out' sub groups in ...</h3>",
886 shorten_text($text, 41));
887 $this->assertSame("<h3>standard 'break-out' sub groups in TGs?...</h3>",
888 shorten_text($text, 42));
889 $this->assertSame("<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;...",
890 shorten_text($text, 43));
893 public function test_shorten_text_no_spaces() {
894 // ..........123456789.
895 $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
896 $this->assertSame("<h1>12345...</h1>", shorten_text($text, 8));
899 public function test_shorten_text_utf8_european() {
900 // Text without tags.
901 // ......123456789012345678901234567.
902 $text = "Žluťoučký koníček přeskočil";
903 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
904 $this->assertSame("Žluťoučký koníče...", shorten_text($text, 19, true));
905 $this->assertSame("Žluťoučký ...", shorten_text($text, 19, false));
906 // And try it with 2-less (that are, in bytes, the middle of a sequence).
907 $this->assertSame("Žluťoučký koní...", shorten_text($text, 17, true));
908 $this->assertSame("Žluťoučký ...", shorten_text($text, 17, false));
910 // .........123456789012345678...901234567....89012345.
911 $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
912 $this->assertSame($text, shorten_text($text, 60));
913 $this->assertSame("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
914 $this->assertSame("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
915 $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
916 // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
917 $this->assertSame("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
918 $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
919 // And try over one tag (start/end), it does proper text len.
920 $this->assertSame("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
921 $this->assertSame("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
922 // And in the middle of one tag.
923 $this->assertSame("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
926 public function test_shorten_text_utf8_oriental() {
927 // Japanese
928 // text without tags
929 // ......123456789012345678901234.
930 $text = '言語設定言語設定abcdefghijkl';
931 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
932 $this->assertSame("言語設定言語...", shorten_text($text, 9, true));
933 $this->assertSame("言語設定言語...", shorten_text($text, 9, false));
934 $this->assertSame("言語設定言語設定ab...", shorten_text($text, 13, true));
935 $this->assertSame("言語設定言語設定...", shorten_text($text, 13, false));
937 // Chinese
938 // text without tags
939 // ......123456789012345678901234.
940 $text = '简体中文简体中文abcdefghijkl';
941 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
942 $this->assertSame("简体中文简体...", shorten_text($text, 9, true));
943 $this->assertSame("简体中文简体...", shorten_text($text, 9, false));
944 $this->assertSame("简体中文简体中文ab...", shorten_text($text, 13, true));
945 $this->assertSame("简体中文简体中文...", shorten_text($text, 13, false));
948 public function test_shorten_text_multilang() {
949 // This is not necessaryily specific to multilang. The issue is really
950 // tags with attributes, where before we were generating invalid HTML
951 // output like shorten_text('<span id="x" class="y">A</span> B', 1)
952 // returning '<span id="x" ...</span>'. It is just that multilang
953 // requires the sort of HTML that is quite likely to trigger this.
954 // ........................................1...
955 $text = '<span lang="en" class="multilang">A</span>' .
956 '<span lang="fr" class="multilang">B</span>';
957 $this->assertSame('<span lang="en" class="multilang">...</span>',
958 shorten_text($text, 1));
961 public function test_usergetdate() {
962 global $USER, $CFG, $DB;
963 $this->resetAfterTest();
965 $this->setAdminUser();
967 $USER->timezone = 2;// Set the timezone to a known state.
969 $ts = 1261540267; // The time this function was created.
971 $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
972 $arr = array_values($arr);
974 list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
975 $this->assertSame(7, $seconds);
976 $this->assertSame(51, $minutes);
977 $this->assertSame(4, $hours);
978 $this->assertSame(23, $mday);
979 $this->assertSame(3, $wday);
980 $this->assertSame(12, $mon);
981 $this->assertSame(2009, $year);
982 $this->assertSame(356, $yday);
983 $this->assertSame('Wednesday', $weekday);
984 $this->assertSame('December', $month);
985 $arr = usergetdate($ts); // Gets the timezone from the $USER object.
986 $arr = array_values($arr);
988 list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
989 $this->assertSame(7, $seconds);
990 $this->assertSame(51, $minutes);
991 $this->assertSame(5, $hours);
992 $this->assertSame(23, $mday);
993 $this->assertSame(3, $wday);
994 $this->assertSame(12, $mon);
995 $this->assertSame(2009, $year);
996 $this->assertSame(356, $yday);
997 $this->assertSame('Wednesday', $weekday);
998 $this->assertSame('December', $month);
1001 public function test_mark_user_preferences_changed() {
1002 $this->resetAfterTest();
1003 $otheruser = $this->getDataGenerator()->create_user();
1004 $otheruserid = $otheruser->id;
1006 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1007 mark_user_preferences_changed($otheruserid);
1009 $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1010 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1013 public function test_check_user_preferences_loaded() {
1014 global $DB;
1015 $this->resetAfterTest();
1017 $otheruser = $this->getDataGenerator()->create_user();
1018 $otheruserid = $otheruser->id;
1020 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1021 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1023 $user = new stdClass();
1024 $user->id = $otheruserid;
1026 // Load.
1027 check_user_preferences_loaded($user);
1028 $this->assertTrue(isset($user->preference));
1029 $this->assertTrue(is_array($user->preference));
1030 $this->assertArrayHasKey('_lastloaded', $user->preference);
1031 $this->assertCount(1, $user->preference);
1033 // Add preference via direct call.
1034 $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1036 // No cache reload yet.
1037 check_user_preferences_loaded($user);
1038 $this->assertCount(1, $user->preference);
1040 // Forced reloading of cache.
1041 unset($user->preference);
1042 check_user_preferences_loaded($user);
1043 $this->assertCount(2, $user->preference);
1044 $this->assertSame('yyy', $user->preference['xxx']);
1046 // Add preference via direct call.
1047 $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1049 // Test timeouts and modifications from different session.
1050 set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1051 $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1052 check_user_preferences_loaded($user);
1053 $this->assertCount(2, $user->preference);
1054 check_user_preferences_loaded($user, 10);
1055 $this->assertCount(3, $user->preference);
1056 $this->assertSame('bbb', $user->preference['aaa']);
1057 set_cache_flag('userpreferenceschanged', $user->id, null);
1060 public function test_set_user_preference() {
1061 global $DB, $USER;
1062 $this->resetAfterTest();
1064 $this->setAdminUser();
1066 $otheruser = $this->getDataGenerator()->create_user();
1067 $otheruserid = $otheruser->id;
1069 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1070 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1072 $user = new stdClass();
1073 $user->id = $otheruserid;
1075 set_user_preference('aaa', 'bbb', $otheruserid);
1076 $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1077 $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
1079 set_user_preference('xxx', 'yyy', $user);
1080 $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1081 $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
1082 $this->assertTrue(is_array($user->preference));
1083 $this->assertSame('bbb', $user->preference['aaa']);
1084 $this->assertSame('yyy', $user->preference['xxx']);
1086 set_user_preference('xxx', null, $user);
1087 $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1088 $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
1090 set_user_preference('ooo', true, $user);
1091 $prefs = get_user_preferences(null, null, $otheruserid);
1092 $this->assertSame($user->preference['aaa'], $prefs['aaa']);
1093 $this->assertSame($user->preference['ooo'], $prefs['ooo']);
1094 $this->assertSame('1', $prefs['ooo']);
1096 set_user_preference('null', 0, $user);
1097 $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1099 $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1101 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1102 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1104 // Test $USER default.
1105 set_user_preference('_test_user_preferences_pref', 'ok');
1106 $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1107 unset_user_preference('_test_user_preferences_pref');
1108 $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1110 // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
1111 $longvalue = str_repeat('a', 1333);
1112 set_user_preference('_test_long_user_preference', $longvalue);
1113 $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1114 $this->assertEquals($longvalue,
1115 $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1117 // Test > 1333 char values, coding_exception expected.
1118 $longvalue = str_repeat('a', 1334);
1119 try {
1120 set_user_preference('_test_long_user_preference', $longvalue);
1121 $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1122 } catch (moodle_exception $ex) {
1123 $this->assertInstanceOf('coding_exception', $ex);
1126 // Test invalid params.
1127 try {
1128 set_user_preference('_test_user_preferences_pref', array());
1129 $this->fail('Exception expected - array not valid preference value');
1130 } catch (moodle_exception $ex) {
1131 $this->assertInstanceOf('coding_exception', $ex);
1133 try {
1134 set_user_preference('_test_user_preferences_pref', new stdClass);
1135 $this->fail('Exception expected - class not valid preference value');
1136 } catch (moodle_exception $ex) {
1137 $this->assertInstanceOf('coding_exception', $ex);
1139 try {
1140 set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1141 $this->fail('Exception expected - user instance expected');
1142 } catch (moodle_exception $ex) {
1143 $this->assertInstanceOf('coding_exception', $ex);
1145 try {
1146 set_user_preference('_test_user_preferences_pref', 1, 'abc');
1147 $this->fail('Exception expected - user instance expected');
1148 } catch (moodle_exception $ex) {
1149 $this->assertInstanceOf('coding_exception', $ex);
1151 try {
1152 set_user_preference('', 1);
1153 $this->fail('Exception expected - invalid name accepted');
1154 } catch (moodle_exception $ex) {
1155 $this->assertInstanceOf('coding_exception', $ex);
1157 try {
1158 set_user_preference('1', 1);
1159 $this->fail('Exception expected - invalid name accepted');
1160 } catch (moodle_exception $ex) {
1161 $this->assertInstanceOf('coding_exception', $ex);
1165 public function test_get_extra_user_fields() {
1166 global $CFG, $USER, $DB;
1167 $this->resetAfterTest();
1169 $this->setAdminUser();
1171 // It would be really nice if there were a way to 'mock' has_capability
1172 // checks (either to return true or false) but as there is not, this
1173 // test doesn't test the capability check. Presumably, anyone running
1174 // unit tests will have the capability.
1175 $context = context_system::instance();
1177 // No fields.
1178 $CFG->showuseridentity = '';
1179 $this->assertEquals(array(), get_extra_user_fields($context));
1181 // One field.
1182 $CFG->showuseridentity = 'frog';
1183 $this->assertEquals(array('frog'), get_extra_user_fields($context));
1185 // Two fields.
1186 $CFG->showuseridentity = 'frog,zombie';
1187 $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1189 // No fields, except.
1190 $CFG->showuseridentity = '';
1191 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1193 // One field.
1194 $CFG->showuseridentity = 'frog';
1195 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1197 // Two fields.
1198 $CFG->showuseridentity = 'frog,zombie';
1199 $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1202 public function test_get_extra_user_fields_sql() {
1203 global $CFG, $USER, $DB;
1204 $this->resetAfterTest();
1206 $this->setAdminUser();
1208 $context = context_system::instance();
1210 // No fields.
1211 $CFG->showuseridentity = '';
1212 $this->assertSame('', get_extra_user_fields_sql($context));
1214 // One field.
1215 $CFG->showuseridentity = 'frog';
1216 $this->assertSame(', frog', get_extra_user_fields_sql($context));
1218 // Two fields with table prefix.
1219 $CFG->showuseridentity = 'frog,zombie';
1220 $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1222 // Two fields with field prefix.
1223 $CFG->showuseridentity = 'frog,zombie';
1224 $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
1225 get_extra_user_fields_sql($context, '', 'u_'));
1227 // One field excluded.
1228 $CFG->showuseridentity = 'frog';
1229 $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
1231 // Two fields, one excluded, table+field prefix.
1232 $CFG->showuseridentity = 'frog,zombie';
1233 $this->assertEquals(', u1.zombie AS u_zombie',
1234 get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1238 * Test some critical TZ/DST.
1240 * This method tests some special TZ/DST combinations that were fixed
1241 * by MDL-38999. The tests are done by comparing the results of the
1242 * output using Moodle TZ/DST support and PHP native one.
1244 * Note: If you don't trust PHP TZ/DST support, can verify the
1245 * harcoded expectations below with:
1246 * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
1248 public function test_some_moodle_special_dst() {
1249 $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
1251 // In Europe/Tallinn it was 2013/04/08 05:00:00.
1252 $expectation = '2013/04/08 05:00:00';
1253 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1254 $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1255 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1256 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1257 $this->assertSame($expectation, $phpres);
1258 $this->assertSame($expectation, $moodleres);
1260 // In St. Johns it was 2013/04/07 23:30:00.
1261 $expectation = '2013/04/07 23:30:00';
1262 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1263 $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1264 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1265 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1266 $this->assertSame($expectation, $phpres);
1267 $this->assertSame($expectation, $moodleres);
1269 $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1271 // In Europe/Tallinn it was 2013/11/08 04:00:00.
1272 $expectation = '2013/11/08 04:00:00';
1273 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1274 $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1275 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1276 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1277 $this->assertSame($expectation, $phpres);
1278 $this->assertSame($expectation, $moodleres);
1280 // In St. Johns it was 2013/11/07 22:30:00.
1281 $expectation = '2013/11/07 22:30:00';
1282 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1283 $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1284 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1285 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1286 $this->assertSame($expectation, $phpres);
1287 $this->assertSame($expectation, $moodleres);
1290 public function test_userdate() {
1291 global $USER, $CFG, $DB;
1292 $this->resetAfterTest();
1294 $this->setAdminUser();
1296 $testvalues = array(
1297 array(
1298 'time' => '1309514400',
1299 'usertimezone' => 'America/Moncton',
1300 'timezone' => '0.0', // No dst offset.
1301 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1303 array(
1304 'time' => '1309514400',
1305 'usertimezone' => 'America/Moncton',
1306 'timezone' => '99', // Dst offset and timezone offset.
1307 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1309 array(
1310 'time' => '1309514400',
1311 'usertimezone' => 'America/Moncton',
1312 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
1313 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1315 array(
1316 'time' => '1293876000 ',
1317 'usertimezone' => 'America/Moncton',
1318 'timezone' => '0.0', // No dst offset.
1319 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1321 array(
1322 'time' => '1293876000 ',
1323 'usertimezone' => 'America/Moncton',
1324 'timezone' => '99', // No dst offset in jan, so just timezone offset.
1325 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1327 array(
1328 'time' => '1293876000 ',
1329 'usertimezone' => 'America/Moncton',
1330 'timezone' => 'America/Moncton', // No dst offset in jan.
1331 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1333 array(
1334 'time' => '1293876000 ',
1335 'usertimezone' => '2',
1336 'timezone' => '99', // Take user timezone.
1337 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1339 array(
1340 'time' => '1293876000 ',
1341 'usertimezone' => '-2',
1342 'timezone' => '99', // Take user timezone.
1343 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1345 array(
1346 'time' => '1293876000 ',
1347 'usertimezone' => '-10',
1348 'timezone' => '2', // Take this timezone.
1349 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1351 array(
1352 'time' => '1293876000 ',
1353 'usertimezone' => '-10',
1354 'timezone' => '-2', // Take this timezone.
1355 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1357 array(
1358 'time' => '1293876000 ',
1359 'usertimezone' => '-10',
1360 'timezone' => 'random/time', // This should show server time.
1361 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1363 array(
1364 'time' => '1293876000 ',
1365 'usertimezone' => '20', // Fallback to server time zone.
1366 'timezone' => '99', // This should show user time.
1367 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1371 // Set default timezone to Australia/Perth, else time calculated
1372 // will not match expected values.
1373 $this->setTimezone(99, 'Australia/Perth');
1375 foreach ($testvalues as $vals) {
1376 $USER->timezone = $vals['usertimezone'];
1377 $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1379 // On different systems case of AM PM changes so compare case insensitive.
1380 $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1381 $actualoutput = core_text::strtolower($actualoutput);
1383 $this->assertSame($vals['expectedoutput'], $actualoutput,
1384 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput} \ndata: " . var_export($vals, true));
1389 * Make sure the DST changes happen at the right time in Moodle.
1391 public function test_dst_changes() {
1392 // DST switching in Prague.
1393 // From 2AM to 3AM in 1989.
1394 $date = new DateTime('1989-03-26T01:59:00+01:00');
1395 $this->assertSame('Sunday, 26 March 1989, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1396 $date = new DateTime('1989-03-26T02:01:00+01:00');
1397 $this->assertSame('Sunday, 26 March 1989, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1398 // From 3AM to 2AM in 1989 - not the same as the west Europe.
1399 $date = new DateTime('1989-09-24T01:59:00+01:00');
1400 $this->assertSame('Sunday, 24 September 1989, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1401 $date = new DateTime('1989-09-24T02:01:00+01:00');
1402 $this->assertSame('Sunday, 24 September 1989, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1403 // From 2AM to 3AM in 2014.
1404 $date = new DateTime('2014-03-30T01:59:00+01:00');
1405 $this->assertSame('Sunday, 30 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1406 $date = new DateTime('2014-03-30T02:01:00+01:00');
1407 $this->assertSame('Sunday, 30 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1408 // From 3AM to 2AM in 2014.
1409 $date = new DateTime('2014-10-26T01:59:00+01:00');
1410 $this->assertSame('Sunday, 26 October 2014, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1411 $date = new DateTime('2014-10-26T02:01:00+01:00');
1412 $this->assertSame('Sunday, 26 October 2014, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1413 // From 2AM to 3AM in 2020.
1414 $date = new DateTime('2020-03-29T01:59:00+01:00');
1415 $this->assertSame('Sunday, 29 March 2020, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1416 $date = new DateTime('2020-03-29T02:01:00+01:00');
1417 $this->assertSame('Sunday, 29 March 2020, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1418 // From 3AM to 2AM in 2020.
1419 $date = new DateTime('2020-10-25T01:59:00+01:00');
1420 $this->assertSame('Sunday, 25 October 2020, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1421 $date = new DateTime('2020-10-25T02:01:00+01:00');
1422 $this->assertSame('Sunday, 25 October 2020, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1424 // DST switching in NZ.
1425 // From 3AM to 2AM in 2015.
1426 $date = new DateTime('2015-04-05T02:59:00+13:00');
1427 $this->assertSame('Sunday, 5 April 2015, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1428 $date = new DateTime('2015-04-05T03:01:00+13:00');
1429 $this->assertSame('Sunday, 5 April 2015, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1430 // From 2AM to 3AM in 2009.
1431 $date = new DateTime('2015-09-27T01:59:00+12:00');
1432 $this->assertSame('Sunday, 27 September 2015, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1433 $date = new DateTime('2015-09-27T02:01:00+12:00');
1434 $this->assertSame('Sunday, 27 September 2015, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1436 // DST switching in Perth.
1437 // From 3AM to 2AM in 2009.
1438 $date = new DateTime('2008-03-30T01:59:00+08:00');
1439 $this->assertSame('Sunday, 30 March 2008, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1440 $date = new DateTime('2008-03-30T02:01:00+08:00');
1441 $this->assertSame('Sunday, 30 March 2008, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1442 // From 2AM to 3AM in 2009.
1443 $date = new DateTime('2008-10-26T01:59:00+08:00');
1444 $this->assertSame('Sunday, 26 October 2008, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1445 $date = new DateTime('2008-10-26T02:01:00+08:00');
1446 $this->assertSame('Sunday, 26 October 2008, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1448 // DST switching in US.
1449 // From 2AM to 3AM in 2014.
1450 $date = new DateTime('2014-03-09T01:59:00-05:00');
1451 $this->assertSame('Sunday, 9 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1452 $date = new DateTime('2014-03-09T02:01:00-05:00');
1453 $this->assertSame('Sunday, 9 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1454 // From 3AM to 2AM in 2014.
1455 $date = new DateTime('2014-11-02T01:59:00-04:00');
1456 $this->assertSame('Sunday, 2 November 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1457 $date = new DateTime('2014-11-02T02:01:00-04:00');
1458 $this->assertSame('Sunday, 2 November 2014, 01:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1461 public function test_make_timestamp() {
1462 global $USER, $CFG, $DB;
1463 $this->resetAfterTest();
1465 $this->setAdminUser();
1467 $testvalues = array(
1468 array(
1469 'usertimezone' => 'America/Moncton',
1470 'year' => '2011',
1471 'month' => '7',
1472 'day' => '1',
1473 'hour' => '10',
1474 'minutes' => '00',
1475 'seconds' => '00',
1476 'timezone' => '0.0',
1477 'applydst' => false, // No dst offset.
1478 'expectedoutput' => '1309514400' // 6pm at UTC+0.
1480 array(
1481 'usertimezone' => 'America/Moncton',
1482 'year' => '2011',
1483 'month' => '7',
1484 'day' => '1',
1485 'hour' => '10',
1486 'minutes' => '00',
1487 'seconds' => '00',
1488 'timezone' => '99', // User default timezone.
1489 'applydst' => false, // Don't apply dst.
1490 'expectedoutput' => '1309528800'
1492 array(
1493 'usertimezone' => 'America/Moncton',
1494 'year' => '2011',
1495 'month' => '7',
1496 'day' => '1',
1497 'hour' => '10',
1498 'minutes' => '00',
1499 'seconds' => '00',
1500 'timezone' => '99', // User default timezone.
1501 'applydst' => true, // Apply dst.
1502 'expectedoutput' => '1309525200'
1504 array(
1505 'usertimezone' => 'America/Moncton',
1506 'year' => '2011',
1507 'month' => '7',
1508 'day' => '1',
1509 'hour' => '10',
1510 'minutes' => '00',
1511 'seconds' => '00',
1512 'timezone' => 'America/Moncton', // String timezone.
1513 'applydst' => true, // Apply dst.
1514 'expectedoutput' => '1309525200'
1516 array(
1517 'usertimezone' => '2', // No dst applyed.
1518 'year' => '2011',
1519 'month' => '7',
1520 'day' => '1',
1521 'hour' => '10',
1522 'minutes' => '00',
1523 'seconds' => '00',
1524 'timezone' => '99', // Take user timezone.
1525 'applydst' => true, // Apply dst.
1526 'expectedoutput' => '1309507200'
1528 array(
1529 'usertimezone' => '-2', // No dst applyed.
1530 'year' => '2011',
1531 'month' => '7',
1532 'day' => '1',
1533 'hour' => '10',
1534 'minutes' => '00',
1535 'seconds' => '00',
1536 'timezone' => '99', // Take usertimezone.
1537 'applydst' => true, // Apply dst.
1538 'expectedoutput' => '1309521600'
1540 array(
1541 'usertimezone' => '-10', // No dst applyed.
1542 'year' => '2011',
1543 'month' => '7',
1544 'day' => '1',
1545 'hour' => '10',
1546 'minutes' => '00',
1547 'seconds' => '00',
1548 'timezone' => '2', // Take this timezone.
1549 'applydst' => true, // Apply dst.
1550 'expectedoutput' => '1309507200'
1552 array(
1553 'usertimezone' => '-10', // No dst applyed.
1554 'year' => '2011',
1555 'month' => '7',
1556 'day' => '1',
1557 'hour' => '10',
1558 'minutes' => '00',
1559 'seconds' => '00',
1560 'timezone' => '-2', // Take this timezone.
1561 'applydst' => true, // Apply dst.
1562 'expectedoutput' => '1309521600'
1564 array(
1565 'usertimezone' => '-10', // No dst applyed.
1566 'year' => '2011',
1567 'month' => '7',
1568 'day' => '1',
1569 'hour' => '10',
1570 'minutes' => '00',
1571 'seconds' => '00',
1572 'timezone' => 'random/time', // This should show server time.
1573 'applydst' => true, // Apply dst.
1574 'expectedoutput' => '1309485600'
1576 array(
1577 'usertimezone' => '14', // Server time.
1578 'year' => '2011',
1579 'month' => '7',
1580 'day' => '1',
1581 'hour' => '10',
1582 'minutes' => '00',
1583 'seconds' => '00',
1584 'timezone' => '99', // Get user time.
1585 'applydst' => true, // Apply dst.
1586 'expectedoutput' => '1309485600'
1590 // Set default timezone to Australia/Perth, else time calculated
1591 // will not match expected values.
1592 $this->setTimezone(99, 'Australia/Perth');
1594 // Test make_timestamp with all testvals and assert if anything wrong.
1595 foreach ($testvalues as $vals) {
1596 $USER->timezone = $vals['usertimezone'];
1597 $actualoutput = make_timestamp(
1598 $vals['year'],
1599 $vals['month'],
1600 $vals['day'],
1601 $vals['hour'],
1602 $vals['minutes'],
1603 $vals['seconds'],
1604 $vals['timezone'],
1605 $vals['applydst']
1608 // On different systems case of AM PM changes so compare case insensitive.
1609 $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1610 $actualoutput = core_text::strtolower($actualoutput);
1612 $this->assertSame($vals['expectedoutput'], $actualoutput,
1613 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1614 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1619 * Test get_string and most importantly the implementation of the lang_string
1620 * object.
1622 public function test_get_string() {
1623 global $COURSE;
1625 // Make sure we are using English.
1626 $originallang = $COURSE->lang;
1627 $COURSE->lang = 'en';
1629 $yes = get_string('yes');
1630 $yesexpected = 'Yes';
1631 $this->assertInternalType('string', $yes);
1632 $this->assertSame($yesexpected, $yes);
1634 $yes = get_string('yes', 'moodle');
1635 $this->assertInternalType('string', $yes);
1636 $this->assertSame($yesexpected, $yes);
1638 $yes = get_string('yes', 'core');
1639 $this->assertInternalType('string', $yes);
1640 $this->assertSame($yesexpected, $yes);
1642 $yes = get_string('yes', '');
1643 $this->assertInternalType('string', $yes);
1644 $this->assertSame($yesexpected, $yes);
1646 $yes = get_string('yes', null);
1647 $this->assertInternalType('string', $yes);
1648 $this->assertSame($yesexpected, $yes);
1650 $yes = get_string('yes', null, 1);
1651 $this->assertInternalType('string', $yes);
1652 $this->assertSame($yesexpected, $yes);
1654 $days = 1;
1655 $numdays = get_string('numdays', 'core', '1');
1656 $numdaysexpected = $days.' days';
1657 $this->assertInternalType('string', $numdays);
1658 $this->assertSame($numdaysexpected, $numdays);
1660 $yes = get_string('yes', null, null, true);
1661 $this->assertInstanceOf('lang_string', $yes);
1662 $this->assertSame($yesexpected, (string)$yes);
1664 // Test using a lang_string object as the $a argument for a normal
1665 // get_string call (returning string).
1666 $test = new lang_string('yes', null, null, true);
1667 $testexpected = get_string('numdays', 'core', get_string('yes'));
1668 $testresult = get_string('numdays', null, $test);
1669 $this->assertInternalType('string', $testresult);
1670 $this->assertSame($testexpected, $testresult);
1672 // Test using a lang_string object as the $a argument for an object
1673 // get_string call (returning lang_string).
1674 $test = new lang_string('yes', null, null, true);
1675 $testexpected = get_string('numdays', 'core', get_string('yes'));
1676 $testresult = get_string('numdays', null, $test, true);
1677 $this->assertInstanceOf('lang_string', $testresult);
1678 $this->assertSame($testexpected, "$testresult");
1680 // Make sure that object properties that can't be converted don't cause
1681 // errors.
1682 // Level one: This is as deep as current language processing goes.
1683 $test = new stdClass;
1684 $test->one = 'here';
1685 $string = get_string('yes', null, $test, true);
1686 $this->assertEquals($yesexpected, $string);
1688 // Make sure that object properties that can't be converted don't cause
1689 // errors.
1690 // Level two: Language processing doesn't currently reach this deep.
1691 // only immediate scalar properties are worked with.
1692 $test = new stdClass;
1693 $test->one = new stdClass;
1694 $test->one->two = 'here';
1695 $string = get_string('yes', null, $test, true);
1696 $this->assertEquals($yesexpected, $string);
1698 // Make sure that object properties that can't be converted don't cause
1699 // errors.
1700 // Level three: It should never ever go this deep, but we're making sure
1701 // it doesn't cause any probs anyway.
1702 $test = new stdClass;
1703 $test->one = new stdClass;
1704 $test->one->two = new stdClass;
1705 $test->one->two->three = 'here';
1706 $string = get_string('yes', null, $test, true);
1707 $this->assertEquals($yesexpected, $string);
1709 // Make sure that object properties that can't be converted don't cause
1710 // errors and check lang_string properties.
1711 // Level one: This is as deep as current language processing goes.
1712 $test = new stdClass;
1713 $test->one = new lang_string('yes');
1714 $string = get_string('yes', null, $test, true);
1715 $this->assertEquals($yesexpected, $string);
1717 // Make sure that object properties that can't be converted don't cause
1718 // errors and check lang_string properties.
1719 // Level two: Language processing doesn't currently reach this deep.
1720 // only immediate scalar properties are worked with.
1721 $test = new stdClass;
1722 $test->one = new stdClass;
1723 $test->one->two = new lang_string('yes');
1724 $string = get_string('yes', null, $test, true);
1725 $this->assertEquals($yesexpected, $string);
1727 // Make sure that object properties that can't be converted don't cause
1728 // errors and check lang_string properties.
1729 // Level three: It should never ever go this deep, but we're making sure
1730 // it doesn't cause any probs anyway.
1731 $test = new stdClass;
1732 $test->one = new stdClass;
1733 $test->one->two = new stdClass;
1734 $test->one->two->three = new lang_string('yes');
1735 $string = get_string('yes', null, $test, true);
1736 $this->assertEquals($yesexpected, $string);
1738 // Make sure that array properties that can't be converted don't cause
1739 // errors.
1740 $test = array();
1741 $test['one'] = new stdClass;
1742 $test['one']->two = 'here';
1743 $string = get_string('yes', null, $test, true);
1744 $this->assertEquals($yesexpected, $string);
1746 // Same thing but as above except using an object... this is allowed :P.
1747 $string = get_string('yes', null, null, true);
1748 $object = new stdClass;
1749 $object->$string = 'Yes';
1750 $this->assertEquals($yesexpected, $string);
1751 $this->assertEquals($yesexpected, $object->$string);
1753 // Reset the language.
1754 $COURSE->lang = $originallang;
1758 * @expectedException PHPUnit_Framework_Error_Warning
1760 public function test_get_string_limitation() {
1761 // This is one of the limitations to the lang_string class. It can't be
1762 // used as a key.
1763 $array = array(get_string('yes', null, null, true) => 'yes');
1767 * Test localised float formatting.
1769 public function test_format_float() {
1771 // Special case for null.
1772 $this->assertEquals('', format_float(null));
1774 // Default 1 decimal place.
1775 $this->assertEquals('5.4', format_float(5.43));
1776 $this->assertEquals('5.0', format_float(5.001));
1778 // Custom number of decimal places.
1779 $this->assertEquals('5.43000', format_float(5.43, 5));
1781 // Option to strip ending zeros after rounding.
1782 $this->assertEquals('5.43', format_float(5.43, 5, true, true));
1783 $this->assertEquals('5', format_float(5.0001, 3, true, true));
1785 // Tests with a localised decimal separator.
1786 $this->define_local_decimal_separator();
1788 // Localisation on (default).
1789 $this->assertEquals('5X43000', format_float(5.43, 5));
1790 $this->assertEquals('5X43', format_float(5.43, 5, true, true));
1792 // Localisation off.
1793 $this->assertEquals('5.43000', format_float(5.43, 5, false));
1794 $this->assertEquals('5.43', format_float(5.43, 5, false, true));
1798 * Test localised float unformatting.
1800 public function test_unformat_float() {
1802 // Tests without the localised decimal separator.
1804 // Special case for null, empty or white spaces only strings.
1805 $this->assertEquals(null, unformat_float(null));
1806 $this->assertEquals(null, unformat_float(''));
1807 $this->assertEquals(null, unformat_float(' '));
1809 // Regular use.
1810 $this->assertEquals(5.4, unformat_float('5.4'));
1811 $this->assertEquals(5.4, unformat_float('5.4', true));
1813 // No decimal.
1814 $this->assertEquals(5.0, unformat_float('5'));
1816 // Custom number of decimal.
1817 $this->assertEquals(5.43267, unformat_float('5.43267'));
1819 // Empty decimal.
1820 $this->assertEquals(100.0, unformat_float('100.00'));
1822 // With the thousand separator.
1823 $this->assertEquals(1000.0, unformat_float('1 000'));
1824 $this->assertEquals(1000.32, unformat_float('1 000.32'));
1826 // Negative number.
1827 $this->assertEquals(-100.0, unformat_float('-100'));
1829 // Wrong value.
1830 $this->assertEquals(0.0, unformat_float('Wrong value'));
1831 // Wrong value in strict mode.
1832 $this->assertFalse(unformat_float('Wrong value', true));
1834 // Combining options.
1835 $this->assertEquals(-1023.862567, unformat_float(' -1 023.862567 '));
1837 // Bad decimal separator (should crop the decimal).
1838 $this->assertEquals(50.0, unformat_float('50,57'));
1839 // Bad decimal separator in strict mode (should return false).
1840 $this->assertFalse(unformat_float('50,57', true));
1842 // Tests with a localised decimal separator.
1843 $this->define_local_decimal_separator();
1845 // We repeat the tests above but with the current decimal separator.
1847 // Regular use without and with the localised separator.
1848 $this->assertEquals (5.4, unformat_float('5.4'));
1849 $this->assertEquals (5.4, unformat_float('5X4'));
1851 // Custom number of decimal.
1852 $this->assertEquals (5.43267, unformat_float('5X43267'));
1854 // Empty decimal.
1855 $this->assertEquals (100.0, unformat_float('100X00'));
1857 // With the thousand separator.
1858 $this->assertEquals (1000.32, unformat_float('1 000X32'));
1860 // Bad different separator (should crop the decimal).
1861 $this->assertEquals (50.0, unformat_float('50Y57'));
1862 // Bad different separator in strict mode (should return false).
1863 $this->assertFalse (unformat_float('50Y57', true));
1865 // Combining options.
1866 $this->assertEquals (-1023.862567, unformat_float(' -1 023X862567 '));
1867 // Combining options in strict mode.
1868 $this->assertEquals (-1023.862567, unformat_float(' -1 023X862567 ', true));
1872 * Test deleting of users.
1874 public function test_delete_user() {
1875 global $DB, $CFG;
1877 $this->resetAfterTest();
1879 $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
1880 $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
1881 $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
1883 $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
1884 $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
1885 $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
1886 $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
1887 $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => ''));
1888 $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => ''));
1890 // Delete user and capture event.
1891 $sink = $this->redirectEvents();
1892 $result = delete_user($user);
1893 $events = $sink->get_events();
1894 $sink->close();
1895 $event = array_pop($events);
1897 // Test user is deleted in DB.
1898 $this->assertTrue($result);
1899 $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
1900 $this->assertEquals(1, $deluser->deleted);
1901 $this->assertEquals(0, $deluser->picture);
1902 $this->assertSame('', $deluser->idnumber);
1903 $this->assertSame(md5($user->username), $deluser->email);
1904 $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
1906 $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
1908 // Test Event.
1909 $this->assertInstanceOf('\core\event\user_deleted', $event);
1910 $this->assertSame($user->id, $event->objectid);
1911 $this->assertSame('user_deleted', $event->get_legacy_eventname());
1912 $this->assertEventLegacyData($user, $event);
1913 $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
1914 $this->assertEventLegacyLogData($expectedlogdata, $event);
1915 $eventdata = $event->get_data();
1916 $this->assertSame($eventdata['other']['username'], $user->username);
1917 $this->assertSame($eventdata['other']['email'], $user->email);
1918 $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
1919 $this->assertSame($eventdata['other']['picture'], $user->picture);
1920 $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
1921 $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
1922 $this->assertEventContextNotUsed($event);
1924 // Try invalid params.
1925 $record = new stdClass();
1926 $record->grrr = 1;
1927 try {
1928 delete_user($record);
1929 $this->fail('Expecting exception for invalid delete_user() $user parameter');
1930 } catch (moodle_exception $ex) {
1931 $this->assertInstanceOf('coding_exception', $ex);
1933 $record->id = 1;
1934 try {
1935 delete_user($record);
1936 $this->fail('Expecting exception for invalid delete_user() $user parameter');
1937 } catch (moodle_exception $ex) {
1938 $this->assertInstanceOf('coding_exception', $ex);
1941 $record = new stdClass();
1942 $record->id = 666;
1943 $record->username = 'xx';
1944 $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
1945 $result = delete_user($record);
1946 $this->assertFalse($result);
1948 $result = delete_user($guest);
1949 $this->assertFalse($result);
1951 $result = delete_user($admin);
1952 $this->assertFalse($result);
1954 // Simultaneously deleting users with identical email addresses.
1955 $result1 = delete_user($usersharedemail1);
1956 $result2 = delete_user($usersharedemail2);
1958 $usersharedemail1after = $DB->get_record('user', array('id' => $usersharedemail1->id));
1959 $usersharedemail2after = $DB->get_record('user', array('id' => $usersharedemail2->id));
1960 $this->assertTrue($result1);
1961 $this->assertTrue($result2);
1962 $this->assertStringStartsWith($usersharedemail1->email . '.', $usersharedemail1after->username);
1963 $this->assertStringStartsWith($usersharedemail2->email . '.', $usersharedemail2after->username);
1965 // Simultaneously deleting users without email addresses.
1966 $result1 = delete_user($useremptyemail1);
1967 $result2 = delete_user($useremptyemail2);
1969 $useremptyemail1after = $DB->get_record('user', array('id' => $useremptyemail1->id));
1970 $useremptyemail2after = $DB->get_record('user', array('id' => $useremptyemail2->id));
1971 $this->assertTrue($result1);
1972 $this->assertTrue($result2);
1973 $this->assertStringStartsWith($useremptyemail1->username . '.' . $useremptyemail1->id . '@unknownemail.invalid.',
1974 $useremptyemail1after->username);
1975 $this->assertStringStartsWith($useremptyemail2->username . '.' . $useremptyemail2->id . '@unknownemail.invalid.',
1976 $useremptyemail2after->username);
1978 $this->resetDebugging();
1982 * Test function convert_to_array()
1984 public function test_convert_to_array() {
1985 // Check that normal classes are converted to arrays the same way as (array) would do.
1986 $obj = new stdClass();
1987 $obj->prop1 = 'hello';
1988 $obj->prop2 = array('first', 'second', 13);
1989 $obj->prop3 = 15;
1990 $this->assertEquals(convert_to_array($obj), (array)$obj);
1992 // Check that context object (with iterator) is converted to array properly.
1993 $obj = context_system::instance();
1994 $ar = array(
1995 'id' => $obj->id,
1996 'contextlevel' => $obj->contextlevel,
1997 'instanceid' => $obj->instanceid,
1998 'path' => $obj->path,
1999 'depth' => $obj->depth
2001 $this->assertEquals(convert_to_array($obj), $ar);
2005 * Test the function date_format_string().
2007 public function test_date_format_string() {
2008 global $CFG;
2010 $this->resetAfterTest();
2011 $this->setTimezone(99, 'Australia/Perth');
2013 $tests = array(
2014 array(
2015 'tz' => 99,
2016 'str' => '%A, %d %B %Y, %I:%M %p',
2017 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
2019 array(
2020 'tz' => 0,
2021 'str' => '%A, %d %B %Y, %I:%M %p',
2022 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2024 array(
2025 // Note: this function expected the timestamp in weird format before,
2026 // since 2.9 it uses UTC.
2027 'tz' => 'Pacific/Auckland',
2028 'str' => '%A, %d %B %Y, %I:%M %p',
2029 'expected' => 'Saturday, 01 January 2011, 11:00 PM'
2031 // Following tests pass on Windows only because en lang pack does
2032 // not contain localewincharset, in real life lang pack maintainers
2033 // may use only characters that are present in localewincharset
2034 // in format strings!
2035 array(
2036 'tz' => 99,
2037 'str' => 'Žluťoučký koníček %A',
2038 'expected' => 'Žluťoučký koníček Saturday'
2040 array(
2041 'tz' => 99,
2042 'str' => '言語設定言語 %A',
2043 'expected' => '言語設定言語 Saturday'
2045 array(
2046 'tz' => 99,
2047 'str' => '简体中文简体 %A',
2048 'expected' => '简体中文简体 Saturday'
2052 // Note: date_format_string() uses the timezone only to differenciate
2053 // the server time from the UTC time. It does not modify the timestamp.
2054 // Hence similar results for timezones <= 13.
2055 // On different systems case of AM PM changes so compare case insensitive.
2056 foreach ($tests as $test) {
2057 $str = date_format_string(1293876000, $test['str'], $test['tz']);
2058 $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
2062 public function test_get_config() {
2063 global $CFG;
2065 $this->resetAfterTest();
2067 // Preparation.
2068 set_config('phpunit_test_get_config_1', 'test 1');
2069 set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2070 if (!is_array($CFG->config_php_settings)) {
2071 $CFG->config_php_settings = array();
2073 $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
2075 if (!is_array($CFG->forced_plugin_settings)) {
2076 $CFG->forced_plugin_settings = array();
2078 if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
2079 $CFG->forced_plugin_settings['mod_forum'] = array();
2081 $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2082 $CFG->phpunit_test_get_config_5 = 'test 5';
2084 // Testing.
2085 $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
2086 $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2087 $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
2088 $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2089 $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2090 $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2091 $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2093 // Test config we know to exist.
2094 $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
2095 $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2096 $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2097 $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2099 // Test setting a config var that already exists.
2100 set_config('phpunit_test_get_config_1', 'test a');
2101 $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
2102 $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
2104 // Test cache invalidation.
2105 $cache = cache::make('core', 'config');
2106 $this->assertInternalType('array', $cache->get('core'));
2107 $this->assertInternalType('array', $cache->get('mod_forum'));
2108 set_config('phpunit_test_get_config_1', 'test b');
2109 $this->assertFalse($cache->get('core'));
2110 set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2111 $this->assertFalse($cache->get('mod_forum'));
2114 public function test_get_max_upload_sizes() {
2115 // Test with very low limits so we are not affected by php upload limits.
2116 // Test activity limit smallest.
2117 $sitebytes = 102400;
2118 $coursebytes = 51200;
2119 $modulebytes = 10240;
2120 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2122 $this->assertSame('Activity upload limit (10KB)', $result['0']);
2123 $this->assertCount(2, $result);
2125 // Test course limit smallest.
2126 $sitebytes = 102400;
2127 $coursebytes = 10240;
2128 $modulebytes = 51200;
2129 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2131 $this->assertSame('Course upload limit (10KB)', $result['0']);
2132 $this->assertCount(2, $result);
2134 // Test site limit smallest.
2135 $sitebytes = 10240;
2136 $coursebytes = 102400;
2137 $modulebytes = 51200;
2138 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2140 $this->assertSame('Site upload limit (10KB)', $result['0']);
2141 $this->assertCount(2, $result);
2143 // Test site limit not set.
2144 $sitebytes = 0;
2145 $coursebytes = 102400;
2146 $modulebytes = 51200;
2147 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2149 $this->assertSame('Activity upload limit (50KB)', $result['0']);
2150 $this->assertCount(3, $result);
2152 $sitebytes = 0;
2153 $coursebytes = 51200;
2154 $modulebytes = 102400;
2155 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2157 $this->assertSame('Course upload limit (50KB)', $result['0']);
2158 $this->assertCount(3, $result);
2160 // Test custom bytes in range.
2161 $sitebytes = 102400;
2162 $coursebytes = 51200;
2163 $modulebytes = 51200;
2164 $custombytes = 10240;
2165 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2167 $this->assertCount(3, $result);
2169 // Test custom bytes in range but non-standard.
2170 $sitebytes = 102400;
2171 $coursebytes = 51200;
2172 $modulebytes = 51200;
2173 $custombytes = 25600;
2174 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2176 $this->assertCount(4, $result);
2178 // Test custom bytes out of range.
2179 $sitebytes = 102400;
2180 $coursebytes = 51200;
2181 $modulebytes = 51200;
2182 $custombytes = 102400;
2183 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2185 $this->assertCount(3, $result);
2187 // Test custom bytes out of range and non-standard.
2188 $sitebytes = 102400;
2189 $coursebytes = 51200;
2190 $modulebytes = 51200;
2191 $custombytes = 256000;
2192 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2194 $this->assertCount(3, $result);
2196 // Test site limit only.
2197 $sitebytes = 51200;
2198 $result = get_max_upload_sizes($sitebytes);
2200 $this->assertSame('Site upload limit (50KB)', $result['0']);
2201 $this->assertSame('50KB', $result['51200']);
2202 $this->assertSame('10KB', $result['10240']);
2203 $this->assertCount(3, $result);
2205 // Test no limit.
2206 $result = get_max_upload_sizes();
2207 $this->assertArrayHasKey('0', $result);
2208 $this->assertArrayHasKey(get_max_upload_file_size(), $result);
2212 * Test function password_is_legacy_hash().
2214 public function test_password_is_legacy_hash() {
2215 // Well formed md5s should be matched.
2216 foreach (array('some', 'strings', 'to_check!') as $string) {
2217 $md5 = md5($string);
2218 $this->assertTrue(password_is_legacy_hash($md5));
2220 // Strings that are not md5s should not be matched.
2221 foreach (array('', AUTH_PASSWORD_NOT_CACHED, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
2222 $this->assertFalse(password_is_legacy_hash($notmd5));
2227 * Test function validate_internal_user_password().
2229 public function test_validate_internal_user_password() {
2230 // Test bcrypt hashes.
2231 $validhashes = array(
2232 'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2233 'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2234 'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2235 'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
2238 foreach ($validhashes as $password => $hash) {
2239 $user = new stdClass();
2240 $user->auth = 'manual';
2241 $user->password = $hash;
2242 // The correct password should be validated.
2243 $this->assertTrue(validate_internal_user_password($user, $password));
2244 // An incorrect password should not be validated.
2245 $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2250 * Test function hash_internal_user_password().
2252 public function test_hash_internal_user_password() {
2253 $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2255 // Check that some passwords that we convert to hashes can
2256 // be validated.
2257 foreach ($passwords as $password) {
2258 $hash = hash_internal_user_password($password);
2259 $fasthash = hash_internal_user_password($password, true);
2260 $user = new stdClass();
2261 $user->auth = 'manual';
2262 $user->password = $hash;
2263 $this->assertTrue(validate_internal_user_password($user, $password));
2265 // They should not be in md5 format.
2266 $this->assertFalse(password_is_legacy_hash($hash));
2268 // Check that cost factor in hash is correctly set.
2269 $this->assertRegExp('/\$10\$/', $hash);
2270 $this->assertRegExp('/\$04\$/', $fasthash);
2275 * Test function update_internal_user_password().
2277 public function test_update_internal_user_password() {
2278 global $DB;
2279 $this->resetAfterTest();
2280 $passwords = array('password', '1234', 'changeme', '****');
2281 foreach ($passwords as $password) {
2282 $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2283 update_internal_user_password($user, $password);
2284 // The user object should have been updated.
2285 $this->assertTrue(validate_internal_user_password($user, $password));
2286 // The database field for the user should also have been updated to the
2287 // same value.
2288 $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
2291 $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2292 // Manually set the user's password to the md5 of the string 'password'.
2293 $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
2295 $sink = $this->redirectEvents();
2296 // Update the password.
2297 update_internal_user_password($user, 'password');
2298 $events = $sink->get_events();
2299 $sink->close();
2300 $event = array_pop($events);
2302 // Password should have been updated to a bcrypt hash.
2303 $this->assertFalse(password_is_legacy_hash($user->password));
2305 // Verify event information.
2306 $this->assertInstanceOf('\core\event\user_password_updated', $event);
2307 $this->assertSame($user->id, $event->relateduserid);
2308 $this->assertEquals(context_user::instance($user->id), $event->get_context());
2309 $this->assertEventContextNotUsed($event);
2311 // Verify recovery of property 'auth'.
2312 unset($user->auth);
2313 update_internal_user_password($user, 'newpassword');
2314 $this->assertDebuggingCalled('User record in update_internal_user_password() must include field auth',
2315 DEBUG_DEVELOPER);
2316 $this->assertEquals('manual', $user->auth);
2320 * Testing that if the password is not cached, that it does not update
2321 * the user table and fire event.
2323 public function test_update_internal_user_password_no_cache() {
2324 $this->resetAfterTest();
2326 $user = $this->getDataGenerator()->create_user(array('auth' => 'cas'));
2327 $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2329 $sink = $this->redirectEvents();
2330 update_internal_user_password($user, 'wonkawonka');
2331 $this->assertEquals(0, $sink->count(), 'User updated event should not fire');
2335 * Test if the user has a password hash, but now their auth method
2336 * says not to cache it. Then it should update.
2338 public function test_update_internal_user_password_update_no_cache() {
2339 $this->resetAfterTest();
2341 $user = $this->getDataGenerator()->create_user(array('password' => 'test'));
2342 $this->assertNotEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2343 $user->auth = 'cas'; // Change to a auth that does not store passwords.
2345 $sink = $this->redirectEvents();
2346 update_internal_user_password($user, 'wonkawonka');
2347 $this->assertGreaterThanOrEqual(1, $sink->count(), 'User updated event should fire');
2349 $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2352 public function test_fullname() {
2353 global $CFG;
2355 $this->resetAfterTest();
2357 // Create a user to test the name display on.
2358 $record = array();
2359 $record['firstname'] = 'Scott';
2360 $record['lastname'] = 'Fletcher';
2361 $record['firstnamephonetic'] = 'スコット';
2362 $record['lastnamephonetic'] = 'フレチャー';
2363 $record['alternatename'] = 'No friends';
2364 $user = $this->getDataGenerator()->create_user($record);
2366 // Back up config settings for restore later.
2367 $originalcfg = new stdClass();
2368 $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
2369 $originalcfg->alternativefullnameformat = $CFG->alternativefullnameformat;
2371 // Testing existing fullnamedisplay settings.
2372 $CFG->fullnamedisplay = 'firstname';
2373 $testname = fullname($user);
2374 $this->assertSame($user->firstname, $testname);
2376 $CFG->fullnamedisplay = 'firstname lastname';
2377 $expectedname = "$user->firstname $user->lastname";
2378 $testname = fullname($user);
2379 $this->assertSame($expectedname, $testname);
2381 $CFG->fullnamedisplay = 'lastname firstname';
2382 $expectedname = "$user->lastname $user->firstname";
2383 $testname = fullname($user);
2384 $this->assertSame($expectedname, $testname);
2386 $expectedname = get_string('fullnamedisplay', null, $user);
2387 $CFG->fullnamedisplay = 'language';
2388 $testname = fullname($user);
2389 $this->assertSame($expectedname, $testname);
2391 // Test override parameter.
2392 $CFG->fullnamedisplay = 'firstname';
2393 $expectedname = "$user->firstname $user->lastname";
2394 $testname = fullname($user, true);
2395 $this->assertSame($expectedname, $testname);
2397 // Test alternativefullnameformat setting.
2398 // Test alternativefullnameformat that has been set to nothing.
2399 $CFG->alternativefullnameformat = '';
2400 $expectedname = "$user->firstname $user->lastname";
2401 $testname = fullname($user, true);
2402 $this->assertSame($expectedname, $testname);
2404 // Test alternativefullnameformat that has been set to 'language'.
2405 $CFG->alternativefullnameformat = 'language';
2406 $expectedname = "$user->firstname $user->lastname";
2407 $testname = fullname($user, true);
2408 $this->assertSame($expectedname, $testname);
2410 // Test customising the alternativefullnameformat setting with all additional name fields.
2411 $CFG->alternativefullnameformat = 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename';
2412 $expectedname = "$user->firstname $user->lastname $user->firstnamephonetic $user->lastnamephonetic $user->middlename $user->alternatename";
2413 $testname = fullname($user, true);
2414 $this->assertSame($expectedname, $testname);
2416 // Test additional name fields.
2417 $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
2418 $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
2419 $testname = fullname($user);
2420 $this->assertSame($expectedname, $testname);
2422 // Test for handling missing data.
2423 $user->middlename = null;
2424 // Parenthesis with no data.
2425 $CFG->fullnamedisplay = 'firstname (middlename) lastname';
2426 $expectedname = "$user->firstname $user->lastname";
2427 $testname = fullname($user);
2428 $this->assertSame($expectedname, $testname);
2430 // Extra spaces due to no data.
2431 $CFG->fullnamedisplay = 'firstname middlename lastname';
2432 $expectedname = "$user->firstname $user->lastname";
2433 $testname = fullname($user);
2434 $this->assertSame($expectedname, $testname);
2436 // Regular expression testing.
2437 // Remove some data from the user fields.
2438 $user->firstnamephonetic = '';
2439 $user->lastnamephonetic = '';
2441 // Removing empty brackets and excess whitespace.
2442 // All of these configurations should resolve to just firstname lastname.
2443 $configarray = array();
2444 $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
2445 $configarray[] = 'firstname lastname \'middlename\'';
2446 $configarray[] = 'firstname "firstnamephonetic" lastname';
2447 $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
2449 foreach ($configarray as $config) {
2450 $CFG->fullnamedisplay = $config;
2451 $expectedname = "$user->firstname $user->lastname";
2452 $testname = fullname($user);
2453 $this->assertSame($expectedname, $testname);
2456 // Check to make sure that other characters are left in place.
2457 $configarray = array();
2458 $configarray['0'] = new stdClass();
2459 $configarray['0']->config = 'lastname firstname, middlename';
2460 $configarray['0']->expectedname = "$user->lastname $user->firstname,";
2461 $configarray['1'] = new stdClass();
2462 $configarray['1']->config = 'lastname firstname + alternatename';
2463 $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
2464 $configarray['2'] = new stdClass();
2465 $configarray['2']->config = 'firstname aka: alternatename';
2466 $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
2467 $configarray['3'] = new stdClass();
2468 $configarray['3']->config = 'firstname (alternatename)';
2469 $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
2470 $configarray['4'] = new stdClass();
2471 $configarray['4']->config = 'firstname [alternatename]';
2472 $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
2473 $configarray['5'] = new stdClass();
2474 $configarray['5']->config = 'firstname "lastname"';
2475 $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
2477 foreach ($configarray as $config) {
2478 $CFG->fullnamedisplay = $config->config;
2479 $expectedname = $config->expectedname;
2480 $testname = fullname($user);
2481 $this->assertSame($expectedname, $testname);
2484 // Test debugging message displays when
2485 // fullnamedisplay setting is "normal".
2486 $CFG->fullnamedisplay = 'firstname lastname';
2487 unset($user);
2488 $user = new stdClass();
2489 $user->firstname = 'Stan';
2490 $user->lastname = 'Lee';
2491 $namedisplay = fullname($user);
2492 $this->assertDebuggingCalled();
2494 // Tidy up after we finish testing.
2495 $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
2496 $CFG->alternativefullnameformat = $originalcfg->alternativefullnameformat;
2499 public function test_get_all_user_name_fields() {
2500 $this->resetAfterTest();
2502 // Additional names in an array.
2503 $testarray = array('firstnamephonetic' => 'firstnamephonetic',
2504 'lastnamephonetic' => 'lastnamephonetic',
2505 'middlename' => 'middlename',
2506 'alternatename' => 'alternatename',
2507 'firstname' => 'firstname',
2508 'lastname' => 'lastname');
2509 $this->assertEquals($testarray, get_all_user_name_fields());
2511 // Additional names as a string.
2512 $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
2513 $this->assertEquals($teststring, get_all_user_name_fields(true));
2515 // Additional names as a string with an alias.
2516 $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
2517 $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
2519 // Additional name fields with a prefix - object.
2520 $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
2521 'lastnamephonetic' => 'authorlastnamephonetic',
2522 'middlename' => 'authormiddlename',
2523 'alternatename' => 'authoralternatename',
2524 'firstname' => 'authorfirstname',
2525 'lastname' => 'authorlastname');
2526 $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
2528 // Additional name fields with an alias and a title - string.
2529 $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';
2530 $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
2532 // Test the order parameter of the function.
2533 // Returning an array.
2534 $testarray = array('firstname' => 'firstname',
2535 'lastname' => 'lastname',
2536 'firstnamephonetic' => 'firstnamephonetic',
2537 'lastnamephonetic' => 'lastnamephonetic',
2538 'middlename' => 'middlename',
2539 'alternatename' => 'alternatename'
2541 $this->assertEquals($testarray, get_all_user_name_fields(false, null, null, null, true));
2543 // Returning a string.
2544 $teststring = 'firstname,lastname,firstnamephonetic,lastnamephonetic,middlename,alternatename';
2545 $this->assertEquals($teststring, get_all_user_name_fields(true, null, null, null, true));
2548 public function test_order_in_string() {
2549 $this->resetAfterTest();
2551 // Return an array in an order as they are encountered in a string.
2552 $valuearray = array('second', 'firsthalf', 'first');
2553 $formatstring = 'first firsthalf some other text (second)';
2554 $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
2555 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2557 // Try again with a different order for the format.
2558 $valuearray = array('second', 'firsthalf', 'first');
2559 $formatstring = 'firsthalf first second';
2560 $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
2561 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2563 // Try again with yet another different order for the format.
2564 $valuearray = array('second', 'firsthalf', 'first');
2565 $formatstring = 'start seconds away second firstquater first firsthalf';
2566 $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
2567 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2570 public function test_complete_user_login() {
2571 global $USER, $DB;
2573 $this->resetAfterTest();
2574 $user = $this->getDataGenerator()->create_user();
2575 $this->setUser(0);
2577 $sink = $this->redirectEvents();
2578 $loginuser = clone($user);
2579 $this->setCurrentTimeStart();
2580 @complete_user_login($loginuser); // Hide session header errors.
2581 $this->assertSame($loginuser, $USER);
2582 $this->assertEquals($user->id, $USER->id);
2583 $events = $sink->get_events();
2584 $sink->close();
2586 $this->assertCount(1, $events);
2587 $event = reset($events);
2588 $this->assertInstanceOf('\core\event\user_loggedin', $event);
2589 $this->assertEquals('user', $event->objecttable);
2590 $this->assertEquals($user->id, $event->objectid);
2591 $this->assertEquals(context_system::instance()->id, $event->contextid);
2592 $this->assertEventContextNotUsed($event);
2594 $user = $DB->get_record('user', array('id'=>$user->id));
2596 $this->assertTimeCurrent($user->firstaccess);
2597 $this->assertTimeCurrent($user->lastaccess);
2599 $this->assertTimeCurrent($USER->firstaccess);
2600 $this->assertTimeCurrent($USER->lastaccess);
2601 $this->assertTimeCurrent($USER->currentlogin);
2602 $this->assertSame(sesskey(), $USER->sesskey);
2603 $this->assertTimeCurrent($USER->preference['_lastloaded']);
2604 $this->assertObjectNotHasAttribute('password', $USER);
2605 $this->assertObjectNotHasAttribute('description', $USER);
2609 * Test require_logout.
2611 public function test_require_logout() {
2612 $this->resetAfterTest();
2613 $user = $this->getDataGenerator()->create_user();
2614 $this->setUser($user);
2616 $this->assertTrue(isloggedin());
2618 // Logout user and capture event.
2619 $sink = $this->redirectEvents();
2620 require_logout();
2621 $events = $sink->get_events();
2622 $sink->close();
2623 $event = array_pop($events);
2625 // Check if user is logged out.
2626 $this->assertFalse(isloggedin());
2628 // Test Event.
2629 $this->assertInstanceOf('\core\event\user_loggedout', $event);
2630 $this->assertSame($user->id, $event->objectid);
2631 $this->assertSame('user_logout', $event->get_legacy_eventname());
2632 $this->assertEventLegacyData($user, $event);
2633 $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
2634 $event->objectid);
2635 $this->assertEventLegacyLogData($expectedlogdata, $event);
2636 $this->assertEventContextNotUsed($event);
2639 public function test_email_to_user() {
2640 global $CFG;
2642 $this->resetAfterTest();
2644 $user1 = $this->getDataGenerator()->create_user();
2645 $user2 = $this->getDataGenerator()->create_user();
2647 $subject = 'subject';
2648 $messagetext = 'message text';
2649 $subject2 = 'subject 2';
2650 $messagetext2 = 'message text 2';
2652 // Close the default email sink.
2653 $sink = $this->redirectEmails();
2654 $sink->close();
2656 $CFG->noemailever = true;
2657 $this->assertNotEmpty($CFG->noemailever);
2658 email_to_user($user1, $user2, $subject, $messagetext);
2659 $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
2661 unset_config('noemailever');
2663 email_to_user($user1, $user2, $subject, $messagetext);
2664 $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2666 $sink = $this->redirectEmails();
2667 email_to_user($user1, $user2, $subject, $messagetext);
2668 email_to_user($user2, $user1, $subject2, $messagetext2);
2669 $this->assertSame(2, $sink->count());
2670 $result = $sink->get_messages();
2671 $this->assertCount(2, $result);
2672 $sink->close();
2674 $this->assertSame($subject, $result[0]->subject);
2675 $this->assertSame($messagetext, trim($result[0]->body));
2676 $this->assertSame($user1->email, $result[0]->to);
2677 $this->assertSame($user2->email, $result[0]->from);
2679 $this->assertSame($subject2, $result[1]->subject);
2680 $this->assertSame($messagetext2, trim($result[1]->body));
2681 $this->assertSame($user2->email, $result[1]->to);
2682 $this->assertSame($user1->email, $result[1]->from);
2684 email_to_user($user1, $user2, $subject, $messagetext);
2685 $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2687 // Test $CFG->emailonlyfromnoreplyaddress.
2688 set_config('emailonlyfromnoreplyaddress', 1);
2689 $this->assertNotEmpty($CFG->emailonlyfromnoreplyaddress);
2690 $sink = $this->redirectEmails();
2691 email_to_user($user1, $user2, $subject, $messagetext);
2692 unset_config('emailonlyfromnoreplyaddress');
2693 email_to_user($user1, $user2, $subject, $messagetext);
2694 $result = $sink->get_messages();
2695 $this->assertEquals($CFG->noreplyaddress, $result[0]->from);
2696 $this->assertNotEquals($CFG->noreplyaddress, $result[1]->from);
2697 $sink->close();
2701 * Test setnew_password_and_mail.
2703 public function test_setnew_password_and_mail() {
2704 global $DB, $CFG;
2706 $this->resetAfterTest();
2708 $user = $this->getDataGenerator()->create_user();
2710 // Update user password.
2711 $sink = $this->redirectEvents();
2712 $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
2713 setnew_password_and_mail($user);
2714 $events = $sink->get_events();
2715 $sink->close();
2716 $sink2->close();
2717 $event = array_pop($events);
2719 // Test updated value.
2720 $dbuser = $DB->get_record('user', array('id' => $user->id));
2721 $this->assertSame($user->firstname, $dbuser->firstname);
2722 $this->assertNotEmpty($dbuser->password);
2724 // Test event.
2725 $this->assertInstanceOf('\core\event\user_password_updated', $event);
2726 $this->assertSame($user->id, $event->relateduserid);
2727 $this->assertEquals(context_user::instance($user->id), $event->get_context());
2728 $this->assertEventContextNotUsed($event);
2732 * Test remove_course_content deletes course contents
2733 * TODO Add asserts to verify other data related to course is deleted as well.
2735 public function test_remove_course_contents() {
2737 $this->resetAfterTest();
2739 $course = $this->getDataGenerator()->create_course();
2740 $user = $this->getDataGenerator()->create_user();
2741 $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
2742 $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id));
2744 $this->assertNotEquals(false, note_load($note->id));
2745 remove_course_contents($course->id, false);
2746 $this->assertFalse(note_load($note->id));
2750 * Test function username_load_fields_from_object().
2752 public function test_username_load_fields_from_object() {
2753 $this->resetAfterTest();
2755 // This object represents the information returned from an sql query.
2756 $userinfo = new stdClass();
2757 $userinfo->userid = 1;
2758 $userinfo->username = 'loosebruce';
2759 $userinfo->firstname = 'Bruce';
2760 $userinfo->lastname = 'Campbell';
2761 $userinfo->firstnamephonetic = 'ブルース';
2762 $userinfo->lastnamephonetic = 'カンベッル';
2763 $userinfo->middlename = '';
2764 $userinfo->alternatename = '';
2765 $userinfo->email = '';
2766 $userinfo->picture = 23;
2767 $userinfo->imagealt = 'Michael Jordan draining another basket.';
2768 $userinfo->idnumber = 3982;
2770 // Just user name fields.
2771 $user = new stdClass();
2772 $user = username_load_fields_from_object($user, $userinfo);
2773 $expectedarray = new stdClass();
2774 $expectedarray->firstname = 'Bruce';
2775 $expectedarray->lastname = 'Campbell';
2776 $expectedarray->firstnamephonetic = 'ブルース';
2777 $expectedarray->lastnamephonetic = 'カンベッル';
2778 $expectedarray->middlename = '';
2779 $expectedarray->alternatename = '';
2780 $this->assertEquals($user, $expectedarray);
2782 // User information for showing a picture.
2783 $user = new stdClass();
2784 $additionalfields = explode(',', user_picture::fields());
2785 $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
2786 $user->id = $userinfo->userid;
2787 $expectedarray = new stdClass();
2788 $expectedarray->id = 1;
2789 $expectedarray->firstname = 'Bruce';
2790 $expectedarray->lastname = 'Campbell';
2791 $expectedarray->firstnamephonetic = 'ブルース';
2792 $expectedarray->lastnamephonetic = 'カンベッル';
2793 $expectedarray->middlename = '';
2794 $expectedarray->alternatename = '';
2795 $expectedarray->email = '';
2796 $expectedarray->picture = 23;
2797 $expectedarray->imagealt = 'Michael Jordan draining another basket.';
2798 $this->assertEquals($user, $expectedarray);
2800 // Alter the userinfo object to have a prefix.
2801 $userinfo->authorfirstname = 'Bruce';
2802 $userinfo->authorlastname = 'Campbell';
2803 $userinfo->authorfirstnamephonetic = 'ブルース';
2804 $userinfo->authorlastnamephonetic = 'カンベッル';
2805 $userinfo->authormiddlename = '';
2806 $userinfo->authorpicture = 23;
2807 $userinfo->authorimagealt = 'Michael Jordan draining another basket.';
2808 $userinfo->authoremail = 'test@example.com';
2811 // Return an object with user picture information.
2812 $user = new stdClass();
2813 $additionalfields = explode(',', user_picture::fields());
2814 $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
2815 $user->id = $userinfo->userid;
2816 $expectedarray = new stdClass();
2817 $expectedarray->id = 1;
2818 $expectedarray->firstname = 'Bruce';
2819 $expectedarray->lastname = 'Campbell';
2820 $expectedarray->firstnamephonetic = 'ブルース';
2821 $expectedarray->lastnamephonetic = 'カンベッル';
2822 $expectedarray->middlename = '';
2823 $expectedarray->alternatename = '';
2824 $expectedarray->email = 'test@example.com';
2825 $expectedarray->picture = 23;
2826 $expectedarray->imagealt = 'Michael Jordan draining another basket.';
2827 $this->assertEquals($user, $expectedarray);
2831 * Test function count_words().
2833 public function test_count_words() {
2834 $count = count_words("one two three'four");
2835 $this->assertEquals(3, $count);
2837 $count = count_words('one+two three’four');
2838 $this->assertEquals(3, $count);
2840 $count = count_words('one"two three-four');
2841 $this->assertEquals(3, $count);
2843 $count = count_words('one@two three_four');
2844 $this->assertEquals(4, $count);
2846 $count = count_words('one\two three/four');
2847 $this->assertEquals(4, $count);
2849 $count = count_words(' one ... two &nbsp; three...four ');
2850 $this->assertEquals(4, $count);
2852 $count = count_words('one.2 3,four');
2853 $this->assertEquals(4, $count);
2855 $count = count_words('1³ £2 €3.45 $6,789');
2856 $this->assertEquals(4, $count);
2858 $count = count_words('one—two ブルース カンベッル');
2859 $this->assertEquals(4, $count);
2861 $count = count_words('one…two ブルース … カンベッル');
2862 $this->assertEquals(4, $count);
2865 * Tests the getremoteaddr() function.
2867 public function test_getremoteaddr() {
2868 $xforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null;
2870 $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
2871 $noip = getremoteaddr('1.1.1.1');
2872 $this->assertEquals('1.1.1.1', $noip);
2874 $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
2875 $noip = getremoteaddr();
2876 $this->assertEquals('0.0.0.0', $noip);
2878 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1';
2879 $singleip = getremoteaddr();
2880 $this->assertEquals('127.0.0.1', $singleip);
2882 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2';
2883 $twoip = getremoteaddr();
2884 $this->assertEquals('127.0.0.1', $twoip);
2886 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2, 127.0.0.3';
2887 $threeip = getremoteaddr();
2888 $this->assertEquals('127.0.0.1', $threeip);
2890 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1:65535,127.0.0.2';
2891 $portip = getremoteaddr();
2892 $this->assertEquals('127.0.0.1', $portip);
2894 $_SERVER['HTTP_X_FORWARDED_FOR'] = '0:0:0:0:0:0:0:1,127.0.0.2';
2895 $portip = getremoteaddr();
2896 $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
2898 $_SERVER['HTTP_X_FORWARDED_FOR'] = '0::1,127.0.0.2';
2899 $portip = getremoteaddr();
2900 $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
2902 $_SERVER['HTTP_X_FORWARDED_FOR'] = '[0:0:0:0:0:0:0:1]:65535,127.0.0.2';
2903 $portip = getremoteaddr();
2904 $this->assertEquals('0:0:0:0:0:0:0:1', $portip);
2906 $_SERVER['HTTP_X_FORWARDED_FOR'] = $xforwardedfor;
2911 * Test emulation of random_bytes() function.
2913 public function test_random_bytes_emulate() {
2914 $result = random_bytes_emulate(10);
2915 $this->assertSame(10, strlen($result));
2916 $this->assertnotSame($result, random_bytes_emulate(10));
2918 $result = random_bytes_emulate(21);
2919 $this->assertSame(21, strlen($result));
2920 $this->assertnotSame($result, random_bytes_emulate(21));
2922 $result = random_bytes_emulate(666);
2923 $this->assertSame(666, strlen($result));
2925 $this->assertDebuggingNotCalled();
2927 $result = random_bytes_emulate(0);
2928 $this->assertSame('', $result);
2929 $this->assertDebuggingCalled();
2931 $result = random_bytes_emulate(-1);
2932 $this->assertSame('', $result);
2933 $this->assertDebuggingCalled();
2937 * Test function for creation of random strings.
2939 public function test_random_string() {
2940 $pool = 'a-zA-Z0-9';
2942 $result = random_string(10);
2943 $this->assertSame(10, strlen($result));
2944 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
2945 $this->assertNotSame($result, random_string(10));
2947 $result = random_string(21);
2948 $this->assertSame(21, strlen($result));
2949 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
2950 $this->assertNotSame($result, random_string(21));
2952 $result = random_string(666);
2953 $this->assertSame(666, strlen($result));
2954 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
2956 $result = random_string();
2957 $this->assertSame(15, strlen($result));
2958 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
2960 $this->assertDebuggingNotCalled();
2962 $result = random_string(0);
2963 $this->assertSame('', $result);
2964 $this->assertDebuggingCalled();
2966 $result = random_string(-1);
2967 $this->assertSame('', $result);
2968 $this->assertDebuggingCalled();
2972 * Test function for creation of complex random strings.
2974 public function test_complex_random_string() {
2975 $pool = preg_quote('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#%^&*()_+-=[];,./<>?:{} ', '/');
2977 $result = complex_random_string(10);
2978 $this->assertSame(10, strlen($result));
2979 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
2980 $this->assertNotSame($result, complex_random_string(10));
2982 $result = complex_random_string(21);
2983 $this->assertSame(21, strlen($result));
2984 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
2985 $this->assertNotSame($result, complex_random_string(21));
2987 $result = complex_random_string(666);
2988 $this->assertSame(666, strlen($result));
2989 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
2991 $result = complex_random_string();
2992 $this->assertEquals(28, strlen($result), '', 4); // Expected length is 24 - 32.
2993 $this->assertRegExp('/^[' . $pool . ']+$/', $result);
2995 $this->assertDebuggingNotCalled();
2997 $result = complex_random_string(0);
2998 $this->assertSame('', $result);
2999 $this->assertDebuggingCalled();
3001 $result = complex_random_string(-1);
3002 $this->assertSame('', $result);
3003 $this->assertDebuggingCalled();