2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Unit tests for (some of) ../moodlelib.php.
22 * @copyright © 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');
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() {
55 $this->assertNull(cleanremoteaddr('1023.121.234.1'));
56 $this->assertSame('123.121.234.1', cleanremoteaddr('123.121.234.01 '));
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'));
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'));
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'));
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 '));
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:'));
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();
170 $this->assertEquals($object, fix_utf8($object));
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() {
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';
195 optional_param('username', 'default_user', null);
196 $this->fail('coding_exception expected');
197 } catch (moodle_exception $ex) {
198 $this->assertInstanceOf('coding_exception', $ex);
201 @optional_param('username', 'default_user');
202 $this->fail('coding_exception expected');
203 } catch (moodle_exception $ex) {
204 $this->assertInstanceOf('coding_exception', $ex);
207 @optional_param('username');
208 $this->fail('coding_exception expected');
209 } catch (moodle_exception $ex) {
210 $this->assertInstanceOf('coding_exception', $ex);
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() {
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');
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);
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);
253 @optional_param_array('username');
254 $this->fail('coding_exception expected');
255 } catch (moodle_exception $ex) {
256 $this->assertInstanceOf('coding_exception', $ex);
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.
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']);
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';
304 @required_param('username');
305 $this->fail('coding_exception expected');
306 } catch (moodle_exception $ex) {
307 $this->assertInstanceOf('coding_exception', $ex);
310 required_param('username', '');
311 $this->fail('coding_exception expected');
312 } catch (moodle_exception $ex) {
313 $this->assertInstanceOf('coding_exception', $ex);
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() {
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');
341 required_param_array('username', null);
342 $this->fail('coding_exception expected');
343 } catch (moodle_exception $ex) {
344 $this->assertInstanceOf('coding_exception', $ex);
347 @required_param_array('username');
348 $this->fail('coding_exception expected');
349 } catch (moodle_exception $ex) {
350 $this->assertInstanceOf('coding_exception', $ex);
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.
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.
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.
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);
392 $param = new stdClass();
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.
402 clean_param('x', 'xxxxxx');
403 $this->fail('moodle_exception expected');
404 } catch (moodle_exception $ex) {
405 $this->assertInstanceOf('moodle_exception', $ex);
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.
422 clean_param_array(array('x'), 'xxxxxx');
423 $this->fail('moodle_exception expected');
424 } catch (moodle_exception $ex) {
425 $this->assertInstanceOf('moodle_exception', $ex);
428 @clean_param_array(array('x'));
429 $this->fail('moodle_exception expected');
430 } catch (moodle_exception $ex) {
431 $this->assertInstanceOf('moodle_exception', $ex);
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);
444 public function test_clean_param_raw() {
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);
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));
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() {
586 $this->assertSame('', clean_param('http://google.com/', PARAM_LOCALURL));
587 $this->assertSame('', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL));
588 $this->assertSame(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
589 $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_LOCALURL));
590 $this->assertSame('', clean_param('funny:thing', PARAM_LOCALURL));
591 $this->assertSame('course/view.php?id=3', clean_param('course/view.php?id=3', PARAM_LOCALURL));
594 public function test_clean_param_file() {
595 $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_FILE));
596 $this->assertSame('badfile.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE));
597 $this->assertSame('..parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_FILE));
598 $this->assertSame('....grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_FILE));
599 $this->assertSame('..winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_FILE));
600 $this->assertSame('....wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_FILE));
601 $this->assertSame('myfile.a.b.txt', clean_param('myfile.a.b.txt', PARAM_FILE));
602 $this->assertSame('myfile..a..b.txt', clean_param('myfile..a..b.txt', PARAM_FILE));
603 $this->assertSame('myfile.a..b...txt', clean_param('myfile.a..b...txt', PARAM_FILE));
604 $this->assertSame('myfile.a.txt', clean_param('myfile.a.txt', PARAM_FILE));
605 $this->assertSame('myfile...txt', clean_param('myfile...txt', PARAM_FILE));
606 $this->assertSame('...jpg', clean_param('...jpg', PARAM_FILE));
607 $this->assertSame('.a.b.', clean_param('.a.b.', PARAM_FILE));
608 $this->assertSame('', clean_param('.', PARAM_FILE));
609 $this->assertSame('', clean_param('..', PARAM_FILE));
610 $this->assertSame('...', clean_param('...', PARAM_FILE));
611 $this->assertSame('. . . .', clean_param('. . . .', PARAM_FILE));
612 $this->assertSame('dontrtrim.me. .. .. . ', clean_param('dontrtrim.me. .. .. . ', PARAM_FILE));
613 $this->assertSame(' . .dontltrim.me', clean_param(' . .dontltrim.me', PARAM_FILE));
614 $this->assertSame('here is a tab.txt', clean_param("here is a tab\t.txt", PARAM_FILE));
615 $this->assertSame('here is a linebreak.txt', clean_param("here is a line\r\nbreak.txt", PARAM_FILE));
617 // The following behaviours have been maintained although they seem a little odd.
618 $this->assertSame('funnything', clean_param('funny:thing', PARAM_FILE));
619 $this->assertSame('.currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_FILE));
620 $this->assertSame('ctempwindowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_FILE));
621 $this->assertSame('homeuserlinuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_FILE));
622 $this->assertSame('~myfile.txt', clean_param('~/myfile.txt', PARAM_FILE));
625 public function test_clean_param_path() {
626 $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_PATH));
627 $this->assertSame('bad/file.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH));
628 $this->assertSame('/parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_PATH));
629 $this->assertSame('/grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_PATH));
630 $this->assertSame('/winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_PATH));
631 $this->assertSame('/wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_PATH));
632 $this->assertSame('funnything', clean_param('funny:thing', PARAM_PATH));
633 $this->assertSame('./here', clean_param('./././here', PARAM_PATH));
634 $this->assertSame('./currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_PATH));
635 $this->assertSame('c/temp/windowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_PATH));
636 $this->assertSame('/home/user/linuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_PATH));
637 $this->assertSame('/home../user ./.linuxfile.txt', clean_param('/home../user ./.linuxfile.txt', PARAM_PATH));
638 $this->assertSame('~/myfile.txt', clean_param('~/myfile.txt', PARAM_PATH));
639 $this->assertSame('~/myfile.txt', clean_param('~/../myfile.txt', PARAM_PATH));
640 $this->assertSame('/..b../.../myfile.txt', clean_param('/..b../.../myfile.txt', PARAM_PATH));
641 $this->assertSame('..b../.../myfile.txt', clean_param('..b../.../myfile.txt', PARAM_PATH));
642 $this->assertSame('/super/slashes/', clean_param('/super//slashes///', PARAM_PATH));
645 public function test_clean_param_username() {
647 $currentstatus = $CFG->extendedusernamechars;
649 // Run tests with extended character == false;.
650 $CFG->extendedusernamechars = false;
651 $this->assertSame('johndoe123', clean_param('johndoe123', PARAM_USERNAME) );
652 $this->assertSame('john.doe', clean_param('john.doe', PARAM_USERNAME));
653 $this->assertSame('john-doe', clean_param('john-doe', PARAM_USERNAME));
654 $this->assertSame('john-doe', clean_param('john- doe', PARAM_USERNAME));
655 $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
656 $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
657 $this->assertSame('johndoe', clean_param('john~doe', PARAM_USERNAME));
658 $this->assertSame('johndoe', clean_param('john´doe', PARAM_USERNAME));
659 $this->assertSame(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
660 $this->assertSame('johnd', clean_param('JOHNdóé ', PARAM_USERNAME));
661 $this->assertSame(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýá
\9e?
\9eý??
\9adoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
663 // Test success condition, if extendedusernamechars == ENABLE;.
664 $CFG->extendedusernamechars = true;
665 $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
666 $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
667 $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john#$%&()+_^');
668 $this->assertSame('john~doe', clean_param('john~doe', PARAM_USERNAME));
669 $this->assertSame('john´doe', clean_param('joHN´doe', PARAM_USERNAME));
670 $this->assertSame('johndoe', clean_param('johnDOE', PARAM_USERNAME));
671 $this->assertSame('johndóé', clean_param('johndóé ', PARAM_USERNAME));
673 $CFG->extendedusernamechars = $currentstatus;
676 public function test_clean_param_stringid() {
677 // Test string identifiers validation.
679 $this->assertSame('validstring', clean_param('validstring', PARAM_STRINGID));
680 $this->assertSame('mod/foobar:valid_capability', clean_param('mod/foobar:valid_capability', PARAM_STRINGID));
681 $this->assertSame('CZ', clean_param('CZ', PARAM_STRINGID));
682 $this->assertSame('application/vnd.ms-powerpoint', clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID));
683 $this->assertSame('grade2', clean_param('grade2', PARAM_STRINGID));
685 $this->assertSame('', clean_param('trailing ', PARAM_STRINGID));
686 $this->assertSame('', clean_param('space bar', PARAM_STRINGID));
687 $this->assertSame('', clean_param('0numeric', PARAM_STRINGID));
688 $this->assertSame('', clean_param('*', PARAM_STRINGID));
689 $this->assertSame('', clean_param(' ', PARAM_STRINGID));
692 public function test_clean_param_timezone() {
693 // Test timezone validation.
694 $testvalues = array (
695 'America/Jamaica' => 'America/Jamaica',
696 'America/Argentina/Cordoba' => 'America/Argentina/Cordoba',
697 'America/Port-au-Prince' => 'America/Port-au-Prince',
698 'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
699 'PST8PDT' => 'PST8PDT',
701 'Wrong/.Value' => '',
702 'Wrong(Value)' => '',
726 foreach ($testvalues as $testvalue => $expectedvalue) {
727 $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
728 $this->assertEquals($expectedvalue, $actualvalue);
732 public function test_validate_param() {
734 $param = validate_param('11a', PARAM_INT);
735 $this->fail('invalid_parameter_exception expected');
736 } catch (moodle_exception $ex) {
737 $this->assertInstanceOf('invalid_parameter_exception', $ex);
740 $param = validate_param('11', PARAM_INT);
741 $this->assertSame(11, $param);
744 $param = validate_param(null, PARAM_INT, false);
745 $this->fail('invalid_parameter_exception expected');
746 } catch (moodle_exception $ex) {
747 $this->assertInstanceOf('invalid_parameter_exception', $ex);
750 $param = validate_param(null, PARAM_INT, true);
751 $this->assertSame(null, $param);
754 $param = validate_param(array(), PARAM_INT);
755 $this->fail('invalid_parameter_exception expected');
756 } catch (moodle_exception $ex) {
757 $this->assertInstanceOf('invalid_parameter_exception', $ex);
760 $param = validate_param(new stdClass, PARAM_INT);
761 $this->fail('invalid_parameter_exception expected');
762 } catch (moodle_exception $ex) {
763 $this->assertInstanceOf('invalid_parameter_exception', $ex);
766 $param = validate_param('1.0', PARAM_FLOAT);
767 $this->assertSame(1.0, $param);
769 // Make sure valid floats do not cause exception.
770 validate_param(1.0, PARAM_FLOAT);
771 validate_param(10, PARAM_FLOAT);
772 validate_param('0', PARAM_FLOAT);
773 validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
774 validate_param('011.1', PARAM_FLOAT);
775 validate_param('11', PARAM_FLOAT);
776 validate_param('+.1', PARAM_FLOAT);
777 validate_param('-.1', PARAM_FLOAT);
778 validate_param('1e10', PARAM_FLOAT);
779 validate_param('.1e+10', PARAM_FLOAT);
780 validate_param('1E-1', PARAM_FLOAT);
783 $param = validate_param('1,2', PARAM_FLOAT);
784 $this->fail('invalid_parameter_exception expected');
785 } catch (moodle_exception $ex) {
786 $this->assertInstanceOf('invalid_parameter_exception', $ex);
789 $param = validate_param('', PARAM_FLOAT);
790 $this->fail('invalid_parameter_exception expected');
791 } catch (moodle_exception $ex) {
792 $this->assertInstanceOf('invalid_parameter_exception', $ex);
795 $param = validate_param('.', PARAM_FLOAT);
796 $this->fail('invalid_parameter_exception expected');
797 } catch (moodle_exception $ex) {
798 $this->assertInstanceOf('invalid_parameter_exception', $ex);
801 $param = validate_param('e10', PARAM_FLOAT);
802 $this->fail('invalid_parameter_exception expected');
803 } catch (moodle_exception $ex) {
804 $this->assertInstanceOf('invalid_parameter_exception', $ex);
807 $param = validate_param('abc', PARAM_FLOAT);
808 $this->fail('invalid_parameter_exception expected');
809 } catch (moodle_exception $ex) {
810 $this->assertInstanceOf('invalid_parameter_exception', $ex);
814 public function test_shorten_text_no_tags_already_short_enough() {
815 // ......12345678901234567890123456.
816 $text = "short text already no tags";
817 $this->assertSame($text, shorten_text($text));
820 public function test_shorten_text_with_tags_already_short_enough() {
821 // .........123456...7890....12345678.......901234567.
822 $text = "<p>short <b>text</b> already</p><p>with tags</p>";
823 $this->assertSame($text, shorten_text($text));
826 public function test_shorten_text_no_tags_needs_shortening() {
827 // Default truncation is after 30 chars, but allowing 3 for the final '...'.
828 // ......12345678901234567890123456789023456789012345678901234.
829 $text = "long text without any tags blah de blah blah blah what";
830 $this->assertSame('long text without any tags ...', shorten_text($text));
833 public function test_shorten_text_with_tags_needs_shortening() {
834 // .......................................123456789012345678901234567890...
835 $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
836 "be chopped off but <b>should be added back again</b></blockquote></p></div>";
837 $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
838 "tags that ...</blockquote></p></div>", shorten_text($text));
841 public function test_shorten_text_with_entities() {
842 // Remember to allow 3 chars for the final '...'.
843 // ......123456789012345678901234567_____890...
844 $text = "some text which shouldn't break there";
845 $this->assertSame("some text which shouldn't ...", shorten_text($text, 31));
846 $this->assertSame("some text which shouldn't ...", shorten_text($text, 30));
847 $this->assertSame("some text which shouldn't ...", shorten_text($text, 29));
850 public function test_shorten_text_known_tricky_case() {
851 // This case caused a bug up to 1.9.5
852 // ..........123456789012345678901234567890123456789.....0_____1___2___...
853 $text = "<h3>standard 'break-out' sub groups in TGs?</h3> <<There are several";
854 $this->assertSame("<h3>standard 'break-out' sub groups in ...</h3>",
855 shorten_text($text, 41));
856 $this->assertSame("<h3>standard 'break-out' sub groups in TGs?...</h3>",
857 shorten_text($text, 42));
858 $this->assertSame("<h3>standard 'break-out' sub groups in TGs?</h3> ...",
859 shorten_text($text, 43));
862 public function test_shorten_text_no_spaces() {
863 // ..........123456789.
864 $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
865 $this->assertSame("<h1>12345...</h1>", shorten_text($text, 8));
868 public function test_shorten_text_utf8_european() {
869 // Text without tags.
870 // ......123456789012345678901234567.
871 $text = "Žluťoučký koníček přeskočil";
872 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
873 $this->assertSame("Žluťoučký koníče...", shorten_text($text, 19, true));
874 $this->assertSame("Žluťoučký ...", shorten_text($text, 19, false));
875 // And try it with 2-less (that are, in bytes, the middle of a sequence).
876 $this->assertSame("Žluťoučký koní...", shorten_text($text, 17, true));
877 $this->assertSame("Žluťoučký ...", shorten_text($text, 17, false));
879 // .........123456789012345678...901234567....89012345.
880 $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
881 $this->assertSame($text, shorten_text($text, 60));
882 $this->assertSame("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
883 $this->assertSame("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
884 $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
885 // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
886 $this->assertSame("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
887 $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
888 // And try over one tag (start/end), it does proper text len.
889 $this->assertSame("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
890 $this->assertSame("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
891 // And in the middle of one tag.
892 $this->assertSame("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
895 public function test_shorten_text_utf8_oriental() {
898 // ......123456789012345678901234.
899 $text = '言語設定言語設定abcdefghijkl';
900 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
901 $this->assertSame("言語設定言語...", shorten_text($text, 9, true));
902 $this->assertSame("言語設定言語...", shorten_text($text, 9, false));
903 $this->assertSame("言語設定言語設定ab...", shorten_text($text, 13, true));
904 $this->assertSame("言語設定言語設定...", shorten_text($text, 13, false));
908 // ......123456789012345678901234.
909 $text = '简体中文简体中文abcdefghijkl';
910 $this->assertSame($text, shorten_text($text)); // 30 chars by default.
911 $this->assertSame("简体中文简体...", shorten_text($text, 9, true));
912 $this->assertSame("简体中文简体...", shorten_text($text, 9, false));
913 $this->assertSame("简体中文简体中文ab...", shorten_text($text, 13, true));
914 $this->assertSame("简体中文简体中文...", shorten_text($text, 13, false));
917 public function test_shorten_text_multilang() {
918 // This is not necessaryily specific to multilang. The issue is really
919 // tags with attributes, where before we were generating invalid HTML
920 // output like shorten_text('<span id="x" class="y">A</span> B', 1)
921 // returning '<span id="x" ...</span>'. It is just that multilang
922 // requires the sort of HTML that is quite likely to trigger this.
923 // ........................................1...
924 $text = '<span lang="en" class="multilang">A</span>' .
925 '<span lang="fr" class="multilang">B</span>';
926 $this->assertSame('<span lang="en" class="multilang">...</span>',
927 shorten_text($text, 1));
930 public function test_usergetdate() {
931 global $USER, $CFG, $DB;
932 $this->resetAfterTest();
934 // Check if forcetimezone is set then save it and set it to use user timezone.
935 $cfgforcetimezone = null;
936 if (isset($CFG->forcetimezone)) {
937 $cfgforcetimezone = $CFG->forcetimezone;
938 $CFG->forcetimezone = 99; // Get user default timezone.
941 $this->setAdminUser();
943 $userstimezone = $USER->timezone;
944 $USER->timezone = 2;// Set the timezone to a known state.
946 // The string version of date comes from server locale setting and does
947 // not respect user language, so it is necessary to reset that.
948 $oldlocale = setlocale(LC_TIME, '0');
949 setlocale(LC_TIME, 'en_AU.UTF-8');
951 $ts = 1261540267; // The time this function was created.
953 $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
954 $arr = array_values($arr);
956 list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
957 $this->assertSame(7, $seconds);
958 $this->assertSame(51, $minutes);
959 $this->assertSame(4, $hours);
960 $this->assertSame(23, $mday);
961 $this->assertSame(3, $wday);
962 $this->assertSame(12, $mon);
963 $this->assertSame(2009, $year);
964 $this->assertSame(356, $yday);
965 $this->assertSame('Wednesday', $weekday);
966 $this->assertSame('December', $month);
967 $arr = usergetdate($ts); // Gets the timezone from the $USER object.
968 $arr = array_values($arr);
970 list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
971 $this->assertSame(7, $seconds);
972 $this->assertSame(51, $minutes);
973 $this->assertSame(5, $hours);
974 $this->assertSame(23, $mday);
975 $this->assertSame(3, $wday);
976 $this->assertSame(12, $mon);
977 $this->assertSame(2009, $year);
978 $this->assertSame(356, $yday);
979 $this->assertSame('Wednesday', $weekday);
980 $this->assertSame('December', $month);
981 // Set the timezone back to what it was.
982 $USER->timezone = $userstimezone;
984 // Restore forcetimezone if changed.
985 if (!is_null($cfgforcetimezone)) {
986 $CFG->forcetimezone = $cfgforcetimezone;
989 setlocale(LC_TIME, $oldlocale);
992 public function test_mark_user_preferences_changed() {
993 $this->resetAfterTest();
994 $otheruser = $this->getDataGenerator()->create_user();
995 $otheruserid = $otheruser->id;
997 set_cache_flag('userpreferenceschanged', $otheruserid, null);
998 mark_user_preferences_changed($otheruserid);
1000 $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1001 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1004 public function test_check_user_preferences_loaded() {
1006 $this->resetAfterTest();
1008 $otheruser = $this->getDataGenerator()->create_user();
1009 $otheruserid = $otheruser->id;
1011 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1012 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1014 $user = new stdClass();
1015 $user->id = $otheruserid;
1018 check_user_preferences_loaded($user);
1019 $this->assertTrue(isset($user->preference));
1020 $this->assertTrue(is_array($user->preference));
1021 $this->assertArrayHasKey('_lastloaded', $user->preference);
1022 $this->assertCount(1, $user->preference);
1024 // Add preference via direct call.
1025 $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1027 // No cache reload yet.
1028 check_user_preferences_loaded($user);
1029 $this->assertCount(1, $user->preference);
1031 // Forced reloading of cache.
1032 unset($user->preference);
1033 check_user_preferences_loaded($user);
1034 $this->assertCount(2, $user->preference);
1035 $this->assertSame('yyy', $user->preference['xxx']);
1037 // Add preference via direct call.
1038 $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1040 // Test timeouts and modifications from different session.
1041 set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1042 $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1043 check_user_preferences_loaded($user);
1044 $this->assertCount(2, $user->preference);
1045 check_user_preferences_loaded($user, 10);
1046 $this->assertCount(3, $user->preference);
1047 $this->assertSame('bbb', $user->preference['aaa']);
1048 set_cache_flag('userpreferenceschanged', $user->id, null);
1051 public function test_set_user_preference() {
1053 $this->resetAfterTest();
1055 $this->setAdminUser();
1057 $otheruser = $this->getDataGenerator()->create_user();
1058 $otheruserid = $otheruser->id;
1060 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1061 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1063 $user = new stdClass();
1064 $user->id = $otheruserid;
1066 set_user_preference('aaa', 'bbb', $otheruserid);
1067 $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1068 $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
1070 set_user_preference('xxx', 'yyy', $user);
1071 $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1072 $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
1073 $this->assertTrue(is_array($user->preference));
1074 $this->assertSame('bbb', $user->preference['aaa']);
1075 $this->assertSame('yyy', $user->preference['xxx']);
1077 set_user_preference('xxx', null, $user);
1078 $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1079 $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
1081 set_user_preference('ooo', true, $user);
1082 $prefs = get_user_preferences(null, null, $otheruserid);
1083 $this->assertSame($user->preference['aaa'], $prefs['aaa']);
1084 $this->assertSame($user->preference['ooo'], $prefs['ooo']);
1085 $this->assertSame('1', $prefs['ooo']);
1087 set_user_preference('null', 0, $user);
1088 $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1090 $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1092 $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1093 set_cache_flag('userpreferenceschanged', $otheruserid, null);
1095 // Test $USER default.
1096 set_user_preference('_test_user_preferences_pref', 'ok');
1097 $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1098 unset_user_preference('_test_user_preferences_pref');
1099 $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1101 // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
1102 $longvalue = str_repeat('a', 1333);
1103 set_user_preference('_test_long_user_preference', $longvalue);
1104 $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1105 $this->assertEquals($longvalue,
1106 $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1108 // Test > 1333 char values, coding_exception expected.
1109 $longvalue = str_repeat('a', 1334);
1111 set_user_preference('_test_long_user_preference', $longvalue);
1112 $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1113 } catch (moodle_exception $ex) {
1114 $this->assertInstanceOf('coding_exception', $ex);
1117 // Test invalid params.
1119 set_user_preference('_test_user_preferences_pref', array());
1120 $this->fail('Exception expected - array not valid preference value');
1121 } catch (moodle_exception $ex) {
1122 $this->assertInstanceOf('coding_exception', $ex);
1125 set_user_preference('_test_user_preferences_pref', new stdClass);
1126 $this->fail('Exception expected - class not valid preference value');
1127 } catch (moodle_exception $ex) {
1128 $this->assertInstanceOf('coding_exception', $ex);
1131 set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1132 $this->fail('Exception expected - user instance expected');
1133 } catch (moodle_exception $ex) {
1134 $this->assertInstanceOf('coding_exception', $ex);
1137 set_user_preference('_test_user_preferences_pref', 1, 'abc');
1138 $this->fail('Exception expected - user instance expected');
1139 } catch (moodle_exception $ex) {
1140 $this->assertInstanceOf('coding_exception', $ex);
1143 set_user_preference('', 1);
1144 $this->fail('Exception expected - invalid name accepted');
1145 } catch (moodle_exception $ex) {
1146 $this->assertInstanceOf('coding_exception', $ex);
1149 set_user_preference('1', 1);
1150 $this->fail('Exception expected - invalid name accepted');
1151 } catch (moodle_exception $ex) {
1152 $this->assertInstanceOf('coding_exception', $ex);
1156 public function test_get_extra_user_fields() {
1157 global $CFG, $USER, $DB;
1158 $this->resetAfterTest();
1160 $this->setAdminUser();
1162 // It would be really nice if there were a way to 'mock' has_capability
1163 // checks (either to return true or false) but as there is not, this
1164 // test doesn't test the capability check. Presumably, anyone running
1165 // unit tests will have the capability.
1166 $context = context_system::instance();
1169 $CFG->showuseridentity = '';
1170 $this->assertEquals(array(), get_extra_user_fields($context));
1173 $CFG->showuseridentity = 'frog';
1174 $this->assertEquals(array('frog'), get_extra_user_fields($context));
1177 $CFG->showuseridentity = 'frog,zombie';
1178 $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
1180 // No fields, except.
1181 $CFG->showuseridentity = '';
1182 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1185 $CFG->showuseridentity = 'frog';
1186 $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
1189 $CFG->showuseridentity = 'frog,zombie';
1190 $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
1193 public function test_get_extra_user_fields_sql() {
1194 global $CFG, $USER, $DB;
1195 $this->resetAfterTest();
1197 $this->setAdminUser();
1199 $context = context_system::instance();
1202 $CFG->showuseridentity = '';
1203 $this->assertSame('', get_extra_user_fields_sql($context));
1206 $CFG->showuseridentity = 'frog';
1207 $this->assertSame(', frog', get_extra_user_fields_sql($context));
1209 // Two fields with table prefix.
1210 $CFG->showuseridentity = 'frog,zombie';
1211 $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
1213 // Two fields with field prefix.
1214 $CFG->showuseridentity = 'frog,zombie';
1215 $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
1216 get_extra_user_fields_sql($context, '', 'u_'));
1218 // One field excluded.
1219 $CFG->showuseridentity = 'frog';
1220 $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
1222 // Two fields, one excluded, table+field prefix.
1223 $CFG->showuseridentity = 'frog,zombie';
1224 $this->assertEquals(', u1.zombie AS u_zombie',
1225 get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
1229 * Test some critical TZ/DST.
1231 * This method tests some special TZ/DST combinations that were fixed
1232 * by MDL-38999. The tests are done by comparing the results of the
1233 * output using Moodle TZ/DST support and PHP native one.
1235 * Note: If you don't trust PHP TZ/DST support, can verify the
1236 * harcoded expectations below with:
1237 * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
1239 public function test_some_moodle_special_dst() {
1240 $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
1242 // In Europe/Tallinn it was 2013/04/08 05:00:00.
1243 $expectation = '2013/04/08 05:00:00';
1244 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1245 $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1246 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1247 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1248 $this->assertSame($expectation, $phpres);
1249 $this->assertSame($expectation, $moodleres);
1251 // In St. Johns it was 2013/04/07 23:30:00.
1252 $expectation = '2013/04/07 23:30:00';
1253 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1254 $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1255 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1256 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1257 $this->assertSame($expectation, $phpres);
1258 $this->assertSame($expectation, $moodleres);
1260 $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1262 // In Europe/Tallinn it was 2013/11/08 04:00:00.
1263 $expectation = '2013/11/08 04:00:00';
1264 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1265 $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
1266 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1267 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1268 $this->assertSame($expectation, $phpres);
1269 $this->assertSame($expectation, $moodleres);
1271 // In St. Johns it was 2013/11/07 22:30:00.
1272 $expectation = '2013/11/07 22:30:00';
1273 $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
1274 $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
1275 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1276 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1277 $this->assertSame($expectation, $phpres);
1278 $this->assertSame($expectation, $moodleres);
1281 public function test_userdate() {
1282 global $USER, $CFG, $DB;
1283 $this->resetAfterTest();
1285 $this->setAdminUser();
1287 $testvalues = array(
1289 'time' => '1309514400',
1290 'usertimezone' => 'America/Moncton',
1291 'timezone' => '0.0', // No dst offset.
1292 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM'
1295 'time' => '1309514400',
1296 'usertimezone' => 'America/Moncton',
1297 'timezone' => '99', // Dst offset and timezone offset.
1298 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1301 'time' => '1309514400',
1302 'usertimezone' => 'America/Moncton',
1303 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
1304 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM'
1307 'time' => '1293876000 ',
1308 'usertimezone' => 'America/Moncton',
1309 'timezone' => '0.0', // No dst offset.
1310 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM'
1313 'time' => '1293876000 ',
1314 'usertimezone' => 'America/Moncton',
1315 'timezone' => '99', // No dst offset in jan, so just timezone offset.
1316 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1319 'time' => '1293876000 ',
1320 'usertimezone' => 'America/Moncton',
1321 'timezone' => 'America/Moncton', // No dst offset in jan.
1322 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM'
1325 'time' => '1293876000 ',
1326 'usertimezone' => '2',
1327 'timezone' => '99', // Take user timezone.
1328 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1331 'time' => '1293876000 ',
1332 'usertimezone' => '-2',
1333 'timezone' => '99', // Take user timezone.
1334 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1337 'time' => '1293876000 ',
1338 'usertimezone' => '-10',
1339 'timezone' => '2', // Take this timezone.
1340 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM'
1343 'time' => '1293876000 ',
1344 'usertimezone' => '-10',
1345 'timezone' => '-2', // Take this timezone.
1346 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM'
1349 'time' => '1293876000 ',
1350 'usertimezone' => '-10',
1351 'timezone' => 'random/time', // This should show server time.
1352 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1355 'time' => '1293876000 ',
1356 'usertimezone' => '14', // Server time zone.
1357 'timezone' => '99', // This should show user time.
1358 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM'
1362 // Check if forcetimezone is set then save it and set it to use user timezone.
1363 $cfgforcetimezone = null;
1364 if (isset($CFG->forcetimezone)) {
1365 $cfgforcetimezone = $CFG->forcetimezone;
1366 $CFG->forcetimezone = 99; // Get user default timezone.
1368 // Store user default timezone to restore later.
1369 $userstimezone = $USER->timezone;
1371 // The string version of date comes from server locale setting and does
1372 // not respect user language, so it is necessary to reset that.
1373 $oldlocale = setlocale(LC_TIME, '0');
1374 setlocale(LC_TIME, 'en_AU.UTF-8');
1376 // Set default timezone to Australia/Perth, else time calculated
1377 // will not match expected values. Before that save system defaults.
1378 $systemdefaulttimezone = date_default_timezone_get();
1379 date_default_timezone_set('Australia/Perth');
1381 foreach ($testvalues as $vals) {
1382 $USER->timezone = $vals['usertimezone'];
1383 $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1385 // On different systems case of AM PM changes so compare case insensitive.
1386 $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1387 $actualoutput = core_text::strtolower($actualoutput);
1389 $this->assertSame($vals['expectedoutput'], $actualoutput,
1390 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1391 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1394 // Restore user timezone back to what it was.
1395 $USER->timezone = $userstimezone;
1397 // Restore forcetimezone.
1398 if (!is_null($cfgforcetimezone)) {
1399 $CFG->forcetimezone = $cfgforcetimezone;
1402 // Restore system default values.
1403 date_default_timezone_set($systemdefaulttimezone);
1404 setlocale(LC_TIME, $oldlocale);
1407 public function test_make_timestamp() {
1408 global $USER, $CFG, $DB;
1409 $this->resetAfterTest();
1411 $this->setAdminUser();
1413 $testvalues = array(
1415 'usertimezone' => 'America/Moncton',
1422 'timezone' => '0.0',
1423 'applydst' => false, // No dst offset.
1424 'expectedoutput' => '1309514400' // 6pm at UTC+0.
1427 'usertimezone' => 'America/Moncton',
1434 'timezone' => '99', // User default timezone.
1435 'applydst' => false, // Don't apply dst.
1436 'expectedoutput' => '1309528800'
1439 'usertimezone' => 'America/Moncton',
1446 'timezone' => '99', // User default timezone.
1447 'applydst' => true, // Apply dst.
1448 'expectedoutput' => '1309525200'
1451 'usertimezone' => 'America/Moncton',
1458 'timezone' => 'America/Moncton', // String timezone.
1459 'applydst' => true, // Apply dst.
1460 'expectedoutput' => '1309525200'
1463 'usertimezone' => '2', // No dst applyed.
1470 'timezone' => '99', // Take user timezone.
1471 'applydst' => true, // Apply dst.
1472 'expectedoutput' => '1309507200'
1475 'usertimezone' => '-2', // No dst applyed.
1482 'timezone' => '99', // Take usertimezone.
1483 'applydst' => true, // Apply dst.
1484 'expectedoutput' => '1309521600'
1487 'usertimezone' => '-10', // No dst applyed.
1494 'timezone' => '2', // Take this timezone.
1495 'applydst' => true, // Apply dst.
1496 'expectedoutput' => '1309507200'
1499 'usertimezone' => '-10', // No dst applyed.
1506 'timezone' => '-2', // Take this timezone.
1507 'applydst' => true, // Apply dst.
1508 'expectedoutput' => '1309521600'
1511 'usertimezone' => '-10', // No dst applyed.
1518 'timezone' => 'random/time', // This should show server time.
1519 'applydst' => true, // Apply dst.
1520 'expectedoutput' => '1309485600'
1523 'usertimezone' => '14', // Server time.
1530 'timezone' => '99', // Get user time.
1531 'applydst' => true, // Apply dst.
1532 'expectedoutput' => '1309485600'
1536 // Check if forcetimezone is set then save it and set it to use user timezone.
1537 $cfgforcetimezone = null;
1538 if (isset($CFG->forcetimezone)) {
1539 $cfgforcetimezone = $CFG->forcetimezone;
1540 $CFG->forcetimezone = 99; // Get user default timezone.
1543 // Store user default timezone to restore later.
1544 $userstimezone = $USER->timezone;
1546 // The string version of date comes from server locale setting and does
1547 // not respect user language, so it is necessary to reset that.
1548 $oldlocale = setlocale(LC_TIME, '0');
1549 setlocale(LC_TIME, 'en_AU.UTF-8');
1551 // Set default timezone to Australia/Perth, else time calculated
1552 // Will not match expected values. Before that save system defaults.
1553 $systemdefaulttimezone = date_default_timezone_get();
1554 date_default_timezone_set('Australia/Perth');
1556 // Test make_timestamp with all testvals and assert if anything wrong.
1557 foreach ($testvalues as $vals) {
1558 $USER->timezone = $vals['usertimezone'];
1559 $actualoutput = make_timestamp(
1570 // On different systems case of AM PM changes so compare case insensitive.
1571 $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
1572 $actualoutput = core_text::strtolower($actualoutput);
1574 $this->assertSame($vals['expectedoutput'], $actualoutput,
1575 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1576 Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1579 // Restore user timezone back to what it was.
1580 $USER->timezone = $userstimezone;
1582 // Restore forcetimezone.
1583 if (!is_null($cfgforcetimezone)) {
1584 $CFG->forcetimezone = $cfgforcetimezone;
1587 // Restore system default values.
1588 date_default_timezone_set($systemdefaulttimezone);
1589 setlocale(LC_TIME, $oldlocale);
1593 * Test get_string and most importantly the implementation of the lang_string
1596 public function test_get_string() {
1599 // Make sure we are using English.
1600 $originallang = $COURSE->lang;
1601 $COURSE->lang = 'en';
1603 $yes = get_string('yes');
1604 $yesexpected = 'Yes';
1605 $this->assertInternalType('string', $yes);
1606 $this->assertSame($yesexpected, $yes);
1608 $yes = get_string('yes', 'moodle');
1609 $this->assertInternalType('string', $yes);
1610 $this->assertSame($yesexpected, $yes);
1612 $yes = get_string('yes', 'core');
1613 $this->assertInternalType('string', $yes);
1614 $this->assertSame($yesexpected, $yes);
1616 $yes = get_string('yes', '');
1617 $this->assertInternalType('string', $yes);
1618 $this->assertSame($yesexpected, $yes);
1620 $yes = get_string('yes', null);
1621 $this->assertInternalType('string', $yes);
1622 $this->assertSame($yesexpected, $yes);
1624 $yes = get_string('yes', null, 1);
1625 $this->assertInternalType('string', $yes);
1626 $this->assertSame($yesexpected, $yes);
1629 $numdays = get_string('numdays', 'core', '1');
1630 $numdaysexpected = $days.' days';
1631 $this->assertInternalType('string', $numdays);
1632 $this->assertSame($numdaysexpected, $numdays);
1634 $yes = get_string('yes', null, null, true);
1635 $this->assertInstanceOf('lang_string', $yes);
1636 $this->assertSame($yesexpected, (string)$yes);
1638 // Test using a lang_string object as the $a argument for a normal
1639 // get_string call (returning string).
1640 $test = new lang_string('yes', null, null, true);
1641 $testexpected = get_string('numdays', 'core', get_string('yes'));
1642 $testresult = get_string('numdays', null, $test);
1643 $this->assertInternalType('string', $testresult);
1644 $this->assertSame($testexpected, $testresult);
1646 // Test using a lang_string object as the $a argument for an object
1647 // get_string call (returning lang_string).
1648 $test = new lang_string('yes', null, null, true);
1649 $testexpected = get_string('numdays', 'core', get_string('yes'));
1650 $testresult = get_string('numdays', null, $test, true);
1651 $this->assertInstanceOf('lang_string', $testresult);
1652 $this->assertSame($testexpected, "$testresult");
1654 // Make sure that object properties that can't be converted don't cause
1656 // Level one: This is as deep as current language processing goes.
1657 $test = new stdClass;
1658 $test->one = 'here';
1659 $string = get_string('yes', null, $test, true);
1660 $this->assertEquals($yesexpected, $string);
1662 // Make sure that object properties that can't be converted don't cause
1664 // Level two: Language processing doesn't currently reach this deep.
1665 // only immediate scalar properties are worked with.
1666 $test = new stdClass;
1667 $test->one = new stdClass;
1668 $test->one->two = 'here';
1669 $string = get_string('yes', null, $test, true);
1670 $this->assertEquals($yesexpected, $string);
1672 // Make sure that object properties that can't be converted don't cause
1674 // Level three: It should never ever go this deep, but we're making sure
1675 // it doesn't cause any probs anyway.
1676 $test = new stdClass;
1677 $test->one = new stdClass;
1678 $test->one->two = new stdClass;
1679 $test->one->two->three = 'here';
1680 $string = get_string('yes', null, $test, true);
1681 $this->assertEquals($yesexpected, $string);
1683 // Make sure that object properties that can't be converted don't cause
1684 // errors and check lang_string properties.
1685 // Level one: This is as deep as current language processing goes.
1686 $test = new stdClass;
1687 $test->one = new lang_string('yes');
1688 $string = get_string('yes', null, $test, true);
1689 $this->assertEquals($yesexpected, $string);
1691 // Make sure that object properties that can't be converted don't cause
1692 // errors and check lang_string properties.
1693 // Level two: Language processing doesn't currently reach this deep.
1694 // only immediate scalar properties are worked with.
1695 $test = new stdClass;
1696 $test->one = new stdClass;
1697 $test->one->two = new lang_string('yes');
1698 $string = get_string('yes', null, $test, true);
1699 $this->assertEquals($yesexpected, $string);
1701 // Make sure that object properties that can't be converted don't cause
1702 // errors and check lang_string properties.
1703 // Level three: It should never ever go this deep, but we're making sure
1704 // it doesn't cause any probs anyway.
1705 $test = new stdClass;
1706 $test->one = new stdClass;
1707 $test->one->two = new stdClass;
1708 $test->one->two->three = new lang_string('yes');
1709 $string = get_string('yes', null, $test, true);
1710 $this->assertEquals($yesexpected, $string);
1712 // Make sure that array properties that can't be converted don't cause
1715 $test['one'] = new stdClass;
1716 $test['one']->two = 'here';
1717 $string = get_string('yes', null, $test, true);
1718 $this->assertEquals($yesexpected, $string);
1720 // Same thing but as above except using an object... this is allowed :P.
1721 $string = get_string('yes', null, null, true);
1722 $object = new stdClass;
1723 $object->$string = 'Yes';
1724 $this->assertEquals($yesexpected, $string);
1725 $this->assertEquals($yesexpected, $object->$string);
1727 // Reset the language.
1728 $COURSE->lang = $originallang;
1732 * @expectedException PHPUnit_Framework_Error_Warning
1734 public function test_get_string_limitation() {
1735 // This is one of the limitations to the lang_string class. It can't be
1737 $array = array(get_string('yes', null, null, true) => 'yes');
1741 * Test localised float formatting.
1743 public function test_format_float() {
1745 // Special case for null.
1746 $this->assertEquals('', format_float(null));
1748 // Default 1 decimal place.
1749 $this->assertEquals('5.4', format_float(5.43));
1750 $this->assertEquals('5.0', format_float(5.001));
1752 // Custom number of decimal places.
1753 $this->assertEquals('5.43000', format_float(5.43, 5));
1755 // Option to strip ending zeros after rounding.
1756 $this->assertEquals('5.43', format_float(5.43, 5, true, true));
1757 $this->assertEquals('5', format_float(5.0001, 3, true, true));
1759 // Tests with a localised decimal separator.
1760 $this->define_local_decimal_separator();
1762 // Localisation on (default).
1763 $this->assertEquals('5X43000', format_float(5.43, 5));
1764 $this->assertEquals('5X43', format_float(5.43, 5, true, true));
1766 // Localisation off.
1767 $this->assertEquals('5.43000', format_float(5.43, 5, false));
1768 $this->assertEquals('5.43', format_float(5.43, 5, false, true));
1772 * Test localised float unformatting.
1774 public function test_unformat_float() {
1776 // Tests without the localised decimal separator.
1778 // Special case for null, empty or white spaces only strings.
1779 $this->assertEquals(null, unformat_float(null));
1780 $this->assertEquals(null, unformat_float(''));
1781 $this->assertEquals(null, unformat_float(' '));
1784 $this->assertEquals(5.4, unformat_float('5.4'));
1785 $this->assertEquals(5.4, unformat_float('5.4', true));
1788 $this->assertEquals(5.0, unformat_float('5'));
1790 // Custom number of decimal.
1791 $this->assertEquals(5.43267, unformat_float('5.43267'));
1794 $this->assertEquals(100.0, unformat_float('100.00'));
1796 // With the thousand separator.
1797 $this->assertEquals(1000.0, unformat_float('1 000'));
1798 $this->assertEquals(1000.32, unformat_float('1 000.32'));
1801 $this->assertEquals(-100.0, unformat_float('-100'));
1804 $this->assertEquals(0.0, unformat_float('Wrong value'));
1805 // Wrong value in strict mode.
1806 $this->assertFalse(unformat_float('Wrong value', true));
1808 // Combining options.
1809 $this->assertEquals(-1023.862567, unformat_float(' -1 023.862567 '));
1811 // Bad decimal separator (should crop the decimal).
1812 $this->assertEquals(50.0, unformat_float('50,57'));
1813 // Bad decimal separator in strict mode (should return false).
1814 $this->assertFalse(unformat_float('50,57', true));
1816 // Tests with a localised decimal separator.
1817 $this->define_local_decimal_separator();
1819 // We repeat the tests above but with the current decimal separator.
1821 // Regular use without and with the localised separator.
1822 $this->assertEquals (5.4, unformat_float('5.4'));
1823 $this->assertEquals (5.4, unformat_float('5X4'));
1825 // Custom number of decimal.
1826 $this->assertEquals (5.43267, unformat_float('5X43267'));
1829 $this->assertEquals (100.0, unformat_float('100X00'));
1831 // With the thousand separator.
1832 $this->assertEquals (1000.32, unformat_float('1 000X32'));
1834 // Bad different separator (should crop the decimal).
1835 $this->assertEquals (50.0, unformat_float('50Y57'));
1836 // Bad different separator in strict mode (should return false).
1837 $this->assertFalse (unformat_float('50Y57', true));
1839 // Combining options.
1840 $this->assertEquals (-1023.862567, unformat_float(' -1 023X862567 '));
1841 // Combining options in strict mode.
1842 $this->assertEquals (-1023.862567, unformat_float(' -1 023X862567 ', true));
1846 * Test deleting of users.
1848 public function test_delete_user() {
1851 $this->resetAfterTest();
1853 $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
1854 $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
1855 $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
1857 $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
1858 $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
1860 // Delete user and capture event.
1861 $sink = $this->redirectEvents();
1862 $result = delete_user($user);
1863 $events = $sink->get_events();
1865 $event = array_pop($events);
1867 // Test user is deleted in DB.
1868 $this->assertTrue($result);
1869 $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
1870 $this->assertEquals(1, $deluser->deleted);
1871 $this->assertEquals(0, $deluser->picture);
1872 $this->assertSame('', $deluser->idnumber);
1873 $this->assertSame(md5($user->username), $deluser->email);
1874 $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
1876 $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
1879 $this->assertInstanceOf('\core\event\user_deleted', $event);
1880 $this->assertSame($user->id, $event->objectid);
1881 $this->assertSame('user_deleted', $event->get_legacy_eventname());
1882 $this->assertEventLegacyData($user, $event);
1883 $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
1884 $this->assertEventLegacyLogData($expectedlogdata, $event);
1885 $eventdata = $event->get_data();
1886 $this->assertSame($eventdata['other']['username'], $user->username);
1887 $this->assertSame($eventdata['other']['email'], $user->email);
1888 $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
1889 $this->assertSame($eventdata['other']['picture'], $user->picture);
1890 $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
1891 $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
1892 $this->assertEventContextNotUsed($event);
1894 // Try invalid params.
1895 $record = new stdClass();
1898 delete_user($record);
1899 $this->fail('Expecting exception for invalid delete_user() $user parameter');
1900 } catch (moodle_exception $ex) {
1901 $this->assertInstanceOf('coding_exception', $ex);
1905 delete_user($record);
1906 $this->fail('Expecting exception for invalid delete_user() $user parameter');
1907 } catch (moodle_exception $ex) {
1908 $this->assertInstanceOf('coding_exception', $ex);
1911 $record = new stdClass();
1913 $record->username = 'xx';
1914 $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
1915 $result = delete_user($record);
1916 $this->assertFalse($result);
1918 $result = delete_user($guest);
1919 $this->assertFalse($result);
1921 $result = delete_user($admin);
1922 $this->assertFalse($result);
1924 $this->resetDebugging();
1928 * Test function convert_to_array()
1930 public function test_convert_to_array() {
1931 // Check that normal classes are converted to arrays the same way as (array) would do.
1932 $obj = new stdClass();
1933 $obj->prop1 = 'hello';
1934 $obj->prop2 = array('first', 'second', 13);
1936 $this->assertEquals(convert_to_array($obj), (array)$obj);
1938 // Check that context object (with iterator) is converted to array properly.
1939 $obj = context_system::instance();
1942 'contextlevel' => $obj->contextlevel,
1943 'instanceid' => $obj->instanceid,
1944 'path' => $obj->path,
1945 'depth' => $obj->depth
1947 $this->assertEquals(convert_to_array($obj), $ar);
1951 * Test the function date_format_string().
1953 public function test_date_format_string() {
1956 // Forcing locale and timezone.
1957 $oldlocale = setlocale(LC_TIME, '0');
1958 if ($CFG->ostype == 'WINDOWS') {
1959 setlocale(LC_TIME, 'English_Australia.1252');
1961 setlocale(LC_TIME, 'en_AU.UTF-8');
1963 $systemdefaulttimezone = date_default_timezone_get();
1964 date_default_timezone_set('Australia/Perth');
1969 'str' => '%A, %d %B %Y, %I:%M %p',
1970 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
1974 'str' => '%A, %d %B %Y, %I:%M %p',
1975 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
1979 'str' => '%A, %d %B %Y, %I:%M %p',
1980 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
1982 // Following tests pass on Windows only because en lang pack does
1983 // not contain localewincharset, in real life lang pack maintainers
1984 // may use only characters that are present in localewincharset
1985 // in format strings!
1988 'str' => 'Žluťoučký koníček %A',
1989 'expected' => 'Žluťoučký koníček Saturday'
1993 'str' => '言語設定言語 %A',
1994 'expected' => '言語設定言語 Saturday'
1998 'str' => '简体中文简体 %A',
1999 'expected' => '简体中文简体 Saturday'
2003 // Note: date_format_string() uses the timezone only to differenciate
2004 // the server time from the UTC time. It does not modify the timestamp.
2005 // Hence similar results for timezones <= 13.
2006 // On different systems case of AM PM changes so compare case insensitive.
2007 foreach ($tests as $test) {
2008 $str = date_format_string(1293876000, $test['str'], $test['tz']);
2009 $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
2012 // Restore system default values.
2013 date_default_timezone_set($systemdefaulttimezone);
2014 setlocale(LC_TIME, $oldlocale);
2017 public function test_get_config() {
2020 $this->resetAfterTest();
2023 set_config('phpunit_test_get_config_1', 'test 1');
2024 set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2025 if (!is_array($CFG->config_php_settings)) {
2026 $CFG->config_php_settings = array();
2028 $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
2030 if (!is_array($CFG->forced_plugin_settings)) {
2031 $CFG->forced_plugin_settings = array();
2033 if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
2034 $CFG->forced_plugin_settings['mod_forum'] = array();
2036 $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2037 $CFG->phpunit_test_get_config_5 = 'test 5';
2040 $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
2041 $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2042 $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
2043 $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2044 $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2045 $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2046 $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2048 // Test config we know to exist.
2049 $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
2050 $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2051 $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2052 $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2054 // Test setting a config var that already exists.
2055 set_config('phpunit_test_get_config_1', 'test a');
2056 $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
2057 $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
2059 // Test cache invalidation.
2060 $cache = cache::make('core', 'config');
2061 $this->assertInternalType('array', $cache->get('core'));
2062 $this->assertInternalType('array', $cache->get('mod_forum'));
2063 set_config('phpunit_test_get_config_1', 'test b');
2064 $this->assertFalse($cache->get('core'));
2065 set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2066 $this->assertFalse($cache->get('mod_forum'));
2069 public function test_get_max_upload_sizes() {
2070 // Test with very low limits so we are not affected by php upload limits.
2071 // Test activity limit smallest.
2072 $sitebytes = 102400;
2073 $coursebytes = 51200;
2074 $modulebytes = 10240;
2075 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2077 $this->assertSame('Activity upload limit (10KB)', $result['0']);
2078 $this->assertCount(2, $result);
2080 // Test course limit smallest.
2081 $sitebytes = 102400;
2082 $coursebytes = 10240;
2083 $modulebytes = 51200;
2084 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2086 $this->assertSame('Course upload limit (10KB)', $result['0']);
2087 $this->assertCount(2, $result);
2089 // Test site limit smallest.
2091 $coursebytes = 102400;
2092 $modulebytes = 51200;
2093 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2095 $this->assertSame('Site upload limit (10KB)', $result['0']);
2096 $this->assertCount(2, $result);
2098 // Test site limit not set.
2100 $coursebytes = 102400;
2101 $modulebytes = 51200;
2102 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2104 $this->assertSame('Activity upload limit (50KB)', $result['0']);
2105 $this->assertCount(3, $result);
2108 $coursebytes = 51200;
2109 $modulebytes = 102400;
2110 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2112 $this->assertSame('Course upload limit (50KB)', $result['0']);
2113 $this->assertCount(3, $result);
2115 // Test custom bytes in range.
2116 $sitebytes = 102400;
2117 $coursebytes = 51200;
2118 $modulebytes = 51200;
2119 $custombytes = 10240;
2120 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2122 $this->assertCount(3, $result);
2124 // Test custom bytes in range but non-standard.
2125 $sitebytes = 102400;
2126 $coursebytes = 51200;
2127 $modulebytes = 51200;
2128 $custombytes = 25600;
2129 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2131 $this->assertCount(4, $result);
2133 // Test custom bytes out of range.
2134 $sitebytes = 102400;
2135 $coursebytes = 51200;
2136 $modulebytes = 51200;
2137 $custombytes = 102400;
2138 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2140 $this->assertCount(3, $result);
2142 // Test custom bytes out of range and non-standard.
2143 $sitebytes = 102400;
2144 $coursebytes = 51200;
2145 $modulebytes = 51200;
2146 $custombytes = 256000;
2147 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2149 $this->assertCount(3, $result);
2151 // Test site limit only.
2153 $result = get_max_upload_sizes($sitebytes);
2155 $this->assertSame('Site upload limit (50KB)', $result['0']);
2156 $this->assertSame('50KB', $result['51200']);
2157 $this->assertSame('10KB', $result['10240']);
2158 $this->assertCount(3, $result);
2161 $result = get_max_upload_sizes();
2162 $this->assertArrayHasKey('0', $result);
2163 $this->assertArrayHasKey(get_max_upload_file_size(), $result);
2167 * Test function password_is_legacy_hash().
2169 public function test_password_is_legacy_hash() {
2170 // Well formed md5s should be matched.
2171 foreach (array('some', 'strings', 'to_check!') as $string) {
2172 $md5 = md5($string);
2173 $this->assertTrue(password_is_legacy_hash($md5));
2175 // Strings that are not md5s should not be matched.
2176 foreach (array('', AUTH_PASSWORD_NOT_CACHED, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
2177 $this->assertFalse(password_is_legacy_hash($notmd5));
2182 * Test function validate_internal_user_password().
2184 public function test_validate_internal_user_password() {
2185 // Test bcrypt hashes.
2186 $validhashes = array(
2187 'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2188 'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2189 'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2190 'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
2193 foreach ($validhashes as $password => $hash) {
2194 $user = new stdClass();
2195 $user->auth = 'manual';
2196 $user->password = $hash;
2197 // The correct password should be validated.
2198 $this->assertTrue(validate_internal_user_password($user, $password));
2199 // An incorrect password should not be validated.
2200 $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2205 * Test function hash_internal_user_password().
2207 public function test_hash_internal_user_password() {
2208 $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
2210 // Check that some passwords that we convert to hashes can
2212 foreach ($passwords as $password) {
2213 $hash = hash_internal_user_password($password);
2214 $fasthash = hash_internal_user_password($password, true);
2215 $user = new stdClass();
2216 $user->auth = 'manual';
2217 $user->password = $hash;
2218 $this->assertTrue(validate_internal_user_password($user, $password));
2220 // They should not be in md5 format.
2221 $this->assertFalse(password_is_legacy_hash($hash));
2223 // Check that cost factor in hash is correctly set.
2224 $this->assertRegExp('/\$10\$/', $hash);
2225 $this->assertRegExp('/\$04\$/', $fasthash);
2230 * Test function update_internal_user_password().
2232 public function test_update_internal_user_password() {
2234 $this->resetAfterTest();
2235 $passwords = array('password', '1234', 'changeme', '****');
2236 foreach ($passwords as $password) {
2237 $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2238 update_internal_user_password($user, $password);
2239 // The user object should have been updated.
2240 $this->assertTrue(validate_internal_user_password($user, $password));
2241 // The database field for the user should also have been updated to the
2243 $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
2246 $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2247 // Manually set the user's password to the md5 of the string 'password'.
2248 $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
2250 // Update the password.
2251 update_internal_user_password($user, 'password');
2253 // Password should have been updated to a bcrypt hash.
2254 $this->assertFalse(password_is_legacy_hash($user->password));
2257 public function test_fullname() {
2260 $this->resetAfterTest();
2262 // Create a user to test the name display on.
2264 $record['firstname'] = 'Scott';
2265 $record['lastname'] = 'Fletcher';
2266 $record['firstnamephonetic'] = 'スコット';
2267 $record['lastnamephonetic'] = 'フレチャー';
2268 $record['alternatename'] = 'No friends';
2269 $user = $this->getDataGenerator()->create_user($record);
2271 // Back up config settings for restore later.
2272 $originalcfg = new stdClass();
2273 $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
2275 // Testing existing fullnamedisplay settings.
2276 $CFG->fullnamedisplay = 'firstname';
2277 $testname = fullname($user);
2278 $this->assertSame($user->firstname, $testname);
2280 $CFG->fullnamedisplay = 'firstname lastname';
2281 $expectedname = "$user->firstname $user->lastname";
2282 $testname = fullname($user);
2283 $this->assertSame($expectedname, $testname);
2285 $CFG->fullnamedisplay = 'lastname firstname';
2286 $expectedname = "$user->lastname $user->firstname";
2287 $testname = fullname($user);
2288 $this->assertSame($expectedname, $testname);
2290 $expectedname = get_string('fullnamedisplay', null, $user);
2291 $CFG->fullnamedisplay = 'language';
2292 $testname = fullname($user);
2293 $this->assertSame($expectedname, $testname);
2295 // Test override parameter.
2296 $CFG->fullnamedisplay = 'firstname';
2297 $expectedname = "$user->firstname $user->lastname";
2298 $testname = fullname($user, true);
2299 $this->assertSame($expectedname, $testname);
2301 // Test additional name fields.
2302 $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
2303 $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
2304 $testname = fullname($user);
2305 $this->assertSame($expectedname, $testname);
2307 // Test for handling missing data.
2308 $user->middlename = null;
2309 // Parenthesis with no data.
2310 $CFG->fullnamedisplay = 'firstname (middlename) lastname';
2311 $expectedname = "$user->firstname $user->lastname";
2312 $testname = fullname($user);
2313 $this->assertSame($expectedname, $testname);
2315 // Extra spaces due to no data.
2316 $CFG->fullnamedisplay = 'firstname middlename lastname';
2317 $expectedname = "$user->firstname $user->lastname";
2318 $testname = fullname($user);
2319 $this->assertSame($expectedname, $testname);
2321 // Regular expression testing.
2322 // Remove some data from the user fields.
2323 $user->firstnamephonetic = '';
2324 $user->lastnamephonetic = '';
2326 // Removing empty brackets and excess whitespace.
2327 // All of these configurations should resolve to just firstname lastname.
2328 $configarray = array();
2329 $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
2330 $configarray[] = 'firstname lastname \'middlename\'';
2331 $configarray[] = 'firstname "firstnamephonetic" lastname';
2332 $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
2334 foreach ($configarray as $config) {
2335 $CFG->fullnamedisplay = $config;
2336 $expectedname = "$user->firstname $user->lastname";
2337 $testname = fullname($user);
2338 $this->assertSame($expectedname, $testname);
2341 // Check to make sure that other characters are left in place.
2342 $configarray = array();
2343 $configarray['0'] = new stdClass();
2344 $configarray['0']->config = 'lastname firstname, middlename';
2345 $configarray['0']->expectedname = "$user->lastname $user->firstname,";
2346 $configarray['1'] = new stdClass();
2347 $configarray['1']->config = 'lastname firstname + alternatename';
2348 $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
2349 $configarray['2'] = new stdClass();
2350 $configarray['2']->config = 'firstname aka: alternatename';
2351 $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
2352 $configarray['3'] = new stdClass();
2353 $configarray['3']->config = 'firstname (alternatename)';
2354 $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
2355 $configarray['4'] = new stdClass();
2356 $configarray['4']->config = 'firstname [alternatename]';
2357 $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
2358 $configarray['5'] = new stdClass();
2359 $configarray['5']->config = 'firstname "lastname"';
2360 $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
2362 foreach ($configarray as $config) {
2363 $CFG->fullnamedisplay = $config->config;
2364 $expectedname = $config->expectedname;
2365 $testname = fullname($user);
2366 $this->assertSame($expectedname, $testname);
2369 // Test debugging message displays when
2370 // fullnamedisplay setting is "normal".
2371 $CFG->fullnamedisplay = 'firstname lastname';
2373 $user = new stdClass();
2374 $user->firstname = 'Stan';
2375 $user->lastname = 'Lee';
2376 $namedisplay = fullname($user);
2377 $this->assertDebuggingCalled();
2379 // Tidy up after we finish testing.
2380 $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
2383 public function test_get_all_user_name_fields() {
2384 $this->resetAfterTest();
2386 // Additional names in an array.
2387 $testarray = array('firstnamephonetic' => 'firstnamephonetic',
2388 'lastnamephonetic' => 'lastnamephonetic',
2389 'middlename' => 'middlename',
2390 'alternatename' => 'alternatename',
2391 'firstname' => 'firstname',
2392 'lastname' => 'lastname');
2393 $this->assertEquals($testarray, get_all_user_name_fields());
2395 // Additional names as a string.
2396 $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
2397 $this->assertEquals($teststring, get_all_user_name_fields(true));
2399 // Additional names as a string with an alias.
2400 $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
2401 $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
2403 // Additional name fields with a prefix - object.
2404 $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
2405 'lastnamephonetic' => 'authorlastnamephonetic',
2406 'middlename' => 'authormiddlename',
2407 'alternatename' => 'authoralternatename',
2408 'firstname' => 'authorfirstname',
2409 'lastname' => 'authorlastname');
2410 $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
2412 // Additional name fields with an alias and a title - string.
2413 $teststring = 'u.firstnamephonetic AS authorfirstnamephonetic,u.lastnamephonetic AS authorlastnamephonetic,u.middlename AS authormiddlename,u.alternatename AS authoralternatename,u.firstname AS authorfirstname,u.lastname AS authorlastname';
2414 $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
2417 public function test_order_in_string() {
2418 $this->resetAfterTest();
2420 // Return an array in an order as they are encountered in a string.
2421 $valuearray = array('second', 'firsthalf', 'first');
2422 $formatstring = 'first firsthalf some other text (second)';
2423 $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
2424 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2426 // Try again with a different order for the format.
2427 $valuearray = array('second', 'firsthalf', 'first');
2428 $formatstring = 'firsthalf first second';
2429 $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
2430 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2432 // Try again with yet another different order for the format.
2433 $valuearray = array('second', 'firsthalf', 'first');
2434 $formatstring = 'start seconds away second firstquater first firsthalf';
2435 $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
2436 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
2439 public function test_complete_user_login() {
2442 $this->resetAfterTest();
2443 $user = $this->getDataGenerator()->create_user();
2446 $sink = $this->redirectEvents();
2447 $loginuser = clone($user);
2448 $this->setCurrentTimeStart();
2449 @complete_user_login($loginuser); // Hide session header errors.
2450 $this->assertSame($loginuser, $USER);
2451 $this->assertEquals($user->id, $USER->id);
2452 $events = $sink->get_events();
2455 $this->assertCount(1, $events);
2456 $event = reset($events);
2457 $this->assertInstanceOf('\core\event\user_loggedin', $event);
2458 $this->assertEquals('user', $event->objecttable);
2459 $this->assertEquals($user->id, $event->objectid);
2460 $this->assertEquals(context_system::instance()->id, $event->contextid);
2461 $this->assertEventContextNotUsed($event);
2463 $user = $DB->get_record('user', array('id'=>$user->id));
2465 $this->assertTimeCurrent($user->firstaccess);
2466 $this->assertTimeCurrent($user->lastaccess);
2468 $this->assertTimeCurrent($USER->firstaccess);
2469 $this->assertTimeCurrent($USER->lastaccess);
2470 $this->assertTimeCurrent($USER->currentlogin);
2471 $this->assertSame(sesskey(), $USER->sesskey);
2472 $this->assertTimeCurrent($USER->preference['_lastloaded']);
2473 $this->assertObjectNotHasAttribute('password', $USER);
2474 $this->assertObjectNotHasAttribute('description', $USER);
2478 * Test require_logout.
2480 public function test_require_logout() {
2481 $this->resetAfterTest();
2482 $user = $this->getDataGenerator()->create_user();
2483 $this->setUser($user);
2485 $this->assertTrue(isloggedin());
2487 // Logout user and capture event.
2488 $sink = $this->redirectEvents();
2490 $events = $sink->get_events();
2492 $event = array_pop($events);
2494 // Check if user is logged out.
2495 $this->assertFalse(isloggedin());
2498 $this->assertInstanceOf('\core\event\user_loggedout', $event);
2499 $this->assertSame($user->id, $event->objectid);
2500 $this->assertSame('user_logout', $event->get_legacy_eventname());
2501 $this->assertEventLegacyData($user, $event);
2502 $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
2504 $this->assertEventLegacyLogData($expectedlogdata, $event);
2505 $this->assertEventContextNotUsed($event);
2508 public function test_email_to_user() {
2511 $this->resetAfterTest();
2513 $user1 = $this->getDataGenerator()->create_user();
2514 $user2 = $this->getDataGenerator()->create_user();
2516 $subject = 'subject';
2517 $messagetext = 'message text';
2518 $subject2 = 'subject 2';
2519 $messagetext2 = 'message text 2';
2521 $this->assertNotEmpty($CFG->noemailever);
2522 email_to_user($user1, $user2, $subject, $messagetext);
2523 $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
2525 unset_config('noemailever');
2527 email_to_user($user1, $user2, $subject, $messagetext);
2528 $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2530 $sink = $this->redirectEmails();
2531 email_to_user($user1, $user2, $subject, $messagetext);
2532 email_to_user($user2, $user1, $subject2, $messagetext2);
2533 $this->assertSame(2, $sink->count());
2534 $result = $sink->get_messages();
2535 $this->assertCount(2, $result);
2538 $this->assertSame($subject, $result[0]->subject);
2539 $this->assertSame($messagetext, trim($result[0]->body));
2540 $this->assertSame($user1->email, $result[0]->to);
2541 $this->assertSame($user2->email, $result[0]->from);
2543 $this->assertSame($subject2, $result[1]->subject);
2544 $this->assertSame($messagetext2, trim($result[1]->body));
2545 $this->assertSame($user2->email, $result[1]->to);
2546 $this->assertSame($user1->email, $result[1]->from);
2548 email_to_user($user1, $user2, $subject, $messagetext);
2549 $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
2553 * Test user_updated event trigger by various apis.
2555 public function test_user_updated_event() {
2558 $this->resetAfterTest();
2560 $user = $this->getDataGenerator()->create_user();
2562 // Set config to allow email_to_user() to be called.
2563 $CFG->noemailever = false;
2565 // Update user password.
2566 $sink = $this->redirectEvents();
2567 $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
2568 setnew_password_and_mail($user);
2569 update_internal_user_password($user, 'randompass');
2570 $events = $sink->get_events();
2574 // Test updated value.
2575 $dbuser = $DB->get_record('user', array('id' => $user->id));
2576 $this->assertSame($user->firstname, $dbuser->firstname);
2577 $this->assertNotSame('M00dLe@T', $dbuser->password);
2580 foreach ($events as $event) {
2581 $this->assertInstanceOf('\core\event\user_updated', $event);
2582 $this->assertSame($user->id, $event->objectid);
2583 $this->assertSame('user_updated', $event->get_legacy_eventname());
2584 $this->assertEventLegacyData($user, $event);
2585 $this->assertEquals(context_user::instance($user->id), $event->get_context());
2586 $expectedlogdata = array(SITEID, 'user', 'update', 'view.php?id='.$user->id, '');
2587 $this->assertEventLegacyLogData($expectedlogdata, $event);
2588 $this->assertEventContextNotUsed($event);
2593 * Test remove_course_content deletes course contents
2594 * TODO Add asserts to verify other data related to course is deleted as well.
2596 public function test_remove_course_contents() {
2598 $this->resetAfterTest();
2600 $course = $this->getDataGenerator()->create_course();
2601 $user = $this->getDataGenerator()->create_user();
2602 $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
2603 $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id));
2605 $this->assertNotEquals(false, note_load($note->id));
2606 remove_course_contents($course->id, false);
2607 $this->assertFalse(note_load($note->id));
2611 * Test function username_load_fields_from_object().
2613 public function test_username_load_fields_from_object() {
2614 $this->resetAfterTest();
2616 // This object represents the information returned from an sql query.
2617 $userinfo = new stdClass();
2618 $userinfo->userid = 1;
2619 $userinfo->username = 'loosebruce';
2620 $userinfo->firstname = 'Bruce';
2621 $userinfo->lastname = 'Campbell';
2622 $userinfo->firstnamephonetic = 'ブルース';
2623 $userinfo->lastnamephonetic = 'カンベッル';
2624 $userinfo->middlename = '';
2625 $userinfo->alternatename = '';
2626 $userinfo->email = '';
2627 $userinfo->picture = 23;
2628 $userinfo->imagealt = 'Michael Jordan draining another basket.';
2629 $userinfo->idnumber = 3982;
2631 // Just user name fields.
2632 $user = new stdClass();
2633 $user = username_load_fields_from_object($user, $userinfo);
2634 $expectedarray = new stdClass();
2635 $expectedarray->firstname = 'Bruce';
2636 $expectedarray->lastname = 'Campbell';
2637 $expectedarray->firstnamephonetic = 'ブルース';
2638 $expectedarray->lastnamephonetic = 'カンベッル';
2639 $expectedarray->middlename = '';
2640 $expectedarray->alternatename = '';
2641 $this->assertEquals($user, $expectedarray);
2643 // User information for showing a picture.
2644 $user = new stdClass();
2645 $additionalfields = explode(',', user_picture::fields());
2646 $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
2647 $user->id = $userinfo->userid;
2648 $expectedarray = new stdClass();
2649 $expectedarray->id = 1;
2650 $expectedarray->firstname = 'Bruce';
2651 $expectedarray->lastname = 'Campbell';
2652 $expectedarray->firstnamephonetic = 'ブルース';
2653 $expectedarray->lastnamephonetic = 'カンベッル';
2654 $expectedarray->middlename = '';
2655 $expectedarray->alternatename = '';
2656 $expectedarray->email = '';
2657 $expectedarray->picture = 23;
2658 $expectedarray->imagealt = 'Michael Jordan draining another basket.';
2659 $this->assertEquals($user, $expectedarray);
2661 // Alter the userinfo object to have a prefix.
2662 $userinfo->authorfirstname = 'Bruce';
2663 $userinfo->authorlastname = 'Campbell';
2664 $userinfo->authorfirstnamephonetic = 'ブルース';
2665 $userinfo->authorlastnamephonetic = 'カンベッル';
2666 $userinfo->authormiddlename = '';
2667 $userinfo->authorpicture = 23;
2668 $userinfo->authorimagealt = 'Michael Jordan draining another basket.';
2669 $userinfo->authoremail = 'test@testing.net';
2672 // Return an object with user picture information.
2673 $user = new stdClass();
2674 $additionalfields = explode(',', user_picture::fields());
2675 $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
2676 $user->id = $userinfo->userid;
2677 $expectedarray = new stdClass();
2678 $expectedarray->id = 1;
2679 $expectedarray->firstname = 'Bruce';
2680 $expectedarray->lastname = 'Campbell';
2681 $expectedarray->firstnamephonetic = 'ブルース';
2682 $expectedarray->lastnamephonetic = 'カンベッル';
2683 $expectedarray->middlename = '';
2684 $expectedarray->alternatename = '';
2685 $expectedarray->email = 'test@testing.net';
2686 $expectedarray->picture = 23;
2687 $expectedarray->imagealt = 'Michael Jordan draining another basket.';
2688 $this->assertEquals($user, $expectedarray);
2692 * Test function count_words().
2694 public function test_count_words() {
2695 $count = count_words("one two three'four");
2696 $this->assertEquals(3, $count);
2698 $count = count_words('one+two three’four');
2699 $this->assertEquals(3, $count);
2701 $count = count_words('one"two three-four');
2702 $this->assertEquals(3, $count);
2704 $count = count_words('one@two three_four');
2705 $this->assertEquals(4, $count);
2707 $count = count_words('one\two three/four');
2708 $this->assertEquals(4, $count);
2710 $count = count_words(' one ... two three...four ');
2711 $this->assertEquals(4, $count);
2713 $count = count_words('one.2 3,four');
2714 $this->assertEquals(4, $count);
2716 $count = count_words('1³ £2 €3.45 $6,789');
2717 $this->assertEquals(4, $count);
2719 $count = count_words('one—two ブルース カンベッル');
2720 $this->assertEquals(4, $count);
2722 $count = count_words('one…two ブルース … カンベッル');
2723 $this->assertEquals(4, $count);